branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>package org.ajm.laforkids.desktop.tests
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.utils.Array
import org.ajm.laforkids.actors.IMatrix
import org.ajm.laforkids.actors.Matrix
import org.ajm.laforkids.desktop.DesktopLauncher
import org.junit.Assert
import org.junit.Test
import org.junit.runners.Parameterized
import java.util.*
/**
* Tests the properties of [Matrix] defined in [IMatrix].
*/
class MatrixTest {
val random = Random()
/**
* Test that the functions reject values that make no sense.
*/
@Test
fun illegalArgumentTest1() {
val skin = DesktopLauncher.skin!!
val rows = random.nextInt(100) + 1
val columns = random.nextInt(100) + 1
val matrix: IMatrix = Matrix(skin, rows, columns)
for (i in 0 until 100) {
assertExceptionThrown {
matrix.set(-random.nextInt(100) - 1, -random.nextInt(100) - 1, random.nextLong())
}
}
for (i in 0 until 100) {
assertExceptionThrown {
matrix.get(-random.nextInt(100) - 1, -random.nextInt(100) - 1)
}
}
for (i in 0 until 100) {
assertExceptionThrown {
matrix.getCell(-random.nextInt(100) - 1, -random.nextInt(100) - 1)
}
}
}
/**
* Test that the variables reject values that make no sense.
*/
@Test
fun illegalArgumentTest2() {
val skin = DesktopLauncher.skin!!
val rows = random.nextInt(100) + 1
val columns = random.nextInt(100) + 1
val matrix: IMatrix = Matrix(skin, rows, columns)
for (i in 0 until 100) {
assertExceptionThrown {
matrix.outlineThickness = -(0.00001f + random.nextFloat()) * 100f
}
assertExceptionThrown {
matrix.entryPad = -(0.00001f + random.nextFloat()) * 100f
}
assertExceptionThrown {
matrix.entryWidth = -(0.00001f + random.nextFloat()) * 100f
}
assertExceptionThrown {
matrix.entryHeight = -(0.00001f + random.nextFloat()) * 100f
}
assertExceptionThrown {
matrix.backgroundTextWidth = -(0.00001f + random.nextFloat()) * 100f
}
assertExceptionThrown {
matrix.backgroundTextHeight = -(0.00001f + random.nextFloat()) * 100f
}
}
}
/**
* Test that the constructor reject values that make no sense.
*/
@Test
fun illegalArgumentTest3() {
val skin = DesktopLauncher.skin!!
for (i in 0 until 100) {
val rows = -random.nextInt(100)
val columns = -random.nextInt(100)
assertExceptionThrown { Matrix(skin, rows, columns) }
}
}
@Test
fun setGet1() {
val skin = DesktopLauncher.skin!!
val rows = random.nextInt(100) + 1
val columns = random.nextInt(100) + 1
// test constructor
val matrix: IMatrix = Matrix(skin, rows, columns)
Assert.assertEquals(rows, matrix.matrixRows)
Assert.assertEquals(columns, matrix.matrixColumns)
// test set get
val drawOutlines = random.nextBoolean()
val outlineThickness = random.nextFloat() * 1000f
val entryPad = random.nextFloat() * 1000f
val entryWidth = random.nextFloat() * 1000f
val entryHeight = random.nextFloat() * 1000f
val backgroundTextWidth = random.nextFloat() * 1000f
val backgroundTextHeight = random.nextFloat() * 1000f
val backgroundText = random.nextLong().toString()
val backgroundTextColor = Color(random.nextFloat(), random.nextFloat(), random.nextFloat(), random.nextFloat())
matrix.drawOutlines = drawOutlines
Assert.assertEquals(drawOutlines, matrix.drawOutlines)
matrix.outlineThickness = outlineThickness
Assert.assertEquals(outlineThickness, matrix.outlineThickness)
matrix.entryPad = entryPad
Assert.assertEquals(entryPad, matrix.entryPad)
matrix.entryWidth = entryWidth
Assert.assertEquals(entryWidth, matrix.entryWidth)
matrix.entryHeight = entryHeight
Assert.assertEquals(entryHeight, matrix.entryHeight)
matrix.backgroundTextWidth = backgroundTextWidth
Assert.assertEquals(backgroundTextWidth, matrix.backgroundTextWidth)
matrix.backgroundTextHeight = backgroundTextHeight
Assert.assertEquals(backgroundTextHeight, matrix.backgroundTextHeight)
matrix.backgroundText = backgroundText
Assert.assertEquals(backgroundText, matrix.backgroundText)
matrix.backgroundTextColor = backgroundTextColor
Assert.assertEquals(backgroundTextColor, matrix.backgroundTextColor)
}
@Test
fun setGet2() {
val skin = DesktopLauncher.skin!!
val rows = random.nextInt(100) + 1
val columns = random.nextInt(100) + 1
val matrix: IMatrix = Matrix(skin, rows, columns)
val control = IntArray(rows * columns)
// test set get on each entry
for (row in 0 until rows) {
for (col in 0 until columns) {
val i = random.nextInt()
control[row * columns + col] = i
matrix.set(row, col, i)
}
}
for (row in 0 until rows) {
for (col in 0 until columns) {
val expected = control[row * columns + col].toString()
val actual = matrix.get(row, col)
val actual2 = matrix.getCell(row, col)!!.actor.text.toString()
Assert.assertEquals(expected, actual)
Assert.assertEquals(expected, actual2)
}
}
}
}<file_sep>package org.ajm.laforkids.desktop.tests
import org.ajm.laforkids.Settings
import java.util.*
class SettingsFactory(val tag: String = "Test Tag 223", val max: Int = 25) {
private val random = Random()
fun generateTestSettings(): Settings {
val settings = Settings(tag)
settings.maxValue = random.nextInt(max * max) + 1
settings.minValue = -random.nextInt(max * max) - 1
settings.answerAlternatives = random.nextInt(max) + 1
settings.answerMaxError = random.nextInt(max) + 1
settings.minColumnsLeft = random.nextInt(max) + 1
settings.maxColumnsLeft = settings.minColumnsLeft + random.nextInt(max) + 1
settings.minRowsLeft = random.nextInt(max) + 1
settings.maxRowsLeft = settings.minRowsLeft + random.nextInt(max) + 1
settings.minColumnsRight = random.nextInt(max) + 1
settings.maxColumnsRight = settings.minColumnsRight + random.nextInt(max) + 1
return settings
}
}<file_sep>package org.ajm.laforkids
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.utils.Array
import org.ajm.laforkids.actors.IColoredMultiplicationTable
import java.util.*
/**
* The rules of the game is implemented here.
*/
class GameLogic {
var score = 0
private set(value) {
field = value
}
private var multiplicationTable: IColoredMultiplicationTable? = null
private set(value) {
if (value == null) throw IllegalArgumentException()
field = value
}
private val settings: Settings
private val random = Random()
/** The progress of the game, iterates over all the entries in the product matrix C. */
var progress = 0
set(value) {
if (value < 0) throw IllegalArgumentException()
field = value
}
var rowsLeft = 0
private set(value) {
field = value
}
var columnsLeft = 0
private set(value) {
field = value
}
var columnsRight = 0
private set(value) {
field = value
}
var answerAlternatives = 0
private set(value) {
field = value
}
private var completed = false
private var scoreThisRound = 0
constructor(settings: Settings) {
this.settings = settings
}
/**
*
* 1. [newGame]
* 2. [init]
* 3. [progress]
* 4. [progress]
* 5. ...
* 6. [newGame]
* 7. [init]
* 8. ...
*/
fun init(multiplicationTable: IColoredMultiplicationTable) {
if (multiplicationTable.rowsLeft != rowsLeft || rowsLeft <= 0) throw IllegalArgumentException()
if (multiplicationTable.columnsLeft != columnsLeft || columnsLeft <= 0) throw IllegalArgumentException()
if (multiplicationTable.columnsRight != columnsRight || columnsRight <= 0) throw IllegalArgumentException()
if (multiplicationTable.answerAlternatives != answerAlternatives || answerAlternatives <= 0) throw IllegalArgumentException()
this.multiplicationTable = multiplicationTable
multiplicationTable.highlightCol = getHighlightCol()
multiplicationTable.highlightRow = getHighlightRow()
// increment score if completed previous game
if (completed) score += Math.max(scoreThisRound / 2, 0)
completed = false
scoreThisRound = 0
}
/**
*
* 1. [newGame]
* 2. [init]
* 3. [progress]
* 4. [progress]
* 5. ...
* 6. [newGame]
* 7. [init]
* 8. ...
*
* @return whether given answer was the correct one.
*/
fun progress(answer: Int): Boolean {
assertInitialized()
// set entry of product matrix to the correct answer
val correctAnswer = getCorrectAnswer()
if (answer != correctAnswer) {
score -= score(correctAnswer)
scoreThisRound -= score(correctAnswer)
return false
}
multiplicationTable!!.matrixProduct.set(getHighlightRow(), getHighlightCol(), correctAnswer)
progress = MathUtils.clamp(progress + 1, 0, maxProgress())
val completed = isComplete()
if (!completed) {
multiplicationTable!!.highlightCol = getHighlightCol()
multiplicationTable!!.highlightRow = getHighlightRow()
} else {
this.completed = true
}
score += score(correctAnswer)
scoreThisRound += score(correctAnswer)
return true
}
private fun score(answer: Int): Int {
val i = Math.max(1.0, Math.log((settings.maxValue - settings.minValue).toDouble())).toInt()
return i * columnsLeft * Math.max(2, Math.log(answer.toDouble()).toInt())
}
fun maxProgress(): Int {
return multiplicationTable!!.rowsLeft * multiplicationTable!!.columnsRight
}
fun isComplete(): Boolean {
assertInitialized()
return progress >= maxProgress()
}
/**
*
* 1. [newGame]
* 2. [init]
* 3. [progress]
* 4. [progress]
* 5. ...
* 6. [newGame]
* 7. [init]
* 8. ...
*/
fun newGame(rowsLeft: Int = getRandomLeftRowCount(),
columnsLeft: Int = getRandomLeftColumnCount(),
columnsRight: Int = getRandomRightColumnCount(),
answerAlternatives: Int = getAnswerAlternativesCount()) {
if (rowsLeft < 1) throw IllegalArgumentException()
if (columnsLeft < 1) throw IllegalArgumentException()
if (columnsRight < 1) throw IllegalArgumentException()
if (answerAlternatives < 1) throw IllegalArgumentException()
this.rowsLeft = rowsLeft
this.columnsLeft = columnsLeft
this.columnsRight = columnsRight
this.answerAlternatives = answerAlternatives
progress = 0
}
/**
* Compute the correct answer for currently highlighted entry.
* @throws [NumberFormatException] if a needed entry is not a number
*/
fun getCorrectAnswer(): Int {
assertInitialized()
return getCorrectAnswer(getHighlightRow(), getHighlightCol())
}
/**
* Compute the correct answer for currently highlighted entry.
* @throws [NumberFormatException] if a needed entry is not a number
*/
fun getCorrectAnswer(row: Int, col: Int): Int {
assertInitialized()
// convolve i'th left row with j'th right col
var correctAnswer = 0
for (k in 0 until multiplicationTable!!.columnsLeft) {
val a = multiplicationTable!!.matrixLeft.get(row, k).toInt()
val b = multiplicationTable!!.matrixRight.get(k, col).toInt()
correctAnswer += a * b
}
return correctAnswer
}
/**
* Correct any non empty entry in the product matrix.
*/
fun updateAnswers() {
assertInitialized()
for (row in 0 until rowsLeft) {
for (col in 0 until columnsRight) {
val current = multiplicationTable!!.matrixProduct.get(row, col)
if (current.isEmpty()) continue
multiplicationTable!!.matrixProduct.set(row, col, getCorrectAnswer(row, col))
}
}
}
fun getHighlightRow(): Int {
return Math.min(progress , maxProgress() - 1)% multiplicationTable!!.rowsLeft
}
fun getHighlightCol(): Int {
return Math.min(progress , maxProgress() - 1)/ multiplicationTable!!.rowsLeft
}
fun getRandomLeftRowCount() = random.nextInt(settings.maxRowsLeft - settings.minRowsLeft + 1) + settings.minRowsLeft
fun getRandomLeftColumnCount() = random.nextInt(settings.maxColumnsLeft - settings.minColumnsLeft + 1) + settings.minColumnsLeft
fun getRandomRightColumnCount() = random.nextInt(settings.maxColumnsRight - settings.minColumnsRight + 1) + settings.minColumnsRight
fun getAnswerAlternativesCount() = settings.answerAlternatives
/**
* Generate some answer alternatives.
* @throws [NumberFormatException] if a needed entry is not a number
*/
fun getAnswerAlternatives(): Array<String> {
assertInitialized()
if (progress < 0) throw IllegalStateException()
if (progress >= maxProgress()) throw IllegalStateException()
val alternatives = Array<String>()
val correctAnswer = getCorrectAnswer()
// make up some alternatives
val errors = Array<Int>()
for (i in 0 until multiplicationTable!!.answerAlternatives) {
var error = 0
var j = 0
while ((error == 0 || errors.contains(error, false)) && j++ < 10) {
error = random.nextInt(Math.max(settings.answerMaxError * 2, 1)) - settings.answerMaxError
}
errors.add(error)
alternatives.add((correctAnswer + error).toString())
}
// let one be correct
alternatives.set(random.nextInt(alternatives.size), correctAnswer.toString())
return alternatives
}
/**
* Update the answer alternatives found on the bottom
* of the screen.
* @throws [NumberFormatException] if a needed entry is not a number
*/
fun updateAnswerAlternatives() {
assertInitialized()
var i = 0
for (cell in multiplicationTable!!.matrixAnswers.cells) {
cell.actor.isVisible = true
}
for (alternative in getAnswerAlternatives()) {
multiplicationTable!!.matrixAnswers.set(0, i++, alternative)
}
}
fun assertInitialized() {
if (multiplicationTable == null) throw IllegalStateException()
if (!multiplicationTable!!.initialized) throw IllegalStateException()
}
}<file_sep>package org.ajm.laforkids.actors
import org.ajm.laforkids.actors.IMultiplicationTable
/**
* Contains 3 matrices that are set up to visualize a matrix multiplication.
* Also contains a vector with answer alternatives.
* Entries can be highlighted to help players.
*/
interface IColoredMultiplicationTable : IMultiplicationTable {
var highlight: Boolean
var highlightRow: Int
var highlightCol: Int
}<file_sep>package org.ajm.laforkids.actors
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.math.Interpolation
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.utils.Align
import org.ajm.laforkids.getTextWidth
/**
* Label for showing an integer score.
*/
class ScoreLabel : Label {
// settings
var interpolationMethod: Interpolation = Interpolation.pow4Out
var interpolationTime = 0.75f
private var diffLabel: Label? = null
var score = 0
set(value) {
previousDisplayedScore = displayedScore
val diff = value - score
field = value
scoreSetAtTime = System.currentTimeMillis()
// count up or down the displayed score
fun animate() = { lerp: Float ->
displayedScore = MathUtils.lerp(previousDisplayedScore.toFloat(), score.toFloat(), lerp).toInt()
setText(displayedScore.toString())
}
org.ajm.laforkids.animate(animate(), interpolationMethod, interpolationTime)
// display the difference for a while, if there is one
if (diff != 0 && stage != null) {
diffLabel?.remove() // only one at a time
// prepare label
val sign = if (diff < 0) "" else "+"
diffLabel = Label(sign + diff.toString(), style)
val label = diffLabel as Label
stage.addActor(diffLabel)
val pos = localToStageCoordinates(Vector2())
label.setPosition(pos.x + width - getTextWidth(style.font, score.toString()) - label.width - style.font.spaceWidth * 2f, pos.y)
// prepare opacity animation
val interpolationTime = interpolationTime * 4
fun displayDiff() { // recursive
var alpha = MathUtils.clamp((System.currentTimeMillis() - scoreSetAtTime) / 1000f, 0f,
interpolationTime) / interpolationTime
// remove if done, otherwise continue animation
if (alpha == 1f) label.remove()
else Gdx.app.postRunnable { displayDiff() }
// animate
alpha *= 2f
if (alpha > 1) alpha = 2f - alpha
val lerp = Interpolation.sine.apply(interpolationMethod.apply(alpha))
label.color.a = lerp
}
displayDiff()
}
}
// auxiliary
private var previousDisplayedScore = 0
private var displayedScore = 0
private var scoreSetAtTime = System.currentTimeMillis()
constructor(skin: Skin, score: Int) : super("000000000", skin) {
setAlignment(Align.center)
previousDisplayedScore = score
displayedScore = score
this.score = score
}
}<file_sep>package org.ajm.laforkids.actors
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.utils.Array
import org.ajm.laforkids.actors.Matrix
import java.util.*
/**
* Contains 3 matrices that are set up to visualize a matrix multiplication.
* Also contains a vector with answer alternatives.
*/
interface IMultiplicationTable {
val initialized: Boolean
/** These are invoked when something changes. */
val changeListeners: Array<Runnable>
/** A */
val matrixLeft: Matrix
/** AB=C */
val matrixProduct: Matrix
/** B */
val matrixRight: Matrix
/** Vector at the bottom displaying answer alternatives.*/
val matrixAnswers: Matrix
/** Can show some useful information. */
val topLeftActor: Actor
/** The number of rows in the left matrix. */
val rowsLeft: Int
/** The number of columns in the left matrix. Equal to the number of rows in the right matrix.*/
val columnsLeft: Int
/** The number of rows in the right matrix. Equal to the number of columns in the left matrix. */
val rowsRight: Int
/** The number of columns in the right matrix. */
val columnsRight: Int
/** The number of entries in the answer alternative vector at the bottom */
val answerAlternatives: Int
/** The height of each entry, in all matrices and also the answer vector. May be overridden by
* accessing the individual matrices and could therefore be incorrect. */
var entryHeight: Float
/** The width of each entry, in all matrices and also the answer vector. May be overridden by
* accessing the individual matrices and could therefore be incorrect. */
var entryWidth: Float
/** The padding inside each matrix boundary. May be overridden by
* accessing the individual matrices and could therefore be incorrect. */
var matrixInsidePad: Float
/** The padding outside each matrix boundary. May be overridden by
* accessing the individual matrices and could therefore be incorrect. */
var matrixOutsidePad: Float
/** The padding around each entry of each matrix. May be overridden by
* accessing the individual matrices and could therefore be incorrect. */
var matrixEntryPad: Float
/** Copy the entry values from all the matrices of given multiplication table.
* @param copyFrom the one to copy all the entries from
* */
fun init(copyFrom: IMultiplicationTable) {
if (rowsLeft != copyFrom.rowsLeft) throw IllegalArgumentException()
if (columnsLeft != copyFrom.columnsLeft) throw IllegalArgumentException()
if (columnsRight != copyFrom.columnsRight) throw IllegalArgumentException()
for (row in 0 until rowsLeft) {
for (col in 0 until columnsLeft) {
matrixLeft.set(row, col, copyFrom.matrixLeft.get(row, col))
}
}
for (row in 0 until rowsLeft) {
for (col in 0 until columnsRight) {
matrixProduct.set(row, col, copyFrom.matrixProduct.get(row, col))
}
}
for (row in 0 until rowsRight) {
for (col in 0 until columnsRight) {
matrixRight.set(row, col, copyFrom.matrixRight.get(row, col))
}
}
for (col in 0 until matrixAnswers.columns) {
matrixAnswers.set(0, col, copyFrom.matrixAnswers.get(0, col))
}
}
/**
* Randomize the entries in the left and right matrix, erase the entries in the product matrix.
* @param min the smallest possible value
* @param max the largest possible value
*/
fun init(min: Int, max: Int) {
val random = Random()
for (row in 0 until rowsLeft) {
for (col in 0 until columnsLeft) {
matrixLeft.set(row, col, random.nextInt(max - min + 1) + min)
}
}
for (row in 0 until rowsRight) {
for (col in 0 until columnsRight) {
matrixRight.set(row, col, random.nextInt(max - min + 1) + min)
}
}
for (row in 0 until rowsLeft) {
for (col in 0 until columnsRight) {
matrixProduct.set(row, col, "")
}
}
}
fun clearListeners()
}<file_sep>package org.ajm.laforkids
import com.badlogic.gdx.ApplicationAdapter
class Adapter : ApplicationAdapter {
var main: Main? = null
constructor() {
}
override fun create() {
main = Main()
}
override fun resize(width: Int, height: Int) {
main!!.resize()
}
override fun render() {
main!!.render()
}
override fun dispose() {
main!!.dispose()
}
}
<file_sep>package org.ajm.laforkids.actors
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.Touchable
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.utils.Align
/**
* Creates appropriate visualizer for given multiplication table.
*/
class VisualizerFactory {
/**
* Creates appropriate visualizer for given multiplication table.
*/
fun create(skin: Skin, multiplicationTable: MultiplicationTable): Actor {
val left = multiplicationTable.matrixLeft
val leftEntries = left.matrixColumns * left.matrixRows
val right = multiplicationTable.matrixRight
val rightEntries = right.matrixColumns * right.matrixRows
val product = multiplicationTable.matrixProduct
val productEntries = product.matrixColumns * product.matrixRows
if (productEntries == 2 && (leftEntries == 2 || rightEntries == 2))
return Visualizer2D(skin, multiplicationTable)
// default is just a label
val label = Label("AB=C", skin)
label.touchable = Touchable.disabled
label.setAlignment(Align.center)
return label
}
}<file_sep>package org.ajm.laforkids.desktop
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.backends.lwjgl.LwjglApplication
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import org.ajm.laforkids.Adapter
import org.ajm.laforkids.Main
import org.ajm.laforkids.desktop.tests.GameLogicTest
import org.ajm.laforkids.desktop.tests.MatrixTest
import org.ajm.laforkids.desktop.tests.MultiplicationTableTest
import org.ajm.laforkids.desktop.tests.SettingsTest
import org.junit.runner.Description
import org.junit.runner.JUnitCore
import org.junit.runner.notification.Failure
import org.junit.runner.notification.RunListener
import java.util.*
object DesktopLauncher {
var skin: Skin? = null
val testClasses: com.badlogic.gdx.utils.Array<Class<*>> = com.badlogic.gdx.utils.Array<Class<*>>()
init {
testClasses.add(SettingsTest::class.java)
testClasses.add(MatrixTest::class.java)
testClasses.add(MultiplicationTableTest::class.java)
testClasses.add(GameLogicTest::class.java)
}
fun allTests(main: Main) {
skin = main.skin
val core = JUnitCore()
core.addListener(object : RunListener() {
override fun testFinished(description: Description?) {
println(description!!.className + ": " + description.methodName)
}
})
val failures = ArrayList<Failure>()
var total = 0
for (klass in testClasses) {
val results = core.run(klass)
failures.addAll(results.failures)
total += results.runCount
}
println(total.toString() + " tests have been run.\n" + failures.size.toString() + " tests failed:")
for (failure in failures) {
println(failure.message)
println(failure.trace)
}
}
@JvmStatic fun main(arg: Array<String>) {
//TexturePacker.process("gdx-skins-master\\kenney-pixel\\custom-raw",
// "gdx-skins-master\\kenney-pixel\\custom-skin", "skin");
val config = LwjglApplicationConfiguration()
val adapter = Adapter()
LwjglApplication(adapter, config)
Gdx.app.postRunnable({
allTests(adapter.main!!)
})
}
}
<file_sep>package org.ajm.laforkids.actors
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import org.ajm.laforkids.actors.ColoredMultiplicationTable
import org.ajm.laforkids.actors.VisualizerFactory
import org.ajm.laforkids.actors.IMultiplicationTable
/**
* Also displays some additional information in the free top left space.
*/
class VisualizedMultiplicationTable : ColoredMultiplicationTable {
/**
* RowsRight is always the same as ColumnsLeft
*
* @param skin contains some custom graphics, also needed for labels
* @param rowsLeft the number of rows in the left matrix A
* @param columnsLeft the number of columns in the left matrix A, the same as the number of rows in the right matrix, B
* @param columnsRight the number of columns in the right matrix B
* @param answerAlternatives the number of answer buttons to choose from
*/
constructor(skin: Skin, rowsLeft: Int, columnsLeft: Int, columnsRight: Int, answerAlternatives: Int)
: super(skin, rowsLeft, columnsLeft, columnsRight, answerAlternatives) {
}
override fun prepareTopLeftActor(): Actor {
val actor = VisualizerFactory().create(skin, this)
return actor
}
override fun init(copyFrom: IMultiplicationTable) {
super<ColoredMultiplicationTable>.init(copyFrom)
notifyChangeListeners()
}
override fun init(min: Int, max: Int) {
super<ColoredMultiplicationTable>.init(min, max)
notifyChangeListeners()
}
}<file_sep>package org.ajm.laforkids.actors
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.Interpolation
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import org.ajm.laforkids.actors.MultiplicationTable
import org.ajm.laforkids.actors.IColoredMultiplicationTable
/**
* Contains 3 matrices that are set up to visualize a matrix multiplication.
* Also contains a vector with answer alternatives.
* Also draws some colored rectangles for helping the player compute.
*/
open class ColoredMultiplicationTable : IColoredMultiplicationTable, MultiplicationTable {
// settings, all can be changed
var interpolationMethod: Interpolation = Interpolation.pow3Out
var selectionColor: Color = Color.FOREST
override var highlight = true
var interpolationTime = 0.5f
set(value) {
if (value <= 0) throw IllegalArgumentException()
field = value
}
override var highlightRow = 0
set(value) {
if (value < 0) throw IllegalArgumentException()
if (value >= matrixLeft.rows) throw IllegalArgumentException()
field = value
beginAnimation()
}
override var highlightCol = 0
set(value) {
if (value < 0) throw IllegalArgumentException()
if (value >= matrixRight.columns) throw IllegalArgumentException()
field = value
beginAnimation()
}
var outlineThickness = 5f
set(value) {
if (value < 0) throw IllegalArgumentException()
field = value
matrixLeft.outlineThickness = outlineThickness
matrixProduct.outlineThickness = outlineThickness
matrixRight.outlineThickness = outlineThickness
}
// stuff for drawing the helping rectangles
private var doneAnimating = false
private var beganAnimation = System.currentTimeMillis()
private val dot: TextureRegion
private val productRectangle = Rectangle(Gdx.graphics.width.toFloat(),0f,0f,0f)
private val leftRectangle = Rectangle()
private val rightRectangle = Rectangle(Gdx.graphics.width.toFloat(),Gdx.graphics.height.toFloat(),0f,0f)
/**
* RowsRight is always the same as ColumnsLeft
*
* @param skin contains some custom graphics, also needed for labels
* @param rowsLeft the number of rows in the left matrix A
* @param columnsLeft the number of columns in the left matrix A, the same as the number of rows in the right matrix, B
* @param columnsRight the number of columns in the right matrix B
* @param answerAlternatives the number of answer buttons to choose from
*/
constructor(skin: Skin, rowsLeft: Int, columnsLeft: Int, columnsRight: Int, answerAlternatives: Int)
: super(skin, rowsLeft, columnsLeft, columnsRight, answerAlternatives) {
// dot is just a pixel used to draw rectangles
dot = skin.getRegion("dot")
}
/**
* Draw all the matrices and also, if enabled, some rectangles for helping the player.
*/
override fun draw(batch: Batch?, parentAlpha: Float) {
super.draw(batch, parentAlpha)
if (highlight) {
batch!!.color = selectionColor
animate(batch)
}
}
/**
* Start the animation that moves the helping rectangles
* to their correct position.
*/
private fun beginAnimation() {
doneAnimating = false
beganAnimation = System.currentTimeMillis()
}
/**
* Move and draw help rectangles.
*/
private fun animate(batch: Batch) {
// determine how far the animation is
var linearInterp = (System.currentTimeMillis() - beganAnimation) / 1000f
linearInterp = MathUtils.clamp(linearInterp / interpolationTime, 0f, 1f)
val nonLinearInterp = interpolationMethod.apply(linearInterp)
val interp = nonLinearInterp
// request render if not done animating
if (linearInterp < 1) Gdx.graphics.requestRendering()
val pad = matrixInsidePad * 2
val thickness = outlineThickness
// animate product rectangle
var actor = matrixProduct.getCell(highlightRow, highlightCol)!!.actor
var pos = actor.localToStageCoordinates(Vector2(0f, 0f))
var x = productRectangle.x * (1f - interp) + floor(pos.x) * interp
var y = productRectangle.y * (1f - interp) + floor(pos.y) * interp
var width = productRectangle.width * (1f - interp) + floor(actor.width) * interp
var height = productRectangle.height * (1f - interp) + floor(actor.height) * interp
outlineRectangle(batch, x, y, width, height, thickness)
if (MathUtils.isEqual(interp, 1f)) {
productRectangle.set(x, y, width, height)
}
// animate left rectangle
actor = matrixLeft.getCell(highlightRow, 0)!!.actor
pos = actor.localToStageCoordinates(Vector2(0f, 0f))
x = leftRectangle.x * (1f - interp) + floor(pos.x) * interp
y = leftRectangle.y * (1f - interp) + floor(pos.y) * interp
width = (leftRectangle.width + pad) * (1f - interp) + floor(matrixLeft.width) * interp
height = leftRectangle.height * (1f - interp) + floor(actor.height) * interp
outlineRectangle(batch, x, y, width - pad, height, thickness)
if (MathUtils.isEqual(interp, 1f)) {
leftRectangle.set(x, y, width - pad, height)
}
// animate right rectangle
actor = matrixRight.getCell(rowsRight - 1, highlightCol)!!.actor
pos = actor.localToStageCoordinates(Vector2(0f, 0f))
x = rightRectangle.x * (1f - interp) + floor(pos.x) * interp
y = rightRectangle.y * (1f - interp) + floor(pos.y) * interp
width = rightRectangle.width * (1f - interp) + floor(actor.width) * interp
height = (rightRectangle.height + pad) * (1f - interp) + floor(matrixRight.height) * interp
outlineRectangle(batch, x, y, width, height - pad, thickness)
if (MathUtils.isEqual(interp, 1f)) {
rightRectangle.set(x, y, width, height - pad)
}
if (MathUtils.isEqual(interp, 1f)) {
doneAnimating = true
}
}
/**
* Draw a rectangle.
*
* @param x lower left
* @param y lower left
* @param width width of rect
* @param height height of rect
* @param outlineThickness thickness of outline
*
*/
private fun outlineRectangle(batch: Batch, x: Float, y: Float, width: Float, height: Float, outlineThickness: Float) {
val _y = floor(y)
val _x = floor(x)
val _height = floor(height)
val _width = floor(width)
val _outlineThickness = floor(outlineThickness)
batch.draw(dot, _x, _y, _outlineThickness, _height)
batch.draw(dot, _x, _y, _width, _outlineThickness)
batch.draw(dot, _x, _y + _height - _outlineThickness, _width, _outlineThickness)
batch.draw(dot, _x + _width - _outlineThickness, _y, _outlineThickness, _height)
}
private fun floor(a: Float) = Math.floor(a.toDouble()).toFloat()
}<file_sep>package org.ajm.laforkids.desktop.tests
import org.ajm.laforkids.Settings
import org.junit.Test
import org.junit.Assert.*
import java.util.*
/**
* Tests for [Settings].
*/
class SettingsTest {
val random = Random()
@Test
fun rejectImpossibleValues() {
for (i in 0 until 100) {
// test that illegal values cause exceptions
// also ensure that illegal values can not be saved in the gdx preferences
val k = random.nextInt(10) + 1
var settings = Settings("Test Tag")
assertEquals(0, settings.dataInvariant().size) // check that everything is ok
val minValue = random.nextInt(k * 2) - k
val maxValue = minValue - random.nextInt(k) - 1
settings.minValue = minValue
settings.maxValue = maxValue
assertNotEquals(0, settings.dataInvariant().size) // check that the illegal values are detected
assertFalse(settings.saveSettingsForever()) // check that the illegal values can not be saved
settings = Settings("Test Tag")
assertEquals(0, settings.dataInvariant().size) // check that the previous illegal values are gone
val minRowsLeft = random.nextInt(k) + 1
val maxRowsLeft = minRowsLeft - random.nextInt(k) - 1
settings.minRowsLeft = minRowsLeft
settings.maxRowsLeft = maxRowsLeft
assertNotEquals(0, settings.dataInvariant().size) // check that the illegal values are detected
assertFalse(settings.saveSettingsForever()) // check that the illegal values can not be saved
settings = Settings("Test Tag")
assertEquals(0, settings.dataInvariant().size) // check that the previous illegal values are gone
val minColumnsLeft = random.nextInt(k) + 1
val maxColumnsLeft = minColumnsLeft - random.nextInt(k) - 1
settings.minColumnsLeft = minColumnsLeft
settings.maxColumnsLeft = maxColumnsLeft
assertNotEquals(0, settings.dataInvariant().size) // check that the illegal values are detected
assertFalse(settings.saveSettingsForever()) // check that the illegal values can not be saved
settings = Settings("Test Tag")
assertEquals(0, settings.dataInvariant().size) // check that the previous illegal values are gone
val minColumnsRight = random.nextInt(k) + 1
val maxColumnsRight = minColumnsRight - random.nextInt(k) - 1
settings.minColumnsRight = minColumnsRight
settings.maxColumnsRight = maxColumnsRight
assertNotEquals(0, settings.dataInvariant().size) // check that the illegal values are detected
assertFalse(settings.saveSettingsForever()) // check that the illegal values can not be saved
settings = Settings("Test Tag")
assertEquals(0, settings.dataInvariant().size) // check that the previous illegal values are gone
val answerAlternatives = -random.nextInt(k)
settings.answerAlternatives = answerAlternatives
assertNotEquals(0, settings.dataInvariant().size) // check that the illegal values are detected
assertFalse(settings.saveSettingsForever()) // check that the illegal values can not be saved
settings = Settings("Test Tag")
assertEquals(0, settings.dataInvariant().size) // check that the previous illegal values are gone
val answerMaxError = -random.nextInt(k) - 1
settings.answerMaxError = answerMaxError
assertNotEquals(0, settings.dataInvariant().size) // check that the illegal values are detected
assertFalse(settings.saveSettingsForever()) // check that the illegal values can not be saved
}
}
@Test
fun setGetPersist() {
for (i in 0 until 10) {
// test set and get with values that should be legal
var settings = Settings("Test Tag")
val k = random.nextInt(500) + 1
val minValue = random.nextInt(k * 2) - k
val maxValue = minValue + random.nextInt(k)
settings.minValue = minValue
settings.maxValue = maxValue
assertEquals(minValue, settings.minValue)
assertEquals(maxValue, settings.maxValue)
val minRowsLeft = random.nextInt(k) + 1
val maxRowsLeft = minRowsLeft + random.nextInt(k)
settings.minRowsLeft = minRowsLeft
settings.maxRowsLeft = maxRowsLeft
assertEquals(minRowsLeft, settings.minRowsLeft)
assertEquals(maxRowsLeft, settings.maxRowsLeft)
val minColumnsLeft = random.nextInt(k) + 1
val maxColumnsLeft = minColumnsLeft + random.nextInt(k)
settings.minColumnsLeft = minColumnsLeft
settings.maxColumnsLeft = maxColumnsLeft
assertEquals(minColumnsLeft, settings.minColumnsLeft)
assertEquals(maxColumnsLeft, settings.maxColumnsLeft)
val minColumnsRight = random.nextInt(k) + 1
val maxColumnsRight = minColumnsRight + random.nextInt(k)
settings.minColumnsRight = minColumnsRight
settings.maxColumnsRight = maxColumnsRight
assertEquals(minColumnsRight, settings.minColumnsRight)
assertEquals(maxColumnsRight, settings.maxColumnsRight)
val answerAlternatives = random.nextInt(k) + 1
settings.answerAlternatives = answerAlternatives
assertEquals(answerAlternatives, settings.answerAlternatives)
val answerMaxError = random.nextInt(k)
settings.answerMaxError = answerMaxError
assertEquals(answerMaxError, settings.answerMaxError)
settings.dataInvariant()
settings.saveSettingsForever()
// test that the values persist in the gdx preferences
settings = Settings("Test Tag")
assertEquals(minValue, settings.minValue)
assertEquals(maxValue, settings.maxValue)
assertEquals(minRowsLeft, settings.minRowsLeft)
assertEquals(maxRowsLeft, settings.maxRowsLeft)
assertEquals(minColumnsLeft, settings.minColumnsLeft)
assertEquals(maxColumnsLeft, settings.maxColumnsLeft)
assertEquals(minColumnsRight, settings.minColumnsRight)
assertEquals(maxColumnsRight, settings.maxColumnsRight)
assertEquals(answerAlternatives, settings.answerAlternatives)
assertEquals(answerMaxError, settings.answerMaxError)
}
}
}<file_sep>package org.ajm.laforkids.actors
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.GlyphLayout
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.Touchable
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import org.ajm.laforkids.actors.MultiplicationTable
/**
* If one of the matrices on the left side, and the matrix on the right side,
* has two entries(are 2d vectors) then the multiplication can be visualized by this class.
*/
class Visualizer2D : Actor {
private var beforeX = 0
private var beforeY = 0
private var beforeName = "B"
private var afterX = 0
private var afterY = 0
private var afterName = "C"
private var afterXStringWidth = 0f
private var afterYStringWidth = 0f
private var drawAfterX = false
private var drawAfterY = false
val axisColor = Color(Color.GRAY)
val beforeColor = Color(Color.RED)
val afterColor = Color(Color.BLUE)
/** Used for drawing stuff */
private val dot: TextureRegion
private val multiplicationTable: MultiplicationTable
private val font: BitmapFont
constructor(skin: Skin, multiplicationTable: MultiplicationTable) {
touchable = Touchable.disabled
font = skin.getFont("default")
val left = multiplicationTable.matrixLeft
val leftEntries = left.matrixColumns * left.matrixRows
val right = multiplicationTable.matrixRight
val rightEntries = right.matrixColumns * right.matrixRows
val product = multiplicationTable.matrixProduct
val productEntries = product.matrixColumns * product.matrixRows
val ok = productEntries == 2 && (leftEntries == 2 || rightEntries == 2)
if (!ok) throw IllegalArgumentException()
dot = skin.getRegion("dot")
this.multiplicationTable = multiplicationTable
multiplicationTable.changeListeners.add(Runnable {
update()
})
}
/**
* Determine the vectors to be drawn.
*/
fun update() {
val left = multiplicationTable.matrixLeft
val right = multiplicationTable.matrixRight
val product = multiplicationTable.matrixProduct
try {
if (left.matrixRows == 1 && left.matrixColumns == 2) {
beforeX = left.get(0, 0).toInt()
beforeY = left.get(0, 1).toInt()
beforeName = left.backgroundText
} else if (left.matrixRows == 2 && left.matrixColumns == 1) {
beforeX = left.get(0, 0).toInt()
beforeY = left.get(1, 0).toInt()
beforeName = left.backgroundText
} else if (right.matrixRows == 1 && right.matrixColumns == 2) {
beforeX = right.get(0, 0).toInt()
beforeY = right.get(0, 1).toInt()
beforeName = right.backgroundText
} else if (right.matrixRows == 2 && right.matrixColumns == 1) {
beforeX = right.get(0, 0).toInt()
beforeY = right.get(1, 0).toInt()
beforeName = right.backgroundText
} else throw IllegalStateException()
if (product.matrixRows == 1 && product.matrixColumns == 2) {
afterX = computeProductEntry(0, 0)
afterY = computeProductEntry(0, 1)
afterName = product.backgroundText
} else if (product.matrixRows == 2 && product.matrixColumns == 1) {
afterX = computeProductEntry(0, 0)
afterY = computeProductEntry(1, 0)
afterName = product.backgroundText
} else throw IllegalStateException()
} catch (e: NumberFormatException) {
// may happen text is just "-" (minus)
}
val layout = GlyphLayout()
layout.setText(font,afterX.toString())
afterXStringWidth = layout.width
layout.setText(font,afterY.toString())
afterYStringWidth = layout.width
drawAfterX = !product.get(0).isEmpty()
drawAfterY = !product.get(1).isEmpty()
}
fun computeProductEntry(row: Int, col: Int): Int {
// convolve i'th left row with j'th right col
var correctAnswer = 0
for (k in 0 until multiplicationTable.columnsLeft) {
val a = multiplicationTable.matrixLeft.get(row, k).toInt()
val b = multiplicationTable.matrixRight.get(k, col).toInt()
correctAnswer += a * b
}
return correctAnswer
}
override fun draw(batch: Batch?, parentAlpha: Float) {
batch as Batch
val lineThickness = (2f + 6f * Math.min(width, height) / (1000f)).toInt().toFloat()
val pos = localToStageCoordinates(Vector2())
val finalPos = Vector2()
val beforeScale = font.data.scaleX
font.data.setScale(0.75f)
// draw axes
batch.color = axisColor
batch.draw(dot, pos.x, pos.y + height / 2f - lineThickness / 2f, width, lineThickness)
batch.draw(dot, pos.x + width / 2f - lineThickness / 2f, pos.y, lineThickness, height)
// determine scale
val dim: Float = Math.min(width, height) / 2f
var scale = Float.MAX_VALUE
if (beforeX != 0) scale = Math.min(Math.abs(dim / beforeX), scale)
if (beforeY != 0) scale = Math.min(Math.abs(dim / beforeY), scale)
if (afterX != 0) scale = Math.min(Math.abs(dim / afterX), scale)
if (afterY != 0) scale = Math.min(Math.abs(dim / afterY), scale)
scale *= 0.9f
// mark the axes
if (drawAfterX) {
batch.color = axisColor
font.color = axisColor
finalPos.set(pos.x + width / 2f + afterX * scale, pos.y + height / 2f)
cross(batch, finalPos.x, finalPos.y, lineThickness)
font.draw(batch, afterX.toString(), finalPos.x-afterXStringWidth/2f, finalPos.y-font.capHeight/2)
}
if (drawAfterY) {
batch.color = axisColor
font.color = axisColor
finalPos.set(pos.x + width / 2f, pos.y + height / 2f + afterY * scale)
cross(batch, finalPos.x, finalPos.y, lineThickness)
font.draw(batch, afterY.toString(), finalPos.x+font.spaceWidth, finalPos.y+font.capHeight/2)
}
// draw crosses representing the matrices(vectors) with 2 entries
batch.color = beforeColor
font.color = beforeColor
finalPos.set(pos.x + width / 2f + beforeX * scale, pos.y + height / 2f + beforeY * scale)
cross(batch, finalPos.x, finalPos.y, lineThickness)
font.draw(batch, beforeName, finalPos.x+font.spaceWidth, finalPos.y)
if (drawAfterX && drawAfterY) {
batch.color = afterColor
font.color = afterColor
finalPos.set(pos.x + width / 2f + afterX * scale, pos.y + height / 2f + afterY * scale)
cross(batch, finalPos.x, finalPos.y, lineThickness)
font.draw(batch, afterName, finalPos.x+font.spaceWidth, finalPos.y)
}
font.data.setScale(beforeScale)
}
private fun cross(batch: Batch, x: Float, y: Float, thickness: Float) {
batch.draw(dot, x - thickness * 3f, y - thickness / 2f, thickness * 6f, thickness)
batch.draw(dot, x - thickness / 2f, y - thickness * 3f, thickness, thickness * 6f)
}
}<file_sep>package org.ajm.laforkids.desktop.tests
import org.ajm.laforkids.actors.ColoredMultiplicationTable
import org.ajm.laforkids.GameLogic
import org.ajm.laforkids.desktop.DesktopLauncher
import org.junit.Assert
import org.junit.Test
import java.util.*
class GameLogicTest {
private val random = Random()
@Test
fun run() {
for (i in 0 until 10) {
val settings = SettingsFactory("Test Tag 53").generateTestSettings()
val gameLogic = GameLogic(settings)
gameLogic.newGame()
val multiplicationTable = ColoredMultiplicationTable(DesktopLauncher.skin!!,
gameLogic.rowsLeft, gameLogic.columnsLeft, gameLogic.columnsRight, gameLogic.answerAlternatives)
multiplicationTable.init(settings.minValue, settings.maxValue)
gameLogic.init(multiplicationTable)
for (j in 0 until gameLogic.maxProgress()) {
Assert.assertFalse(gameLogic.isComplete())
gameLogic.updateAnswerAlternatives()
gameLogic.progress(gameLogic.getCorrectAnswer())
}
assertExceptionThrown {
gameLogic.updateAnswerAlternatives()
}
Assert.assertTrue(gameLogic.isComplete())
}
}
}<file_sep>package org.ajm.laforkids.desktop.tests
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import org.ajm.laforkids.actors.ColoredMultiplicationTable
import org.ajm.laforkids.actors.IMultiplicationTable
import org.ajm.laforkids.actors.MultiplicationTable
import java.util.*
/**
* This factory facilitates testing of [MultiplicationTable] and [ColoredMultiplicationTable] with the same
* code.
*/
class MultiplicationTableFactory<T : IMultiplicationTable>(klass: Class<T>) {
val a = klass.isAssignableFrom(ColoredMultiplicationTable::class.java)
val b = klass.isAssignableFrom(MultiplicationTable::class.java)
/**
* Create a [IMultiplicationTable] of class T with random specifications.
*/
fun create(skin: Skin): IMultiplicationTable {
val random = Random()
if (b) {
return MultiplicationTable(skin, random.nextInt(100) + 1, random.nextInt(100) + 1, random.nextInt(100) + 1, random.nextInt(100) + 1)
} else if (a) {
return ColoredMultiplicationTable(skin, random.nextInt(100) + 1, random.nextInt(100) + 1, random.nextInt(100) + 1, random.nextInt(100) + 1)
}
throw IllegalArgumentException()
}
/**
* Create a [IMultiplicationTable] of class T with given specifications.
*/
fun create(skin: Skin, rowsLeft: Int, columnsLeft: Int, columnsRight: Int, answerAlternatives: Int): IMultiplicationTable {
if (b) {
return MultiplicationTable(skin, rowsLeft, columnsLeft, columnsRight, answerAlternatives)
} else if (a) {
return ColoredMultiplicationTable(skin, rowsLeft, columnsLeft, columnsRight, answerAlternatives)
}
throw IllegalArgumentException()
}
}<file_sep>package org.ajm.laforkids.desktop.tests
import org.ajm.laforkids.actors.ColoredMultiplicationTable
import org.ajm.laforkids.actors.MultiplicationTable
import org.ajm.laforkids.desktop.DesktopLauncher
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.util.*
/**
* Test the properties of [MultiplicationTable] and [ColoredMultiplicationTable] defined in [IMultiplicationTable].
* Each test function is run two times, once where the factory generates [MultiplicationTable],
* and once where the factory generates [ColoredMultiplicationTable].
*/
@RunWith(Parameterized::class)
class MultiplicationTableTest(val factory: MultiplicationTableFactory<*>) {
val random = Random()
/**
* Gives the test functions access to a [MultiplicationTableFactory].
*/
companion object {
@JvmStatic
@Parameterized.Parameters
fun data(): Collection<Array<Any>> {
val factory1 = MultiplicationTableFactory<MultiplicationTable>(MultiplicationTable::class.java)
val factory2 = MultiplicationTableFactory<ColoredMultiplicationTable>(ColoredMultiplicationTable::class.java)
return listOf(arrayOf(factory1 as Any), arrayOf(factory2 as Any))
}
}
/**
* Test that the variables reject values that make no sense.
*/
@Test
fun illegalArguments1() {
val table = factory.create(DesktopLauncher.skin!!)
assertExceptionThrown({
table.entryHeight = -(random.nextFloat() + 0.00001f) * 100f
})
assertExceptionThrown({
table.entryWidth = -(random.nextFloat() + 0.00001f) * 100f
})
assertExceptionThrown({
table.matrixInsidePad = -(random.nextFloat() + 0.00001f) * 100f
})
assertExceptionThrown({
table.matrixOutsidePad = -(random.nextFloat() + 0.00001f) * 100f
})
assertExceptionThrown({
table.matrixEntryPad = -(random.nextFloat() + 0.00001f) * 100f
})
}
/**
* Test that the constructor reject values that make no sense.
*/
@Test
fun illegalArguments2() {
val skin = DesktopLauncher.skin!!
for (i in 0 until 100) {
val rowsLeft = 50 - random.nextInt(100)
val columnsLeft = 50 - random.nextInt(100)
val columnsRight = 50 - random.nextInt(100)
val answerAlternatives = 50 - random.nextInt(100)
if (rowsLeft < 1 || columnsLeft < 1 || columnsRight < 1 || answerAlternatives < 1) {
assertExceptionThrown({
factory.create(skin, rowsLeft, columnsLeft, columnsRight, answerAlternatives)
})
}
}
}
/**
* Test that the copy function reject values that make no sense.
*/
@Test
fun illegalArguments3() {
val skin = DesktopLauncher.skin!!
// make two incompatible tables
var rowsLeft = random.nextInt(100) + 1
var columnsLeft = random.nextInt(100) + 1
var columnsRight = random.nextInt(100) + 1
var answerAlternatives = random.nextInt(100) + 1
val table1 = factory.create(skin, rowsLeft, columnsLeft, columnsRight, answerAlternatives)
while (rowsLeft == table1.rowsLeft && columnsLeft == table1.columnsLeft &&
columnsRight == table1.columnsRight) {
rowsLeft = random.nextInt(100) + 1
columnsLeft = random.nextInt(100) + 1
columnsRight = random.nextInt(100) + 1
answerAlternatives = random.nextInt(100) + 1
}
val table2 = factory.create(skin, rowsLeft, columnsLeft, columnsRight, answerAlternatives)
assertExceptionThrown({ table1.init(table2) })
}
@Test
fun setGet() {
val skin = DesktopLauncher.skin!!
val rowsLeft = random.nextInt(100) + 1
val columnsLeft = random.nextInt(100) + 1
val columnsRight = random.nextInt(100) + 1
val answerAlternatives = random.nextInt(100) + 1
val multiplicationTable = factory.create(skin,
rowsLeft, columnsLeft, columnsRight, answerAlternatives)
// test constructor
Assert.assertEquals(rowsLeft, multiplicationTable.rowsLeft)
Assert.assertEquals(columnsLeft, multiplicationTable.columnsLeft)
Assert.assertEquals(columnsRight, multiplicationTable.columnsRight)
Assert.assertEquals(answerAlternatives, multiplicationTable.answerAlternatives)
// test set get
val entryHeight = random.nextFloat() * 100f
val entryWidth = random.nextFloat() * 100f
val matrixInsidePad = random.nextFloat() * 100f
val matrixOutsidePad = random.nextFloat() * 100f
val matrixEntryPad = random.nextFloat() * 100f
multiplicationTable.entryHeight = entryHeight
multiplicationTable.entryWidth = entryWidth
multiplicationTable.matrixInsidePad = matrixInsidePad
multiplicationTable.matrixOutsidePad = matrixOutsidePad
multiplicationTable.matrixEntryPad = matrixEntryPad
Assert.assertEquals(entryHeight, multiplicationTable.entryHeight)
Assert.assertEquals(entryWidth, multiplicationTable.entryWidth)
Assert.assertEquals(matrixInsidePad, multiplicationTable.matrixInsidePad)
Assert.assertEquals(matrixOutsidePad, multiplicationTable.matrixOutsidePad)
Assert.assertEquals(matrixEntryPad, multiplicationTable.matrixEntryPad)
}
@Test
fun copyEntries() {
val skin = DesktopLauncher.skin!!
// make two compatible tables
val rowsLeft = random.nextInt(100) + 1
val columnsLeft = random.nextInt(100) + 1
val rowsRight = columnsLeft
val columnsRight = random.nextInt(100) + 1
val answerAlternatives = random.nextInt(100) + 1
val table1 = factory.create(skin,
rowsLeft, columnsLeft, columnsRight, answerAlternatives)
val table2 = factory.create(skin,
rowsLeft, columnsLeft, columnsRight, answerAlternatives)
// test the copy functionality
table1.init(table2)
for (row in 0 until rowsLeft) {
for (col in 0 until columnsLeft) {
val actual = table1.matrixLeft.get(row, col)
val expected = table2.matrixLeft.get(row, col)
Assert.assertEquals(expected, actual)
}
}
for (row in 0 until rowsLeft) {
for (col in 0 until columnsRight) {
val actual = table1.matrixProduct.get(row, col)
val expected = table2.matrixProduct.get(row, col)
Assert.assertEquals(expected, actual)
}
}
for (row in 0 until rowsRight) {
for (col in 0 until columnsRight) {
val actual = table1.matrixRight.get(row, col)
val expected = table2.matrixRight.get(row, col)
Assert.assertEquals(expected, actual)
}
}
}
}<file_sep>package org.ajm.laforkids.actors
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.ui.*
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.utils.Align
import com.badlogic.gdx.utils.Array
import org.ajm.laforkids.Main
import org.ajm.laforkids.animate
import org.ajm.laforkids.getAllChildren
/**
* Interface for adjusting the settings defined in [Settings].
*/
class SettingsInterface : ScrollPane {
/** Stuff to do when ok is clicked. */
var onSaved = Runnable { }
/** Stuff to do when cancel is clicked. */
var onCancel = Runnable { }
/**
* Interface for adjusting the settings defined in GameLogic.
*/
constructor(main: Main) : super(Table()) {
val s = main.settings
val skin = main.skin
// filter for text input
val digitInput = TextField.TextFieldFilter { textField, c -> c.isDigit() || c.equals('-') }
// create the text fields for input
val minValue = TextField(s.minValue.toString(), skin)
minValue.textFieldFilter = digitInput
val maxValue = TextField(s.maxValue.toString(), skin)
maxValue.textFieldFilter = digitInput
val minRowsLeft = TextField(s.minRowsLeft.toString(), skin)
minRowsLeft.textFieldFilter = digitInput
val maxRowsLeft = TextField(s.maxRowsLeft.toString(), skin)
maxRowsLeft.textFieldFilter = digitInput
val minColumnsLeft = TextField(s.minColumnsLeft.toString(), skin)
minColumnsLeft.textFieldFilter = digitInput
val maxColumnsLeft = TextField(s.maxColumnsLeft.toString(), skin)
maxColumnsLeft.textFieldFilter = digitInput
val minColumnsRight = TextField(s.minColumnsRight.toString(), skin)
minColumnsRight.textFieldFilter = digitInput
val maxColumnsRight = TextField(s.maxColumnsRight.toString(), skin)
maxColumnsRight.textFieldFilter = digitInput
val answerAlternatives = TextField(s.answerAlternatives.toString(), skin)
answerAlternatives.textFieldFilter = digitInput
val answerMaxError = TextField(s.answerMaxError.toString(), skin)
answerMaxError.textFieldFilter = digitInput
// create the labels
val labelValue = Label("Value", skin)
val labelRowsLeft = Label("Rows left", skin)
val labelColumnsLeft = Label("Columns left", skin)
val labelColumnsRight = Label("Columns right", skin)
val labelAnswerAlternatives = Label("Answer alternatives", skin)
val labelAnswerMaxError = Label("Alternative error", skin)
// put labels and text fields in a table
val pad = 3f
val tableSettings = Table()
var width = Math.min(Gdx.graphics.width / 3f, labelRowsLeft.width)
var aux = Table()
aux.add(Label("Min", skin)).width(width).pad(pad)
aux.add(Label("Max", skin)).width(width).pad(pad)
tableSettings.add(aux).padBottom(pad * 5).align(Align.left).row()
tableSettings.add(labelValue).pad(pad).align(Align.left).row()
aux = Table()
aux.add(minValue).width(width).pad(pad)
aux.add(maxValue).width(width).pad(pad)
tableSettings.add(aux).padBottom(pad * 5).align(Align.left).row()
tableSettings.add(labelRowsLeft).pad(pad).align(Align.left).row()
aux = Table()
aux.add(minRowsLeft).width(width).pad(pad)
aux.add(maxRowsLeft).width(width).pad(pad)
tableSettings.add(aux).padBottom(pad * 5).align(Align.left).row()
tableSettings.add(labelColumnsLeft).pad(pad).align(Align.left).row()
aux = Table()
aux.add(minColumnsLeft).width(width).pad(pad)
aux.add(maxColumnsLeft).width(width).pad(pad)
tableSettings.add(aux).padBottom(pad * 5).align(Align.left).row()
tableSettings.add(labelColumnsRight).pad(pad).align(Align.left).row()
aux = Table()
aux.add(minColumnsRight).width(width).pad(pad)
aux.add(maxColumnsRight).width(width).pad(pad)
tableSettings.add(aux).padBottom(pad * 5).align(Align.left).row()
tableSettings.add(labelAnswerAlternatives).pad(pad).align(Align.left).row()
aux = Table()
aux.add(answerAlternatives).width(width).pad(pad)
tableSettings.add(aux).padBottom(pad * 5).align(Align.left).row()
tableSettings.add(labelAnswerMaxError).pad(pad).align(Align.left).row()
aux = Table()
aux.add(answerMaxError).width(width).pad(pad)
tableSettings.add(aux).padBottom(pad * 5).align(Align.left).row()
// replace onscreen keyboard
for (actor in getAllChildren(tableSettings)) {
if (actor !is TextField) continue
actor.onscreenKeyboard = TextField.OnscreenKeyboard { }
actor.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
actor.selectAll()
val keypad = main.keypad
Gdx.app.postRunnable { keypad.scrollIn(main.stage) }
// scroll down if needed
val scrollPane = this@SettingsInterface
val pos = actor.localToAscendantCoordinates(tableSettings.parent, Vector2())
scrollPane.scrollTo(pos.x, pos.y - keypad.height, 1f, 1f)
// listener for removing the keypad
stage.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
val hitActor = main.stage.hit(x, y, true)
if (hitActor == actor) return
if (keypad.contains(x, y)) return
if (hitActor is TextField) return
main.stage.removeListener(this)
keypad.scrollOut()
actor.clearSelection()
}
})
}
})
}
// prepare ok and cancel buttons
val ok = TextButton("Save", skin)
ok.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
// try to save settings
s.minValue = minValue.text.toInt()
s.maxValue = maxValue.text.toInt()
s.minRowsLeft = minRowsLeft.text.toInt()
s.maxRowsLeft = maxRowsLeft.text.toInt()
s.minColumnsLeft = minColumnsLeft.text.toInt()
s.maxColumnsLeft = maxColumnsLeft.text.toInt()
s.minColumnsRight = minColumnsRight.text.toInt()
s.maxColumnsRight = maxColumnsRight.text.toInt()
s.answerAlternatives = answerAlternatives.text.toInt()
s.answerMaxError = answerMaxError.text.toInt()
val errors = s.dataInvariant()
if (errors.size == 0) {
// all is ok
s.saveSettingsForever()
onSaved.run()
} else {
// mark the illegal values
labelValue.setText("Value" + if (errors.contains(0, false)) "***" else "")
labelRowsLeft.setText("Rows left" + if (errors.contains(1, false)) "***" else "")
labelColumnsLeft.setText("Columns left" + if (errors.contains(2, false)) "***" else "")
labelColumnsRight.setText("Columns right" + if (errors.contains(3, false)) "***" else "")
labelAnswerAlternatives.setText("Answer alternatives" + if (errors.contains(4, false)) "***" else "")
labelAnswerMaxError.setText("Alternative error" + if (errors.contains(5, false)) "***" else "")
}
}
})
val cancel = TextButton("Cancel", skin)
cancel.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
s.reload()
onCancel.run()
}
})
// ok and cancel button in their own table
val tableButtons = Table()
width = Math.max(width, cancel.width)
tableButtons.add(cancel).width(width).pad(width * 0.1f)
tableButtons.add(ok).width(width).pad(width * 0.1f)
// put it all in the main table
val table = children.first() as Table
table.add(tableSettings).row()
table.add(tableButtons)
table.padBottom(Gdx.graphics.width / 3f)
}
fun setFontColor(color: Color) {
for (actor in getAllChildren(this)) {
if (actor is Label)
actor.style.fontColor.set(color)
}
}
}<file_sep>package org.ajm.laforkids.desktop.tests
import org.junit.Assert
fun assertExceptionThrown(inlined: () -> Unit) {
var illegal = false
try {
inlined.invoke()
} catch(e: Exception) {
illegal = true
}
Assert.assertTrue(illegal)
}<file_sep>package org.ajm.laforkids.actors
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.math.Interpolation
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.utils.Align
/**
* Button that displays a menu when clicked.
*/
class Menu : Label {
val nextLabel: Label
val helpLabel: Label
val settingsLabel: Label
private var table = Table()
// settings
var interpolationTime = 1f
var interpolationMethod = Interpolation.linear
var menuBackgroundColor = Color(Color.GRAY)
/** Remove all listeners from the buttons(labels) in the dropdown menu.*/
fun clearMenuItemListeners() {
nextLabel.clearListeners()
helpLabel.clearListeners()
settingsLabel.clearListeners()
}
/** Hide the dropdown menu. Does not hide the button for the menu. */
fun hideMenu() {
table.remove()
}
/**
* Convenience function for setting the color of all the labels at once.
*/
fun setTextColor(color: Color) {
nextLabel.style.fontColor.set(color)
helpLabel.style.fontColor.set(color)
settingsLabel.style.fontColor.set(color)
}
constructor(stage: Stage, skin: Skin) : super("Menu", skin) {
nextLabel = Label("Next", skin)
nextLabel.setAlignment(Align.left)
helpLabel = Label("Help", skin)
helpLabel.setAlignment(Align.left)
settingsLabel = Label("Settings", skin)
settingsLabel.setAlignment(Align.left)
// add dropdown functionality
addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
if (stage.actors.contains(table, true)) return // already visible
stage.actors.removeValue(table, true)
// prepare the dropdown menu
table = Table()
table.background = skin.getDrawable("dot")
table.color.set(menuBackgroundColor)
// determine size
var width = nextLabel.prefWidth
width = Math.max(helpLabel.prefWidth, width)
width = Math.max(settingsLabel.prefWidth, width)
width *= 1.25f
val height = nextLabel.prefHeight * 1.25f
// add labels and finalize layout
table.add(nextLabel).height(height).width(width).row()
table.add(helpLabel).height(height).width(width).row()
table.add(settingsLabel).height(height).width(width).row()
table.pack()
stage.addActor(table)
// drop down gradually
fun animate() = { lerp: Float ->
val pos = localToStageCoordinates(Vector2())
table.setPosition(pos.x - table.width * (1 - lerp), pos.y - table.height)
}
org.ajm.laforkids.animate(animate(), interpolationMethod, interpolationTime)
// add functionality that hides the dropdown menu when player clicks somewhere else
stage.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
val pos = Vector2(0f, stage.height - table.height) // final position after animation
val rectangle = Rectangle(pos.x, pos.y, table.width, table.height)
val hit = rectangle.contains(x, y)
if (!hit)
hideMenu()
}
})
}
})
}
}<file_sep>package org.ajm.laforkids
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.ui.Cell
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane
import com.badlogic.gdx.scenes.scene2d.ui.TextField
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.utils.Align
import com.badlogic.gdx.utils.Array
import org.ajm.laforkids.actors.IColoredMultiplicationTable
import org.ajm.laforkids.actors.Keypad
import org.ajm.laforkids.actors.VisualizedMultiplicationTable
/**
* The progress of the game is implemented here: listeners are added to the different
* buttons and labels so that the game can progress.
*/
class GameIterator {
private var multiplicationTable: IColoredMultiplicationTable? = null
private val settings: Settings
var gameLogic: GameLogic
private var main: Main? = null
constructor(settings: Settings, gameLogic: GameLogic = GameLogic(settings)) {
this.settings = settings
this.gameLogic = gameLogic
}
/**
* [newGame] must be called before [init].
*
* 1. [newGame]
* 2. [init]
* 3. [progress]
* 4. [progress]
* 5. ...
* 6. [newGame]
* 7. [init]
* 8. ...
* */
fun newGame(rowsLeft: Int = gameLogic.getRandomLeftRowCount(),
columnsLeft: Int = gameLogic.getRandomLeftColumnCount(),
columnsRight: Int = gameLogic.getRandomRightColumnCount()) {
gameLogic.newGame(rowsLeft, columnsLeft, columnsRight)
}
/**
* @return whether the given answer was correct
*
* 1. [newGame]
* 2. [init]
* 3. [progress]
* 4. [progress]
* 5. ...
* 6. [newGame]
* 7. [init]
* 8. ...
*/
fun progress(answer: Int): Boolean {
val correctAnswer = gameLogic.progress(answer)
main!!.scoreLabel!!.score = gameLogic.score
return correctAnswer
}
/**
* Adds functionality to certain buttons. Prepares the entries of the matrices
* and prepares the answers. The size of the matrices must match the sizes
* determined by a previous [newGame] call.
*
* 1. [newGame]
* 2. [init]
* 3. [progress]
* 4. [progress]
* 5. ...
* 6. [newGame]
* 7. [init]
* 8. ...
*/
fun init(multiplicationTable: VisualizedMultiplicationTable, main: Main, newGame: Boolean) {
this.main = main
val old = this.multiplicationTable
this.multiplicationTable = multiplicationTable
gameLogic.init(multiplicationTable)
main.scoreLabel!!.score = gameLogic.score
// set the entries of left and right matrices
if (newGame) {
multiplicationTable.init(settings.minValue, settings.maxValue)
gameLogic.updateAnswerAlternatives()
} else {
multiplicationTable.init(old!!)
}
if (gameLogic.isComplete())
newGameMessage()
// add functionality to the answer buttons
for (cell in multiplicationTable.matrixAnswers.cells) {
val actor = cell.actor
if (actor !is Label) continue
actor.clearListeners()
actor.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
val answer = actor.text.toString().toInt()
try {
val correctAnswer = progress(answer)
if (correctAnswer) {
val completed = gameLogic.isComplete()
if (completed)
newGameMessage()
else
gameLogic.updateAnswerAlternatives()
multiplicationTable.notifyChangeListeners()
main.scoreLabel!!.score = gameLogic.score
} else {
// wrong answer, hide label
actor.isVisible = false
}
} catch (e: Exception) {
// an entry may be just "-" (minus) if its currently being edited
Main.log("Trouble when user clicked on answer button.")
Main.log(e)
}
}
})
}
// add functionality to help button
main.menu!!.helpLabel.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
try {
if (gameLogic.isComplete()) return
var help = ""
val i = gameLogic.getHighlightRow()
val j = gameLogic.getHighlightCol()
// convolve i'th left row with j'th right col
for (k in 0 until multiplicationTable.columnsLeft) {
val a = multiplicationTable.matrixLeft.get(i, k).toInt()
val b = multiplicationTable.matrixRight.get(k, j).toInt()
help += parentheses(a) + "*" + parentheses(b) + "+"
}
help = help.dropLast(1)
main.showMessage(help)
main.menu!!.hideMenu()
} catch (e: Exception) {
Main.log(e)
}
}
})
// add functionality to next button
main.menu!!.nextLabel.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
main.init(true, false)
}
})
// let user change values in left and right matrix
val entries = Array<Actor>()
entries.addAll(multiplicationTable.matrixLeft.children)
entries.addAll(multiplicationTable.matrixRight.children)
var notIntegerLock = false
for (actor in entries) {
if (actor !is Label) continue
actor.clearListeners()
actor.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
if (notIntegerLock) return
if (gameLogic.isComplete()) return
// add TextField on top of cell
val textField = object : TextField(actor.text.toString(), main.skin) {
override fun draw(batch: Batch?, parentAlpha: Float) {
updateTextFieldPos()
super.draw(batch, parentAlpha)
}
fun updateTextFieldPos() {
val pos = actor.localToStageCoordinates(Vector2())
setPosition(pos.x, pos.y)
setSize(actor.width, actor.height)
}
}
textField.updateTextFieldPos()
main.stage.addActor(textField)
textField.setAlignment(Align.center)
textField.style.focusedFontColor = Color.WHITE
textField.style.font = actor.style.font
textField.style = textField.style
textField.maxLength = 6
main.stage.keyboardFocus = textField
textField.selectAll()
// replace keypad
textField.onscreenKeyboard = TextField.OnscreenKeyboard { }
val keypad = main.keypad
keypad.scrollIn(main.stage)
// scroll down if needed
val scrollPane = main.multiplicationTable!!.parent as ScrollPane
val pos = actor.localToAscendantCoordinates(multiplicationTable, Vector2())
scrollPane.scrollTo(pos.x, pos.y - keypad.height, 1f, 1f)
// filter for text input
val digitInput = TextField.TextFieldFilter { textField, c ->
c.isDigit() || (c.equals('-') && !textField.text.contains('-') && textField.cursorPosition == 0)
}
textField.textFieldFilter = digitInput
var textChanged = false
// change value in matrix
textField.addListener(object : ChangeListener() {
override fun changed(event: ChangeEvent?, _actor: Actor?) {
textChanged = true
if (textField.text.length > 0) {
actor.setText(textField.text)
multiplicationTable.notifyChangeListeners()
}
try { // determine if text is integer
notIntegerLock = false
textField.text.toInt()
gameLogic.updateAnswers()
} catch (e: NumberFormatException) {
notIntegerLock = true
}
}
})
// remove text field when click elsewhere
main.stage.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
fun removeIfNecessary() {
val hitActor = main.stage.hit(x, y, false)
if (hitActor == textField) return
if (keypad.contains(x, y)) return
if (notIntegerLock) return // do not allow to close if not integer
try {
if (!gameLogic.isComplete() && textChanged)
gameLogic.updateAnswerAlternatives()
textField.remove()
main.stage.removeListener(this)
multiplicationTable.notifyChangeListeners()
if (hitActor !is TextField){
keypad.scrollOut()
scrollPane.scrollPercentY = 0f
}
} catch (e: IllegalStateException) {
Main.log("Trouble removing text field:")
//Main.log(e)
throw e
}
}
Gdx.app.postRunnable { removeIfNecessary() }
}
})
}
})
}
}
private fun newGameMessage() {
multiplicationTable!!.clearListeners()
Gdx.app.postRunnable {
main!!.showMessage("Touch anywhere for new game", "", {
main!!.init(true, false)
})
}
}
private fun parentheses(i: Int): String {
if (i >= 0) return i.toString()
return "($i)"
}
}<file_sep>package org.ajm.laforkids
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.InputProcessor
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Vector2
import java.util.*
/**
* Clicks randomly really fast.
* Revealed some weaknesses that are now fixed.
*/
class StressTester(val inputProcessor: InputProcessor,val adapter: Main) {
private val random = Random()
var active = false
fun invoke() {
if (!active) return
Gdx.graphics.requestRendering()
val pos = Vector2()
val add = Vector2()
try {
if(MathUtils.randomBoolean(0.1f))
adapter.resize(100+MathUtils.random(1000),100+MathUtils.random(1000))
for (i in 0 until 10) {
// chose a position and a radius
pos.set(random.nextFloat() * Gdx.graphics.width, random.nextFloat() * Gdx.graphics.height)
val radius = random.nextFloat() * Math.min(Gdx.graphics.width, Gdx.graphics.height).toFloat()
// click 10 times inside this radius
for (j in 0 until 10) {
add.set(0f, radius)
add.rotate(random.nextFloat() * 360f)
pos.add(add)
inputProcessor.touchDown(pos.x.toInt(), pos.y.toInt(), 1, 1)
inputProcessor.touchUp(pos.x.toInt(), pos.y.toInt(), 1, 1)
}
}
} catch (e: Exception) {
Gdx.app.log("Stress Test", "Stress test crashed at x=$pos.")
throw e
}
}
}<file_sep># Matrix-Multiplication
Android game for practicing matrix multiplication.
https://play.google.com/store/apps/details?id=org.ajm.laforkids
#License
http://www.apache.org/licenses/LICENSE-2.0
#Libraries
https://libgdx.badlogicgames.com/
https://github.com/jrenner/gdx-smart-font
<file_sep>package org.ajm.laforkids
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Preferences
import com.badlogic.gdx.utils.Array
/**
* The settings that can be adjusted in the [SettingsInterface].
*/
class Settings {
private val prefs: Preferences
val SETTING_MIN_VALUE = "minValue"
val SETTING_MAX_VALUE = "maxValue"
val SETTING_MIN_ROWS_LEFT = "minRowsLeft"
val SETTING_MAX_ROWS_LEFT = "maxRowsLeft"
val SETTING_MIN_COLUMNS_LEFT = "minColumnsLeft"
val SETTING_MAX_COLUMNS_LEFT = "maxColumnsLeft"
val SETTING_MIN_COLUMNS_RIGHT = "minColumnsRight"
val SETTING_MAX_COLUMNS_RIGHT = "maxColumnsRight"
val SETTING_ANSWER_ALTERNATIVES = "answerAlternatives"
val SETTING_ANSWER_MAX_ERROR = "answerMaxError"
/**
* Load and save settings using the given tag.
*/
constructor(tag: String) {
prefs = Gdx.app.getPreferences(tag)
minValue = prefs.getInteger(SETTING_MIN_VALUE, -10)
maxValue = prefs.getInteger(SETTING_MAX_VALUE, 10)
minRowsLeft = prefs.getInteger(SETTING_MIN_ROWS_LEFT, 1)
maxRowsLeft = prefs.getInteger(SETTING_MAX_ROWS_LEFT, 3)
minColumnsLeft = prefs.getInteger(SETTING_MIN_COLUMNS_LEFT, 1)
maxColumnsLeft = prefs.getInteger(SETTING_MAX_COLUMNS_LEFT, 3)
minColumnsRight = prefs.getInteger(SETTING_MIN_COLUMNS_RIGHT, 1)
maxColumnsRight = prefs.getInteger(SETTING_MAX_COLUMNS_RIGHT, 3)
answerAlternatives = prefs.getInteger(SETTING_ANSWER_ALTERNATIVES, 3)
answerMaxError = prefs.getInteger(SETTING_ANSWER_MAX_ERROR, 10)
}
/**
* Reload settings from gdx preferences.
*/
fun reload() {
minValue = prefs.getInteger(SETTING_MIN_VALUE, -10)
maxValue = prefs.getInteger(SETTING_MAX_VALUE, 10)
minRowsLeft = prefs.getInteger(SETTING_MIN_ROWS_LEFT, 1)
maxRowsLeft = prefs.getInteger(SETTING_MAX_ROWS_LEFT, 3)
minColumnsLeft = prefs.getInteger(SETTING_MIN_COLUMNS_LEFT, 1)
maxColumnsLeft = prefs.getInteger(SETTING_MAX_COLUMNS_LEFT, 3)
minColumnsRight = prefs.getInteger(SETTING_MIN_COLUMNS_RIGHT, 1)
maxColumnsRight = prefs.getInteger(SETTING_MAX_COLUMNS_RIGHT, 3)
answerAlternatives = prefs.getInteger(SETTING_ANSWER_ALTERNATIVES, 3)
answerMaxError = prefs.getInteger(SETTING_ANSWER_MAX_ERROR, 10)
}
/** Smallest possible entry value. */
var minValue: Int
/** Largest possible entry value. */
var maxValue: Int
/** Lowest possible number of rows in left matrix, A. */
var minRowsLeft: Int
/** Highest possible number of rows in left matrix, A. */
var maxRowsLeft: Int
/** Lowest possible number of columns in left matrix, A. The number of rows in the right matrix B must be
* the same. */
var minColumnsLeft: Int
/** Highest possible number of columns in left matrix, A. The number of rows in the right matrix B must be
* the same. */
var maxColumnsLeft: Int
/** Lowest possible number of rows in right matrix, B. */
var minColumnsRight: Int
/** Highest possible number of rows in right matrix, B. */
var maxColumnsRight: Int
/** The number of value to choose from when entering your answer. */
var answerAlternatives: Int
/** The maximum error of the answer alternatives. */
var answerMaxError: Int
/**
* Checks if the current settings make sense. For every setting that
* is illegal a integer is added to the returned array.
*/
fun dataInvariant(): Array<Int> {
val errors = Array<Int>()
if (minValue > maxValue) errors.add(0)
if (minRowsLeft < 0) errors.add(1)
if (maxRowsLeft < 0) errors.add(1)
if (minRowsLeft > maxRowsLeft) errors.add(1)
if (minColumnsLeft < 0) errors.add(2)
if (maxColumnsLeft < 0) errors.add(2)
if (minColumnsLeft > maxColumnsLeft) errors.add(2)
if (minColumnsRight < 0) errors.add(3)
if (maxColumnsRight < 0) errors.add(3)
if (minColumnsRight > maxColumnsRight) errors.add(3)
if (answerAlternatives < 1) errors.add(4)
if (answerMaxError < 1) errors.add(5)
return errors
}
/**
*
* Must be called after updating settings to ensure they
* persist after app is closed.
* @return whether settings were saved
* */
fun saveSettingsForever(): Boolean {
val ok = dataInvariant().size == 0
if (ok) {
prefs.putInteger(SETTING_MIN_VALUE, minValue)
prefs.putInteger(SETTING_MAX_VALUE, maxValue)
prefs.putInteger(SETTING_MIN_ROWS_LEFT, minRowsLeft)
prefs.putInteger(SETTING_MAX_ROWS_LEFT, maxRowsLeft)
prefs.putInteger(SETTING_MIN_COLUMNS_LEFT, minColumnsLeft)
prefs.putInteger(SETTING_MAX_COLUMNS_LEFT, maxColumnsLeft)
prefs.putInteger(SETTING_MIN_COLUMNS_RIGHT, minColumnsRight)
prefs.putInteger(SETTING_MAX_COLUMNS_RIGHT, maxColumnsRight)
prefs.putInteger(SETTING_ANSWER_ALTERNATIVES, answerAlternatives)
prefs.putInteger(SETTING_ANSWER_MAX_ERROR, answerMaxError)
prefs.flush()
}
return ok
}
}<file_sep>package org.ajm.laforkids
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.GlyphLayout
import com.badlogic.gdx.math.Interpolation
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.Group
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.utils.Array
/**
* Recursively get all children.
*/
fun getAllChildren(table: Group): Array<Actor> {
fun getAllChildren(table: Group, found: Array<Actor>): Array<Actor> {
for (child in table.children) {
found.add(child)
if (child is Group)
getAllChildren(child, found)
}
return found
}
return getAllChildren(table, Array<Actor>())
}
fun isAscendant(actor: Actor, possibleParent: Group): Boolean {
if (actor.parent == null) return false
if (actor.parent == possibleParent) return true
return isAscendant(actor.parent, possibleParent)
}
fun getTextWidth(font: BitmapFont, text: String): Float {
val layout = GlyphLayout()
layout.setText(font, text)
val width = layout.width
return width
}
/**
* Calls the given function once every frame until the animation is done.
*/
fun animate(function: (lerp: Float) -> Unit,
interpolationMethod: Interpolation,
interpolationTime: Float) {
val beganAnimation = System.currentTimeMillis()
fun animate() {
val seconds = (System.currentTimeMillis() - beganAnimation) / 1000f
val alpha = MathUtils.clamp(seconds, 0f, interpolationTime) / interpolationTime
val lerp = interpolationMethod.apply(alpha)
function.invoke(lerp)
if (alpha < 1f) Gdx.app.postRunnable { animate() }
}
animate()
}<file_sep>package org.ajm.laforkids.actors
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.scenes.scene2d.ui.Cell
import com.badlogic.gdx.scenes.scene2d.ui.Label
/**
* Matrix with string entries.
*/
interface IMatrix {
/** Whether to draw the matrix left and right outlines. */
var drawOutlines: Boolean
/** The width of the outlines. */
var outlineThickness: Float
/** The padding around each entry. */
var entryPad: Float
/** The width of each entry. */
var entryWidth: Float
/** The height of each entry. */
var entryHeight: Float
/** The width of the text displayed in the background. */
var backgroundTextWidth: Float
/** The height of the text displayed in the background. */
var backgroundTextHeight: Float
/** Text drawn behind the entries. Intended for displaying
* the name of the matrix, for example: A */
var backgroundText: String
/** The color of the background text. */
var backgroundTextColor: Color
/** The number of rows. */
val matrixRows: Int
/** The number of columns*/
val matrixColumns: Int
/**
*
* Set the value of the entry at given row and column.
*
* toString() is called on given value and the resulting string
* is the value that is saved in the indicated position.
*
* (0,0) is top left
*
* @param row the row of the entry
* @param col the column of the entry
* @param value toString() is called on this value
*/
fun set(row: Int, col: Int, value: Any)
/**
* Get the string stored in the indicated position.
*
* (0,0) is top left
*
* @param row the row of the entry
* @param col the column of the entry
* @return the string stored in the indicated position
*/
fun get(row: Int, col: Int): String
/**
* Get the cell of indicated position.
*
* (0,0) is top left
*
* @param row the row of the entry
* @param col the column of the entry
* @return the cell of indicated position
*/
fun getCell(row: Int, col: Int): Cell<Label>?
/**
* @return the string stored in the ith position.
*/
fun get(entry: Int): String
/**
* @return the number of entries in this matrix.
* */
fun size():Int
}
<file_sep>package org.ajm.laforkids.actors
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.GlyphLayout
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.ui.Cell
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.utils.Align
import org.ajm.laforkids.actors.IMatrix
/**
* Table representing a matrix with integer entries.
*/
open class Matrix : IMatrix, Table {
/** Whether to draw the matrix left and right outlines. */
override var drawOutlines = true
/** The width of the outlines. */
override var outlineThickness = 5f
set(value) {
if (value < 0) throw IllegalArgumentException()
field = value
}
/** The padding around each entry. */
override var entryPad = 0f
set(value) {
if (value < 0) throw IllegalArgumentException()
for (cell in cells) {
cell.pad(value)
}
mustPack = true
field = value
}
/** The width of each entry. */
override var entryWidth = 15f
set(value) {
if (value < 0) throw IllegalArgumentException()
if (field != value) {
mustPack = true
for (cell in cells)
cell.width(value)
}
field = value
}
/** The height of each entry. */
override var entryHeight = 15f
set(value) {
if (value < 0) throw IllegalArgumentException()
if (field != value) {
mustPack = true
for (cell in cells)
cell.height(value)
}
field = value
}
/** Used for drawing the outlines. */
private val dot: TextureRegion
private var mustPack = false
private var backgroundFont: BitmapFont? = null
/** The width of the text displayed in the background. */
override var backgroundTextWidth = 0f
set(value) {
if (value < 0) throw IllegalArgumentException()
field = value
}
/** The height of the text displayed in the background. */
override var backgroundTextHeight = 0f
set(value) {
if (value < 0) throw IllegalArgumentException()
field = value
}
/** Text drawn behind the entries. Intended for displaying
* the name of the matrix, for example: A */
override var backgroundText = ""
set(value) {
field = value
val glyphLayout = GlyphLayout(backgroundFont, value)
backgroundTextWidth = glyphLayout.width
backgroundTextHeight = glyphLayout.height
}
/** The color of the background text. */
override var backgroundTextColor = Color(0.9f, 0.9f, 0.9f, 1f)
override val matrixRows: Int
override val matrixColumns: Int
/**
*
* @param skin needed for the fonts
* @param matrixRows number of rows the matrix should have
* @param matrixColumns number of columns the matrix should have
*/
constructor(skin: Skin, matrixRows: Int, matrixColumns: Int) {
if (matrixRows < 1) throw IllegalArgumentException()
if (matrixColumns < 1) throw IllegalArgumentException()
this.matrixRows = matrixRows
this.matrixColumns = matrixColumns
dot = skin.getRegion("dot")
backgroundFont = skin.get("OpenSans-Large", BitmapFont::class.java)
for (row in 0 until matrixRows) {
for (col in 0 until matrixColumns) {
val label1 = Label("", skin, "OpenSans-Entry")
label1.setAlignment(Align.center)
add(label1).width(entryWidth).height(entryHeight)
}
row()
}
}
/**
* Get the index of the label. If matrix does not contain the label
* a [IllegalArgumentException] is thrown.
*/
fun getIndex(label: Label): Int {
var i = 0
var found = false
for (actor in children) {
if (actor == label) {
found = true
break
}
i++
}
if (!found) throw IllegalArgumentException()
return i
}
fun getRow(label: Label): Int {
val index = getIndex(label)
return index / matrixColumns
}
fun getColumn(label: Label): Int {
val index = getIndex(label)
return index % matrixColumns
}
fun set(index: Int, value: Any) {
if (index < 0) throw IllegalArgumentException()
val actor = cells.get(index).actor
if (actor is Label) {
actor.isVisible = true
actor.setText(value.toString())
}
}
/**
*
* Set the value of the entry at given row and column.
*
* toString() is called on given value and the resulting string
* is the value that is saved in the indicated position.
*
* (0,0) is top left
*
* @param row the row of the entry
* @param col the column of the entry
* @param value toString() is called on this value
* */
override fun set(row: Int, col: Int, value: Any) {
if (row < 0 || col < 0) throw IllegalArgumentException()
val actor = cells.get(row * columns + col).actor
if (actor is Label) {
actor.isVisible = true
actor.setText(value.toString())
}
}
/**
* Get the string stored in the indicated position.
*
* (0,0) is top left
*
* @param row the row of the entry
* @param col the column of the entry
*/
override fun get(row: Int, col: Int): String {
if (row < 0 || col < 0) throw IllegalArgumentException()
val actor = cells.get(row * columns + col).actor
if (actor is Label)
return actor.text.toString()
return actor.toString()
}
/**
* Get the cell of indicated position.
*
* (0,0) is top left
*
* @param row the row of the entry
* @param col the column of the entry
*/
override fun getCell(row: Int, col: Int): Cell<Label>? {
if (row < 0 || col < 0) throw IllegalArgumentException()
val cell = cells.get(row * columns + col)
if (cell.actor != null && cell.actor is Label)
return cell as Cell<Label>
return null
}
override fun draw(batch: Batch?, parentAlpha: Float) {
if (mustPack) {
pack()
mustPack = false
}
// draw background text
if (backgroundText.length > 0) {
backgroundFont!!.color = backgroundTextColor
val matrixCenter = localToStageCoordinates(Vector2(width / 2f, height / 2f))
val x = matrixCenter.x - backgroundTextWidth / 2f
val y = matrixCenter.y + backgroundTextHeight / 2f
backgroundFont!!.draw(batch, backgroundText, x, y)
}
super.draw(batch, parentAlpha)
// draw outlines
if (!drawOutlines) return
batch!!.color = Color.BLACK
// left vertical outline
val pos = localToStageCoordinates(Vector2(0f, 0f))
val x = round(pos.x)
val y = round(pos.y)
val width = round(width)
val height = round(height)
val outlineThickness = round(outlineThickness)
// left vertical outline
filledRectangle(batch, x, y, outlineThickness, height)
// left bottom horizontal outline
filledRectangle(batch, x, y, outlineThickness * 5, outlineThickness)
// left top horizontal outline
filledRectangle(batch, x, y + height - outlineThickness, outlineThickness * 5, outlineThickness)
// right vertical outline
filledRectangle(batch, x + width - outlineThickness, y, outlineThickness, height)
// left bottom horizontal outline
filledRectangle(batch, x + width - outlineThickness - outlineThickness * 4, y, outlineThickness * 5, outlineThickness)
// left top horizontal outline
filledRectangle(batch, x + width - outlineThickness - outlineThickness * 4,
y + height - outlineThickness, outlineThickness * 5, outlineThickness)
}
private fun filledRectangle(batch: Batch, x: Float, y: Float, width: Float, height: Float) {
batch.draw(dot, round(x), round(y), round(width), round(height))
}
private fun round(a: Float) = Math.floor(a.toDouble()).toFloat()
override fun get(entry: Int): String {
val label = cells.get(entry).actor as Label
return label.text.toString()
}
override fun size(): Int {
return cells.size
}
override fun clearListeners() {
super.clearListeners()
for (cell in cells) {
cell.actor.clearListeners()
}
}
}<file_sep>package org.ajm.laforkids.actors
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.ui.Cell
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.utils.Align
import com.badlogic.gdx.utils.Array
import org.ajm.laforkids.actors.Matrix
import org.ajm.laforkids.actors.IMultiplicationTable
open class MultiplicationTable : IMultiplicationTable, Table {
override val changeListeners = Array<Runnable>()
override var initialized: Boolean = false
// i don't know why i had to redeclare these values
override val matrixLeft: Matrix
override val matrixProduct: Matrix
override val matrixRight: Matrix
override val matrixAnswers: Matrix
override val topLeftActor: Actor
override val rowsLeft: Int
override val columnsLeft: Int
override val rowsRight: Int
override val columnsRight: Int
override val answerAlternatives: Int
/** The height of each entry, in all matrices and also the answer vector. May be overridden by
* accessing the individual matrices and could therefore be incorrect. */
override var entryHeight = 0f
set(value) {
if (value < 0) throw IllegalArgumentException()
field = value
matrixLeft.entryHeight = entryHeight
matrixProduct.entryHeight = entryHeight
matrixRight.entryHeight = entryHeight
matrixAnswers.entryHeight = entryHeight
mustPack = true
}
/** The width of each entry, in all matrices and also the answer vector. May be overridden by
* accessing the individual matrices and could therefore be incorrect. */
override var entryWidth = 0f
set(value) {
if (value < 0) throw IllegalArgumentException()
field = value
matrixLeft.entryWidth = entryWidth
matrixProduct.entryWidth = entryWidth
matrixRight.entryWidth = entryWidth
matrixAnswers.entryWidth = entryWidth
mustPack = true
}
/** The padding inside each matrix boundary. May be overridden by
* accessing the individual matrices and could therefore be incorrect. */
override var matrixInsidePad = 0f
set(value) {
if (value < 0) throw IllegalArgumentException()
field = value
for (cell in table.cells) {
val actor = cell.actor
if (actor is Matrix)
actor.pad(value)
}
for (cell in cells) {
val actor = cell.actor
if (actor is Matrix)
actor.pad(value)
}
mustPack = true
}
/** The padding outside each matrix boundary. May be overridden by
* accessing the individual matrices and could therefore be incorrect. */
override var matrixOutsidePad = 0f
set(value) {
if (value < 0) throw IllegalArgumentException()
field = value
for (cell in table.cells) {
cell.pad(value)
}
for (cell in cells) {
cell.pad(value)
}
mustPack = true
}
/** The padding around each entry of each matrix. May be overridden by
* accessing the individual matrices and could therefore be incorrect. */
override var matrixEntryPad = 0f
set(value) {
if (value < 0) throw IllegalArgumentException()
field = value
matrixLeft.entryPad = value
matrixProduct.entryPad = value
matrixRight.entryPad = value
matrixAnswers.entryPad = value
mustPack = true
}
internal val table: Table
internal var mustPack = false
/**
* RowsRight is always the same as ColumnsLeft
*
* @param skin contains some custom graphics, also needed for labels
* @param rowsLeft the number of rows in the left matrix A
* @param columnsLeft the number of columns in the left matrix A, the same as the number of rows in the right matrix, B
* @param columnsRight the number of columns in the right matrix B
* @param answerAlternatives the number of answer buttons to choose from
*/
constructor(skin: Skin, rowsLeft: Int, columnsLeft: Int, columnsRight: Int, answerAlternatives: Int) {
if (rowsLeft < 1) throw IllegalArgumentException()
if (columnsLeft < 1) throw IllegalArgumentException()
if (columnsRight < 1) throw IllegalArgumentException()
if (answerAlternatives < 1) throw IllegalArgumentException()
this.skin = skin
this.rowsLeft = rowsLeft
this.columnsLeft = columnsLeft
this.columnsRight = columnsRight
this.rowsRight = columnsLeft
this.answerAlternatives = answerAlternatives
matrixRight = Matrix(skin, rowsRight, columnsRight)
matrixLeft = Matrix(skin, rowsLeft, columnsLeft)
matrixProduct = Matrix(skin, rowsLeft, columnsRight)
matrixAnswers = Matrix(skin, 1, answerAlternatives)
matrixAnswers.drawOutlines = false
topLeftActor = prepareTopLeftActor()
table = Table()
table.add(topLeftActor)
table.add(matrixRight)
table.row()
table.add(matrixLeft)
table.add(matrixProduct)
add(table)
row()
add(matrixAnswers)
matrixLeft.align(Align.bottomRight)
matrixProduct.align(Align.bottomLeft)
matrixRight.align(Align.topLeft)
matrixLeft.backgroundText = "A"
matrixRight.backgroundText = "B"
matrixProduct.backgroundText = "C"
}
internal fun notifyChangeListeners() {
for (runnable in changeListeners) {
runnable.run()
}
}
/**
* Convenience method for setting the backgrund text color of all the matrices at once.
*/
fun setMatrixBackgroundTextColor(color: Color) {
matrixAnswers.backgroundTextColor.set(color)
matrixLeft.backgroundTextColor.set(color)
matrixRight.backgroundTextColor.set(color)
matrixProduct.backgroundTextColor.set(color)
}
fun updateTopLeftActorSize() {
val cell = table.getCell(topLeftActor)
val width = columnsLeft * (entryWidth + matrixEntryPad * 2)
+(matrixInsidePad + matrixOutsidePad) * 2
val height = rowsRight * (entryHeight + matrixEntryPad * 2)
+(matrixInsidePad + matrixOutsidePad) * 2
topLeftActor.width = width
topLeftActor.height = height
cell.align(Align.center)
}
open internal fun prepareTopLeftActor(): Actor {
return Label("AB=C", skin)
}
override fun init(copyFrom: IMultiplicationTable) {
super.init(copyFrom)
initialized = true
}
override fun init(min: Int, max: Int) {
super.init(min, max)
initialized = true
}
override fun draw(batch: Batch?, parentAlpha: Float) {
if (mustPack) {
pack()
mustPack = false
}
super.draw(batch, parentAlpha)
}
override fun clearListeners() {
super.clearListeners()
for (cell in cells) {
cell.actor.clearListeners()
}
}
}<file_sep>package org.ajm.laforkids.actors
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.math.Interpolation
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.Touchable
import com.badlogic.gdx.scenes.scene2d.ui.*
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.utils.Array
import org.ajm.laforkids.animate
/**
* Onscreen keyboard for numbers.
*/
class Keypad : ScrollPane {
private var animator: (lerp: Float) -> Unit = {}
private var beganAnimation = System.currentTimeMillis()
var interpolationMethod: Interpolation = Interpolation.pow3Out
var interpolationTime = 0.5f
constructor(skin: Skin) : super(Table()) {
val table = widget as Table
// determine sizes
val totalHeight = Gdx.graphics.height / 3f
val totalWidth = Gdx.graphics.width.toFloat()
var entryWidth = totalWidth / 3f
var entryHeight = totalHeight / 4f
val pad = Math.min(entryWidth, entryHeight) / 10f
entryWidth -= pad * 2f
entryHeight -= pad * 2f
width = totalWidth
height = totalHeight
// prepare buttons
val buttons = Array<String>()
buttons.add("1")
buttons.add("2")
buttons.add("3")
buttons.add("4")
buttons.add("5")
buttons.add("6")
buttons.add("7")
buttons.add("8")
buttons.add("9")
buttons.add("0")
buttons.add("-")
buttons.add("rem")
// add listeners that forward the input
var i = 0
for (text in buttons) {
val textButton = TextButton(text, skin)
textButton.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
val backspace = text.equals("rem")
val char: Char
if (backspace)
char = 8.toChar()
else
char = text.first()
Gdx.input.inputProcessor.keyTyped(char)
}
})
table.add(textButton).pad(pad).width(entryWidth).height(entryHeight)
if (++i % 3 == 0)
table.row()
}
// don't want touches going through
touchable = Touchable.enabled
// make it somewhat opaque
style.background = skin.getDrawable("dot")
touchable = Touchable.enabled
}
fun scrollIn(stage: Stage) {
beganAnimation = System.currentTimeMillis()
if (!stage.actors.contains(this, true)) {
stage.addActor(this)
y = -height
}
val begin = y
val end = 0f
animator = { lerp -> setPosition(0f, (1 - lerp) * begin + lerp * end) }
}
fun scrollOut(animationDelay: Float = 10f) {
beganAnimation = System.currentTimeMillis()
val begin = y
val end = -height
animator = { lerp ->
setPosition(0f, (1 - lerp) * begin + lerp * end)
if (lerp == 1f) Gdx.app.postRunnable { remove() }
}
}
fun contains(x: Float, y: Float): Boolean {
val rectangle = Rectangle(this.x, this.y, width, height)
return rectangle.contains(x, y)
}
override fun draw(batch: Batch?, parentAlpha: Float) {
val seconds = (System.currentTimeMillis() - beganAnimation) / 1000f
val alpha = MathUtils.clamp(seconds, 0f, interpolationTime) / interpolationTime
val lerp = interpolationMethod.apply(alpha)
animator.invoke(lerp)
if (lerp < 1) Gdx.graphics.requestRendering()
super.draw(batch, parentAlpha)
}
}<file_sep>package org.ajm.laforkids
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.math.Interpolation
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.Touchable
import com.badlogic.gdx.scenes.scene2d.ui.*
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.utils.Align
import com.badlogic.gdx.utils.Array
import com.badlogic.gdx.utils.viewport.ScreenViewport
import org.ajm.laforkids.actors.*
import org.jrenner.smartfont.SmartFontGenerator
import java.util.*
class Main {
companion object {
val showStackTrace = false
fun log(e: Exception) {
if (showStackTrace)
Gdx.app.log("Exception", e.toString() + "\n" + Arrays.toString(e.stackTrace).replace(",", "\n"))
else
Gdx.app.log("Exception", e.toString())
//throw e
}
fun log(s: String) {
Gdx.app.log("Log", s)
}
}
val palette = Array<Color>()
init {
palette.add(Color.valueOf("#70AD47"))
palette.add(Color.valueOf("#4472C4"))
palette.add(Color.valueOf("#FFC000"))
palette.add(Color.valueOf("#A5A5A5"))
palette.add(Color.valueOf("#ED7D31"))
palette.add(Color.valueOf("#5B9BD5"))
palette.add(Color.valueOf("#44546A"))
palette.add(Color.valueOf("#44546A"))
palette.add(Color.valueOf("#E7E6E6"))
palette.add(Color.valueOf("#000000"))
palette.add(Color.valueOf("#FFFFFF"))
}
// hardcoded parameters
val selectionColor: Color = Color(palette[4])
val topBarBackgroundColor: Color = Color(palette[2])
val backgroundColor: Color = Color(palette[10])
val matrixBackgroundTextColor: Color = Color(palette[8])
val fontColor: Color = Color(palette[9])
val menuBackgroundColor: Color = Color(palette[2])
val keyboardBackgroundColor: Color = Color(palette[0]).lerp(Color.WHITE, 0.5f)
val entryPad = 0f
val screenFill = 1f // 1 = 100%
val outlineThickness = 5f // just a factor
val interpolationMethod: Interpolation = Interpolation.pow3Out // used for most animations
val interpolationTime = 0.5f // used for most animations
val stage = Stage(ScreenViewport())
var multiplicationTable: VisualizedMultiplicationTable? = null
var menu: Menu? = null
var helpFrame: ScrollPane? = null
val skin = Skin()
val settings = Settings("Matrix Multiplication")
val gameIterator = GameIterator(settings)
var entryFont: BitmapFont? = null
var font_large: BitmapFont? = null
var defaultFont: BitmapFont? = null
var scoreLabel: ScoreLabel? = null
var keypad: Keypad
private val generator = SmartFontGenerator(Gdx.files.internal("OpenSans.ttf"))
private val generatorDigits = SmartFontGenerator(Gdx.files.internal("OpenSans-Digits.ttf"))
private val generatorABC = SmartFontGenerator(Gdx.files.internal("OpenSans-ABC.ttf"))
private var firstInit = true
val stressTest = false
private val stressTester: StressTester
constructor() {
Gdx.input.inputProcessor = stage
Gdx.graphics.isContinuousRendering = false
Gdx.graphics.requestRendering()
skin.addRegions(TextureAtlas(Gdx.files.internal("gdx-skins-master/kenney-pixel/custom-skin/skin.atlas")))
init(true, true)
stressTester = StressTester(stage, this)
stressTester.active = stressTest
if (stressTest) {
settings.minColumnsLeft = 1
settings.maxColumnsLeft = 5
settings.minRowsLeft = 1
settings.maxRowsLeft = 5
settings.minColumnsRight = 1
settings.maxColumnsRight = 5
// do not save
}
keypad = Keypad(skin)
keypad.color.set(keyboardBackgroundColor)
for (child in keypad.children) {
if (child !is TextButton) continue
child.label.style.fontColor = fontColor
}
keypad.interpolationMethod = interpolationMethod
keypad.interpolationTime = interpolationTime
}
fun resize(width: Int = Gdx.graphics.width, height: Int = Gdx.graphics.height) {
init(false, true, width, height)
}
fun init(newGame: Boolean, resize: Boolean, width: Int = Gdx.graphics.width, height: Int = Gdx.graphics.height) {
Gdx.graphics.requestRendering()
if (newGame) gameIterator.newGame()
// to update the fonts everything is rebuilt
stage.viewport.update(width, height, true)
stage.clear()
// prepare default font
var size = (10f + 0.5f * Math.sqrt(Math.sqrt(Gdx.graphics.density.toDouble())) * Math.min(width, height) / 10f).toInt()
if (resize) {
if (defaultFont != null) {
skin.remove("default", BitmapFont::class.java)
defaultFont!!.dispose()
}
defaultFont = generator.createFont(Gdx.files.internal("OpenSans.ttf"), "default", size)
skin.add("default", defaultFont!!, defaultFont!!.javaClass)
}
// determine some visual details
val padTop = defaultFont!!.capHeight * 2f
val tableHeight = (height - padTop).toInt()
val gl = gameIterator.gameLogic
val columns = gl.columnsLeft + gl.columnsRight
val rows = gl.rowsLeft + gl.columnsLeft + 1
var outlineThickness = this.outlineThickness * (2f +
6f * Math.min(width, tableHeight) / (1000f)).toInt().toFloat()
outlineThickness /= Math.max(columns, rows).toFloat()
val matrixInsidePad = 3 * outlineThickness
val matrixOutsidePad = outlineThickness
val pad = matrixInsidePad + matrixOutsidePad
val entryWidth = (width.toFloat() * screenFill - pad * 4 - columns * entryPad * 2) /
Math.max(columns, gl.answerAlternatives).toFloat()
val entryHeight = (tableHeight * screenFill - pad * 6 - rows * entryPad * 2) / rows.toFloat()
// prepare entry font
if (entryFont != null) {
skin.remove("OpenSans-Entry", entryFont!!.javaClass)
entryFont!!.dispose()
}
size = (Math.max(Math.min(entryHeight, entryWidth) / 1.8f, 8f)).toInt()
entryFont = generatorDigits.createFont(Gdx.files.internal("OpenSans-Regular-Digits.ttf"), "OpenSans-Entry", size)
skin.add("OpenSans-Entry", entryFont!!, entryFont!!.javaClass)
// prepare large font
size = 250
if (firstInit) {
font_large = generatorABC.createFont(Gdx.files.internal("OpenSans-ABC.ttf"), "OpenSans-Large", size)
skin.add("OpenSans-Large", font_large!!, font_large!!.javaClass)
}
var min = Math.min(gl.rowsLeft * entryHeight, gl.columnsLeft * entryWidth)
min = Math.min(min, gl.columnsRight * entryWidth)
min = Math.min(min, gl.columnsLeft * entryHeight)
font_large!!.data.setScale((min + pad) / size)
// skin must be reloaded to include the new fonts
skin.load(Gdx.files.internal("gdx-skins-master/kenney-pixel/custom-skin/skin.json"))
// prepare a new multiplication table
multiplicationTable = VisualizedMultiplicationTable(skin,
gl.rowsLeft, gl.columnsLeft, gl.columnsRight, gl.answerAlternatives)
multiplicationTable!!.interpolationMethod = interpolationMethod
multiplicationTable!!.interpolationTime = interpolationTime
multiplicationTable!!.entryWidth = entryWidth
multiplicationTable!!.entryHeight = entryHeight
multiplicationTable!!.matrixInsidePad = matrixInsidePad
multiplicationTable!!.matrixOutsidePad = matrixOutsidePad
multiplicationTable!!.selectionColor = selectionColor
multiplicationTable!!.outlineThickness = outlineThickness
multiplicationTable!!.matrixEntryPad = entryPad
multiplicationTable!!.setFillParent(true)
multiplicationTable!!.padTop(padTop)
multiplicationTable!!.padBottom(height / 3f)
multiplicationTable!!.align(Align.bottom)
multiplicationTable!!.matrixAnswers.entryWidth = width / gl.answerAlternatives.toFloat()
multiplicationTable!!.matrixAnswers.entryPad = 0f
multiplicationTable!!.setMatrixBackgroundTextColor(matrixBackgroundTextColor)
// put in scrollPane so when soft keyboard is visible one can scroll to view what is under it
val scrollPane = object : ScrollPane(multiplicationTable!!) {
val dot = skin.getDrawable("dot")
override fun draw(batch: Batch?, parentAlpha: Float) {
batch as Batch
batch.color = backgroundColor
dot.draw(batch, x, y, width.toFloat(), height.toFloat())
super.draw(batch, parentAlpha)
}
}
stage.addActor(scrollPane)
scrollPane.setFillParent(true)
scrollPane.setScrollingDisabled(true, false)
// prepare top bar
val topBar = Table()
topBar.background = skin.getDrawable("dot")
topBar.color.set(topBarBackgroundColor)
stage.addActor(topBar)
// add menu
if (resize) menu = Menu(stage, skin)
menu!!.setTextColor(fontColor)
menu!!.clearMenuItemListeners()
topBar.add(menu).width(width * 0.5f)
menu!!.isVisible = true
menu!!.menuBackgroundColor = menuBackgroundColor
menu!!.interpolationMethod = interpolationMethod
menu!!.interpolationTime = interpolationTime
// add score display
scoreLabel = ScoreLabel(skin, gameIterator.gameLogic.score)
topBar.add(scoreLabel).width(width * (0.49f)).padRight(width * 0.01f)
scoreLabel!!.setAlignment(Align.right)
scoreLabel!!.interpolationTime = interpolationTime
scoreLabel!!.interpolationMethod = interpolationMethod
scoreLabel!!.style.fontColor = fontColor
topBar.pack()
topBar.setPosition(0f, stage.height - topBar.height)
// add settings functionality
menu!!.settingsLabel.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
if (stressTester.active) return
// hide everything else
menu!!.hideMenu()
multiplicationTable!!.isVisible = false
topBar.isVisible = false
// prepare settings interface
val settings = SettingsInterface(this@Main)
settings.setFontColor(fontColor)
settings.onSaved = Runnable { init(true, false) }
settings.onCancel = Runnable {
stage.actors.removeValue(settings, true)
multiplicationTable!!.isVisible = true
topBar.isVisible = true
}
// show settings interface
stage.addActor(settings)
settings.setFillParent(true)
}
})
// connect the game logic to the new MultiplicationTable
gameIterator.init(multiplicationTable!!, this, newGame)
multiplicationTable!!.updateTopLeftActorSize()
keypad = Keypad(skin)
keypad.color.set(keyboardBackgroundColor)
for (child in keypad.children) {
if (child !is TextButton) continue
child.label.style.fontColor = fontColor
}
keypad.interpolationMethod = interpolationMethod
keypad.interpolationTime = interpolationTime
firstInit = false
}
/**
* Show a message on the bottom of the screen. It is removed the next time the user clicks anywhere.
*/
fun showMessage(message: String, buttonText: String = "Ok", onOk: () -> Unit = {}) {
// remove previous just in case
stage.actors.removeValue(helpFrame, true)
Gdx.app.postRunnable {
// prepare table with message and a button that does nothing
val label = Label(message, skin)
val button = Label(buttonText, skin)
val table = Table()
table.add(label).row()
table.add(button)
table.background = skin.getDrawable("dot")
// put it in ScrollPane in case the message is too big
helpFrame = ScrollPane(table)
// add to the bottom of the stage
stage.addActor(helpFrame)
helpFrame!!.setOverscroll(false, false)
helpFrame!!.setPosition(0f, 0f)
helpFrame!!.height = multiplicationTable!!.matrixAnswers.height
helpFrame!!.width = stage.width
// scroll to the right in case the message is to big
val interpolationTime = interpolationTime * 2 * (label.width / helpFrame!!.width)
animate({ lerp -> helpFrame!!.scrollPercentX = lerp }, interpolationMethod, interpolationTime)
// when user clicks anywhere remove the message
stage.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
stage.actors.removeValue(helpFrame, true)
stage.removeListener(this)
onOk.invoke()
}
})
}
}
fun render() {
try {
stressTester.invoke()
Gdx.gl.glClearColor(1f, 1f, 1f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
stage.act()
stage.draw()
} catch(exception: Exception) {
dispose()
throw exception
}
}
fun dispose() {
_try { stage.dispose() }
_try { skin.dispose() }
_try { entryFont!!.dispose() }
_try { font_large!!.dispose() }
_try { defaultFont!!.dispose() }
_try { generator.dispose() }
_try { generatorDigits.dispose() }
_try { generatorABC.dispose() }
}
fun _try(inline: () -> Unit) {
try {
inline.invoke()
} catch (e: Exception) {
// ignore
}
}
} | 976e0f24fce397c21e318dd32a6bf817ca75cf25 | [
"Markdown",
"Kotlin"
]
| 29 | Kotlin | Korkemoms/Matrix-Multiplication | 15ecf19aaa14c97a380054fb5b3a1935aced30c2 | f137586c93b02df119e0bfd1246d9b0fe63fb732 |
refs/heads/main | <repo_name>stelar-3023/CatchOfTheDay<file_sep>/src/base.js
import Rebase from "re-base";
import firebase from "firebase";
const firebaseApp = firebase.initializeApp({
apiKey: "<KEY>",
authDomain: "catch-of-the-day-steve-l-93dd9.firebaseapp.com",
databaseURL: "https://catch-of-the-day-steve-l-93dd9-default-rtdb.firebaseio.com",
projectId: "catch-of-the-day-steve-l-93dd9",
storageBucket: "catch-of-the-day-steve-l-93dd9.appspot.com",
messagingSenderId: "200852801746",
appId: "1:200852801746:web:4fdd5f1e165cf85560c50b",
measurementId: "G-S5NS96Z29E"
});
const base = Rebase.createClass(firebaseApp.database());
// This is a named export
export { firebaseApp };
// This is a default export
export default base;
| 591a886f80f0dd10d55a8783923a57fdc216a12e | [
"JavaScript"
]
| 1 | JavaScript | stelar-3023/CatchOfTheDay | 5b5ddf6b5e68a607cf95cdbee3d6243a87578373 | 0244ae71b2609cb3420bc1dc55b808a485c4cf2d |
refs/heads/master | <file_sep>using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(WebApplication3.Startup))]
namespace WebApplication3
{
public partial class Startup {
public void Configuration(IAppBuilder app) {
ConfigureAuth(app);
// this section should not be edited by anyone
// please dont edit
// section creation by <NAME> and ANil
}
}
}
| b3803648563f64163908ffdd561ce2182fbf32ab | [
"C#"
]
| 1 | C# | subhghosh/SAPReportUS | a72506132e6304b8a8a20bb023401118263ca919 | 8383efc240a74e7ea4c7e47580a2d11bb59700e7 |
refs/heads/master | <repo_name>alexg-dev/React-simple-app<file_sep>/src/client/state.ts
import * as Immutable from 'immutable'
let data = Immutable.fromJS({
'notes': [],
'is_loading': false
})
function createCursor(path) {
return (updater?: Function) => {
if (updater) {
data = data.updateIn(path, updater)
return
}
return data.getIn(path)
}
}
export default {
notes: createCursor(['notes']),
isLoading: createCursor(['is_loading'])
}<file_sep>/gulpfile.js
var gulp = require('gulp')
var gutil = require('gulp-util')
var webpack = require('webpack')
var webpackConfig = require('./webpack.config.js')
var ts = require('gulp-typescript')
gulp.task('default', ['server:build', 'client:build'])
gulp.task('client:build', function(callback) {
webpack(Object.create(webpackConfig), function(err, stats) {
if(err) throw new gutil.PluginError('client:build', err);
gutil.log('[client:build]', stats.toString({
colors: true
}))
callback();
})
})
gulp.task('client:watch', function(callback) {
var cfg = Object.create(webpackConfig)
cfg.plugins = []
cfg.devtool = 'eval'
cfg.watch = true
cfg.debug = true
webpack(cfg, function(err, stats) {
if(err) throw new gutil.PluginError('client:watch', err);
gutil.log('[client:watch]', stats.toString({
colors: true
}))
})
})
gulp.task('server:build', function () {
return gulp.src([
'src/server/**/*.ts',
'typings/node/node.d.ts',
'typings/mime/mime.d.ts',
'typings/config/config.d.ts',
'typings/express/express.d.ts',
'typings/serve-static/serve-static.d.ts'
])
.pipe(ts({
noImplicitAny: false,
module: 'commonjs'
}))
.pipe(gulp.dest('src/server'))
})
gulp.task('server:watch', function(callback) {
gulp.watch('src/server/**/*.ts', ['server:build'])
})<file_sep>/webpack.config.js
var webpack = require("webpack");
module.exports = {
entry: [
'bootstrap-sass!./bootstrap-sass.config.js',
'./src/client/app.tsx'
],
output: {
path: './build',
filename: 'bundle.js'
},
resolve: {
extensions: ['', '.ts', '.tsx', '.js'],
modulesDirectories: ['node_modules', 'src']
},
module: {
loaders: [
{ test: /\.ts(x?)$/, loader: 'ts-loader' },
{ test: /\.scss$/, loader: "style!css!sass?outputStyle=expanded" },
{ test: /\.css$/, loader: "style-loader!css-loader" },
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&minetype=application/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&minetype=application/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&minetype=application/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&minetype=image/svg+xml" },
{ test: /\.png$/, loader: "url?limit=10000&minetype=image/png" }
]
},
'plugins': [
new webpack.optimize.UglifyJsPlugin()
]
}<file_sep>/src/client/sys/router.ts
let router
export default function() {
return router
}
import {create as RouterCreate} from 'react-router'
import routes from '../routes'
router = RouterCreate({
routes: routes
});<file_sep>/README.md
React simple application
========================
###Tools:
- TypeScript 1.6.2
- React 0.13.3
- React-router 0.13.4
- Flux
- Immutable
###Getting started:
1. `npm install -g gulp`
2. `npm install`
3. `npm run build`
4. `npm run start`
<file_sep>/src/client/sys/store.ts
import Dispatcher from './dispatcher'
export abstract class Store {
public disptachToken: string;
constructor() {
this.disptachToken = Dispatcher.register(this.onDispatch.bind(this))
}
protected abstract onDispatch(action: any)
}<file_sep>/src/client/stores/preloader.ts
import Dispatcher from '../sys/dispatcher'
import {ActionType} from '../const'
import {Store} from '../sys/store'
import State from '../state'
import NotesStore from './notes'
class PreloaderStore extends Store {
public isLoading(): boolean {
return State.isLoading()
}
protected onDispatch(action: any) {
switch (action.type) {
case ActionType.LIST:
case ActionType.ITEM_EDIT:
case ActionType.ITEM_LOAD:
case ActionType.ITEM_ADD:
State.isLoading(() => true)
break
case ActionType.LIST_LOADED:
case ActionType.ITEM_EDITED:
case ActionType.ITEM_LOADED:
case ActionType.ITEM_ADDED:
Dispatcher.waitFor([NotesStore.disptachToken])
State.isLoading(() => false)
break
}
}
}
export default new PreloaderStore()<file_sep>/src/server/server.ts
import * as Express from 'express'
import * as Config from 'config'
import * as path from 'path'
let db = [
'A bro is always allowed to do something stupid as long as his bro’s are doing it.',
'If a Bro, for whatever reason must drive another Bro’s car, he shall not adjust the preprogrammed radio stations.',
'A bro never dances with his hands above his head.',
'If a Bro should fail at anything during sporting activities or games, he is required to make an excuse for himself, it is always the ball, bat, racket, shoes, glove, controller or equipment’s fault.',
'If a Bro lends another Bro a DVD, video game, or piece of lawn machinery, he shall not expect to ever get it back.',
'A bro doesn’t get lost, he merely finds an alternate route.',
'Bros don’t speak French to each other.',
'If a bro wins a trophy that can be in any way used as a cup, he will drink alcohol out of it as soon as possible.',
'If a bro gets a dog, it must be at least as tall as his knee when fully grown.',
'If two Bros get into a heated argument over something and one says something out of line, the other shall not expect him to take it back or apologize.'
]
function getRealId(id: number): number {
return db.length - 1 - id
}
let app = Express()
let cfg = Config.get('Server')
app.use(Express.static(cfg.assets))
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'jade')
app.get('/', (req, res) => {
res.render('index', { title: 'Sample app' })
})
app.post('/notes', (req, res) => {
db.push(req.query.text)
res.json({
result: true,
text: req.query.text
})
})
app.get('/notes', (req, res) => {
res.json(db.reverse())
db.reverse()
})
app.get('/notes/:id', (req, res) => {
let response = { result: false, id: null, text: null }
let id = getRealId(req.params.id)
if (db.length > id) {
response.id = req.params.id
response.text = db[id]
response.result = true
}
res.json(response)
})
app.delete('/notes/:id', (req, res) => {
let response = { result: false }
let id = getRealId(req.params.id)
if (db.length > id) {
db.splice(id, 1)
response.result = true
}
res.json(response)
})
app.put('/notes/:id', (req, res) => {
let response = { result: false }
let id = getRealId(req.params.id)
if (db.length > id) {
db[id] = req.query.text
response.result = true
}
res.json(response)
})
let server = app.listen(cfg.port, cfg.host, () => {
let host = server.address().address
let port = server.address().port
console.log('Server listening at http://%s:%s', host, port)
})
<file_sep>/tsconfig.json
{
"compilerOptions": {
"target": "es5",
"jsx": "react"
},
"files": [
"typings/flux/flux.d.ts",
"typings/react/react.d.ts",
"typings/react-router/react-router.d.ts",
"typings/react-spinkit/react-spinkit.d.ts",
"typings/superagent/superagent.d.ts",
"typings/immutable/immutable.d.ts"
]
}<file_sep>/src/client/actions/notes.ts
import * as request from 'superagent'
import Dispatcher from '../sys/dispatcher'
import {ActionType} from '../const'
import Router from '../sys/router'
export function loadList() {
Dispatcher.dispatch({ type: ActionType.LIST })
request.get('/notes').end((err, res) => {
Dispatcher.dispatch({
type: ActionType.LIST_LOADED,
data: JSON.parse(res.text)
})
Router().refresh()
})
}
export function loadItem(id: number) {
Dispatcher.dispatch({ type: ActionType.ITEM_LOAD })
request.get('/notes/' + id).end((err, res) => {
Dispatcher.dispatch({
type: ActionType.ITEM_LOADED,
data: JSON.parse(res.text)
})
Router().refresh()
})
}
export function deleteItem(id: number) {
request.del('/notes/' + id).end((err, res) => {
let response = JSON.parse(res.text)
if (response.result) {
Dispatcher.dispatch({
type: ActionType.ITEM_REMOVED,
data: {id: id}
})
}
Router().refresh()
})
}
export function editItem(id: number, text: string) {
Dispatcher.dispatch({ type: ActionType.ITEM_EDIT })
request
.put('/notes/' + id)
.query({ text: text })
.end((err, res) => {
let response = JSON.parse(res.text)
if (response.result) {
Dispatcher.dispatch({
type: ActionType.ITEM_EDITED,
data: { id: id, text: text }
})
}
Router().refresh()
})
}
export function addItem(text: string) {
Dispatcher.dispatch({ type: ActionType.ITEM_ADD })
request
.post('/notes')
.query({ text: text })
.end((err, res) => {
Dispatcher.dispatch({
type: ActionType.ITEM_ADDED,
data: JSON.parse(res.text)
})
Router().refresh()
})
}<file_sep>/src/client/const.ts
export enum ActionType {
LIST,
LIST_LOADED,
ITEM_REMOVED,
ITEM_EDIT,
ITEM_EDITED,
ITEM_LOAD,
ITEM_LOADED,
ITEM_ADD,
ITEM_ADDED
}<file_sep>/src/client/stores/notes.ts
import * as Immutable from 'immutable'
import Dispatcher from '../sys/dispatcher'
import {ActionType} from '../const'
import {Store} from '../sys/store'
import State from '../state'
class NotesStore extends Store {
public getAll(): Immutable.List<String> {
return State.notes()
}
public get(id: number): string {
return State.notes().get(id)
}
protected onDispatch(action: any) {
switch (action.type) {
case ActionType.LIST_LOADED:
State.notes(() => {
return Immutable.fromJS(action.data)
})
break
case ActionType.ITEM_LOADED:
if (action.data.result) {
State.notes((current) => {
return current.set(action.data.id, action.data.text)
})
}
break
case ActionType.ITEM_ADDED:
if (action.data.result) {
State.notes((current) => {
return current.unshift(action.data.text)
})
}
break
case ActionType.ITEM_REMOVED:
State.notes((current) => {
return current.delete(action.data.id)
})
break
case ActionType.ITEM_EDITED:
State.notes((current) => {
return current.set(action.data.id, action.data.text)
})
break
}
}
}
export default new NotesStore() | 58a0b2fa45b54d1d9b8cf305bc5b5fb13950464d | [
"JavaScript",
"TypeScript",
"JSON with Comments",
"Markdown"
]
| 12 | TypeScript | alexg-dev/React-simple-app | d256595c653535cb895388d96c86c6d262e413a2 | 498cc32529e8751b6538fe8a9132b4fa4a8ebfed |
refs/heads/master | <repo_name>jdesboeufs/connect-mongo<file_sep>/.github/ISSUE_TEMPLATE.md
- **I'm submitting a ...**
[ ] bug report
[ ] feature request
[ ] question about the decisions made in the repository
[ ] question about how to use this project
- **Summary**
- **Other information** (e.g. detailed explanation, stack traces, related issues, suggestions how to fix, links for us to have context, eg. StackOverflow, personal fork, etc.)
<file_sep>/README.md
# connect-mongo
MongoDB session store for [Connect](https://github.com/senchalabs/connect) and [Express](http://expressjs.com/) written in Typescript.
[](https://www.npmjs.com/package/connect-mongo)
[](https://www.npmjs.com/package/connect-mongo)
[](https://github.com/jdesboeufs/connect-mongo/actions/workflows/sanity.yml)
[](https://coveralls.io/github/jdesboeufs/connect-mongo?branch=master)
> Breaking change in V4 and rewritten the whole project using Typescript. Please checkout the [migration guide](MIGRATION_V4.md) and [changelog](CHANGELOG.md) for details.
- [Install](#install)
- [Compatibility](#compatibility)
- [Usage](#usage)
- [Express or Connect integration](#express-or-connect-integration)
- [Connection to MongoDB](#connection-to-mongodb)
- [Known issues](#known-issues)
- [Native autoRemove causing error on close](#native-autoremove-causing-error-on-close)
- [MongoError exports circular dependency](#mongoerror-exports-circular-dependency)
- [Existing encrypted v3.2.0 sessions are not decrypted correctly by v4](#existing-encrypted-v320-sessions-are-not-decrypted-correctly-by-v4)
- [Events](#events)
- [Session expiration](#session-expiration)
- [Remove expired sessions](#remove-expired-sessions)
- [Set MongoDB to clean expired sessions (default mode)](#set-mongodb-to-clean-expired-sessions-default-mode)
- [Set the compatibility mode](#set-the-compatibility-mode)
- [Disable expired sessions cleaning](#disable-expired-sessions-cleaning)
- [Lazy session update](#lazy-session-update)
- [Transparent encryption/decryption of session data](#transparent-encryptiondecryption-of-session-data)
- [Options](#options)
- [Connection-related options (required)](#connection-related-options-required)
- [More options](#more-options)
- [Crypto-related options](#crypto-related-options)
- [Development](#development)
- [Example application](#example-application)
- [Release](#release)
- [License](#license)
## Install
```
npm install connect-mongo
yarn add connect-mongo
```
* You may also need to run install `mongodb` if you do not have it installed already because `mongodb` is not a `peerDependencies` instead.
* If you are upgrading from v3.x to v4, please checkout the [migration guide](./MIGRATION_V4.md) for details.
* If you are upgrading v4.x to latest version, you may check the [example](./example) and [options](#options) for details.
## Compatibility
* Support Express up to `5.0`
* Support [native MongoDB driver](http://mongodb.github.io/node-mongodb-native/) `>= 5.0`
* Support Node.js 14, 16 and 18
* Support [MongoDB](https://www.mongodb.com/) `3.6+`
For extended compatibility, see previous versions [v3.x](https://github.com/jdesboeufs/connect-mongo/tree/v3.x).
But please note that we are not maintaining v3.x anymore.
## Usage
### Express or Connect integration
Express `4.x`, `5.0` and Connect `3.x`:
```js
const session = require('express-session');
const MongoStore = require('connect-mongo');
app.use(session({
secret: 'foo',
store: MongoStore.create(options)
}));
```
```ts
import session from 'express-session'
import MongoStore from 'connect-mongo'
app.use(session({
secret: 'foo',
store: MongoStore.create(options)
}));
```
### Connection to MongoDB
In many circumstances, `connect-mongo` will not be the only part of your application which need a connection to a MongoDB database. It could be interesting to re-use an existing connection.
Alternatively, you can configure `connect-mongo` to establish a new connection.
#### Create a new connection from a MongoDB connection string
[MongoDB connection strings](http://docs.mongodb.org/manual/reference/connection-string/) are __the best way__ to configure a new connection. For advanced usage, [more options](http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect-options) can be configured with `mongoOptions` property.
```js
// Basic usage
app.use(session({
store: MongoStore.create({ mongoUrl: 'mongodb://localhost/test-app' })
}));
// Advanced usage
app.use(session({
store: MongoStore.create({
mongoUrl: 'mongodb://user12345:foobar@localhost/test-app?authSource=admin&w=1',
mongoOptions: advancedOptions // See below for details
})
}));
```
#### Re-use an existing native MongoDB driver client promise
In this case, you just have to give your `MongoClient` instance to `connect-mongo`.
```js
/*
** There are many ways to create MongoClient.
** You should refer to the driver documentation.
*/
// Database name present in the connection string will be used
app.use(session({
store: MongoStore.create({ clientPromise })
}));
// Explicitly specifying database name
app.use(session({
store: MongoStore.create({
clientPromise,
dbName: 'test-app'
})
}));
```
## Known issues
[Known issues](https://github.com/jdesboeufs/connect-mongo/issues?q=is%3Aopen+is%3Aissue+label%3Abug) in GitHub Issues page.
### Native autoRemove causing error on close
- Calling `close()` immediately after creating the session store may cause error when the async index creation is in process when `autoRemove: 'native'`. You may want to manually manage the autoRemove index. [#413](https://github.com/jdesboeufs/connect-mongo/issues/413)
### MongoError exports circular dependency
The following error can be safely ignored from [official reply](https://developer.mongodb.com/community/forums/t/warning-accessing-non-existent-property-mongoerror-of-module-exports-inside-circular-dependency/15411/5).
```
(node:16580) Warning: Accessing non-existent property 'MongoError' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
```
### Existing encrypted v3.2.0 sessions are not decrypted correctly by v4
v4 cannot decrypt the session encrypted from v3.2 due to a bug. Please take a look on this issue for possible workaround. [#420](https://github.com/jdesboeufs/connect-mongo/issues/420)
## Events
A `MongoStore` instance will emit the following events:
| Event name | Description | Payload
| ----- | ----- | ----- |
| `create` | A session has been created | `sessionId` |
| `touch` | A session has been touched (but not modified) | `sessionId` |
| `update` | A session has been updated | `sessionId` |
| `set` | A session has been created OR updated _(for compatibility purpose)_ | `sessionId` |
| `destroy` | A session has been destroyed manually | `sessionId` |
## Session expiration
When the session cookie has an expiration date, `connect-mongo` will use it.
Otherwise, it will create a new one, using `ttl` option.
```js
app.use(session({
store: MongoStore.create({
mongoUrl: 'mongodb://localhost/test-app',
ttl: 14 * 24 * 60 * 60 // = 14 days. Default
})
}));
```
__Note:__ Each time a user interacts with the server, its session expiration date is refreshed.
## Remove expired sessions
By default, `connect-mongo` uses MongoDB's TTL collection feature (2.2+) to have mongodb automatically remove expired sessions. But you can change this behavior.
### Set MongoDB to clean expired sessions (default mode)
`connect-mongo` will create a TTL index for you at startup. You MUST have MongoDB 2.2+ and administration permissions.
```js
app.use(session({
store: MongoStore.create({
mongoUrl: 'mongodb://localhost/test-app',
autoRemove: 'native' // Default
})
}));
```
__Note:__ If you use `connect-mongo` in a very concurrent environment, you should avoid this mode and prefer setting the index yourself, once!
### Set the compatibility mode
In some cases you can't or don't want to create a TTL index, e.g. Azure Cosmos DB.
`connect-mongo` will take care of removing expired sessions, using defined interval.
```js
app.use(session({
store: MongoStore.create({
mongoUrl: 'mongodb://localhost/test-app',
autoRemove: 'interval',
autoRemoveInterval: 10 // In minutes. Default
})
}));
```
### Disable expired sessions cleaning
You are in production environnement and/or you manage the TTL index elsewhere.
```js
app.use(session({
store: MongoStore.create({
mongoUrl: 'mongodb://localhost/test-app',
autoRemove: 'disabled'
})
}));
```
## Lazy session update
If you are using [express-session](https://github.com/expressjs/session) >= [1.10.0](https://github.com/expressjs/session/releases/tag/v1.10.0) and don't want to resave all the session on database every single time that the user refreshes the page, you can lazy update the session, by limiting a period of time.
```js
app.use(express.session({
secret: 'keyboard cat',
saveUninitialized: false, // don't create session until something stored
resave: false, //don't save session if unmodified
store: MongoStore.create({
mongoUrl: 'mongodb://localhost/test-app',
touchAfter: 24 * 3600 // time period in seconds
})
}));
```
by doing this, setting `touchAfter: 24 * 3600` you are saying to the session be updated only one time in a period of 24 hours, does not matter how many request's are made (with the exception of those that change something on the session data)
## Transparent encryption/decryption of session data
When working with sensitive session data it is [recommended](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md) to use encryption
```js
const store = MongoStore.create({
mongoUrl: 'mongodb://localhost/test-app',
crypto: {
secret: 'squirrel'
}
})
```
## Options
### Connection-related options (required)
One of the following options should be provided. If more than one option are provided, each option will take precedence over others according to priority.
|Priority|Option|Description|
|:------:|------|-----------|
|1|`mongoUrl`|A [connection string](https://docs.mongodb.com/manual/reference/connection-string/) for creating a new MongoClient connection. If database name is not present in the connection string, database name should be provided using `dbName` option. |
|2|`clientPromise`|A Promise that is resolved with MongoClient connection. If the connection was established without database name being present in the connection string, database name should be provided using `dbName` option.|
|3|`client`|An existing MongoClient connection. If the connection was established without database name being present in the connection string, database name should be provided using `dbName` option.|
### More options
|Option|Default|Description|
|------|:-----:|-----------|
|`mongoOptions`|`{ useUnifiedTopology: true }`|Options object for [`MongoClient.connect()`](https://mongodb.github.io/node-mongodb-native/3.3/api/MongoClient.html#.connect) method. Can be used with `mongoUrl` option.|
|`dbName`||A name of database used for storing sessions. Can be used with `mongoUrl`, or `clientPromise` options. Takes precedence over database name present in the connection string.|
|`collectionName`|`'sessions'`|A name of collection used for storing sessions.|
|`ttl`|`1209600`|The maximum lifetime (in seconds) of the session which will be used to set `session.cookie.expires` if it is not yet set. Default is 14 days.|
|`autoRemove`|`'native'`|Behavior for removing expired sessions. Possible values: `'native'`, `'interval'` and `'disabled'`.|
|`autoRemoveInterval`|`10`|Interval (in minutes) used when `autoRemove` option is set to `interval`.|
|`touchAfter`|`0`|Interval (in seconds) between session updates.|
|`stringify`|`true`|If `true`, connect-mongo will serialize sessions using `JSON.stringify` before setting them, and deserialize them with `JSON.parse` when getting them. This is useful if you are using types that MongoDB doesn't support.|
|`serialize`||Custom hook for serializing sessions to MongoDB. This is helpful if you need to modify the session before writing it out.|
|`unserialize`||Custom hook for unserializing sessions from MongoDB. This can be used in scenarios where you need to support different types of serializations (e.g., objects and JSON strings) or need to modify the session before using it in your app.|
|`writeOperationOptions`||Options object to pass to every MongoDB write operation call that supports it (e.g. `update`, `remove`). Useful for adjusting the write concern. Only exception: If `autoRemove` is set to `'interval'`, the write concern from the `writeOperationOptions` object will get overwritten.|
|`transformId`||Transform original `sessionId` in whatever you want to use as storage key.|
|`crypto`||Crypto related options. See below.|
### Crypto-related options
|Option|Default|Description|
|------|:-----:|-----------|
|`secret`|`false`|Enables transparent crypto in accordance with [OWASP session management recommendations](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md).|
|`algorithm`|`'aes-256-gcm'`|Allows for changes to the default symmetric encryption cipher. See [`crypto.getCiphers()`](https://nodejs.org/api/crypto.html#crypto_crypto_getciphers) for supported algorithms.|
|`hashing`|`'sha512'`|May be used to change the default hashing algorithm. See [`crypto.getHashes()`](https://nodejs.org/api/crypto.html#crypto_crypto_gethashes) for supported hashing algorithms.|
|`encodeas`|`'hex'`|Specify to change the session data cipher text encoding.|
|`key_size`|`32`|When using varying algorithms the key size may be used. Default value `32` is based on the `AES` blocksize.|
|`iv_size`|`16`|This can be used to adjust the default [IV](https://csrc.nist.gov/glossary/term/IV) size if a different algorithm requires a different size.|
|`at_size`|`16`|When using newer `AES` modes such as the default `GCM` or `CCM` an authentication tag size can be defined.|
## Development
```
yarn install
docker-compose up -d
# Run these 2 lines in 2 shell
yarn watch:build
yarn watch:test
```
### Example application
```
yarn link
cd example
yarn link "connect-mongo"
yarn install
yarn start
```
### Release
Since I cannot access the setting page. I can only do it manually.
1. Bump version, update `CHANGELOG.md` and README. Commit and push.
2. Run `yarn build && yarn test && npm publish`
3. `git tag vX.Y.Z && git push --tags`
## License
The MIT License
<file_sep>/example/index.js
const express = require('express')
const session = require('express-session')
const MongoStore = require('connect-mongo')
const app = express()
const port = 3000
app.use(session({
secret: 'foo',
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: 'mongodb://root:[email protected]:27017',
dbName: "example-db",
stringify: false,
})
}));
app.get('/', (req, res) => {
req.session.foo = 'test-id'
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
<file_sep>/src/index.ts
import MongoStore from './lib/MongoStore'
export = MongoStore
<file_sep>/src/test/integration.spec.ts
import test from 'ava'
import request from 'supertest'
import express from 'express'
import session, { SessionOptions } from 'express-session'
import MongoStore from '../'
import { ConnectMongoOptions } from '../lib/MongoStore'
declare module 'express-session' {
interface SessionData {
[key: string]: any
}
}
function createSupertetAgent(
sessionOpts: SessionOptions,
mongoStoreOpts: ConnectMongoOptions
) {
const app = express()
const store = MongoStore.create(mongoStoreOpts)
app.use(
session({
...sessionOpts,
store: store,
})
)
app.get('/', function (req, res) {
if (typeof req.session.views === 'number') {
req.session.views++
} else {
req.session.views = 0
}
res.status(200).send({ views: req.session.views })
})
app.get('/ping', function (req, res) {
res.status(200).send({ views: req.session.views })
})
const agent = request.agent(app)
return agent
}
function createSupertetAgentWithDefault(
sessionOpts: Omit<SessionOptions, 'secret'> = {},
mongoStoreOpts: ConnectMongoOptions = {}
) {
return createSupertetAgent(
{ secret: 'foo', ...sessionOpts },
{
mongoUrl: 'mongodb://root:[email protected]:27017',
dbName: 'itegration-test-db',
stringify: false,
...mongoStoreOpts,
}
)
}
test.serial.cb('simple case', (t) => {
const agent = createSupertetAgentWithDefault()
agent
.get('/')
.expect(200)
.then((response) => response.headers['set-cookie'])
.then((cookie) => {
agent
.get('/')
.expect(200)
.end((err, res) => {
t.is(err, null)
t.deepEqual(res.body, { views: 1 })
return t.end()
})
})
})
test.serial.cb('simple case with touch after', (t) => {
const agent = createSupertetAgentWithDefault(
{ resave: false, saveUninitialized: false, rolling: true },
{ touchAfter: 1 }
)
agent
.get('/')
.expect(200)
.then(() => {
agent
.get('/')
.expect(200)
.end((err, res) => {
t.is(err, null)
t.deepEqual(res.body, { views: 1 })
new Promise<void>((resolve) => {
setTimeout(() => {
resolve()
}, 1200)
}).then(() => {
agent
.get('/ping')
.expect(200)
.end((err, res) => {
t.is(err, null)
t.deepEqual(res.body, { views: 1 })
return t.end()
})
})
})
})
})
<file_sep>/.github/CONTRIBUTING.md
# Example Contributing Guidelines
This is an example of GitHub's contributing guidelines file. Check out GitHub's [CONTRIBUTING.md help center article](https://help.github.com/articles/setting-guidelines-for-repository-contributors/) for more information.
<file_sep>/MIGRATION_V4.md
# V4 migration guide
To migrate the library from V3 to V4, re-install the dependencies.
If you are using `npm`
```
npm uninstall connect-mongo
npm uninstall @types/connect-mongo
npm install connect-mongo
```
If you are using `yarn`
```
yarn remove connect-mongo
yarn remove @types/connect-mongo
yarn add connect-mongo
```
Next step is to import the dependencies
Javascript:
```js
const MongoStore = require('connect-mongo');
```
Typescript:
```ts
import MongoStore from 'connect-mongo';
```
Create the store using `MongoStore.create(options)` instead of `new MongoStore(options)`
```js
app.use(session({
secret: 'foo',
store: MongoStore.create(options)
}));
```
For the options, you should make the following changes:
* Change `url` to `mongoUrl`
* Change `collection` to `collectionName` if you are using it
* Keep `clientPromise` if you are using it
* `mongooseConnection` has been removed. Please update your application code to use either `mongoUrl`, `client` or `clientPromise`
* To reuse an existing mongoose connection retreive the mongoDb driver from you mongoose connection using `Connection.prototype.getClient()` and pass it to the store in the `client`-option.
* Remove `fallbackMemory` option and if you are using it, you can import from:
```js
const session = require('express-session');
app.use(session({
store: isDev ? new session.MemoryStore() : MongoStore.create(options)
}));
```
> You can also take a look at [example](example) directory for example usage.
<file_sep>/example/ts-example.ts
import express from 'express'
import session from 'express-session'
import MongoStore from 'connect-mongo'
const app = express()
const port = 3000
declare module 'express-session' {
interface SessionData {
foo: string
}
}
app.use(session({
secret: 'foo',
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: 'mongodb://root:[email protected]:27017',
dbName: "example-db",
stringify: false,
})
}));
app.get('/', (req, res) => {
req.session.foo = 'test-id'
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
<file_sep>/src/test/testHelper.ts
// eslint-disable-next-line eslint-comments/disable-enable-pair
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import util from 'util'
import ExpressSession from 'express-session'
import MongoStore, { ConnectMongoOptions } from '../lib/MongoStore'
// Create a connect cookie instance
export const makeCookie = () => {
const cookie = new ExpressSession.Cookie()
cookie.maxAge = 10000 // This sets cookie.expire through a setter
cookie.secure = true
cookie.domain = 'cow.com'
cookie.sameSite = false
return cookie
}
// Create session data
export const makeData = () => {
return {
foo: 'bar',
baz: {
cow: 'moo',
chicken: 'cluck',
},
num: 1,
cookie: makeCookie(),
}
}
export const makeDataNoCookie = () => {
return {
foo: 'bar',
baz: {
cow: 'moo',
fish: 'blub',
fox: 'nobody knows!',
},
num: 2,
}
}
export const createStoreHelper = (opt: Partial<ConnectMongoOptions> = {}) => {
const store = MongoStore.create({
mongoUrl: 'mongodb://root:[email protected]:27017',
mongoOptions: {},
dbName: 'testDb',
collectionName: 'test-collection',
...opt,
})
const storePromise = {
length: util.promisify(store.length).bind(store),
clear: util.promisify(store.clear).bind(store),
get: util.promisify(store.get).bind(store),
set: util.promisify(store.set).bind(store),
all: util.promisify(store.all).bind(store),
touch: util.promisify(store.touch).bind(store),
destroy: util.promisify(store.destroy).bind(store),
close: store.close.bind(store),
}
return { store, storePromise }
}
<file_sep>/src/lib/MongoStore.spec.ts
import test from 'ava'
import { SessionData } from 'express-session'
import { MongoClient } from 'mongodb'
import MongoStore from './MongoStore'
import {
createStoreHelper,
makeData,
makeDataNoCookie,
} from '../test/testHelper'
let { store, storePromise } = createStoreHelper()
test.before(async () => {
await storePromise.clear().catch((err) => {
if (err.message.match(/ns not found/)) {
return null
} else {
throw err
}
})
})
test.afterEach.always(async () => {
await storePromise.close()
})
test.serial('create store w/o provide required options', (t) => {
t.throws(() => MongoStore.create({}), {
message: /Cannot init client/,
})
})
test.serial('create store with clientPromise', async (t) => {
const clientP = MongoClient.connect('mongodb://root:[email protected]:27017')
const store = MongoStore.create({ clientPromise: clientP })
t.not(store, null)
t.not(store, undefined)
await store.collectionP
store.close()
})
test.serial('create store with client', async (t) => {
const client = await MongoClient.connect(
'mongodb://root:[email protected]:27017'
)
const store = MongoStore.create({ client: client })
t.not(store, null)
t.not(store, undefined)
await store.collectionP
store.close()
})
test.serial('length should be 0', async (t) => {
;({ store, storePromise } = createStoreHelper())
const length = await storePromise.length()
t.is(length, 0)
})
test.serial('get non-exist session should throw error', async (t) => {
;({ store, storePromise } = createStoreHelper())
const res = await storePromise.get('fake-sid')
t.is(res, null)
})
test.serial('get all session should work for no session', async (t) => {
;({ store, storePromise } = createStoreHelper())
const allSessions = await storePromise.all()
t.deepEqual(allSessions, [])
})
test.serial('basic operation flow', async (t) => {
;({ store, storePromise } = createStoreHelper())
let orgSession = makeData()
const sid = 'test-basic-flow'
const res = await storePromise.set(sid, orgSession)
t.is(res, undefined)
const session = await storePromise.get(sid)
t.is(typeof session, 'object')
orgSession = JSON.parse(JSON.stringify(orgSession))
t.deepEqual(session, orgSession)
const allSessions = await storePromise.all()
t.deepEqual(allSessions, [orgSession])
t.is(await storePromise.length(), 1)
const err = await storePromise.destroy(sid)
t.is(err, undefined)
t.is(await storePromise.length(), 0)
})
test.serial.cb('set and listen to event', (t) => {
;({ store, storePromise } = createStoreHelper())
let orgSession = makeData()
const sid = 'test-set-event'
store.set(sid, orgSession)
orgSession = JSON.parse(JSON.stringify(orgSession))
store.on('set', (sessionId) => {
t.is(sessionId, sid)
store.get(sid, (err, session) => {
t.is(err, null)
t.is(typeof session, 'object')
t.deepEqual(session, orgSession)
t.end()
})
})
})
test.serial.cb('set and listen to create event', (t) => {
;({ store, storePromise } = createStoreHelper())
const orgSession = makeData()
const sid = 'test-create-event'
store.set(sid, orgSession)
store.on('create', (sessionId) => {
t.is(sessionId, sid)
t.end()
})
})
test.serial.cb('set and listen to update event', (t) => {
;({ store, storePromise } = createStoreHelper())
const orgSession = makeData()
const sid = 'test-update-event'
store.set(sid, orgSession)
store.set(sid, { ...orgSession, foo: 'new-bar' } as SessionData)
store.on('update', (sessionId) => {
t.is(sessionId, sid)
t.end()
})
})
test.serial('set with no stringify', async (t) => {
;({ store, storePromise } = createStoreHelper({ stringify: false }))
const orgSession = makeData()
const cookie = orgSession.cookie
const sid = 'test-no-stringify'
const res = await storePromise.set(sid, orgSession)
t.is(res, undefined)
const session = await storePromise.get(sid)
t.is(typeof session, 'object')
t.deepEqual(orgSession.cookie, cookie)
// @ts-ignore
t.deepEqual(cookie.expires.toJSON(), session.cookie.expires.toJSON())
// @ts-ignore
t.deepEqual(cookie.secure, session.cookie.secure)
const err = await storePromise.clear()
t.is(err, undefined)
t.is(await storePromise.length(), 0)
})
test.serial.cb('test destory event', (t) => {
;({ store, storePromise } = createStoreHelper())
const orgSession = makeData()
const sid = 'test-destory-event'
store.on('destroy', (sessionId) => {
t.is(sessionId, sid)
t.end()
})
storePromise.set(sid, orgSession).then(() => {
store.destroy(sid)
})
})
test.serial('test set default TTL', async (t) => {
const defaultTTL = 10
;({ store, storePromise } = createStoreHelper({
ttl: defaultTTL,
}))
const orgSession = makeDataNoCookie()
const sid = 'test-set-default-ttl'
const timeBeforeSet = new Date().valueOf()
// @ts-ignore
await storePromise.set(sid, orgSession)
const collection = await store.collectionP
const session = await collection.findOne({ _id: sid })
const timeAfterSet = new Date().valueOf()
const expires = session?.expires?.valueOf()
t.truthy(expires)
if (expires) {
t.truthy(timeBeforeSet + defaultTTL * 1000 <= expires)
t.truthy(expires <= timeAfterSet + defaultTTL * 1000)
}
})
test.serial('test default TTL', async (t) => {
const defaultExpirationTime = 1000 * 60 * 60 * 24 * 14
;({ store, storePromise } = createStoreHelper())
const orgSession = makeDataNoCookie()
const sid = 'test-no-set-default-ttl'
const timeBeforeSet = new Date().valueOf()
// @ts-ignore
await storePromise.set(sid, orgSession)
const collection = await store.collectionP
const session = await collection.findOne({ _id: sid })
const timeAfterSet = new Date().valueOf()
const expires = session?.expires?.valueOf()
t.truthy(expires)
if (expires) {
t.truthy(timeBeforeSet + defaultExpirationTime <= expires)
t.truthy(expires <= timeAfterSet + defaultExpirationTime)
}
})
test.serial('test custom serializer', async (t) => {
;({ store, storePromise } = createStoreHelper({
serialize: (obj) => {
obj.ice = 'test-ice-serializer'
return JSON.stringify(obj)
},
}))
const orgSession = makeData()
const sid = 'test-custom-serializer'
await storePromise.set(sid, orgSession)
const session = await storePromise.get(sid)
t.is(typeof session, 'string')
t.not(session, undefined)
// @ts-ignore
orgSession.ice = 'test-ice-serializer'
// @ts-ignore
t.is(session, JSON.stringify(orgSession))
})
test.serial('test custom deserializer', async (t) => {
;({ store, storePromise } = createStoreHelper({
unserialize: (obj) => {
obj.ice = 'test-ice-deserializer'
return obj
},
}))
const orgSession = makeData()
const sid = 'test-custom-deserializer'
await storePromise.set(sid, orgSession)
const session = await storePromise.get(sid)
t.is(typeof session, 'object')
// @ts-ignore
orgSession.cookie = orgSession.cookie.toJSON()
// @ts-ignore
orgSession.ice = 'test-ice-deserializer'
t.not(session, undefined)
t.deepEqual(session, orgSession)
})
test.serial('touch ops', async (t) => {
;({ store, storePromise } = createStoreHelper())
const orgSession = makeDataNoCookie()
const sid = 'test-touch'
// @ts-ignore
await storePromise.set(sid, orgSession)
const collection = await store.collectionP
const session = await collection.findOne({ _id: sid })
await new Promise((resolve) => setTimeout(resolve, 500))
t.not(session, undefined)
await storePromise.touch(sid, session?.session)
const session2 = await collection.findOne({ _id: sid })
t.not(session2, undefined)
// Check if both expiry date are different
t.truthy(session2?.expires?.getTime())
t.truthy(session?.expires?.getTime())
if (session?.expires?.getTime() && session2?.expires?.getTime()) {
t.truthy(session2?.expires.getTime() > session?.expires.getTime())
}
})
test.serial('touch ops with touchAfter', async (t) => {
;({ store, storePromise } = createStoreHelper({ touchAfter: 1 }))
const orgSession = makeDataNoCookie()
const sid = 'test-touch-with-touchAfter'
// @ts-ignore
await storePromise.set(sid, orgSession)
const collection = await store.collectionP
const session = await collection.findOne({ _id: sid })
const lastModifiedBeforeTouch = session?.lastModified?.getTime()
t.not(session, undefined)
await storePromise.touch(sid, session as unknown as SessionData)
const session2 = await collection.findOne({ _id: sid })
t.not(session2, undefined)
const lastModifiedAfterTouch = session2?.lastModified?.getTime()
// Check if both expiry date are different
t.is(lastModifiedBeforeTouch, lastModifiedAfterTouch)
})
test.serial('touch ops with touchAfter with touch', async (t) => {
;({ store, storePromise } = createStoreHelper({ touchAfter: 1 }))
const orgSession = makeDataNoCookie()
const sid = 'test-touch-with-touchAfter-should-touch'
// @ts-ignore
await storePromise.set(sid, orgSession)
const collection = await store.collectionP
const session = await collection.findOne({ _id: sid })
const lastModifiedBeforeTouch = session?.lastModified?.getTime()
await new Promise((resolve) => setTimeout(resolve, 1200))
t.not(session, undefined)
await storePromise.touch(sid, session as unknown as SessionData)
const session2 = await collection.findOne({ _id: sid })
t.not(session2, undefined)
const lastModifiedAfterTouch = session2?.lastModified?.getTime()
// Check if both expiry date are different
t.truthy(lastModifiedAfterTouch)
t.truthy(lastModifiedBeforeTouch)
if (lastModifiedAfterTouch && lastModifiedBeforeTouch) {
t.truthy(lastModifiedAfterTouch > lastModifiedBeforeTouch)
}
})
test.serial('basic operation flow with crypto', async (t) => {
;({ store, storePromise } = createStoreHelper({
crypto: { secret: 'secret' },
collectionName: 'crypto-test',
autoRemove: 'disabled',
}))
let orgSession = makeData()
const sid = 'test-basic-flow-with-crypto'
const res = await storePromise.set(sid, orgSession)
t.is(res, undefined)
const session = await storePromise.get(sid)
orgSession = JSON.parse(JSON.stringify(orgSession))
// @ts-ignore
t.deepEqual(session, orgSession)
const sessions = await storePromise.all()
t.not(sessions, undefined)
t.not(sessions, null)
t.is(sessions?.length, 1)
})
test.serial('with touch after and get non-exist session', async (t) => {
;({ store, storePromise } = createStoreHelper({
touchAfter: 10,
}))
const sid = 'fake-sid-for-test-touch-after'
const res = await storePromise.get(sid)
t.is(res, null)
})
<file_sep>/example/mongoose-multiple-connections.js
const express = require('express')
const mongoose = require('mongoose')
const session = require('express-session')
const MongoStore = require('connect-mongo')
// App Init
const app = express()
const port = 3000
// Starting Server
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
// Mongoose Connection
const appDBConnection = mongoose
.createConnection('mongodb://root:[email protected]:27017', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then((connection) => {
console.log('Connected to AppDB.')
return connection
})
const sessionDBConnection = mongoose
.createConnection('mongodb://root:[email protected]:27017', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then((connection) => {
console.log('Connected to SessionsDB.')
return connection
})
// Session Init
const sessionInit = (client) => {
app.use(
session({
store: MongoStore.create({
client: client,
mongoOptions: {
useNewUrlParser: true,
useUnifiedTopology: true,
},
}),
secret: 'hello',
resave: false,
saveUninitialized: false,
cookie: { maxAge: 24 * 60 * 60 * 1000 },
})
)
}
// Router Init
const router = express.Router()
router.get('', (req, res) => {
req.session.foo = 'bar'
res.send('Session Updated')
})
(async function () {
const connection = await sessionDBConnection
const mongoClient = connection.getClient()
sessionInit(mongoClient)
app.use('/', router)
})()
<file_sep>/CHANGELOG.md
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Changed
- Upgrade dependency
## [5.0.0] - 2023-03-14
### **BREAKING CHANGES**
- Upgraded peer dependency `mongodb` to 5.0.0
- Change `engines` to require Node 12.9 or newer, matching the upgrade to `mongodb` that occurred in `v4.5.0`
### Fixed
- Declare `express-session` as a peer dependency.
## [4.6.0] - 2021-09-17
### Changed
- Moved `mongodb` to a peer dependency (and also as a dev dependency for `connect-mongo` developers). `connect-mongo` is no longer pinned to a specific version of `mongodb`. This allows end users to avoid errors due to Typescript definition changes when moving to new versions of `mongodb`. Users can use any version of `mongodb` that provides a compatible (non-breaking) interface to `mongodb ^4.1.0`. Tested on `mongodb` `4.1.0` and `4.1.1`. Should fix: [#433](https://github.com/jdesboeufs/connect-mongo/issues/433) [#434](https://github.com/jdesboeufs/connect-mongo/issues/434) [#436](https://github.com/jdesboeufs/connect-mongo/issues/436)
### Fixed
- Fixed "Callback was already called" when some code throws immediately after calling the set function
## [4.5.0] - 2021-08-17
### **BREAKING CHANGES**
- Drop Node 10 support
### Changed
- Upgrade `mongodb` to V4 [#422] [#426]
### Fixed
- Move `writeConcern` away from top-level option to fix deprecation warning [#422](https://github.com/jdesboeufs/connect-mongo/issues/422)
## [4.4.1] - 2021-03-23
### Fixed
- `store.all()` method not working with encrypted store [#410](https://github.com/jdesboeufs/connect-mongo/issues/410) [#411](https://github.com/jdesboeufs/connect-mongo/issues/411)
- Update and unpin `mongodb` dependency due to upstream fix has been deployed [#409](https://github.com/jdesboeufs/connect-mongo/issues/409)
## [4.4.0] - 2021-03-11
### **BREAKING CHANGES**
- Use `export =` for better cjs require without `.default`
### Added
- Add typescript example
## [4.3.1] - 2021-03-09
### Fixed
- Fix incorrect assertion checking after adding `client` options
## [4.3.0] - 2021-03-08
### Added
- Add `client` option for non-promise client
## [4.2.2] - 2021-03-02
### Fixed
- Fix crypto parsing error by upgrading `kruptein` to `v3.0.0` and change encodeas to `base64`
## [4.2.0] - 2021-02-24
### Added
- Added mongoose example
- Revert `createAutoRemoveIdx` and add back `autoRemove` and `autoRemoveInterval`
### Fixed
- Use `matchedCount` instead of `modifiedCount` to avoid throwing exceptions when nothing to modify [#390](https://github.com/jdesboeufs/connect-mongo/issues/390)
- Fixed `Warning: Accessing non-existent property 'MongoError' of module exports inside circular dependency` by downgrade to `[email protected]`
- Revert update session when touch #351
- Fix cannot read property `lastModified` of null
- Fix TS typing error
## [4.1.0] - 2021-02-22
### **BREAKING CHANGES**
- Support Node.Js 10.x, 12.x and 14.x and drop older support.
- Review method to connect to MongoDB and keep only `mongoUrl` and `clientPromise` options.
- Remove the "Remove expired sessions compatibility mode". Now library user can choose to create auto remove index on startup or not.
- Remove `fallbackMemory` options.
- Rewrite the library and test case using typescript.
> Checkout the complete [migration guide](MIGRATION_V4.md) for more details.
## [3.2.0] - 2019-11-29
### Added
- Add dbName option (#343)
### Fixed
- Add missing `secret` option to TS definition (#342)
## [3.1.2] - 2019-11-01
### Fixed
- Add @types/ dev dependencies for tsc. fixes #340 (#341)
## [3.1.1] - 2019-10-30
### Added
- Add TS type definition
## [3.1.0] - 2019-10-23
### Added
- Added `useUnifiedTopology=true` to mongo options
### Changed
- Refactor merge config logic
- chore: update depns (#326)
## [3.0.0] - 2019-06-17
### **BREAKING CHANGES**
- Drop Node.js 4 & 6 support
- Upgrade `mongoose` to v5 and `mongodb` to v3 and drop old version support
- Replace deprecated mongo operation
- MongoStore need to supply client/clientPromise instead of db/dbPromise due to depns upgrade
## Added
- Add Node.js 10 & 12 support
- Implement store.all function (#291)
- Add option `writeOperationOptions` (#295)
- Add Transparent crypto support (#314)
## Changed
* Change test framework from Mocha to Jest
* Change linter from `xo` to `eslint`
## [2.0.3] - 2018-12-03
## Fixed
- Fixed interval autoremove mode to use current date with every interval (#304, #305) (jlampise)
## [2.0.2] - 2018-11-20
## Fixed
- Fxi #300 DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead
- Fxi #297 DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead
## [2.0.1] - 2018-01-04
## Fixed
- Fixed #271 TypeError: cb is not a function (brainthinks)
## [2.0.0] - 2017-10-09
### **BREAKING CHANGES**
* __Drop__ Node.js 0.12 and io.js support
* __Drop__ MongoDB 2.x support
* __Drop__ mongodb driver < 2.0.36 support
* __Drop__ mongoose < 4.1.2 support
## Changed
* __Fix__ `ensureIndex` deprecation warning ([#268](https://github.com/jdesboeufs/connect-mongo/issues/268), [#269](https://github.com/jdesboeufs/connect-mongo/pulls/269), [#270](https://github.com/jdesboeufs/connect-mongo/pulls/270))
* Improve `get()` ([#246](https://github.com/jdesboeufs/connect-mongo/pulls/246))
* Pass session in `touch` event
* Remove `bluebird` from dependencies
<!-- Legacy changelog format -->
1.3.2 / 2016-07-27
=================
* __Fix__ #228 Broken with [email protected]
1.3.1 / 2016-07-23
=================
* Restrict `bluebird` accepted versions to 3.x
1.3.0 / 2016-07-23
=================
* __Add__ `create` and `update` events ([#215](https://github.com/jdesboeufs/connect-mongo/issues/215))
* Extend `mongodb` compatibility to `2.x`
1.2.1 / 2016-06-20
=================
* __Fix__ bluebird warning (Awk34)
1.2.0 / 2016-05-13
=================
* Accept `dbPromise` as connection param
* __Add__ `close()` method to close current connection
1.1.0 / 2015-12-24
=================
* Support mongodb `2.1.x`
1.0.2 / 2015-12-18
=================
* Enforce entry-points
1.0.1 / 2015-12-17
=================
* __Fix__ entry-point
1.0.0 (deprecated) / 2015-12-17
==================
__Breaking changes:__
* __For older Node.js version (`< 4.0`), the module must be loaded using `require('connect-mongo/es5')`__
* __Drop__ `hash` option (advanced)
__Others changes:__
* __Add__ `transformId` option to allow custom transformation on session id (advanced)
* __Rewrite in ES6__ (w/ fallback)
* Update dependencies
* Improve compatibility
0.8.2 / 2015-07-14
==================
* Bug fixes and improvements (whitef0x0, TimothyGu, behcet-li)
0.8.1 / 2015-04-21
==================
* __Fix__ initialization when a connecting `mongodb` `2.0.x` instance is given (1999)
0.8.0 / 2015-03-24
==================
* __Add__ `touchAfter` option to enable lazy update behavior on `touch()` method (rafaelcardoso)
* __Add__ `fallbackMemory` option to switch to `MemoryStore` in some case.
0.7.0 / 2015-01-24
==================
* __Add__ `touch()` method to be fully compliant with `express-session` `>= 1.10` (rafaelcardoso)
0.6.0 / 2015-01-12
==================
* __Add__ `ttl` option
* __Add__ `autoRemove` option
* __Deprecate__ `defaultExpirationTime` option. Use `ttl` instead (in seconds)
0.5.3 / 2014-12-30
==================
* Make callbacks optional
0.5.2 / 2014-12-29
==================
* Extend compatibility to `mongodb` `2.0.x`
0.5.1 / 2014-12-28
==================
* [bugfix] #143 Missing Sessions from DB should still make callback (brekkehj)
0.5.0 (deprecated) / 2014-12-25
==================
* Accept full-featured [MongoDB connection strings](http://docs.mongodb.org/manual/reference/connection-string/) as `url` + [advanced options](http://mongodb.github.io/node-mongodb-native/1.4/driver-articles/mongoclient.html)
* Re-use existing or upcoming mongoose connection
* [DEPRECATED] `mongoose_connection` is renamed `mongooseConnection`
* [DEPRECATED] `auto_reconnect` is renamed `autoReconnect`
* [BREAKING] `autoReconnect` option is now `true` by default
* [BREAKING] Insert `collection` option in `url` in not possible any more
* [BREAKING] Replace for-testing-purpose `callback` by `connected` event
* Add debug (use with `DEBUG=connect-mongo`)
* Improve error management
* Compatibility with `mongodb` `>= 1.2.0` and `< 2.0.0`
* Fix many bugs
0.4.2 / 2014-12-18
==================
* Bumped mongodb version from 1.3.x to 1.4.x (B0k0)
* Add `sid` hash capability (ZheFeng)
* Add `serialize` and `unserialize` options (ksheedlo)
0.3.3 / 2013-07-04
==================
* Merged a change which reduces data duplication
0.3.0 / 2013-01-20
==================
* Merged several changes by <NAME>, including Write Concern support
* Updated to `mongodb` version 1.2
0.2.0 / 2012-09-09
==================
* Integrated pull request for `mongoose_connection` option
* Move to mongodb 1.0.x
0.1.5 / 2010-07-07
==================
* Made collection setup more robust to avoid race condition
0.1.4 / 2010-06-28
==================
* Added session expiry
0.1.3 / 2010-06-27
==================
* Added url support
0.1.2 / 2010-05-18
==================
* Added auto_reconnect option
0.1.1 / 2010-03-18
==================
* Fixed authentication
0.1.0 / 2010-03-08
==================
* Initial release
<file_sep>/src/types/kruptein.d.ts
/**
* If you import a dependency which does not include its own type definitions,
* TypeScript will try to find a definition for it by following the `typeRoots`
* compiler option in tsconfig.json. For this project, we've configured it to
* fall back to this folder if nothing is found in node_modules/@types.
*
* Often, you can install the DefinitelyTyped
* (https://github.com/DefinitelyTyped/DefinitelyTyped) type definition for the
* dependency in question. However, if no one has yet contributed definitions
* for the package, you may want to declare your own. (If you're using the
* `noImplicitAny` compiler options, you'll be required to declare it.)
*
* This is an example type definition which allows import from `module-name`,
* e.g.:
* ```ts
* import something from 'module-name';
* something();
* ```
*/
declare module 'kruptein' {
type Callback = (msg?: string, data?: string) => void
class Kruptein {
public set(
secret: string,
plaintext: string | any,
callback: Callback
): void
public get(secret: string, ciphertext: string, callback: Callback): void
}
export = Kruptein
}
<file_sep>/src/lib/MongoStore.ts
import { assert } from 'console'
import util from 'util'
import * as session from 'express-session'
import {
Collection,
MongoClient,
MongoClientOptions,
WriteConcernSettings,
} from 'mongodb'
import Debug from 'debug'
import Kruptein from 'kruptein'
const debug = Debug('connect-mongo')
export type CryptoOptions = {
secret: false | string
algorithm?: string
hashing?: string
encodeas?: string
key_size?: number
iv_size?: number
at_size?: number
}
export type ConnectMongoOptions = {
mongoUrl?: string
clientPromise?: Promise<MongoClient>
client?: MongoClient
collectionName?: string
mongoOptions?: MongoClientOptions
dbName?: string
ttl?: number
touchAfter?: number
stringify?: boolean
createAutoRemoveIdx?: boolean
autoRemove?: 'native' | 'interval' | 'disabled'
autoRemoveInterval?: number
// FIXME: remove those any
serialize?: (a: any) => any
unserialize?: (a: any) => any
writeOperationOptions?: WriteConcernSettings
transformId?: (a: any) => any
crypto?: CryptoOptions
}
type ConcretCryptoOptions = Required<CryptoOptions>
type ConcretConnectMongoOptions = {
mongoUrl?: string
clientPromise?: Promise<MongoClient>
client?: MongoClient
collectionName: string
mongoOptions: MongoClientOptions
dbName?: string
ttl: number
createAutoRemoveIdx?: boolean
autoRemove: 'native' | 'interval' | 'disabled'
autoRemoveInterval: number
touchAfter: number
stringify: boolean
// FIXME: remove those any
serialize?: (a: any) => any
unserialize?: (a: any) => any
writeOperationOptions?: WriteConcernSettings
transformId?: (a: any) => any
// FIXME: remove above any
crypto: ConcretCryptoOptions
}
type InternalSessionType = {
_id: string
session: any
expires?: Date
lastModified?: Date
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {}
const unit: <T>(a: T) => T = (a) => a
function defaultSerializeFunction(
session: session.SessionData
): session.SessionData {
// Copy each property of the session to a new object
const obj = {}
let prop
for (prop in session) {
if (prop === 'cookie') {
// Convert the cookie instance to an object, if possible
// This gets rid of the duplicate object under session.cookie.data property
// @ts-ignore FIXME:
obj.cookie = session.cookie.toJSON
? // @ts-ignore FIXME:
session.cookie.toJSON()
: session.cookie
} else {
// @ts-ignore FIXME:
obj[prop] = session[prop]
}
}
return obj as session.SessionData
}
function computeTransformFunctions(options: ConcretConnectMongoOptions) {
if (options.serialize || options.unserialize) {
return {
serialize: options.serialize || defaultSerializeFunction,
unserialize: options.unserialize || unit,
}
}
if (options.stringify === false) {
return {
serialize: defaultSerializeFunction,
unserialize: unit,
}
}
// Default case
return {
serialize: JSON.stringify,
unserialize: JSON.parse,
}
}
export default class MongoStore extends session.Store {
private clientP: Promise<MongoClient>
private crypto: Kruptein | null = null
private timer?: NodeJS.Timeout
collectionP: Promise<Collection<InternalSessionType>>
private options: ConcretConnectMongoOptions
// FIXME: remvoe any
private transformFunctions: {
serialize: (a: any) => any
unserialize: (a: any) => any
}
constructor({
collectionName = 'sessions',
ttl = 1209600,
mongoOptions = {},
autoRemove = 'native',
autoRemoveInterval = 10,
touchAfter = 0,
stringify = true,
crypto,
...required
}: ConnectMongoOptions) {
super()
debug('create MongoStore instance')
const options: ConcretConnectMongoOptions = {
collectionName,
ttl,
mongoOptions,
autoRemove,
autoRemoveInterval,
touchAfter,
stringify,
crypto: {
...{
secret: false,
algorithm: 'aes-256-gcm',
hashing: 'sha512',
encodeas: 'base64',
key_size: 32,
iv_size: 16,
at_size: 16,
},
...crypto,
},
...required,
}
// Check params
assert(
options.mongoUrl || options.clientPromise || options.client,
'You must provide either mongoUrl|clientPromise|client in options'
)
assert(
options.createAutoRemoveIdx === null ||
options.createAutoRemoveIdx === undefined,
'options.createAutoRemoveIdx has been reverted to autoRemove and autoRemoveInterval'
)
assert(
!options.autoRemoveInterval || options.autoRemoveInterval <= 71582,
/* (Math.pow(2, 32) - 1) / (1000 * 60) */ 'autoRemoveInterval is too large. options.autoRemoveInterval is in minutes but not seconds nor mills'
)
this.transformFunctions = computeTransformFunctions(options)
let _clientP: Promise<MongoClient>
if (options.mongoUrl) {
_clientP = MongoClient.connect(options.mongoUrl, options.mongoOptions)
} else if (options.clientPromise) {
_clientP = options.clientPromise
} else if (options.client) {
_clientP = Promise.resolve(options.client)
} else {
throw new Error('Cannot init client. Please provide correct options')
}
assert(!!_clientP, 'Client is null|undefined')
this.clientP = _clientP
this.options = options
this.collectionP = _clientP.then(async (con) => {
const collection = con
.db(options.dbName)
.collection<InternalSessionType>(options.collectionName)
await this.setAutoRemove(collection)
return collection
})
if (options.crypto.secret) {
this.crypto = require('kruptein')(options.crypto)
}
}
static create(options: ConnectMongoOptions): MongoStore {
return new MongoStore(options)
}
private setAutoRemove(
collection: Collection<InternalSessionType>
): Promise<unknown> {
const removeQuery = () => ({
expires: {
$lt: new Date(),
},
})
switch (this.options.autoRemove) {
case 'native':
debug('Creating MongoDB TTL index')
return collection.createIndex(
{ expires: 1 },
{
background: true,
expireAfterSeconds: 0,
}
)
case 'interval':
debug('create Timer to remove expired sessions')
this.timer = setInterval(
() =>
collection.deleteMany(removeQuery(), {
writeConcern: {
w: 0,
j: false,
},
}),
this.options.autoRemoveInterval * 1000 * 60
)
this.timer.unref()
return Promise.resolve()
case 'disabled':
default:
return Promise.resolve()
}
}
private computeStorageId(sessionId: string) {
if (
this.options.transformId &&
typeof this.options.transformId === 'function'
) {
return this.options.transformId(sessionId)
}
return sessionId
}
/**
* promisify and bind the `this.crypto.get` function.
* Please check !!this.crypto === true before using this getter!
*/
private get cryptoGet() {
if (!this.crypto) {
throw new Error('Check this.crypto before calling this.cryptoGet!')
}
return util.promisify(this.crypto.get).bind(this.crypto)
}
/**
* Decrypt given session data
* @param session session data to be decrypt. Mutate the input session.
*/
private async decryptSession(
session: session.SessionData | undefined | null
) {
if (this.crypto && session) {
const plaintext = await this.cryptoGet(
this.options.crypto.secret as string,
session.session
).catch((err) => {
throw new Error(err)
})
// @ts-ignore
session.session = JSON.parse(plaintext)
}
}
/**
* Get a session from the store given a session ID (sid)
* @param sid session ID
*/
get(
sid: string,
callback: (err: any, session?: session.SessionData | null) => void
): void {
;(async () => {
try {
debug(`MongoStore#get=${sid}`)
const collection = await this.collectionP
const session = await collection.findOne({
_id: this.computeStorageId(sid),
$or: [
{ expires: { $exists: false } },
{ expires: { $gt: new Date() } },
],
})
if (this.crypto && session) {
await this.decryptSession(
session as unknown as session.SessionData
).catch((err) => callback(err))
}
const s =
session && this.transformFunctions.unserialize(session.session)
if (this.options.touchAfter > 0 && session?.lastModified) {
s.lastModified = session.lastModified
}
this.emit('get', sid)
callback(null, s === undefined ? null : s)
} catch (error) {
callback(error)
}
})()
}
/**
* Upsert a session into the store given a session ID (sid) and session (session) object.
* @param sid session ID
* @param session session object
*/
set(
sid: string,
session: session.SessionData,
callback: (err: any) => void = noop
): void {
;(async () => {
try {
debug(`MongoStore#set=${sid}`)
// Removing the lastModified prop from the session object before update
// @ts-ignore
if (this.options.touchAfter > 0 && session?.lastModified) {
// @ts-ignore
delete session.lastModified
}
const s: InternalSessionType = {
_id: this.computeStorageId(sid),
session: this.transformFunctions.serialize(session),
}
// Expire handling
if (session?.cookie?.expires) {
s.expires = new Date(session.cookie.expires)
} else {
// If there's no expiration date specified, it is
// browser-session cookie or there is no cookie at all,
// as per the connect docs.
//
// So we set the expiration to two-weeks from now
// - as is common practice in the industry (e.g Django) -
// or the default specified in the options.
s.expires = new Date(Date.now() + this.options.ttl * 1000)
}
// Last modify handling
if (this.options.touchAfter > 0) {
s.lastModified = new Date()
}
if (this.crypto) {
const cryptoSet = util.promisify(this.crypto.set).bind(this.crypto)
const data = await cryptoSet(
this.options.crypto.secret as string,
s.session
).catch((err) => {
throw new Error(err)
})
s.session = data as unknown as session.SessionData
}
const collection = await this.collectionP
const rawResp = await collection.updateOne(
{ _id: s._id },
{ $set: s },
{
upsert: true,
writeConcern: this.options.writeOperationOptions,
}
)
if (rawResp.upsertedCount > 0) {
this.emit('create', sid)
} else {
this.emit('update', sid)
}
this.emit('set', sid)
} catch (error) {
return callback(error)
}
return callback(null)
})()
}
touch(
sid: string,
session: session.SessionData & { lastModified?: Date },
callback: (err: any) => void = noop
): void {
;(async () => {
try {
debug(`MongoStore#touch=${sid}`)
const updateFields: {
lastModified?: Date
expires?: Date
session?: session.SessionData
} = {}
const touchAfter = this.options.touchAfter * 1000
const lastModified = session.lastModified
? session.lastModified.getTime()
: 0
const currentDate = new Date()
// If the given options has a touchAfter property, check if the
// current timestamp - lastModified timestamp is bigger than
// the specified, if it's not, don't touch the session
if (touchAfter > 0 && lastModified > 0) {
const timeElapsed = currentDate.getTime() - lastModified
if (timeElapsed < touchAfter) {
debug(`Skip touching session=${sid}`)
return callback(null)
}
updateFields.lastModified = currentDate
}
if (session?.cookie?.expires) {
updateFields.expires = new Date(session.cookie.expires)
} else {
updateFields.expires = new Date(Date.now() + this.options.ttl * 1000)
}
const collection = await this.collectionP
const rawResp = await collection.updateOne(
{ _id: this.computeStorageId(sid) },
{ $set: updateFields },
{ writeConcern: this.options.writeOperationOptions }
)
if (rawResp.matchedCount === 0) {
return callback(new Error('Unable to find the session to touch'))
} else {
this.emit('touch', sid, session)
return callback(null)
}
} catch (error) {
return callback(error)
}
})()
}
/**
* Get all sessions in the store as an array
*/
all(
callback: (
err: any,
obj?:
| session.SessionData[]
| { [sid: string]: session.SessionData }
| null
) => void
): void {
;(async () => {
try {
debug('MongoStore#all()')
const collection = await this.collectionP
const sessions = collection.find({
$or: [
{ expires: { $exists: false } },
{ expires: { $gt: new Date() } },
],
})
const results: session.SessionData[] = []
for await (const session of sessions) {
if (this.crypto && session) {
await this.decryptSession(session as unknown as session.SessionData)
}
results.push(this.transformFunctions.unserialize(session.session))
}
this.emit('all', results)
callback(null, results)
} catch (error) {
callback(error)
}
})()
}
/**
* Destroy/delete a session from the store given a session ID (sid)
* @param sid session ID
*/
destroy(sid: string, callback: (err: any) => void = noop): void {
debug(`MongoStore#destroy=${sid}`)
this.collectionP
.then((colleciton) =>
colleciton.deleteOne(
{ _id: this.computeStorageId(sid) },
{ writeConcern: this.options.writeOperationOptions }
)
)
.then(() => {
this.emit('destroy', sid)
callback(null)
})
.catch((err) => callback(err))
}
/**
* Get the count of all sessions in the store
*/
length(callback: (err: any, length: number) => void): void {
debug('MongoStore#length()')
this.collectionP
.then((collection) => collection.countDocuments())
.then((c) => callback(null, c))
// @ts-ignore
.catch((err) => callback(err))
}
/**
* Delete all sessions from the store.
*/
clear(callback: (err: any) => void = noop): void {
debug('MongoStore#clear()')
this.collectionP
.then((collection) => collection.drop())
.then(() => callback(null))
.catch((err) => callback(err))
}
/**
* Close database connection
*/
close(): Promise<void> {
debug('MongoStore#close()')
return this.clientP.then((c) => c.close())
}
}
| aaafb945a2248851f0e9f5b351d667854afee941 | [
"Markdown",
"TypeScript",
"JavaScript"
]
| 14 | Markdown | jdesboeufs/connect-mongo | d52dc41996909e3f3d98ce4a194a16a6afde246c | 8d24267b724ccbc656e3f664c2b60f33afbc267a |
refs/heads/master | <repo_name>chuxi/spark-server<file_sep>/server/src/main/public/scripts/controllers/jobs.js
angular.module('webApp')
.controller('JobsCtrl', function ($scope, $location, $resource) {
$scope.sideMenu = function(page) {
var current = $location.hash() || 'overview';
return page === current ? "active" : "";
};
$scope.tagClass = function(page) {
var current = $location.hash() || 'overview';
return page === current ? "show" : "hidden"
};
var api = $resource('/api/jobs/:jobId',
{
'jobId': '@id'
});
var setJobResultById = function(id) {
var res = api.get({ 'jobId': id }, function() {
$scope.job.result = res.result;
}, function(error) {
$scope.job.result = "Error, can not get result for " + error.data;
});
};
$scope.tableRows = api.query(function() {
$scope.job = $scope.tableRows[0];
setJobResultById($scope.job.jobId);
});
$scope.showJobInfo = function(row) {
$scope.job = row;
setJobResultById($scope.job.jobId);
};
$scope.submitJob = function() {
var params = {};
if ($scope.appName && $scope.classPath) {
params['appName'] = $scope.appName;
params['classPath'] = $scope.classPath;
}
if ($scope.contextOpt) {
params['contextOpt'] = $scope.contextOpt;
}
if ($scope.syncOpt) {
params['syncOpt'] = $scope.syncOpt;
}
if ($scope.configString) {
params['config'] = $scope.configString;
}
api.save(params, function(value, resp) {
$scope.uploadResult = 'Job Submitted Successfully!';
}, function(resp) {
$scope.uploadResult = 'Submit Job failed. Because ' + resp.data;
});
};
});
<file_sep>/server/src/main/public/scripts/controllers/main.js
angular.module('webApp')
.controller('MainCtrl', function ($scope, $location) {
});<file_sep>/README.md
## About this project.
It is built based on spark extending package spark-jobserver(including the backend end service structure), I replace the spray framework by play, add the front end which is based on angularjs.
On the process, I used play route and angularjs route with html5mode, to combine routes together. It is implemented by the play demo project https://github.com/lashford/modern-web-template, which I could not understand how it is implemented. Because I am fresh to the front end and just spend several hours completing reading \<\<Professional JavaScript for Web Developers\>\>.(Of course, I bought(payed) the(for) book(it)...).
It solved a big question along a long time with my head. How to combine the front-end with back-end. Separately or how to together. Separate the front-end and back-end, which is really popular and I found many front-end developers are devoting this kind of style, is spread out the world with Nodejs. However, most of the time, I do not want to use two frameworks. I use the backend route for supporting static html pages. At the same time, I really want to enhance the ability of front end, so it could route some simple pages just in the client side. It is the best situation, right?
Now I am still have one twirl template file in my project. I would remove it once I could find more about Play route... I really hate template in web design. It mixes html code with server code, which is the same as PHP. So here comes the question: PHP is the best language in the world. HAHAHAHA. How to defeat some guys not admit their mis-knowledge.
So just leave some words about the web framework...meaning less...
## How to run the project
git clone and sbt run......then view localhost:9000 ( so low style, I swear I would add docker later ....)
the difference between spark-jobserver and this project.
Tu Cao to spark-jobserver::
I do not think it is a good idea that run this project by submit it to spark cluster, which aims to avoid assembling the spark dependency into jar, and I guess as a surprising trick... However, it is up to the authors and I would like to keep the system standalone. Besides, the project folders structure is so terrible. Are you sure you want it or just show your sbt ability ( I am a sbt fresher...)
## How to Operate it.
I will write this part after completing algolibs and some demos.
personal todo list:
1. complete the algolibs project
1. define the config format
2. complete a extraction process
3. complete the etl process demo
2. do a performance between hive and spark sql
3. complete the paper....<file_sep>/server/src/main/public/scripts/app.js
angular.module('webApp', [
'ngRoute',
'ngResource',
'ngFileUpload'
]).config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/assets/views/dashboard.html',
controller: 'DashboardCtrl',
controllerAs: 'dash'
}).when('/applications', {
templateUrl: '/assets/views/applications.html',
controller: 'ApplicationsCtrl',
controllerAs: 'apps'
}).when('/contexts', {
templateUrl: '/assets/views/contexts.html',
controller: 'ContextsCtrl',
controllerAs: 'ctxs'
}).when('/jobs', {
templateUrl: '/assets/views/jobs.html',
controller: 'JobsCtrl',
controllerAs: 'jobs'
}).otherwise({
redirectTo: '/'})
}).config(function($locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
}).hashPrefix("!")
});
<file_sep>/server/src/main/public/scripts/controllers/contexts.js
angular.module('webApp')
.controller('ContextsCtrl', function ($scope, $location, $resource) {
$scope.sideMenu = function(page) {
var current = $location.hash() || 'overview';
return page === current ? "active" : "";
};
$scope.tagClass = function(page) {
var current = $location.hash() || 'overview';
return page === current ? "show" : "hidden"
};
var api = $resource('/api/contexts/:contextName',
{
'contextName': '@ctxName',
'num-cpu-cores': '@cores',
'memory-per-node': '@memory'
},
{
create: {method: 'POST', params: {}},
stop: {method: 'DELETE', params: {}}
}
);
$scope.tableRows = api.query();
$scope.createContext = function() {
if ($scope.ctxName) {
var params = {};
params['ctxName'] = $scope.ctxName;
if ($scope.num_cpu_cores)
params['cores'] = $scope.num_cpu_cores;
if ($scope.mem_per_node)
params['memory'] = $scope.mem_per_node;
api.create(params, function(value, resp) {
$scope.uploadResult = 'Context Created Successfully!';
}, function(resp) {
$scope.uploadResult = 'Create Context ' + $scope.ctxName + ' failed. Because ' + resp.data;
});
}
};
$scope.stopContext = function(cn) {
api.stop({'contextName': cn}, function(value, resp) {
$scope.uploadResult = 'Context Stopped Successfully!';
}, function(resp) {
$scope.uploadResult = 'Stop Context ' + cn + ' failed. Because ' + resp.data;
});
$scope.tableRows = api.query();
}
});<file_sep>/server/src/main/public/scripts/controllers/dashboard.js
angular.module('webApp')
.controller('DashboardCtrl', function ($scope, $location, $resource) {
$scope.sideMenu = function(page) {
var current = $location.hash() || 'overview';
return page === current ? "active" : "";
};
$scope.tagClass = function(page) {
var current = $location.hash() || 'overview';
return page === current ? "show" : "hidden"
};
}); | acf7744543c4307d77c621fde9de763fa973edc1 | [
"JavaScript",
"Markdown"
]
| 6 | JavaScript | chuxi/spark-server | 652e19bf1914fe13efc4ae9cc803db653f100e3d | 5566cc93d4cebe0b2310c978ee1cefb7a172aebc |
refs/heads/master | <file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.tag;
import java.util.Date;
import edu.wisc.my.stats.util.Table;
import edu.wisc.my.stats.util.Table.Entry;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public class Functions {
public static Date toDate(long timestamp) {
return new Date(timestamp);
}
public static <R, C, V> Iterable<Entry<R, C, V>> rowEntries(Table<R, C, V> table, R rowKey) {
return table.getRowEntries(rowKey);
}
}
<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.web.command.validation;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public interface PageValidator extends Validator {
/**
* Same as {@link Validator#validate(Object, Errors)} but only validates a portion of
* the object based on the specified page number.
*
* @param page The page number to validate the object for, likely does not validate the entire object.
* @param target the object that is to be validated (can be <code>null</code>)
* @param errors contextual state about the validation process (never <code>null</code>)
* @see ValidationUtils
*/
public void validatePage(int page, Object target, Errors errors);
}
<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.query.support;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import edu.wisc.my.stats.domain.ExtraParameter;
import edu.wisc.my.stats.query.ExtraParameterValuesProvider;
/**
* Associates a simple SQL query to an {@link ExtraParameter}. When the values are needed for the ExtraParameter
* the query is run and the contents of the first column of each row in the result set are returned as a List of
* Strings.
*
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public class JdbcExtraParameterValuesProvider extends JdbcDaoSupport implements ExtraParameterValuesProvider {
private static final SimpleRowMapper SIMPLE_ROW_MAPPER = new SimpleRowMapper();
private Map<ExtraParameter, String> parameterSqlMap = new HashMap<ExtraParameter, String>();
/**
* @return the parameterSqlMap
*/
public Map<ExtraParameter, String> getParameterSqlMap() {
return this.parameterSqlMap;
}
/**
* @param parameterSqlMap the parameterSqlMap to set
*/
public void setParameterSqlMap(Map<ExtraParameter, String> parameterSqlMap) {
this.parameterSqlMap = parameterSqlMap;
}
/**
* @see edu.wisc.my.stats.query.ExtraParameterValuesProvider#getPossibleValues(edu.wisc.my.stats.domain.ExtraParameter)
*/
@SuppressWarnings("unchecked")
public List<String> getPossibleValues(ExtraParameter extraParameter) {
final String parameterSql = this.parameterSqlMap.get(extraParameter);
if (parameterSql != null) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Executing '" + parameterSql + "' to get values List for parameter '" + extraParameter + "'");
}
final JdbcTemplate jdbcTemplate = this.getJdbcTemplate();
final List<String> values = jdbcTemplate.query(parameterSql, SIMPLE_ROW_MAPPER);
return values;
}
else {
this.logger.warn("Parameter '" + extraParameter + "' has not associated SQL");
return Collections.emptyList();
}
}
private static class SimpleRowMapper implements RowMapper {
/**
* @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet, int)
*/
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString(1);
}
}
}
<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.query.support;
import java.util.Set;
import org.springframework.beans.factory.annotation.Required;
import edu.wisc.my.stats.domain.Fact;
import edu.wisc.my.stats.domain.QueryInformation;
import edu.wisc.my.stats.query.QueryExecutionManager;
import edu.wisc.my.stats.query.QueryInformationProvider;
import edu.wisc.my.stats.query.QueryRunner;
import edu.wisc.my.stats.util.DefaultValueSortedKeyTable;
import edu.wisc.my.stats.util.Table;
import edu.wisc.my.stats.web.command.QueryCommand;
import edu.wisc.my.stats.web.command.QueryParameters;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public class QueryExecutionManagerImpl implements QueryExecutionManager<Long, Fact, Double> {
private QueryInformationProvider queryInformationProvider;
private QueryRunner<Long, Fact, Double> queryRunner;
/**
* @return the queryInformationProvider
*/
public QueryInformationProvider getQueryInformationProvider() {
return this.queryInformationProvider;
}
/**
* @param queryInformationProvider the queryInformationProvider to set
*/
@Required
public void setQueryInformationProvider(QueryInformationProvider queryInformationProvider) {
this.queryInformationProvider = queryInformationProvider;
}
/**
* @return the queryRunner
*/
public QueryRunner<Long, Fact, Double> getQueryRunner() {
return this.queryRunner;
}
/**
* @param queryRunner the queryRunner to set
*/
@Required
public void setQueryRunner(QueryRunner<Long, Fact, Double> queryRunner) {
this.queryRunner = queryRunner;
}
/**
* @see edu.wisc.my.stats.query.QueryExecutionManager#executeQuery(edu.wisc.my.stats.web.command.QueryParameters)
*/
public Table<Long, Fact, Double> executeQuery(QueryCommand queryCommand) {
final QueryParameters queryParameters = queryCommand.getQueryParameters();
//Get the queries for the requested facts
final Set<Fact> facts = queryParameters.getFacts();
final Set<QueryInformation> queryInfoSet = this.queryInformationProvider.getQueryInformation(facts);
final Table<Long, Fact, Double> results = new DefaultValueSortedKeyTable<Long, Fact, Double>(0.0);
for (final QueryInformation queryInformation : queryInfoSet) {
final Table<Long, Fact, Double> queryResults = this.queryRunner.runQuery(queryCommand, queryInformation);
results.putAll(queryResults);
//TODO more inteligent merging (perhaps via some interface)
}
return results;
}
}<file_sep>portlet.queryinfo.error.start.required=A Start Date is required for graph queries
portlet.queryinfo.error.start.greater_than_end=The Start Date must be less than the End Date
portlet.queryinfo.error.end.required=An End Date is required for graph queries
portlet.queryinfo.error.facts.required=At least one Fact must be selected for graphing
<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.domain;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public class CompositeFact extends Fact {
private Fact baseFact;
public CompositeFact() {
}
public CompositeFact(Fact baseFact, String compositeName) {
this.baseFact = baseFact;
super.setName(compositeName);
}
/**
* @return the baseFact
*/
public Fact getBaseFact() {
return this.baseFact;
}
/**
* @param baseFact the baseFact to set
*/
public void setBaseFact(Fact baseFact) {
this.baseFact = baseFact;
}
/**
* @see edu.wisc.my.stats.domain.Fact#getName()
*/
@Override
public String getName() {
return this.baseFact.getName() + " - " + super.getName();
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return new ToStringBuilder(this)
.appendSuper(super.toString())
.append("baseFact", this.baseFact)
.toString();
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return new HashCodeBuilder(1382715189, -115202965)
.appendSuper(super.hashCode())
.append(this.baseFact)
.toHashCode();
}
/**
* @see java.lang.Object#equals(Object)
*/
public boolean equals(final Object object) {
if (object == this) {
return true;
}
if (!(object instanceof CompositeFact)) {
return false;
}
CompositeFact rhs = (CompositeFact)object;
return new EqualsBuilder()
.appendSuper(super.equals(object))
.append(this.baseFact, rhs.baseFact)
.isEquals();
}
/**
* @see java.lang.Comparable#compareTo(Object)
*/
public int compareTo(final Fact myClass) {
if (!(myClass instanceof CompositeFact)) {
return -1;
}
CompositeFact rhs = (CompositeFact)myClass;
return new CompareToBuilder()
.appendSuper(super.compareTo(myClass))
.append(this.baseFact, rhs.baseFact)
.toComparison();
}
}
<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.domain;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.time.DateUtils;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public enum TimeResolution {
MINUTE (1, Calendar.MINUTE),
FIVE_MINUTE (5, MINUTE),
HOUR (60, MINUTE, Calendar.HOUR),
DAY (24, HOUR, Calendar.DAY_OF_MONTH),
WEEK (7, DAY, Calendar.WEEK_OF_YEAR),
MONTH (30, WEEK, Calendar.MONTH),
YEAR (365, DAY, Calendar.YEAR);
private final int minutes;
private final List<Integer> calendarFields;
private TimeResolution(int minutes, int... calendarFields) {
this.minutes = minutes;
final List<Integer> fields = new ArrayList<Integer>(calendarFields.length);
for (final int field : calendarFields) {
fields.add(field);
}
this.calendarFields = Collections.unmodifiableList(fields);
}
private TimeResolution(int count, TimeResolution base, int... calendarFields) {
this(count * base.getMinutes(), calendarFields);
}
public String getName() {
return this.name();
}
public String getCode() {
return this.name();
}
/**
* @return Returns the number of minutes in this TimeResolution.
*/
public int getMinutes() {
return this.minutes;
}
/**
* @return Returns the calendarFields.
*/
public List<Integer> getCalendarFields() {
return this.calendarFields;
}
/**
* A convience for {@link #instanceCount(long, long)}
*/
public long instanceCount(Date start, Date end) {
return this.instanceCount(start.getTime(), end.getTime());
}
/**
* Returns the number of instances of the resolution that occur between the two dates.
*
* @param start The start date in milliseconds - inclusive. See {@link Date#getTime()}
* @param end The end date in milliseconds - exclusive. See {@link Date#getTime()}
* @return The number of instances between the two ex: 8/1/2006 12:00:00.000 AM to 8/2/2006 12:00:00.000 AM for {@link #HOUR} should return 24.
*/
public long instanceCount(long start, long end) {
if (end <= start) {
throw new IllegalArgumentException("Start must be before end");
}
final long milliDiff = end - start;
final long minuteDiff = milliDiff / DateUtils.MILLIS_PER_MINUTE;
final long instances = minuteDiff / this.minutes;
return instances;
}
}
<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.domain;
import java.util.Map;
import java.util.Set;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*
*/
public class QueryInformation {
private static long idGen = 0;
private long id = idGen++;
private String baseSelectSql;
private String fromSql;
private String baseWhereSql;
private Map<Fact, Set<ColumnInformation>> factsToColumns;
private Map<ExtraParameter, ColumnInformation> extraParameters;
/**
* @return the baseSelectSql
*/
public String getBaseSelectSql() {
return this.baseSelectSql;
}
/**
* @param baseSelectSql the baseSelectSql to set
*/
public void setBaseSelectSql(String baseSelectSql) {
this.baseSelectSql = baseSelectSql;
}
/**
* @return the baseWhereSql
*/
public String getBaseWhereSql() {
return this.baseWhereSql;
}
/**
* @param baseWhereSql the baseWhereSql to set
*/
public void setBaseWhereSql(String baseWhereSql) {
this.baseWhereSql = baseWhereSql;
}
/**
* @return the factsToColumns
*/
public Map<Fact, Set<ColumnInformation>> getFactsToColumns() {
return this.factsToColumns;
}
/**
* @param factsToColumns the factsToColumns to set
*/
public void setFactsToColumns(Map<Fact, Set<ColumnInformation>> factsToColumns) {
this.factsToColumns = factsToColumns;
}
/**
* @return the fromSql
*/
public String getFromSql() {
return this.fromSql;
}
/**
* @param fromSql the fromSql to set
*/
public void setFromSql(String fromSql) {
this.fromSql = fromSql;
}
/**
* @return the id
*/
public long getId() {
return this.id;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the extraParameters
*/
public Map<ExtraParameter, ColumnInformation> getExtraParameters() {
return this.extraParameters;
}
/**
* @param extraParameters the extraParameters to set
*/
public void setExtraParameters(Map<ExtraParameter, ColumnInformation> extraParameters) {
this.extraParameters = extraParameters;
}
}<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.web;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractFormController;
import org.springframework.web.servlet.mvc.AbstractWizardFormController;
import edu.wisc.my.stats.web.command.validation.PageValidator;
/**
* <p>
* A semi-clone of Spring's {@link AbstractWizardFormController} that removes the next/previous/finish/cancel
* page management. There are two abstract methods {@link #getCurrentPageNumber(HttpServletRequest, HttpServletResponse, Object, BindException)}
* and {@link #getTargetPageNumber(HttpServletRequest, HttpServletResponse, Object, BindException)} that the sub-class
* must implemenet to ensure the correct page is rendered.
* </p>
*
* <p>
* When the controller is initialy viewed the initital page will be displayed. The initial
* page is determined by a call to {@link #getInitialPage(HttpServletRequest, Object)}.
* </p>
* <p>
* {@link #referenceData(HttpServletRequest, Object, Errors, int)} is called before any page
* is rendered to allow for data to be added to the model by the implementing class.
* </p>
* <p>
* The target page will be ignored during a form submission that has bind errors. In that
* case the current page will be re-displayed.
* </p>
*
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public abstract class DynamicMultiPageFormController extends AbstractFormController {
private String[] pages;
private String pageAttribute;
public DynamicMultiPageFormController() {
// AbstractFormController sets default cache seconds to 0.
super();
// Always needs session to keep data from all pages.
this.setSessionForm(true);
// Never validate everything on binding -> validate individual pages.
this.setValidateOnBinding(false);
}
/**
* @return the pageAttribute
*/
public final String getPageAttribute() {
return this.pageAttribute;
}
/**
* @param pageAttribute the pageAttribute to set
*/
public void setPageAttribute(String pageAttribute) {
this.pageAttribute = pageAttribute;
}
/**
* @return the pages
*/
public final String[] getPages() {
return this.pages;
}
/**
* @param pages the pages to set
*/
@Required
public void setPages(String[] pages) {
this.pages = pages;
}
/**
* Gets the current page number for the request.
*
* @param request Current request.
* @param command Current command object, binding for this request has already occured.
* @param errors Current errors object, binding for this request has already occured.
* @return The page number that the current request originates from.
* @throws Exception
*/
protected abstract int getCurrentPageNumber(HttpServletRequest request, Object command, Errors errors) throws Exception;
/**
* Gets the page number that should be displayed for the request.
*
* @param request Current request.
* @param command Current command object, binding for this request has already occured.
* @param errors Current errors object, binding for this request has already occured.
* @param page The current page number, as returned by {@link #getCurrentPageNumber(HttpServletRequest, Object, Errors)}
* @return The page number that should be displayed for the request.
* @throws Exception
*/
protected abstract int getTargetPageNumber(HttpServletRequest request, Object command, Errors errors, int page) throws Exception;
/**
* @see org.springframework.web.servlet.mvc.AbstractFormController#processFormSubmission(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
*/
@Override
protected final ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
//get the current page number
final int currentPage = this.getCurrentPageNumberInternal(request, command, errors);
//Set page number as request attribute
this.addPageNumberToRequest(request, currentPage, false);
//validate page if not suppressed
if (!this.suppressValidation(request)) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Validating wizard page " + currentPage + " for form bean '" + this.getCommandName() + "'");
}
this.validatePage(command, errors, currentPage);
}
//post process page
this.postProcessPage(request, command, errors, currentPage);
if (errors.hasErrors()) {
return this.showPage(request, errors, currentPage);
}
else {
//get target page number
final int targetPage = this.getTargetPageNumber(request, command, errors, currentPage);
return this.showPage(request, errors, targetPage);
}
}
/**
* Tries to get the current page number via {@link #getPageNumberFromRequest(HttpServletRequest)} if not found it goes to
* {@link #getCurrentPageNumber(HttpServletRequest, Object, Errors)}.
*/
protected final int getCurrentPageNumberInternal(HttpServletRequest request, Object command, Errors errors) throws Exception {
final Integer currentPage = this.getPageNumberFromRequest(request);
if (currentPage != null) {
return currentPage;
}
return this.getCurrentPageNumber(request, command, errors);
}
/**
* @see org.springframework.web.servlet.mvc.AbstractFormController#showForm(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.validation.BindException)
*/
@Override
protected final ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors) throws Exception {
//Call showPage with the inital page
final Object command = errors.getTarget();
final int initialPage = this.getInitialPage(request, command);
return this.showPage(request, errors, initialPage);
}
protected final ModelAndView showPage(HttpServletRequest request, BindException errors, int page) throws Exception {
//Check for valid page number
final Object command = errors.getTarget();
final int pageCount = this.getPageCount(request, command);
if (page < 0 || page > pageCount) {
throw new ServletException("Invalid wizard page number: " + page);
}
//Set page number as request attribute
this.addPageNumberToRequest(request, page, true);
//Add page number to model
final Map<Object, Object> controlModel = this.createControlModel(page);
//Get the viewName (based on the current page)
final String viewName = this.getViewName(request, errors.getTarget(), page);
return this.showForm(request, errors, viewName, controlModel);
}
/**
* Calls page-specific referenceData method.
*/
protected final Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
final int currentPage = this.getCurrentPageNumberInternal(request, command, errors);
return this.referenceData(request, command, errors, currentPage);
}
/**
* Create a reference data map for the given request, consisting of
* bean name/bean instance pairs as expected by ModelAndView.
* <p>Default implementation delegates to referenceData(HttpServletRequest, int).
* Subclasses can override this to set reference data used in the view.
* @param request current HTTP request
* @param command form object with request parameters bound onto it
* @param errors validation errors holder
* @param page current wizard page
* @return a Map with reference data entries, or <code>null</code> if none
* @throws Exception in case of invalid state or arguments
* @see #referenceData(HttpServletRequest, int)
* @see ModelAndView
*/
protected Map referenceData(HttpServletRequest request, Object command, Errors errors, int page) throws Exception {
return this.referenceData(request, page);
}
/**
* Create a reference data map for the given request, consisting of
* bean name/bean instance pairs as expected by ModelAndView.
* <p>Default implementation returns null.
* Subclasses can override this to set reference data used in the view.
* @param request current HTTP request
* @param page current wizard page
* @return a Map with reference data entries, or <code>null</code> if none
* @throws Exception in case of invalid state or arguments
* @see ModelAndView
*/
protected Map referenceData(HttpServletRequest request, int page) throws Exception {
return null;
}
/**
* Creates a base control model for the specified page, by default if a pageAttribute
* is set the current page is added to the model using the pageAttribute.
*
* @param page The page to create a control model for
* @return A control model for the page, null is ok.
*/
protected Map<Object, Object> createControlModel(int page) {
final Map<Object, Object> controlModel = new HashMap<Object, Object>();
if (this.pageAttribute != null) {
controlModel.put(this.pageAttribute, new Integer(page));
}
return controlModel;
}
/**
* Adds the page number as a request attribute using the key returned by
* {@link #getPageSessionAttributeName(HttpServletRequest)}. If this is
* a session for the page number is also added to the session using the
* same key.
*
* @param request The request to set the page value on.
* @param page The page value to set on the request and possibly session.
* @param setInSession If true and is a session form the page will be stored in the session, if false and is a session form the page will be removed from the session.
*/
protected final void addPageNumberToRequest(HttpServletRequest request, int page, boolean setInSession) {
// Set page session attribute, expose overriding request attribute.
final Integer pageInteger = new Integer(page);
final String pageAttrName = this.getPageSessionAttributeName(request);
if (this.isSessionForm()) {
final HttpSession session = request.getSession();
if (setInSession) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Setting page session attribute [" + pageAttrName + "] to: " + pageInteger);
}
session.setAttribute(pageAttrName, pageInteger);
}
else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Removing page session attribute [" + pageAttrName + "]");
}
session.removeAttribute(pageAttrName);
}
}
request.setAttribute(pageAttrName, pageInteger);
}
protected final Integer getPageNumberFromRequest(HttpServletRequest request) {
// Check for overriding attribute in request.
final String pageAttrName = this.getPageSessionAttributeName(request);
Integer pageAttr = (Integer)request.getAttribute(pageAttrName);
if (pageAttr != null) {
return pageAttr;
}
// Check for explicit request parameter. ?
// Check for original attribute in session.
if (this.isSessionForm()) {
final HttpSession session = request.getSession();
pageAttr = (Integer)session.getAttribute(pageAttrName);
if (pageAttr != null) {
return pageAttr;
}
}
return null;
}
/**
* Return the initial page of the wizard, i.e. the page shown at wizard startup.
* Default implementation delegates to <code>getInitialPage(HttpServletRequest)</code>.
* @param request current HTTP request
* @param command the command object as returned by formBackingObject
* @return the initial page number
* @see #getInitialPage(HttpServletRequest)
* @see #formBackingObject
*/
protected int getInitialPage(HttpServletRequest request, Object command) {
return this.getInitialPage(request);
}
/**
* Return the initial page of the wizard, i.e. the page shown at wizard startup.
* Default implementation returns 0 for first page.
* @param request current HTTP request
* @return the initial page number
*/
protected int getInitialPage(HttpServletRequest request) {
return 0;
}
/**
* Return the page count for this wizard form controller.
* Default implementation delegates to <code>getPageCount()</code>.
* <p>Can be overridden to dynamically adapt the page count.
* @param request current HTTP request
* @param command the command object as returned by formBackingObject
* @return the current page count
* @see #getPageCount
*/
protected int getPageCount(HttpServletRequest request, Object command) {
return this.getPageCount();
}
/**
* Return the number of wizard pages.
* Useful to check whether the last page has been reached.
* <p>Note that a concrete wizard form controller might override
* <code>getPageCount(HttpServletRequest, Object)</code> to determine
* the page count dynamically. The default implementation of that extended
* <code>getPageCount</code> variant returns the static page count as
* determined by this <code>getPageCount()</code> method.
* @see #getPageCount(javax.servlet.http.HttpServletRequest, Object)
*/
protected final int getPageCount() {
return this.pages.length;
}
/**
* Return the name of the HttpSession attribute that holds the page object
* for this wizard form controller.
* <p>Default implementation delegates to the <code>getPageSessionAttributeName</code>
* version without arguments.
* @param request current HTTP request
* @return the name of the form session attribute, or <code>null</code> if not in session form mode
* @see #getPageSessionAttributeName
* @see #getFormSessionAttributeName(javax.servlet.http.HttpServletRequest)
* @see javax.servlet.http.HttpSession#getAttribute
*/
protected String getPageSessionAttributeName(HttpServletRequest request) {
return this.getPageSessionAttributeName();
}
/**
* Return the name of the HttpSession attribute that holds the page object
* for this wizard form controller.
* <p>Default is an internal name, of no relevance to applications, as the form
* session attribute is not usually accessed directly. Can be overridden to use
* an application-specific attribute name, which allows other code to access
* the session attribute directly.
* @return the name of the page session attribute
* @see #getFormSessionAttributeName
* @see javax.servlet.http.HttpSession#getAttribute
*/
protected String getPageSessionAttributeName() {
return this.getClass().getName() + ".PAGE." + this.getCommandName();
}
/**
* Return the name of the view for the specified page of this wizard form controller.
* Default implementation takes the view name from the <code>getPages()</code> array.
* <p>Can be overridden to dynamically switch the page view or to return view names
* for dynamically defined pages.
* @param request current HTTP request
* @param command the command object as returned by formBackingObject
* @return the current page count
* @see #getPageCount
*/
protected String getViewName(HttpServletRequest request, Object command, int page) {
return this.pages[page];
}
/**
* Template method for custom validation logic for individual pages.
* Default implementation looks at all configured validators and for each validator
* that implements the {@link PageValidator} interface the {@link PageValidator#validatePage(int, Object, Errors)}
* method is called.
*
* <p>Implementations will typically call fine-granular validateXXX methods of this
* instance's validator, combining them to validation of the corresponding pages.
* The validator's default <code>validate</code> method will not be called by a
* dynamic page form controller!
* @param command form object with the current wizard state
* @param errors validation errors holder
* @param page number of page to validate
* @see org.springframework.validation.Validator#validate
*/
protected void validatePage(Object command, Errors errors, int page) {
final Validator[] validators = this.getValidators();
if (validators == null) {
return;
}
for (final Validator validator : validators) {
if (validator instanceof PageValidator) {
((PageValidator)validator).validatePage(page, command, errors);
}
}
}
/**
* Post-process the given page after binding and validation, potentially
* updating its command object. The passed-in request might contain special
* parameters sent by the page.
* <p>Only invoked when displaying another page or the same page again,
* not when finishing or cancelling.
* @param request current HTTP request
* @param command form object with request parameters bound onto it
* @param errors validation errors holder
* @param page number of page to post-process
* @throws Exception in case of invalid state or arguments
*/
protected void postProcessPage(HttpServletRequest request, Object command, Errors errors, int page) throws Exception {
}
}
<file_sep>StatisticsReporting
===================
In src/main/resources/ there is a .SAMPLE file that needs to be copied to the .properties file and proper information filled out.
<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.web;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.validation.Errors;
import org.springframework.web.util.WebUtils;
import edu.wisc.my.stats.domain.ColumnInformation;
import edu.wisc.my.stats.domain.ExtraParameter;
import edu.wisc.my.stats.domain.Fact;
import edu.wisc.my.stats.domain.QueryInformation;
import edu.wisc.my.stats.domain.TimeResolution;
import edu.wisc.my.stats.query.ExtraParameterValuesProvider;
import edu.wisc.my.stats.query.FactProvider;
import edu.wisc.my.stats.query.QueryExecutionManager;
import edu.wisc.my.stats.query.QueryInformationProvider;
import edu.wisc.my.stats.util.Table;
import edu.wisc.my.stats.web.chart.StatsTableDatasetProducer;
import edu.wisc.my.stats.web.command.QueryCommand;
import edu.wisc.my.stats.web.command.QueryParameters;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public class GraphingFormController extends DynamicMultiPageFormController {
private FactProvider factProvider;
private QueryInformationProvider queryInformationProvider;
private ExtraParameterValuesProvider extraParameterValuesProvider;
private QueryExecutionManager<Long, Fact, Double> queryExecutionManager;
/**
* @return the extraParameterValuesProvider
*/
public ExtraParameterValuesProvider getExtraParameterValuesProvider() {
return this.extraParameterValuesProvider;
}
/**
* @param extraParameterValuesProvider the extraParameterValuesProvider to set
*/
@Required
public void setExtraParameterValuesProvider(ExtraParameterValuesProvider extraParameterValuesProvider) {
this.extraParameterValuesProvider = extraParameterValuesProvider;
}
/**
* @return the factProvider
*/
public FactProvider getFactProvider() {
return this.factProvider;
}
/**
* @param factProvider the factProvider to set
*/
@Required
public void setFactProvider(FactProvider factProvider) {
this.factProvider = factProvider;
}
/**
* @return the queryExecutionManager
*/
public QueryExecutionManager<Long, Fact, Double> getQueryExecutionManager() {
return this.queryExecutionManager;
}
/**
* @param queryExecutionManager the queryExecutionManager to set
*/
@Required
public void setQueryExecutionManager(QueryExecutionManager<Long, Fact, Double> queryExecutionManager) {
this.queryExecutionManager = queryExecutionManager;
}
/**
* @return the queryInformationProvider
*/
public QueryInformationProvider getQueryInformationProvider() {
return this.queryInformationProvider;
}
/**
* @param queryInformationProvider the queryInformationProvider to set
*/
@Required
public void setQueryInformationProvider(QueryInformationProvider queryInformationProvider) {
this.queryInformationProvider = queryInformationProvider;
}
/**
* @see edu.wisc.my.stats.web.DynamicMultiPageFormController#getCurrentPageNumber(javax.servlet.http.HttpServletRequest, java.lang.Object, org.springframework.validation.Errors)
*/
@Override
protected int getCurrentPageNumber(HttpServletRequest request, Object command, Errors errors) throws Exception {
int page = this.getInitialPage(request, command);
final String[] values = request.getParameterValues("ISSUBMIT");
if (values == null) {
return page;
}
for (final String value : values) {
try {
page = Math.max(page, Integer.parseInt(value));
}
catch (NumberFormatException nfe) {
//Ignore
}
}
return page;
}
/**
* @see edu.wisc.my.stats.web.DynamicMultiPageFormController#getTargetPageNumber(javax.servlet.http.HttpServletRequest, java.lang.Object, org.springframework.validation.Errors, int)
*/
@Override
protected int getTargetPageNumber(HttpServletRequest request, Object command, Errors errors, int page) throws Exception {
final QueryCommand queryCommand = (QueryCommand)command;
final boolean hasRequiredExtraParameters = hasRequiredExtraParameters(queryCommand);
if (!hasRequiredExtraParameters) {
return 1;
}
else if (page < 2 && queryCommand.isHasAdvancedOptions()) {
return 2;
}
else {
return 3;
}
}
//TODO move this into a validator & use the validator.validatePage2 in getTargetPageNumber to see if page2 should be returned
protected boolean hasRequiredExtraParameters(final QueryCommand queryCommand) {
final QueryParameters queryParameters = queryCommand.getQueryParameters();
final Map<String, List<String>> extraParameterValues = queryCommand.getExtraParameterValues();
final Set<Fact> queryFacts = queryParameters.getFacts();
final Set<QueryInformation> queryInformationSet = this.queryInformationProvider.getQueryInformation(queryFacts);
for (final QueryInformation queryInformation : queryInformationSet) {
final Map<ExtraParameter, ColumnInformation> extraParametersMap = queryInformation.getExtraParameters();
if (extraParametersMap != null) {
final Set<ExtraParameter> extraParameters = extraParametersMap.keySet();
for (final ExtraParameter extraParameter : extraParameters) {
if (!extraParameterValues.containsKey(extraParameter.getName())) {
return false;
}
}
}
}
return true;
}
/**
* @see org.springframework.web.servlet.mvc.AbstractFormController#isFormSubmission(javax.servlet.http.HttpServletRequest)
*/
@Override
protected boolean isFormSubmission(HttpServletRequest request) {
return WebUtils.hasSubmitParameter(request, "ISSUBMIT");
}
/**
* @see edu.wisc.my.stats.web.DynamicMultiPageFormController#referenceData(javax.servlet.http.HttpServletRequest, java.lang.Object, org.springframework.validation.Errors, int)
*/
@Override
protected Map referenceData(HttpServletRequest request, Object command, Errors errors, int page) throws Exception {
final QueryCommand queryCommand = (QueryCommand)command;
final Map<Object, Object> model = new HashMap<Object, Object>();
switch (page) {
case 0: {
final Set<Fact> facts = this.factProvider.getFacts();
model.put("facts", facts);
model.put("resolutions", TimeResolution.values());
} break;
case 1: {
final Map<Object, Object> extraParametersMap = this.showExtraParameters(queryCommand, errors);
model.putAll(extraParametersMap);
} break;
case 3: {
//Execute the query
final Table<Long, Fact, Double> results = this.queryExecutionManager.executeQuery(queryCommand);
model.put("results", results);
final StatsTableDatasetProducer datasetProducer = new StatsTableDatasetProducer(results);
model.put("resultsProducer", datasetProducer);
}
}
return model;
}
protected Map<Object, Object> showExtraParameters(QueryCommand queryCommand, Errors errors) {
//Get the Set of QueryInformation objects for the Facts
final QueryParameters queryParameters = queryCommand.getQueryParameters();
final Set<Fact> facts = queryParameters.getFacts();
final Set<QueryInformation> allQueryInformation = this.queryInformationProvider.getQueryInformation(facts);
//The Map to store the ExtraParameters and their possible values that need to be prompted for
final Map<ExtraParameter, List<String>> extraParametersData = new HashMap<ExtraParameter,List<String>>();
//Populate the extraParametersData Map
for (final QueryInformation queryInformation : allQueryInformation) {
final Map<ExtraParameter, ColumnInformation> extraParametersMap = queryInformation.getExtraParameters();
if (extraParametersMap != null) {
final Set<ExtraParameter> extraParameters = extraParametersMap.keySet();
for (final ExtraParameter extraParameter : extraParameters) {
if (!extraParametersData.containsKey(extraParameter)) {
final List<String> possibleValues = this.extraParameterValuesProvider.getPossibleValues(extraParameter);
extraParametersData.put(extraParameter, possibleValues);
}
}
}
}
final Map<Object, Object> model = new HashMap<Object, Object>();
model.put("extraParametersData", extraParametersData);
return model;
}
}
<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.query.support;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import edu.wisc.my.stats.domain.ColumnInformation;
import edu.wisc.my.stats.domain.CompositeFact;
import edu.wisc.my.stats.domain.ExtraParameter;
import edu.wisc.my.stats.domain.Fact;
import edu.wisc.my.stats.domain.QueryInformation;
import edu.wisc.my.stats.domain.TimeResolution;
import edu.wisc.my.stats.query.DatabaseInformationProvider;
import edu.wisc.my.stats.query.QueryCompiler;
import edu.wisc.my.stats.query.QueryRunner;
import edu.wisc.my.stats.util.SortedKeyTable;
import edu.wisc.my.stats.util.Table;
import edu.wisc.my.stats.web.command.QueryCommand;
import edu.wisc.my.stats.web.command.QueryParameters;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public class JdbcQueryRunner extends JdbcDaoSupport implements QueryRunner {
private QueryCompiler queryCompiler;
private DatabaseInformationProvider databaseInformationProvider;
/**
* @return the databaseInformationProvider
*/
public DatabaseInformationProvider getDatabaseInformationProvider() {
return this.databaseInformationProvider;
}
/**
* @param databaseInformationProvider the databaseInformationProvider to set
*/
@Required
public void setDatabaseInformationProvider(DatabaseInformationProvider databaseInformationProvider) {
this.databaseInformationProvider = databaseInformationProvider;
}
/**
* @return the queryCompiler
*/
public QueryCompiler getQueryCompiler() {
return this.queryCompiler;
}
/**
* @param queryCompiler the queryCompiler to set
*/
@Required
public void setQueryCompiler(QueryCompiler queryCompiler) {
this.queryCompiler = queryCompiler;
}
/**
* @see edu.wisc.my.stats.query.QueryRunner#runQuery(edu.wisc.my.stats.web.command.QueryParameters, edu.wisc.my.stats.domain.QueryInformation)
*/
@SuppressWarnings("unchecked")
public Table runQuery(QueryCommand queryCommand, QueryInformation queryInformation) {
final String sql = this.queryCompiler.compileQuery(queryCommand, queryInformation);
final JdbcTemplate jdbcTemplate = this.getJdbcTemplate();
final DataPointRowMapper dataPointRowMapper = new DataPointRowMapper(queryCommand, queryInformation);
final Table<Long, Fact, Double> results = (Table<Long, Fact, Double>)jdbcTemplate.query(sql, dataPointRowMapper);
return results;
}
private class DataPointRowMapper implements ResultSetExtractor {
private final QueryCommand queryCommand;
private final QueryInformation queryInformation;
public DataPointRowMapper(final QueryCommand queryCommand, final QueryInformation queryInformation) {
this.queryCommand = queryCommand;
this.queryInformation = queryInformation;
}
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
final Table<Long, Fact, Double> allResults = new SortedKeyTable<Long, Fact, Double>();
final QueryParameters queryParameters = this.queryCommand.getQueryParameters();
final TimeResolution resolution = queryParameters.getResolution();
final Set<Fact> queryFacts = queryParameters.getFacts();
final Map<Fact, Set<ColumnInformation>> factsToColumns = this.queryInformation.getFactsToColumns();
//TODO prime the Facts in the table with the composites of Facts and ExtraParameter ColumnInformations
while (rs.next()) {
final long timestamp = JdbcQueryRunner.this.databaseInformationProvider.getTimeStamp(rs, resolution);
for (final Map.Entry<Fact, Set<ColumnInformation>> factsToColumnsEntry : factsToColumns.entrySet()) {
Fact fact = factsToColumnsEntry.getKey();
if (queryFacts.contains(fact)) {
//TODO move this into another method or class
final Map<ExtraParameter, ColumnInformation> extraParametersMap = this.queryInformation.getExtraParameters();
if (extraParametersMap != null) {
final StringBuilder compositeFactName = new StringBuilder();
for (final Iterator<ColumnInformation> columnInformationItr = extraParametersMap.values().iterator(); columnInformationItr.hasNext();) {
final ColumnInformation columnInformation = columnInformationItr.next();
final String factPart = rs.getString(columnInformation.getAlias());
compositeFactName.append(factPart);
if (columnInformationItr.hasNext()) {
compositeFactName.append(".");
}
}
if (compositeFactName.length() > 0) {
fact = new CompositeFact(fact, compositeFactName.toString());
}
}
double value = 0;
for (final ColumnInformation columnInformation : factsToColumnsEntry.getValue()) {
value += rs.getDouble(columnInformation.getAlias());
}
allResults.put(timestamp, fact, value);
}
}
}
return allResults;
}
}
}
<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.dao.xml;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Required;
import edu.wisc.my.stats.dao.support.AbstractMapQueryInformationDao;
import edu.wisc.my.stats.domain.Fact;
import edu.wisc.my.stats.domain.QueryInformation;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public class XmlQueryInformationDao extends AbstractMapQueryInformationDao {
private Set<QueryInformation> queryInfoSet;
private boolean initialized = false;
private String storeFile;
/**
* @return the storeFile
*/
public String getStoreFile() {
return this.storeFile;
}
/**
* @param storeFile the storeFile to set
*/
@Required
public void setStoreFile(String storeFile) {
this.storeFile = storeFile;
}
/**
* @see edu.wisc.my.stats.dao.QueryInformationDao#getQueryInformationByFactMap()
*/
public Map<Fact, Set<QueryInformation>> getQueryInformationByFactMap() {
this.initialize();
return super.getQueryInformationByFactMap();
}
/**
* @see edu.wisc.my.stats.dao.QueryInformationDao#getfactByIdMap()
*/
public Map<Long, Fact> getfactByIdMap() {
this.initialize();
return super.getfactByIdMap();
}
/**
* @see edu.wisc.my.stats.dao.QueryInformationDao#addQueryInformation(edu.wisc.my.stats.domain.QueryInformation)
*/
public void addQueryInformation(QueryInformation queryInformation) {
this.initialize();
this.writeLock.lock();
try {
this.addQueryInformationInternal(queryInformation);
this.readLock.lock(); //Downgrade the lock so the changes can be persisted
}
finally {
this.writeLock.unlock();
}
try {
this.writeQueryInformationSet(this.queryInfoSet);
}
finally {
this.readLock.unlock();
}
}
/**
* Initializes the DAO if needed by reading the queryInfoSet from the specified XML
* file and configuring the maps
*/
protected void initialize() {
if (this.initialized) {
return; //Already initialized, return immediatly
}
this.writeLock.lock();
try {
if (this.initialized) {
return; //Already initialized, return immediatly
}
final Set<QueryInformation> queryInformationSet = this.readQueryInformationSet();
for (final QueryInformation queryInformation : queryInformationSet) {
this.addQueryInformationInternal(queryInformation);
}
this.queryInfoSet = queryInformationSet;
this.initialized = true;
}
finally {
this.writeLock.unlock();
}
}
/**
* @return Reads the Set of QueryInformation from the specified XML file and returns it.
*/
@SuppressWarnings("unchecked")
protected Set<QueryInformation> readQueryInformationSet() {
final FileInputStream fis;
try {
fis = new FileInputStream(this.storeFile);
}
catch (FileNotFoundException fnfe) {
final String errorMessage = "The specified storeFile='" + this.storeFile + "' could not be found.";
this.logger.error(errorMessage, fnfe);
throw new IllegalArgumentException(errorMessage, fnfe);
}
final BufferedInputStream bis = new BufferedInputStream(fis);
final XMLDecoder xmlDecoder = new XMLDecoder(bis);
try {
return (Set<QueryInformation>)xmlDecoder.readObject();
}
finally {
xmlDecoder.close();
}
}
/**
* @param queryInformationSet The Set of QueryInformation to persist to the specified XML file.
*/
protected void writeQueryInformationSet(Set<QueryInformation> queryInformationSet) {
final FileOutputStream fos;
try {
fos = new FileOutputStream(this.storeFile);
}
catch (FileNotFoundException fnfe) {
final String errorMessage = "The specified storeFile='" + this.storeFile + "' could not be found.";
this.logger.error(errorMessage, fnfe);
throw new IllegalArgumentException(errorMessage, fnfe);
}
final BufferedOutputStream bos = new BufferedOutputStream(fos);
final XMLEncoder xmlEncoder = new XMLEncoder(bos);
try {
xmlEncoder.writeObject(queryInformationSet);
xmlEncoder.flush();
}
finally {
xmlEncoder.close();
}
}
}
<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.query.support;
import java.util.List;
import java.util.Map;
import edu.wisc.my.stats.domain.ExtraParameter;
import edu.wisc.my.stats.query.ExtraParameterValuesProvider;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public class MapExtraParameterValuesProvider implements ExtraParameterValuesProvider {
private Map<ExtraParameter, List<String>> possibleValuesMapping;
/**
* @return the possibleValuesMapping
*/
public Map<ExtraParameter, List<String>> getPossibleValuesMapping() {
return this.possibleValuesMapping;
}
/**
* @param possibleValuesMapping the possibleValuesMapping to set
*/
public void setPossibleValuesMapping(Map<ExtraParameter, List<String>> possibleValuesMapping) {
this.possibleValuesMapping = possibleValuesMapping;
}
/**
* @see edu.wisc.my.stats.query.ExtraParameterValuesProvider#getPossibleValues(edu.wisc.my.stats.domain.ExtraParameter)
*/
public List<String> getPossibleValues(ExtraParameter extraParameter) {
return possibleValuesMapping.get(extraParameter);
}
}
<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.query;
import java.util.List;
import edu.wisc.my.stats.domain.ExtraParameter;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public interface ExtraParameterValuesProvider {
/**
* Gets a List of possible values for the specified ExtraParameter. <code>null</code>
* implies that any value is valid.
*/
public List<String> getPossibleValues(ExtraParameter extraParameter);
}
<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.query;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import edu.wisc.my.stats.domain.ColumnInformation;
import edu.wisc.my.stats.domain.ExtraParameter;
import edu.wisc.my.stats.domain.TimeResolution;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public interface DatabaseInformationProvider {
/**
* Gets a correctly formatted string of resolution columns for the specified TimeResolution
* to be appened to the SELECT portion of the query.
*/
public String getSelectResolutionsString(TimeResolution resolution);
/**
* Gets a correctly formatted string of resolution columns for the specified TimeResolution
* to be appened to the GROUP BY portion of the query.
*/
public String getGroupByString(TimeResolution resolution);
/**
* Gets a correctly formatted string of resolution columns for the specified TimeResolution
* to be appened to the ORDER BY portion of the query.
*/
public String getOrderByString(TimeResolution resolution);
/**
* Gets a correctly formatted string restricting the query to between the specified Dates
* to be appended to the WHERE portion of the query.
*/
public String getDateConstraintString(Date start, Date end);
public String getExtraParameterConstraint(ExtraParameter extraParameter, ColumnInformation columnInformation, List<String> values);
/**
* Gets a timestamp (milliseconds from epoch) from the ResultSet for the specified TimeResolution
*/
public long getTimeStamp(ResultSet rs, TimeResolution resolution) throws SQLException;
}
<file_sep>/* Copyright 2006 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package edu.wisc.my.stats.domain;
/**
* @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a>
* @version $Revision: 1.1 $
*/
public class ExtraParameter {
private static long idGen = 0;
private long id = idGen++;
private String name;
private boolean multivalued;
/**
* @return the id
*/
public long getId() {
return this.id;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return this.name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the multivalued
*/
public boolean isMultivalued() {
return this.multivalued;
}
/**
* @param multivalued the multivalued to set
*/
public void setMultivalued(boolean multivalued) {
this.multivalued = multivalued;
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>edu.wisc</groupId>
<artifactId>StatisticsReporting</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>Statistics Reporting</name>
<description>Web based statistics graphing & reporting tool.</description>
<url>http://my.wisc.edu/</url>
<inceptionYear>2007</inceptionYear>
<scm>
<developerConnection>scm:cvs:extssh:${<EMAIL>:/apps/my/CVS:tools/StatisticsReporting</developerConnection>
<tag>1.0.0-SNAPSHOT</tag>
</scm>
<repositories>
<repository>
<id>Codehaus Snapshots</id>
<url>http://snapshots.repository.codehaus.org/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>Codehaus Snapshots</id>
<url>http://snapshots.repository.codehaus.org/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
<developers>
<developer>
<name><NAME></name>
<id>edalquist</id>
<email><EMAIL></email>
<roles>
<role>Project Admin</role>
<role>Developer</role>
</roles>
<url>http://my.wisc.edu/</url>
<timezone>-6</timezone>
</developer>
</developers>
<dependencies>
<!--
| Compile Dependencies
+-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1</version>
<type>jar</type>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>logkit</groupId>
<artifactId>logkit</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>avalon-framework</groupId>
<artifactId>avalon-framework</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.0.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!--
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.2.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.1</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.3</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cewolf</groupId>
<artifactId>cewolf</artifactId>
<version>1.0</version>
<type>jar</type>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>gnujaxp</artifactId>
<groupId>gnujaxp</groupId>
</exclusion>
<exclusion>
<artifactId>crimson</artifactId>
<groupId>crimson</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.0.3</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>jfree</groupId>
<artifactId>jcommon</artifactId>
<version>1.0.7</version>
<type>jar</type>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>gnujaxp</artifactId>
<groupId>gnujaxp</groupId>
</exclusion>
</exclusions>
</dependency>
<!--
| Provided Dependencies
+-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<!--
| Run Time Dependencies
+-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>[1.2,)</version>
<type>jar</type>
<scope>runtime</scope>
</dependency>
<!--
| Test Dependencies
+-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>[3.8,)</version>
<type>jar</type>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jspc-maven-plugin</artifactId>
<executions>
<execution>
<id>jspc</id>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
<configuration>
<injectString><!-- [INSERT FRAGMENT HERE] --></injectString>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>PortalStats</warName>
<webXml>${basedir}/target/jspweb.xml</webXml>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>surefire-report-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jxr-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<links>
<link>http://java.sun.com/j2se/1.5.0/docs/api/</link>
<link>http://static.springframework.org/spring/docs/2.0.x/api/</link>
<link>http://jakarta.apache.org/commons/logging/commons-logging-1.1/apidocs/</link>
</links>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<configuration>
<targetJdk>1.5</targetJdk>
<format>xml</format>
<linkXref>true</linkXref>
<sourceEncoding>utf-8</sourceEncoding>
<minimumTokens>100</minimumTokens>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>changelog-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>taglist-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
</plugin>
</plugins>
</reporting>
</project>
| 8901b73f5b9502fcb9cdcd3be96bcd6103a56a8f | [
"Markdown",
"Java",
"Maven POM",
"INI"
]
| 18 | Java | UW-Madison-DoIT/StatisticsReporting | 319c1eeb3b9b955c6c280d453d64c346ae4a362b | 0ce021112964522c4a43feb5ac0711af8f2b4fe5 |
refs/heads/master | <repo_name>PMGH/js-football-transfer-market<file_sep>/server.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("client/build"));
// set up mongo client
var MongoClient = require("mongodb").MongoClient;
MongoClient.connect("mongodb://localhost:27017/transfer_market", function(err, client){
if (err){
return console.log(err);
}
db = client.db("transfer_market");
console.log("Connected to DB");
app.listen(3000, function(){
console.log("Listening on port " + this.address().port);
});
});
// get home page (index.html)
app.get("/", function(req, res){
res.sendFile(__dirname + "/client/build/index.html");
});
// get all transfer-listed players
app.get("/players/transfer-listed", function(req, res){
db.collection("players").find({ transferListed: true }).toArray(function(err, results){
if (err){
return console.log(err);
}
res.json(results);
});
});
// get all transer-listed players by club
app.get("/players/transfer-listed/club/:club", function(req, res){
db.collection("players").find({
club: req.params.club,
transferListed: true
}).toArray(function(err, results){
if (err){
return console.log(err);
}
res.json(results);
});
});
// get all transfer-listed players by position
app.get("/players/transfer-listed/position/:position", function(req, res){
db.collection("players").find({
position: req.params.position,
transferListed: true
}).toArray(function(err, results){
if (err){
return console.log(err);
}
res.json(results);
});
});
// get all players by club
app.get("/players/club/:club", function(req, res){
db.collection("players").find({ club: req.params.club }).toArray(function(err, results){
if (err){
return console.log(err);
}
res.json(results);
});
});
// get all players by position
app.get("/players/position/:position", function(req, res){
db.collection("players").find({ position: req.params.position }).toArray(function(err, results){
if (err){
return console.log(err);
}
res.json(results);
});
});
// get all players
app.get("/players", function(req, res){
// find all the players in the db collection 'players' and return as an array within the http response
db.collection("players").find().toArray(function(err, results){
if (err){
return console.log(err);
}
res.json(results);
});
});
// create a player
app.post("/players", function(req, res){
db.collection("players").save(req.body, function(err, result){
if (err){
return console.log(err);
}
console.log("Saved to database");
});
res.redirect("/");
});
// delete all
app.post("/players/delete-all", function(req, res){
db.collection("players").remove();
res.redirect("/");
});
<file_sep>/client/src/app.js
var clubView = require('./views/clubView.js');
var makeRequest = function(url, callback){
var request = new XMLHttpRequest();
request.open("GET", url);
request.addEventListener('load', callback);
request.send();
};
var requestComplete = function(){
if (this.status !== 200){
return console.log("Request failed");
}
console.log("Request successful");
var jsonString = this.responseText;
var apiData = JSON.parse(jsonString);
console.log(apiData);
var clubs = [];
console.log(clubs);
apiData.forEach(function(player){
if (!clubs.includes(player.club)){
clubs.push(player.club);
}
});
var ui = new clubView(clubs);
};
var app = function(){
console.log("Running app.js");
var url = "/players";
makeRequest(url, requestComplete);
};
window.addEventListener("load", app);
<file_sep>/seeds.js
use transfer_market;
db.dropDatabase();
var celticfc = [
{
name: "<NAME>",
nationality: "Scotland",
club: "Celtic FC",
position: "Goalkeeper",
value: "6000000",
transferListed: false
},
{
name: "<NAME>",
nationality: "Sweden",
club: "Celtic FC",
position: "Defender",
value: "4500000",
transferListed: false
},
{
name: "<NAME>",
nationality: "Scotland",
club: "Celtic FC",
position: "Striker",
value: "8000000",
transferListed: false
},
{
name: "<NAME>",
nationality: "Scotland",
club: "Celtic FC",
position: "Midfielder",
value: "1500000",
transferListed: true
}
];
var arsenalfc = [
{
name: "<NAME>",
nationality: "England",
club: "Arsenal FC",
position: "Midfielder",
value: "10000000",
transferListed: true
},
{
name: "<NAME>",
nationality: "France",
club: "Arsenal FC",
position: "Striker",
value: "30000000",
transferListed: false
},
{
name: "<NAME>",
nationality: "Spain",
club: "Arsenal FC",
position: "Defender",
value: "15000000",
transferListed: true
}
];
var arrays = [celticfc, arsenalfc];
var populatePlayers = function(arrays){
var players = [];
arrays.forEach(function(arr){
arr.forEach(function(player){
players.push(player);
});
});
db.players.insertMany(players);
}
populatePlayers(arrays);
db.players.find();
<file_sep>/client/src/views/clubView.js
var ClubView = function(clubs){
this.render(clubs);
};
ClubView.prototype = {
render: function(clubs){
console.log(clubs);
clubs.forEach( function(club){
var li = document.createElement('li');
var text = document.createElement('p');
var ul = document.getElementById('club-list');
text.innerText = club;
li.appendChild(text);
ul.appendChild(li);
});
}
}
module.exports = ClubView;
| 2feec4b2768bbcbe202e87972f022f1fbd1dbcb9 | [
"JavaScript"
]
| 4 | JavaScript | PMGH/js-football-transfer-market | 6e65f748f79b1d496a4f5c1d28920821b308572f | 8ee3868edddb10022f2e93b17f456805833fff76 |
refs/heads/master | <file_sep>// Options:
/* ------------------------------------------------------------
name: "untitled"
Code generated with Faust 2.23.10 (https://faust.grame.fr)
Compilation options: -lang cpp -scal -ftz 0
------------------------------------------------------------ */
#ifndef __mydsp_H__
#define __mydsp_H__
/************************************************************************
IMPORTANT NOTE : this file contains two clearly delimited sections :
the ARCHITECTURE section (in two parts) and the USER section. Each section
is governed by its own copyright and license. Please check individually
each section for license and copyright information.
*************************************************************************/
/*******************BEGIN ARCHITECTURE SECTION (part 1/2)****************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2019-2020 GRAME, Centre National de Creation Musicale &
Aalborg University (Copenhagen, Denmark)
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************
************************************************************************/
#include "untitled.h"
/************************** BEGIN meta.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef __meta__
#define __meta__
struct Meta
{
virtual ~Meta() {};
virtual void declare(const char* key, const char* value) = 0;
};
#endif
/************************** END meta.h **************************/
/************************** BEGIN dsp.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef __dsp__
#define __dsp__
#include <string>
#include <vector>
#ifndef FAUSTFLOAT
#define FAUSTFLOAT float
#endif
struct UI;
struct Meta;
/**
* DSP memory manager.
*/
struct dsp_memory_manager {
virtual ~dsp_memory_manager() {}
virtual void* allocate(size_t size) = 0;
virtual void destroy(void* ptr) = 0;
};
/**
* Signal processor definition.
*/
class dsp {
public:
dsp() {}
virtual ~dsp() {}
/* Return instance number of audio inputs */
virtual int getNumInputs() = 0;
/* Return instance number of audio outputs */
virtual int getNumOutputs() = 0;
/**
* Trigger the ui_interface parameter with instance specific calls
* to 'openTabBox', 'addButton', 'addVerticalSlider'... in order to build the UI.
*
* @param ui_interface - the user interface builder
*/
virtual void buildUserInterface(UI* ui_interface) = 0;
/* Returns the sample rate currently used by the instance */
virtual int getSampleRate() = 0;
/**
* Global init, calls the following methods:
* - static class 'classInit': static tables initialization
* - 'instanceInit': constants and instance state initialization
*
* @param sample_rate - the sampling rate in Hertz
*/
virtual void init(int sample_rate) = 0;
/**
* Init instance state
*
* @param sample_rate - the sampling rate in Hertz
*/
virtual void instanceInit(int sample_rate) = 0;
/**
* Init instance constant state
*
* @param sample_rate - the sampling rate in Hertz
*/
virtual void instanceConstants(int sample_rate) = 0;
/* Init default control parameters values */
virtual void instanceResetUserInterface() = 0;
/* Init instance state (delay lines...) */
virtual void instanceClear() = 0;
/**
* Return a clone of the instance.
*
* @return a copy of the instance on success, otherwise a null pointer.
*/
virtual dsp* clone() = 0;
/**
* Trigger the Meta* parameter with instance specific calls to 'declare' (key, value) metadata.
*
* @param m - the Meta* meta user
*/
virtual void metadata(Meta* m) = 0;
/**
* DSP instance computation, to be called with successive in/out audio buffers.
*
* @param count - the number of frames to compute
* @param inputs - the input audio buffers as an array of non-interleaved FAUSTFLOAT samples (eiher float, double or quad)
* @param outputs - the output audio buffers as an array of non-interleaved FAUSTFLOAT samples (eiher float, double or quad)
*
*/
virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) = 0;
/**
* DSP instance computation: alternative method to be used by subclasses.
*
* @param date_usec - the timestamp in microsec given by audio driver.
* @param count - the number of frames to compute
* @param inputs - the input audio buffers as an array of non-interleaved FAUSTFLOAT samples (either float, double or quad)
* @param outputs - the output audio buffers as an array of non-interleaved FAUSTFLOAT samples (either float, double or quad)
*
*/
virtual void compute(double /*date_usec*/, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { compute(count, inputs, outputs); }
};
/**
* Generic DSP decorator.
*/
class decorator_dsp : public dsp {
protected:
dsp* fDSP;
public:
decorator_dsp(dsp* dsp = nullptr):fDSP(dsp) {}
virtual ~decorator_dsp() { delete fDSP; }
virtual int getNumInputs() { return fDSP->getNumInputs(); }
virtual int getNumOutputs() { return fDSP->getNumOutputs(); }
virtual void buildUserInterface(UI* ui_interface) { fDSP->buildUserInterface(ui_interface); }
virtual int getSampleRate() { return fDSP->getSampleRate(); }
virtual void init(int sample_rate) { fDSP->init(sample_rate); }
virtual void instanceInit(int sample_rate) { fDSP->instanceInit(sample_rate); }
virtual void instanceConstants(int sample_rate) { fDSP->instanceConstants(sample_rate); }
virtual void instanceResetUserInterface() { fDSP->instanceResetUserInterface(); }
virtual void instanceClear() { fDSP->instanceClear(); }
virtual decorator_dsp* clone() { return new decorator_dsp(fDSP->clone()); }
virtual void metadata(Meta* m) { fDSP->metadata(m); }
// Beware: subclasses usually have to overload the two 'compute' methods
virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { fDSP->compute(count, inputs, outputs); }
virtual void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { fDSP->compute(date_usec, count, inputs, outputs); }
};
/**
* DSP factory class.
*/
class dsp_factory {
protected:
// So that to force sub-classes to use deleteDSPFactory(dsp_factory* factory);
virtual ~dsp_factory() {}
public:
virtual std::string getName() = 0;
virtual std::string getSHAKey() = 0;
virtual std::string getDSPCode() = 0;
virtual std::string getCompileOptions() = 0;
virtual std::vector<std::string> getLibraryList() = 0;
virtual std::vector<std::string> getIncludePathnames() = 0;
virtual dsp* createDSPInstance() = 0;
virtual void setMemoryManager(dsp_memory_manager* manager) = 0;
virtual dsp_memory_manager* getMemoryManager() = 0;
};
/**
* On Intel set FZ (Flush to Zero) and DAZ (Denormals Are Zero)
* flags to avoid costly denormals.
*/
#ifdef __SSE__
#include <xmmintrin.h>
#ifdef __SSE2__
#define AVOIDDENORMALS _mm_setcsr(_mm_getcsr() | 0x8040)
#else
#define AVOIDDENORMALS _mm_setcsr(_mm_getcsr() | 0x8000)
#endif
#else
#define AVOIDDENORMALS
#endif
#endif
/************************** END dsp.h **************************/
/************************** BEGIN MapUI.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef FAUST_MAPUI_H
#define FAUST_MAPUI_H
#include <vector>
#include <map>
#include <string>
/************************** BEGIN UI.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2020 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef __UI_H__
#define __UI_H__
#ifndef FAUSTFLOAT
#define FAUSTFLOAT float
#endif
/*******************************************************************************
* UI : Faust DSP User Interface
* User Interface as expected by the buildUserInterface() method of a DSP.
* This abstract class contains only the method that the Faust compiler can
* generate to describe a DSP user interface.
******************************************************************************/
struct Soundfile;
template <typename REAL>
struct UIReal
{
UIReal() {}
virtual ~UIReal() {}
// -- widget's layouts
virtual void openTabBox(const char* label) = 0;
virtual void openHorizontalBox(const char* label) = 0;
virtual void openVerticalBox(const char* label) = 0;
virtual void closeBox() = 0;
// -- active widgets
virtual void addButton(const char* label, REAL* zone) = 0;
virtual void addCheckButton(const char* label, REAL* zone) = 0;
virtual void addVerticalSlider(const char* label, REAL* zone, REAL init, REAL min, REAL max, REAL step) = 0;
virtual void addHorizontalSlider(const char* label, REAL* zone, REAL init, REAL min, REAL max, REAL step) = 0;
virtual void addNumEntry(const char* label, REAL* zone, REAL init, REAL min, REAL max, REAL step) = 0;
// -- passive widgets
virtual void addHorizontalBargraph(const char* label, REAL* zone, REAL min, REAL max) = 0;
virtual void addVerticalBargraph(const char* label, REAL* zone, REAL min, REAL max) = 0;
// -- soundfiles
virtual void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) = 0;
// -- metadata declarations
virtual void declare(REAL* zone, const char* key, const char* val) {}
};
struct UI : public UIReal<FAUSTFLOAT>
{
UI() {}
virtual ~UI() {}
};
#endif
/************************** END UI.h **************************/
/************************** BEGIN PathBuilder.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef FAUST_PATHBUILDER_H
#define FAUST_PATHBUILDER_H
#include <vector>
#include <string>
#include <algorithm>
/*******************************************************************************
* PathBuilder : Faust User Interface
* Helper class to build complete hierarchical path for UI items.
******************************************************************************/
class PathBuilder
{
protected:
std::vector<std::string> fControlsLevel;
public:
PathBuilder() {}
virtual ~PathBuilder() {}
std::string buildPath(const std::string& label)
{
std::string res = "/";
for (size_t i = 0; i < fControlsLevel.size(); i++) {
res += fControlsLevel[i];
res += "/";
}
res += label;
std::replace(res.begin(), res.end(), ' ', '_');
return res;
}
void pushLabel(const std::string& label) { fControlsLevel.push_back(label); }
void popLabel() { fControlsLevel.pop_back(); }
};
#endif // FAUST_PATHBUILDER_H
/************************** END PathBuilder.h **************************/
/*******************************************************************************
* MapUI : Faust User Interface
* This class creates a map of complete hierarchical path and zones for each UI items.
******************************************************************************/
class MapUI : public UI, public PathBuilder
{
protected:
// Complete path map
std::map<std::string, FAUSTFLOAT*> fPathZoneMap;
// Label zone map
std::map<std::string, FAUSTFLOAT*> fLabelZoneMap;
public:
MapUI() {}
virtual ~MapUI() {}
// -- widget's layouts
void openTabBox(const char* label)
{
pushLabel(label);
}
void openHorizontalBox(const char* label)
{
pushLabel(label);
}
void openVerticalBox(const char* label)
{
pushLabel(label);
}
void closeBox()
{
popLabel();
}
// -- active widgets
void addButton(const char* label, FAUSTFLOAT* zone)
{
fPathZoneMap[buildPath(label)] = zone;
fLabelZoneMap[label] = zone;
}
void addCheckButton(const char* label, FAUSTFLOAT* zone)
{
fPathZoneMap[buildPath(label)] = zone;
fLabelZoneMap[label] = zone;
}
void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step)
{
fPathZoneMap[buildPath(label)] = zone;
fLabelZoneMap[label] = zone;
}
void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step)
{
fPathZoneMap[buildPath(label)] = zone;
fLabelZoneMap[label] = zone;
}
void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step)
{
fPathZoneMap[buildPath(label)] = zone;
fLabelZoneMap[label] = zone;
}
// -- passive widgets
void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT fmin, FAUSTFLOAT fmax)
{
fPathZoneMap[buildPath(label)] = zone;
fLabelZoneMap[label] = zone;
}
void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT fmin, FAUSTFLOAT fmax)
{
fPathZoneMap[buildPath(label)] = zone;
fLabelZoneMap[label] = zone;
}
// -- soundfiles
virtual void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) {}
// -- metadata declarations
void declare(FAUSTFLOAT* zone, const char* key, const char* val)
{}
// set/get
void setParamValue(const std::string& path, FAUSTFLOAT value)
{
if (fPathZoneMap.find(path) != fPathZoneMap.end()) {
*fPathZoneMap[path] = value;
} else if (fLabelZoneMap.find(path) != fLabelZoneMap.end()) {
*fLabelZoneMap[path] = value;
}
}
FAUSTFLOAT getParamValue(const std::string& path)
{
if (fPathZoneMap.find(path) != fPathZoneMap.end()) {
return *fPathZoneMap[path];
} else if (fLabelZoneMap.find(path) != fLabelZoneMap.end()) {
return *fLabelZoneMap[path];
} else {
return FAUSTFLOAT(0);
}
}
// map access
std::map<std::string, FAUSTFLOAT*>& getMap() { return fPathZoneMap; }
int getParamsCount() { return int(fPathZoneMap.size()); }
std::string getParamAddress(int index)
{
std::map<std::string, FAUSTFLOAT*>::iterator it = fPathZoneMap.begin();
while (index-- > 0 && it++ != fPathZoneMap.end()) {}
return (*it).first;
}
std::string getParamAddress(FAUSTFLOAT* zone)
{
std::map<std::string, FAUSTFLOAT*>::iterator it = fPathZoneMap.begin();
do {
if ((*it).second == zone) return (*it).first;
}
while (it++ != fPathZoneMap.end());
return "";
}
static bool endsWith(std::string const& str, std::string const& end)
{
size_t l1 = str.length();
size_t l2 = end.length();
return (l1 >= l2) && (0 == str.compare(l1 - l2, l2, end));
}
};
#endif // FAUST_MAPUI_H
/************************** END MapUI.h **************************/
/************************** BEGIN esp32audio.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2020 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef __esp32audio__
#define __esp32audio__
#include <utility>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/i2s.h"
/************************** BEGIN audio.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef __audio__
#define __audio__
#include <set>
#include <utility>
class dsp;
typedef void (* shutdown_callback)(const char* message, void* arg);
typedef void (* compute_callback)(void* arg);
class audio {
protected:
shutdown_callback fShutdown; // Shutdown callback
void* fShutdownArg; // Shutdown callback data
std::set<std::pair<compute_callback, void*> > fComputeCallbackList;
public:
audio():fShutdown(nullptr), fShutdownArg(nullptr) {}
virtual ~audio() {}
virtual bool init(const char* name, dsp* dsp) = 0;
virtual bool start() = 0;
virtual void stop() = 0;
void setShutdownCallback(shutdown_callback cb, void* arg)
{
fShutdown = cb;
fShutdownArg = arg;
}
void addControlCallback(compute_callback cb, void* arg)
{
fComputeCallbackList.insert(std::make_pair(cb, arg));
}
bool removeControlCallback(compute_callback cb, void* arg)
{
return (fComputeCallbackList.erase(std::make_pair(cb, arg)) == 1);
}
void runControlCallbacks()
{
for (auto& it : fComputeCallbackList) {
it.first(it.second);
}
}
virtual int getBufferSize() = 0;
virtual int getSampleRate() = 0;
virtual int getNumInputs() = 0;
virtual int getNumOutputs() = 0;
// Returns the average proportion of available CPU being spent inside the audio callbacks (between 0 and 1.0).
virtual float getCPULoad() { return 0.f; }
};
#endif
/************************** END audio.h **************************/
#define MULT_S32 2147483647
#define DIV_S32 4.6566129e-10
#define clip(sample) std::max(-MULT_S32, std::min(MULT_S32, ((int32_t)(sample * MULT_S32))));
#define AUDIO_MAX_CHAN 2
class esp32audio : public audio {
private:
int fSampleRate;
int fBufferSize;
int fNumInputs;
int fNumOutputs;
float** fInChannel;
float** fOutChannel;
TaskHandle_t fHandle;
dsp* fDSP;
bool fRunning;
template <int INPUTS, int OUTPUTS>
void audioTask()
{
while (fRunning) {
if (INPUTS > 0) {
// Read from the card
int32_t samples_data_in[AUDIO_MAX_CHAN*fBufferSize];
size_t bytes_read = 0;
i2s_read((i2s_port_t)0, &samples_data_in, AUDIO_MAX_CHAN*sizeof(float)*fBufferSize, &bytes_read, portMAX_DELAY);
// Convert and copy inputs
if (INPUTS == AUDIO_MAX_CHAN) {
// if stereo
for (int i = 0; i < fBufferSize; i++) {
fInChannel[0][i] = (float)samples_data_in[i*AUDIO_MAX_CHAN]*DIV_S32;
fInChannel[1][i] = (float)samples_data_in[i*AUDIO_MAX_CHAN+1]*DIV_S32;
}
} else {
// otherwise only first channel
for (int i = 0; i < fBufferSize; i++) {
fInChannel[0][i] = (float)samples_data_in[i*AUDIO_MAX_CHAN]*DIV_S32;
}
}
}
// Call DSP
fDSP->compute(fBufferSize, fInChannel, fOutChannel);
// Convert and copy outputs
int32_t samples_data_out[AUDIO_MAX_CHAN*fBufferSize];
if (OUTPUTS == AUDIO_MAX_CHAN) {
// if stereo
for (int i = 0; i < fBufferSize; i++) {
samples_data_out[i*AUDIO_MAX_CHAN] = clip(fOutChannel[0][i]);
samples_data_out[i*AUDIO_MAX_CHAN+1] = clip(fOutChannel[1][i]);
}
} else {
// otherwise only first channel
for (int i = 0; i < fBufferSize; i++) {
samples_data_out[i*AUDIO_MAX_CHAN] = clip(fOutChannel[0][i]);
samples_data_out[i*AUDIO_MAX_CHAN+1] = samples_data_out[i*AUDIO_MAX_CHAN];
}
}
// Write to the card
size_t bytes_written = 0;
i2s_write((i2s_port_t)0, &samples_data_out, AUDIO_MAX_CHAN*sizeof(float)*fBufferSize, &bytes_written, portMAX_DELAY);
}
// Task has to deleted itself beforee returning
vTaskDelete(nullptr);
}
void destroy()
{
for (int i = 0; i < fNumInputs; i++) {
delete[] fInChannel[i];
}
delete [] fInChannel;
for (int i = 0; i < fNumOutputs; i++) {
delete[] fOutChannel[i];
}
delete [] fOutChannel;
}
static void audioTaskHandler(void* arg)
{
esp32audio* audio = static_cast<esp32audio*>(arg);
if (audio->fNumInputs == 0 && audio->fNumOutputs == 1) {
audio->audioTask<0,1>();
} else if (audio->fNumInputs == 0 && audio->fNumOutputs == 2) {
audio->audioTask<0,2>();
} else if (audio->fNumInputs == 1 && audio->fNumOutputs == 1) {
audio->audioTask<1,1>();
} else if (audio->fNumInputs == 1 && audio->fNumOutputs == 2) {
audio->audioTask<1,2>();
} else if (audio->fNumInputs == 2 && audio->fNumOutputs == 1) {
audio->audioTask<2,1>();
} else if (audio->fNumInputs == 2 && audio->fNumOutputs == 2) {
audio->audioTask<2,2>();
}
}
public:
esp32audio(int srate, int bsize):
fSampleRate(srate),
fBufferSize(bsize),
fNumInputs(0),
fNumOutputs(0),
fInChannel(nullptr),
fOutChannel(nullptr),
fHandle(nullptr),
fDSP(nullptr),
fRunning(false)
{
i2s_pin_config_t pin_config;
#if TTGO_TAUDIO
pin_config = {
.bck_io_num = 33,
.ws_io_num = 25,
.data_out_num = 26,
.data_in_num = 27
};
#elif A1S_BOARD
pin_config = {
.bck_io_num = 27,
.ws_io_num = 26,
.data_out_num = 25,
.data_in_num = 35
};
#else // Default
pin_config = {
.bck_io_num = 33,
.ws_io_num = 25,
.data_out_num = 26,
.data_in_num = 27
};
#endif
#if A1S_BOARD
i2s_config_t i2s_config = {
.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX | I2S_MODE_RX),
.sample_rate = fSampleRate,
.bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,
.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
.communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL3, // high interrupt priority
.dma_buf_count = 3,
.dma_buf_len = fBufferSize,
.use_apll = true
};
#else // default
i2s_config_t i2s_config = {
.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX | I2S_MODE_RX),
.sample_rate = fSampleRate,
.bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,
.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
.communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, // high interrupt priority
.dma_buf_count = 3,
.dma_buf_len = fBufferSize,
.use_apll = false
};
#endif
i2s_driver_install((i2s_port_t)0, &i2s_config, 0, nullptr);
i2s_set_pin((i2s_port_t)0, &pin_config);
PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO0_U, FUNC_GPIO0_CLK_OUT1);
REG_WRITE(PIN_CTRL, 0xFFFFFFF0);
}
virtual ~esp32audio()
{
destroy();
}
virtual bool init(const char* name, dsp* dsp)
{
destroy();
fDSP = dsp;
fNumInputs = fDSP->getNumInputs();
fNumOutputs = fDSP->getNumOutputs();
fDSP->init(fSampleRate);
if (fNumInputs > 0) {
fInChannel = new FAUSTFLOAT*[fNumInputs];
for (int i = 0; i < fNumInputs; i++) {
fInChannel[i] = new FAUSTFLOAT[fBufferSize];
}
} else {
fInChannel = nullptr;
}
if (fNumOutputs > 0) {
fOutChannel = new FAUSTFLOAT*[fNumOutputs];
for (int i = 0; i < fNumOutputs; i++) {
fOutChannel[i] = new FAUSTFLOAT[fBufferSize];
}
} else {
fOutChannel = nullptr;
}
return true;
}
virtual bool start()
{
if (!fRunning) {
fRunning = true;
return (xTaskCreatePinnedToCore(audioTaskHandler, "Faust DSP Task", 4096, (void*)this, 24, &fHandle, 0) == pdPASS);
} else {
return true;
}
}
virtual void stop()
{
if (fRunning) {
fRunning = false;
vTaskDelay(1/portTICK_PERIOD_MS);
fHandle = nullptr;
}
}
virtual int getBufferSize() { return fBufferSize; }
virtual int getSampleRate() { return fSampleRate; }
virtual int getNumInputs() { return AUDIO_MAX_CHAN; }
virtual int getNumOutputs() { return AUDIO_MAX_CHAN; }
// Returns the average proportion of available CPU being spent inside the audio callbacks (between 0 and 1.0).
virtual float getCPULoad() { return 0.f; }
};
#endif
/************************** END esp32audio.h **************************/
#ifndef FAUST_MIDIUI_H
#define FAUST_MIDIUI_H
#include <vector>
#include <string>
#include <utility>
#include <iostream>
#include <cstdlib>
#include <cmath>
/************************** BEGIN GUI.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef __GUI_H__
#define __GUI_H__
#include <list>
#include <map>
#include <vector>
#include <iostream>
#include <assert.h>
#ifdef _WIN32
# pragma warning (disable: 4100)
#else
# pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
/************************** BEGIN ValueConverter.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef __ValueConverter__
#define __ValueConverter__
/***************************************************************************************
ValueConverter.h
(GRAME, Copyright 2015-2019)
Set of conversion objects used to map user interface values (for example a gui slider
delivering values between 0 and 1) to faust values (for example a vslider between
20 and 20000) using a log scale.
-- Utilities
Range(lo,hi) : clip a value x between lo and hi
Interpolator(lo,hi,v1,v2) : Maps a value x between lo and hi to a value y between v1 and v2
Interpolator3pt(lo,mi,hi,v1,vm,v2) : Map values between lo mid hi to values between v1 vm v2
-- Value Converters
ValueConverter::ui2faust(x)
ValueConverter::faust2ui(x)
-- ValueConverters used for sliders depending of the scale
LinearValueConverter(umin, umax, fmin, fmax)
LinearValueConverter2(lo, mi, hi, v1, vm, v2) using 2 segments
LogValueConverter(umin, umax, fmin, fmax)
ExpValueConverter(umin, umax, fmin, fmax)
-- ValueConverters used for accelerometers based on 3 points
AccUpConverter(amin, amid, amax, fmin, fmid, fmax) -- curve 0
AccDownConverter(amin, amid, amax, fmin, fmid, fmax) -- curve 1
AccUpDownConverter(amin, amid, amax, fmin, fmid, fmax) -- curve 2
AccDownUpConverter(amin, amid, amax, fmin, fmid, fmax) -- curve 3
-- lists of ZoneControl are used to implement accelerometers metadata for each axes
ZoneControl(zone, valueConverter) : a zone with an accelerometer data converter
-- ZoneReader are used to implement screencolor metadata
ZoneReader(zone, valueConverter) : a zone with a data converter
****************************************************************************************/
#include <float.h>
#include <algorithm> // std::max
#include <cmath>
#include <vector>
#include <assert.h>
//--------------------------------------------------------------------------------------
// Interpolator(lo,hi,v1,v2)
// Maps a value x between lo and hi to a value y between v1 and v2
// y = v1 + (x-lo)/(hi-lo)*(v2-v1)
// y = v1 + (x-lo) * coef with coef = (v2-v1)/(hi-lo)
// y = v1 + x*coef - lo*coef
// y = v1 - lo*coef + x*coef
// y = offset + x*coef with offset = v1 - lo*coef
//--------------------------------------------------------------------------------------
class Interpolator
{
private:
//--------------------------------------------------------------------------------------
// Range(lo,hi) clip a value between lo and hi
//--------------------------------------------------------------------------------------
struct Range
{
double fLo;
double fHi;
Range(double x, double y) : fLo(std::min<double>(x,y)), fHi(std::max<double>(x,y)) {}
double operator()(double x) { return (x<fLo) ? fLo : (x>fHi) ? fHi : x; }
};
Range fRange;
double fCoef;
double fOffset;
public:
Interpolator(double lo, double hi, double v1, double v2) : fRange(lo,hi)
{
if (hi != lo) {
// regular case
fCoef = (v2-v1)/(hi-lo);
fOffset = v1 - lo*fCoef;
} else {
// degenerate case, avoids division by zero
fCoef = 0;
fOffset = (v1+v2)/2;
}
}
double operator()(double v)
{
double x = fRange(v);
return fOffset + x*fCoef;
}
void getLowHigh(double& amin, double& amax)
{
amin = fRange.fLo;
amax = fRange.fHi;
}
};
//--------------------------------------------------------------------------------------
// Interpolator3pt(lo,mi,hi,v1,vm,v2)
// Map values between lo mid hi to values between v1 vm v2
//--------------------------------------------------------------------------------------
class Interpolator3pt
{
private:
Interpolator fSegment1;
Interpolator fSegment2;
double fMid;
public:
Interpolator3pt(double lo, double mi, double hi, double v1, double vm, double v2) :
fSegment1(lo, mi, v1, vm),
fSegment2(mi, hi, vm, v2),
fMid(mi) {}
double operator()(double x) { return (x < fMid) ? fSegment1(x) : fSegment2(x); }
void getMappingValues(double& amin, double& amid, double& amax)
{
fSegment1.getLowHigh(amin, amid);
fSegment2.getLowHigh(amid, amax);
}
};
//--------------------------------------------------------------------------------------
// Abstract ValueConverter class. Converts values between UI and Faust representations
//--------------------------------------------------------------------------------------
class ValueConverter
{
public:
virtual ~ValueConverter() {}
virtual double ui2faust(double x) = 0;
virtual double faust2ui(double x) = 0;
};
//--------------------------------------------------------------------------------------
// A converter than can be updated
//--------------------------------------------------------------------------------------
class UpdatableValueConverter : public ValueConverter {
protected:
bool fActive;
public:
UpdatableValueConverter():fActive(true)
{}
virtual ~UpdatableValueConverter()
{}
virtual void setMappingValues(double amin, double amid, double amax, double min, double init, double max) = 0;
virtual void getMappingValues(double& amin, double& amid, double& amax) = 0;
void setActive(bool on_off) { fActive = on_off; }
bool getActive() { return fActive; }
};
//--------------------------------------------------------------------------------------
// Linear conversion between ui and Faust values
//--------------------------------------------------------------------------------------
class LinearValueConverter : public ValueConverter
{
private:
Interpolator fUI2F;
Interpolator fF2UI;
public:
LinearValueConverter(double umin, double umax, double fmin, double fmax) :
fUI2F(umin,umax,fmin,fmax), fF2UI(fmin,fmax,umin,umax)
{}
LinearValueConverter() : fUI2F(0.,0.,0.,0.), fF2UI(0.,0.,0.,0.)
{}
virtual double ui2faust(double x) { return fUI2F(x); }
virtual double faust2ui(double x) { return fF2UI(x); }
};
//--------------------------------------------------------------------------------------
// Two segments linear conversion between ui and Faust values
//--------------------------------------------------------------------------------------
class LinearValueConverter2 : public UpdatableValueConverter
{
private:
Interpolator3pt fUI2F;
Interpolator3pt fF2UI;
public:
LinearValueConverter2(double amin, double amid, double amax, double min, double init, double max) :
fUI2F(amin, amid, amax, min, init, max), fF2UI(min, init, max, amin, amid, amax)
{}
LinearValueConverter2() : fUI2F(0.,0.,0.,0.,0.,0.), fF2UI(0.,0.,0.,0.,0.,0.)
{}
virtual double ui2faust(double x) { return fUI2F(x); }
virtual double faust2ui(double x) { return fF2UI(x); }
virtual void setMappingValues(double amin, double amid, double amax, double min, double init, double max)
{
fUI2F = Interpolator3pt(amin, amid, amax, min, init, max);
fF2UI = Interpolator3pt(min, init, max, amin, amid, amax);
}
virtual void getMappingValues(double& amin, double& amid, double& amax)
{
fUI2F.getMappingValues(amin, amid, amax);
}
};
//--------------------------------------------------------------------------------------
// Logarithmic conversion between ui and Faust values
//--------------------------------------------------------------------------------------
class LogValueConverter : public LinearValueConverter
{
public:
LogValueConverter(double umin, double umax, double fmin, double fmax) :
LinearValueConverter(umin, umax, std::log(std::max<double>(DBL_MIN, fmin)), std::log(std::max<double>(DBL_MIN, fmax)))
{}
virtual double ui2faust(double x) { return std::exp(LinearValueConverter::ui2faust(x)); }
virtual double faust2ui(double x) { return LinearValueConverter::faust2ui(std::log(std::max<double>(x, DBL_MIN))); }
};
//--------------------------------------------------------------------------------------
// Exponential conversion between ui and Faust values
//--------------------------------------------------------------------------------------
class ExpValueConverter : public LinearValueConverter
{
public:
ExpValueConverter(double umin, double umax, double fmin, double fmax) :
LinearValueConverter(umin, umax, std::min<double>(DBL_MAX, std::exp(fmin)), std::min<double>(DBL_MAX, std::exp(fmax)))
{}
virtual double ui2faust(double x) { return std::log(LinearValueConverter::ui2faust(x)); }
virtual double faust2ui(double x) { return LinearValueConverter::faust2ui(std::min<double>(DBL_MAX, std::exp(x))); }
};
//--------------------------------------------------------------------------------------
// Convert accelerometer or gyroscope values to Faust values
// Using an Up curve (curve 0)
//--------------------------------------------------------------------------------------
class AccUpConverter : public UpdatableValueConverter
{
private:
Interpolator3pt fA2F;
Interpolator3pt fF2A;
public:
AccUpConverter(double amin, double amid, double amax, double fmin, double fmid, double fmax) :
fA2F(amin,amid,amax,fmin,fmid,fmax),
fF2A(fmin,fmid,fmax,amin,amid,amax)
{}
virtual double ui2faust(double x) { return fA2F(x); }
virtual double faust2ui(double x) { return fF2A(x); }
virtual void setMappingValues(double amin, double amid, double amax, double fmin, double fmid, double fmax)
{
//__android_log_print(ANDROID_LOG_ERROR, "Faust", "AccUpConverter update %f %f %f %f %f %f", amin,amid,amax,fmin,fmid,fmax);
fA2F = Interpolator3pt(amin, amid, amax, fmin, fmid, fmax);
fF2A = Interpolator3pt(fmin, fmid, fmax, amin, amid, amax);
}
virtual void getMappingValues(double& amin, double& amid, double& amax)
{
fA2F.getMappingValues(amin, amid, amax);
}
};
//--------------------------------------------------------------------------------------
// Convert accelerometer or gyroscope values to Faust values
// Using a Down curve (curve 1)
//--------------------------------------------------------------------------------------
class AccDownConverter : public UpdatableValueConverter
{
private:
Interpolator3pt fA2F;
Interpolator3pt fF2A;
public:
AccDownConverter(double amin, double amid, double amax, double fmin, double fmid, double fmax) :
fA2F(amin,amid,amax,fmax,fmid,fmin),
fF2A(fmin,fmid,fmax,amax,amid,amin)
{}
virtual double ui2faust(double x) { return fA2F(x); }
virtual double faust2ui(double x) { return fF2A(x); }
virtual void setMappingValues(double amin, double amid, double amax, double fmin, double fmid, double fmax)
{
//__android_log_print(ANDROID_LOG_ERROR, "Faust", "AccDownConverter update %f %f %f %f %f %f", amin,amid,amax,fmin,fmid,fmax);
fA2F = Interpolator3pt(amin, amid, amax, fmax, fmid, fmin);
fF2A = Interpolator3pt(fmin, fmid, fmax, amax, amid, amin);
}
virtual void getMappingValues(double& amin, double& amid, double& amax)
{
fA2F.getMappingValues(amin, amid, amax);
}
};
//--------------------------------------------------------------------------------------
// Convert accelerometer or gyroscope values to Faust values
// Using an Up-Down curve (curve 2)
//--------------------------------------------------------------------------------------
class AccUpDownConverter : public UpdatableValueConverter
{
private:
Interpolator3pt fA2F;
Interpolator fF2A;
public:
AccUpDownConverter(double amin, double amid, double amax, double fmin, double fmid, double fmax) :
fA2F(amin,amid,amax,fmin,fmax,fmin),
fF2A(fmin,fmax,amin,amax) // Special, pseudo inverse of a non monotonic function
{}
virtual double ui2faust(double x) { return fA2F(x); }
virtual double faust2ui(double x) { return fF2A(x); }
virtual void setMappingValues(double amin, double amid, double amax, double fmin, double fmid, double fmax)
{
//__android_log_print(ANDROID_LOG_ERROR, "Faust", "AccUpDownConverter update %f %f %f %f %f %f", amin,amid,amax,fmin,fmid,fmax);
fA2F = Interpolator3pt(amin, amid, amax, fmin, fmax, fmin);
fF2A = Interpolator(fmin, fmax, amin, amax);
}
virtual void getMappingValues(double& amin, double& amid, double& amax)
{
fA2F.getMappingValues(amin, amid, amax);
}
};
//--------------------------------------------------------------------------------------
// Convert accelerometer or gyroscope values to Faust values
// Using a Down-Up curve (curve 3)
//--------------------------------------------------------------------------------------
class AccDownUpConverter : public UpdatableValueConverter
{
private:
Interpolator3pt fA2F;
Interpolator fF2A;
public:
AccDownUpConverter(double amin, double amid, double amax, double fmin, double fmid, double fmax) :
fA2F(amin,amid,amax,fmax,fmin,fmax),
fF2A(fmin,fmax,amin,amax) // Special, pseudo inverse of a non monotonic function
{}
virtual double ui2faust(double x) { return fA2F(x); }
virtual double faust2ui(double x) { return fF2A(x); }
virtual void setMappingValues(double amin, double amid, double amax, double fmin, double fmid, double fmax)
{
//__android_log_print(ANDROID_LOG_ERROR, "Faust", "AccDownUpConverter update %f %f %f %f %f %f", amin,amid,amax,fmin,fmid,fmax);
fA2F = Interpolator3pt(amin, amid, amax, fmax, fmin, fmax);
fF2A = Interpolator(fmin, fmax, amin, amax);
}
virtual void getMappingValues(double& amin, double& amid, double& amax)
{
fA2F.getMappingValues(amin, amid, amax);
}
};
//--------------------------------------------------------------------------------------
// Base class for ZoneControl
//--------------------------------------------------------------------------------------
class ZoneControl
{
protected:
FAUSTFLOAT* fZone;
public:
ZoneControl(FAUSTFLOAT* zone) : fZone(zone) {}
virtual ~ZoneControl() {}
virtual void update(double v) {}
virtual void setMappingValues(int curve, double amin, double amid, double amax, double min, double init, double max) {}
virtual void getMappingValues(double& amin, double& amid, double& amax) {}
FAUSTFLOAT* getZone() { return fZone; }
virtual void setActive(bool on_off) {}
virtual bool getActive() { return false; }
virtual int getCurve() { return -1; }
};
//--------------------------------------------------------------------------------------
// Useful to implement accelerometers metadata as a list of ZoneControl for each axes
//--------------------------------------------------------------------------------------
class ConverterZoneControl : public ZoneControl
{
protected:
ValueConverter* fValueConverter;
public:
ConverterZoneControl(FAUSTFLOAT* zone, ValueConverter* converter) : ZoneControl(zone), fValueConverter(converter) {}
virtual ~ConverterZoneControl() { delete fValueConverter; } // Assuming fValueConverter is not kept elsewhere...
virtual void update(double v) { *fZone = fValueConverter->ui2faust(v); }
ValueConverter* getConverter() { return fValueConverter; }
};
//--------------------------------------------------------------------------------------
// Association of a zone and a four value converter, each one for each possible curve.
// Useful to implement accelerometers metadata as a list of ZoneControl for each axes
//--------------------------------------------------------------------------------------
class CurveZoneControl : public ZoneControl
{
private:
std::vector<UpdatableValueConverter*> fValueConverters;
int fCurve;
public:
CurveZoneControl(FAUSTFLOAT* zone, int curve, double amin, double amid, double amax, double min, double init, double max) : ZoneControl(zone), fCurve(0)
{
assert(curve >= 0 && curve <= 3);
fValueConverters.push_back(new AccUpConverter(amin, amid, amax, min, init, max));
fValueConverters.push_back(new AccDownConverter(amin, amid, amax, min, init, max));
fValueConverters.push_back(new AccUpDownConverter(amin, amid, amax, min, init, max));
fValueConverters.push_back(new AccDownUpConverter(amin, amid, amax, min, init, max));
fCurve = curve;
}
virtual ~CurveZoneControl()
{
std::vector<UpdatableValueConverter*>::iterator it;
for (it = fValueConverters.begin(); it != fValueConverters.end(); it++) {
delete(*it);
}
}
void update(double v) { if (fValueConverters[fCurve]->getActive()) *fZone = fValueConverters[fCurve]->ui2faust(v); }
void setMappingValues(int curve, double amin, double amid, double amax, double min, double init, double max)
{
fValueConverters[curve]->setMappingValues(amin, amid, amax, min, init, max);
fCurve = curve;
}
void getMappingValues(double& amin, double& amid, double& amax)
{
fValueConverters[fCurve]->getMappingValues(amin, amid, amax);
}
void setActive(bool on_off)
{
std::vector<UpdatableValueConverter*>::iterator it;
for (it = fValueConverters.begin(); it != fValueConverters.end(); it++) {
(*it)->setActive(on_off);
}
}
int getCurve() { return fCurve; }
};
class ZoneReader
{
private:
FAUSTFLOAT* fZone;
Interpolator fInterpolator;
public:
ZoneReader(FAUSTFLOAT* zone, double lo, double hi) : fZone(zone), fInterpolator(lo, hi, 0, 255) {}
virtual ~ZoneReader() {}
int getValue()
{
return (fZone != nullptr) ? int(fInterpolator(*fZone)) : 127;
}
};
#endif
/************************** END ValueConverter.h **************************/
/************************** BEGIN MetaDataUI.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef MetaData_UI_H
#define MetaData_UI_H
#ifndef FAUSTFLOAT
#define FAUSTFLOAT float
#endif
#include <map>
#include <set>
#include <string>
#include <string.h>
#include <assert.h>
/************************** BEGIN SimpleParser.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef SIMPLEPARSER_H
#define SIMPLEPARSER_H
// ---------------------------------------------------------------------
// Simple Parser
// A parser returns true if it was able to parse what it is
// supposed to parse and advance the pointer. Otherwise it returns false
// and the pointer is not advanced so that another parser can be tried.
// ---------------------------------------------------------------------
#include <vector>
#include <map>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <ctype.h>
#ifndef _WIN32
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
struct itemInfo {
std::string type;
std::string label;
std::string url;
std::string address;
int index;
double init;
double min;
double max;
double step;
std::vector<std::pair<std::string, std::string> > meta;
itemInfo():index(0), init(0.), min(0.), max(0.), step(0.)
{}
};
// ---------------------------------------------------------------------
// Elementary parsers
// ---------------------------------------------------------------------
// Report a parsing error
static bool parseError(const char*& p, const char* errmsg)
{
std::cerr << "Parse error : " << errmsg << " here : " << p << std::endl;
return true;
}
/**
* @brief skipBlank : advance pointer p to the first non blank character
* @param p the string to parse, then the remaining string
*/
static void skipBlank(const char*& p)
{
while (isspace(*p)) { p++; }
}
// Parse character x, but don't report error if fails
static bool tryChar(const char*& p, char x)
{
skipBlank(p);
if (x == *p) {
p++;
return true;
} else {
return false;
}
}
/**
* @brief parseChar : parse a specific character x
* @param p the string to parse, then the remaining string
* @param x the character to recognize
* @return true if x was found at the begin of p
*/
static bool parseChar(const char*& p, char x)
{
skipBlank(p);
if (x == *p) {
p++;
return true;
} else {
return false;
}
}
/**
* @brief parseWord : parse a specific string w
* @param p the string to parse, then the remaining string
* @param w the string to recognize
* @return true if string w was found at the begin of p
*/
static bool parseWord(const char*& p, const char* w)
{
skipBlank(p);
const char* saved = p; // to restore position if we fail
while ((*w == *p) && (*w)) {++w; ++p;}
if (*w) {
p = saved;
return false;
} else {
return true;
}
}
/**
* @brief parseDouble : parse number [s]dddd[.dddd] and store the result in x
* @param p the string to parse, then the remaining string
* @param x the float number found if any
* @return true if a float number was found at the begin of p
*/
static bool parseDouble(const char*& p, double& x)
{
std::stringstream reader(p);
std::streambuf* pbuf = reader.rdbuf();
// Keep position before parsing
std::streamsize size1 = pbuf->in_avail();
// Parse the number
reader >> x;
// Keep position after parsing
std::streamsize size2 = pbuf->in_avail();
// Move from the actual size
p += (size1 - size2);
// True if the number contains at least one digit
return (size1 > size2);
}
/**
* @brief parseString, parse an arbitrary quoted string q...q and store the result in s
* @param p the string to parse, then the remaining string
* @param quote the character used to quote the string
* @param s the (unquoted) string found if any
* @return true if a string was found at the begin of p
*/
static bool parseString(const char*& p, char quote, std::string& s)
{
std::string str;
skipBlank(p);
const char* saved = p; // to restore position if we fail
if (*p++ == quote) {
while ((*p != 0) && (*p != quote)) {
str += *p++;
}
if (*p++ == quote) {
s = str;
return true;
}
}
p = saved;
return false;
}
/**
* @brief parseSQString, parse a single quoted string '...' and store the result in s
* @param p the string to parse, then the remaining string
* @param s the (unquoted) string found if any
* @return true if a string was found at the begin of p
*/
static bool parseSQString(const char*& p, std::string& s)
{
return parseString(p, '\'', s);
}
/**
* @brief parseDQString, parse a double quoted string "..." and store the result in s
* @param p the string to parse, then the remaining string
* @param s the (unquoted) string found if any
* @return true if a string was found at the begin of p
*/
static bool parseDQString(const char*& p, std::string& s)
{
return parseString(p, '"', s);
}
// ---------------------------------------------------------------------
//
// IMPLEMENTATION
//
// ---------------------------------------------------------------------
/**
* @brief parseMenuItem, parse a menu item ...'low':440.0...
* @param p the string to parse, then the remaining string
* @param name the name found
* @param value the value found
* @return true if a nemu item was found
*/
static bool parseMenuItem(const char*& p, std::string& name, double& value)
{
const char* saved = p; // to restore position if we fail
if (parseSQString(p, name) && parseChar(p, ':') && parseDouble(p, value)) {
return true;
} else {
p = saved;
return false;
}
}
static bool parseMenuItem2(const char*& p, std::string& name)
{
const char* saved = p; // to restore position if we fail
// single quoted
if (parseSQString(p, name)) {
return true;
} else {
p = saved;
return false;
}
}
/**
* @brief parseMenuList, parse a menu list {'low' : 440.0; 'mid' : 880.0; 'hi' : 1760.0}...
* @param p the string to parse, then the remaining string
* @param names the vector of names found
* @param values the vector of values found
* @return true if a menu list was found
*/
static bool parseMenuList(const char*& p, std::vector<std::string>& names, std::vector<double>& values)
{
std::vector<std::string> tmpnames;
std::vector<double> tmpvalues;
const char* saved = p; // to restore position if we fail
if (parseChar(p, '{')) {
do {
std::string n;
double v;
if (parseMenuItem(p, n, v)) {
tmpnames.push_back(n);
tmpvalues.push_back(v);
} else {
p = saved;
return false;
}
} while (parseChar(p, ';'));
if (parseChar(p, '}')) {
// we suceeded
names = tmpnames;
values = tmpvalues;
return true;
}
}
p = saved;
return false;
}
static bool parseMenuList2(const char*& p, std::vector<std::string>& names, bool debug)
{
std::vector<std::string> tmpnames;
const char* saved = p; // to restore position if we fail
if (parseChar(p, '{')) {
do {
std::string n;
if (parseMenuItem2(p, n)) {
tmpnames.push_back(n);
} else {
goto error;
}
} while (parseChar(p, ';'));
if (parseChar(p, '}')) {
// we suceeded
names = tmpnames;
return true;
}
}
error:
if (debug) { std::cerr << "parseMenuList2 : (" << saved << ") is not a valid list !\n"; }
p = saved;
return false;
}
/// ---------------------------------------------------------------------
// Parse list of strings
/// ---------------------------------------------------------------------
static bool parseList(const char*& p, std::vector<std::string>& items)
{
const char* saved = p; // to restore position if we fail
if (parseChar(p, '[')) {
do {
std::string item;
if (!parseDQString(p, item)) {
p = saved;
return false;
}
items.push_back(item);
} while (tryChar(p, ','));
return parseChar(p, ']');
} else {
p = saved;
return false;
}
}
static bool parseMetaData(const char*& p, std::map<std::string, std::string>& metadatas)
{
const char* saved = p; // to restore position if we fail
std::string metaKey, metaValue;
if (parseChar(p, ':') && parseChar(p, '[')) {
do {
if (parseChar(p, '{') && parseDQString(p, metaKey) && parseChar(p, ':') && parseDQString(p, metaValue) && parseChar(p, '}')) {
metadatas[metaKey] = metaValue;
}
} while (tryChar(p, ','));
return parseChar(p, ']');
} else {
p = saved;
return false;
}
}
static bool parseItemMetaData(const char*& p, std::vector<std::pair<std::string, std::string> >& metadatas)
{
const char* saved = p; // to restore position if we fail
std::string metaKey, metaValue;
if (parseChar(p, ':') && parseChar(p, '[')) {
do {
if (parseChar(p, '{') && parseDQString(p, metaKey) && parseChar(p, ':') && parseDQString(p, metaValue) && parseChar(p, '}')) {
metadatas.push_back(std::make_pair(metaKey, metaValue));
}
} while (tryChar(p, ','));
return parseChar(p, ']');
} else {
p = saved;
return false;
}
}
// ---------------------------------------------------------------------
// Parse metadatas of the interface:
// "name" : "...", "inputs" : "...", "outputs" : "...", ...
// and store the result as key/value
/// ---------------------------------------------------------------------
static bool parseGlobalMetaData(const char*& p, std::string& key, std::string& value, double& dbl, std::map<std::string, std::string>& metadatas, std::vector<std::string>& items)
{
const char* saved = p; // to restore position if we fail
if (parseDQString(p, key)) {
if (key == "meta") {
return parseMetaData(p, metadatas);
} else {
return parseChar(p, ':') && (parseDQString(p, value) || parseList(p, items) || parseDouble(p, dbl));
}
} else {
p = saved;
return false;
}
}
// ---------------------------------------------------------------------
// Parse gui:
// "type" : "...", "label" : "...", "address" : "...", ...
// and store the result in uiItems Vector
/// ---------------------------------------------------------------------
static bool parseUI(const char*& p, std::vector<itemInfo>& uiItems, int& numItems)
{
const char* saved = p; // to restore position if we fail
if (parseChar(p, '{')) {
std::string label;
std::string value;
double dbl = 0;
do {
if (parseDQString(p, label)) {
if (label == "type") {
if (uiItems.size() != 0) {
numItems++;
}
if (parseChar(p, ':') && parseDQString(p, value)) {
itemInfo item;
item.type = value;
uiItems.push_back(item);
}
}
else if (label == "label") {
if (parseChar(p, ':') && parseDQString(p, value)) {
uiItems[numItems].label = value;
}
}
else if (label == "url") {
if (parseChar(p, ':') && parseDQString(p, value)) {
uiItems[numItems].url = value;
}
}
else if (label == "address") {
if (parseChar(p, ':') && parseDQString(p, value)) {
uiItems[numItems].address = value;
}
}
else if (label == "index") {
if (parseChar(p, ':') && parseDouble(p, dbl)) {
uiItems[numItems].index = int(dbl);
}
}
else if (label == "meta") {
if (!parseItemMetaData(p, uiItems[numItems].meta)) {
return false;
}
}
else if (label == "init") {
if (parseChar(p, ':') && parseDouble(p, dbl)) {
uiItems[numItems].init = dbl;
}
}
else if (label == "min") {
if (parseChar(p, ':') && parseDouble(p, dbl)) {
uiItems[numItems].min = dbl;
}
}
else if (label == "max") {
if (parseChar(p, ':') && parseDouble(p, dbl)) {
uiItems[numItems].max = dbl;
}
}
else if (label == "step") {
if (parseChar(p, ':') && parseDouble(p, dbl)) {
uiItems[numItems].step = dbl;
}
}
else if (label == "items") {
if (parseChar(p, ':') && parseChar(p, '[')) {
do {
if (!parseUI(p, uiItems, numItems)) {
p = saved;
return false;
}
} while (tryChar(p, ','));
if (parseChar(p, ']')) {
itemInfo item;
item.type = "close";
uiItems.push_back(item);
numItems++;
}
}
}
} else {
p = saved;
return false;
}
} while (tryChar(p, ','));
return parseChar(p, '}');
} else {
return true; // "items": [] is valid
}
}
// ---------------------------------------------------------------------
// Parse full JSON record describing a JSON/Faust interface :
// {"metadatas": "...", "ui": [{ "type": "...", "label": "...", "items": [...], "address": "...","init": "...", "min": "...", "max": "...","step": "..."}]}
//
// and store the result in map Metadatas and vector containing the items of the interface. Returns true if parsing was successfull.
/// ---------------------------------------------------------------------
static bool parseJson(const char*& p,
std::map<std::string, std::pair<std::string, double> >& metaDatas0,
std::map<std::string, std::string>& metaDatas1,
std::map<std::string, std::vector<std::string> >& metaDatas2,
std::vector<itemInfo>& uiItems)
{
parseChar(p, '{');
do {
std::string key;
std::string value;
double dbl = 0;
std::vector<std::string> items;
if (parseGlobalMetaData(p, key, value, dbl, metaDatas1, items)) {
if (key != "meta") {
// keep "name", "inputs", "outputs" key/value pairs
if (items.size() > 0) {
metaDatas2[key] = items;
items.clear();
} else if (value != "") {
metaDatas0[key].first = value;
} else {
metaDatas0[key].second = dbl;
}
}
} else if (key == "ui") {
int numItems = 0;
parseChar(p, '[') && parseUI(p, uiItems, numItems);
}
} while (tryChar(p, ','));
return parseChar(p, '}');
}
#endif // SIMPLEPARSER_H
/************************** END SimpleParser.h **************************/
static bool startWith(const std::string& str, const std::string& prefix)
{
return (str.substr(0, prefix.size()) == prefix);
}
/**
* Convert a dB value into a scale between 0 and 1 (following IEC standard ?)
*/
static FAUSTFLOAT dB2Scale(FAUSTFLOAT dB)
{
FAUSTFLOAT scale = FAUSTFLOAT(1.0);
/*if (dB < -70.0f)
scale = 0.0f;
else*/
if (dB < FAUSTFLOAT(-60.0))
scale = (dB + FAUSTFLOAT(70.0)) * FAUSTFLOAT(0.0025);
else if (dB < FAUSTFLOAT(-50.0))
scale = (dB + FAUSTFLOAT(60.0)) * FAUSTFLOAT(0.005) + FAUSTFLOAT(0.025);
else if (dB < FAUSTFLOAT(-40.0))
scale = (dB + FAUSTFLOAT(50.0)) * FAUSTFLOAT(0.0075) + FAUSTFLOAT(0.075);
else if (dB < FAUSTFLOAT(-30.0))
scale = (dB + FAUSTFLOAT(40.0)) * FAUSTFLOAT(0.015) + FAUSTFLOAT(0.15);
else if (dB < FAUSTFLOAT(-20.0))
scale = (dB + FAUSTFLOAT(30.0)) * FAUSTFLOAT(0.02) + FAUSTFLOAT(0.3);
else if (dB < FAUSTFLOAT(-0.001) || dB > FAUSTFLOAT(0.001)) /* if (dB < 0.0) */
scale = (dB + FAUSTFLOAT(20.0)) * FAUSTFLOAT(0.025) + FAUSTFLOAT(0.5);
return scale;
}
/*******************************************************************************
* MetaDataUI : Common class for MetaData handling
******************************************************************************/
//============================= BEGIN GROUP LABEL METADATA===========================
// Unlike widget's label, metadata inside group's label are not extracted directly by
// the Faust compiler. Therefore they must be extracted within the architecture file
//-----------------------------------------------------------------------------------
class MetaDataUI {
protected:
std::string fGroupTooltip;
std::map<FAUSTFLOAT*, FAUSTFLOAT> fGuiSize; // map widget zone with widget size coef
std::map<FAUSTFLOAT*, std::string> fTooltip; // map widget zone with tooltip strings
std::map<FAUSTFLOAT*, std::string> fUnit; // map widget zone to unit string (i.e. "dB")
std::map<FAUSTFLOAT*, std::string> fRadioDescription; // map zone to {'low':440; ...; 'hi':1000.0}
std::map<FAUSTFLOAT*, std::string> fMenuDescription; // map zone to {'low':440; ...; 'hi':1000.0}
std::set<FAUSTFLOAT*> fKnobSet; // set of widget zone to be knobs
std::set<FAUSTFLOAT*> fLedSet; // set of widget zone to be LEDs
std::set<FAUSTFLOAT*> fNumSet; // set of widget zone to be numerical bargraphs
std::set<FAUSTFLOAT*> fLogSet; // set of widget zone having a log UI scale
std::set<FAUSTFLOAT*> fExpSet; // set of widget zone having an exp UI scale
std::set<FAUSTFLOAT*> fHiddenSet; // set of hidden widget zone
void clearMetadata()
{
fGuiSize.clear();
fTooltip.clear();
fUnit.clear();
fRadioDescription.clear();
fMenuDescription.clear();
fKnobSet.clear();
fLedSet.clear();
fNumSet.clear();
fLogSet.clear();
fExpSet.clear();
fHiddenSet.clear();
}
/**
* rmWhiteSpaces(): Remove the leading and trailing white spaces of a string
* (but not those in the middle of the string)
*/
static std::string rmWhiteSpaces(const std::string& s)
{
size_t i = s.find_first_not_of(" \t");
size_t j = s.find_last_not_of(" \t");
if ((i != std::string::npos) && (j != std::string::npos)) {
return s.substr(i, 1+j-i);
} else {
return "";
}
}
/**
* Format tooltip string by replacing some white spaces by
* return characters so that line width doesn't exceed n.
* Limitation : long words exceeding n are not cut
*/
std::string formatTooltip(int n, const std::string& tt)
{
std::string ss = tt; // ss string we are going to format
int lws = 0; // last white space encountered
int lri = 0; // last return inserted
for (int i = 0; i < (int)tt.size(); i++) {
if (tt[i] == ' ') lws = i;
if (((i-lri) >= n) && (lws > lri)) {
// insert return here
ss[lws] = '\n';
lri = lws;
}
}
return ss;
}
public:
virtual ~MetaDataUI()
{}
enum Scale {
kLin,
kLog,
kExp
};
Scale getScale(FAUSTFLOAT* zone)
{
if (fLogSet.count(zone) > 0) return kLog;
if (fExpSet.count(zone) > 0) return kExp;
return kLin;
}
bool isKnob(FAUSTFLOAT* zone)
{
return fKnobSet.count(zone) > 0;
}
bool isRadio(FAUSTFLOAT* zone)
{
return fRadioDescription.count(zone) > 0;
}
bool isMenu(FAUSTFLOAT* zone)
{
return fMenuDescription.count(zone) > 0;
}
bool isLed(FAUSTFLOAT* zone)
{
return fLedSet.count(zone) > 0;
}
bool isNumerical(FAUSTFLOAT* zone)
{
return fNumSet.count(zone) > 0;
}
bool isHidden(FAUSTFLOAT* zone)
{
return fHiddenSet.count(zone) > 0;
}
/**
* Extracts metadata from a label : 'vol [unit: dB]' -> 'vol' + metadata(unit=dB)
*/
static void extractMetadata(const std::string& fulllabel, std::string& label, std::map<std::string, std::string>& metadata)
{
enum {kLabel, kEscape1, kEscape2, kEscape3, kKey, kValue};
int state = kLabel; int deep = 0;
std::string key, value;
for (unsigned int i = 0; i < fulllabel.size(); i++) {
char c = fulllabel[i];
switch (state) {
case kLabel :
assert(deep == 0);
switch (c) {
case '\\' : state = kEscape1; break;
case '[' : state = kKey; deep++; break;
default : label += c;
}
break;
case kEscape1:
label += c;
state = kLabel;
break;
case kEscape2:
key += c;
state = kKey;
break;
case kEscape3:
value += c;
state = kValue;
break;
case kKey:
assert(deep > 0);
switch (c) {
case '\\':
state = kEscape2;
break;
case '[':
deep++;
key += c;
break;
case ':':
if (deep == 1) {
state = kValue;
} else {
key += c;
}
break;
case ']':
deep--;
if (deep < 1) {
metadata[rmWhiteSpaces(key)] = "";
state = kLabel;
key="";
value="";
} else {
key += c;
}
break;
default : key += c;
}
break;
case kValue:
assert(deep > 0);
switch (c) {
case '\\':
state = kEscape3;
break;
case '[':
deep++;
value += c;
break;
case ']':
deep--;
if (deep < 1) {
metadata[rmWhiteSpaces(key)] = rmWhiteSpaces(value);
state = kLabel;
key = "";
value = "";
} else {
value += c;
}
break;
default : value += c;
}
break;
default:
std::cerr << "ERROR unrecognized state " << state << std::endl;
}
}
label = rmWhiteSpaces(label);
}
/**
* Analyses the widget zone metadata declarations and takes appropriate actions
*/
void declare(FAUSTFLOAT* zone, const char* key, const char* value)
{
if (zone == 0) {
// special zone 0 means group metadata
if (strcmp(key, "tooltip") == 0) {
// only group tooltip are currently implemented
fGroupTooltip = formatTooltip(30, value);
} else if (strcmp(key, "hidden") == 0) {
fHiddenSet.insert(zone);
}
} else {
if (strcmp(key, "size") == 0) {
fGuiSize[zone] = atof(value);
}
else if (strcmp(key, "tooltip") == 0) {
fTooltip[zone] = formatTooltip(30, value);
}
else if (strcmp(key, "unit") == 0) {
fUnit[zone] = value;
}
else if (strcmp(key, "hidden") == 0) {
fHiddenSet.insert(zone);
}
else if (strcmp(key, "scale") == 0) {
if (strcmp(value, "log") == 0) {
fLogSet.insert(zone);
} else if (strcmp(value, "exp") == 0) {
fExpSet.insert(zone);
}
}
else if (strcmp(key, "style") == 0) {
if (strcmp(value, "knob") == 0) {
fKnobSet.insert(zone);
} else if (strcmp(value, "led") == 0) {
fLedSet.insert(zone);
} else if (strcmp(value, "numerical") == 0) {
fNumSet.insert(zone);
} else {
const char* p = value;
if (parseWord(p, "radio")) {
fRadioDescription[zone] = std::string(p);
} else if (parseWord(p, "menu")) {
fMenuDescription[zone] = std::string(p);
}
}
}
}
}
};
#endif
/************************** END MetaDataUI.h **************************/
/************************** BEGIN ring-buffer.h **************************/
/*
Copyright (C) 2000 <NAME>
Copyright (C) 2003 <NAME>
Copyright (C) 2016 GRAME (renaming for internal use)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
ISO/POSIX C version of Paul Davis's lock free ringbuffer C++ code.
This is safe for the case of one read thread and one write thread.
*/
#ifndef __ring_buffer__
#define __ring_buffer__
#include <stdlib.h>
#include <string.h>
#ifdef WIN32
# pragma warning (disable: 4334)
#else
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
typedef struct {
char *buf;
size_t len;
}
ringbuffer_data_t;
typedef struct {
char *buf;
volatile size_t write_ptr;
volatile size_t read_ptr;
size_t size;
size_t size_mask;
int mlocked;
}
ringbuffer_t;
static ringbuffer_t *ringbuffer_create(size_t sz);
static void ringbuffer_free(ringbuffer_t *rb);
static void ringbuffer_get_read_vector(const ringbuffer_t *rb,
ringbuffer_data_t *vec);
static void ringbuffer_get_write_vector(const ringbuffer_t *rb,
ringbuffer_data_t *vec);
static size_t ringbuffer_read(ringbuffer_t *rb, char *dest, size_t cnt);
static size_t ringbuffer_peek(ringbuffer_t *rb, char *dest, size_t cnt);
static void ringbuffer_read_advance(ringbuffer_t *rb, size_t cnt);
static size_t ringbuffer_read_space(const ringbuffer_t *rb);
static int ringbuffer_mlock(ringbuffer_t *rb);
static void ringbuffer_reset(ringbuffer_t *rb);
static void ringbuffer_reset_size (ringbuffer_t * rb, size_t sz);
static size_t ringbuffer_write(ringbuffer_t *rb, const char *src,
size_t cnt);
static void ringbuffer_write_advance(ringbuffer_t *rb, size_t cnt);
static size_t ringbuffer_write_space(const ringbuffer_t *rb);
/* Create a new ringbuffer to hold at least `sz' bytes of data. The
actual buffer size is rounded up to the next power of two. */
static ringbuffer_t *
ringbuffer_create (size_t sz)
{
size_t power_of_two;
ringbuffer_t *rb;
if ((rb = (ringbuffer_t *) malloc (sizeof (ringbuffer_t))) == NULL) {
return NULL;
}
for (power_of_two = 1u; 1u << power_of_two < sz; power_of_two++);
rb->size = 1u << power_of_two;
rb->size_mask = rb->size;
rb->size_mask -= 1;
rb->write_ptr = 0;
rb->read_ptr = 0;
if ((rb->buf = (char *) malloc (rb->size)) == NULL) {
free (rb);
return NULL;
}
rb->mlocked = 0;
return rb;
}
/* Free all data associated with the ringbuffer `rb'. */
static void
ringbuffer_free (ringbuffer_t * rb)
{
#ifdef USE_MLOCK
if (rb->mlocked) {
munlock (rb->buf, rb->size);
}
#endif /* USE_MLOCK */
free (rb->buf);
free (rb);
}
/* Lock the data block of `rb' using the system call 'mlock'. */
static int
ringbuffer_mlock (ringbuffer_t * rb)
{
#ifdef USE_MLOCK
if (mlock (rb->buf, rb->size)) {
return -1;
}
#endif /* USE_MLOCK */
rb->mlocked = 1;
return 0;
}
/* Reset the read and write pointers to zero. This is not thread
safe. */
static void
ringbuffer_reset (ringbuffer_t * rb)
{
rb->read_ptr = 0;
rb->write_ptr = 0;
memset(rb->buf, 0, rb->size);
}
/* Reset the read and write pointers to zero. This is not thread
safe. */
static void
ringbuffer_reset_size (ringbuffer_t * rb, size_t sz)
{
rb->size = sz;
rb->size_mask = rb->size;
rb->size_mask -= 1;
rb->read_ptr = 0;
rb->write_ptr = 0;
}
/* Return the number of bytes available for reading. This is the
number of bytes in front of the read pointer and behind the write
pointer. */
static size_t
ringbuffer_read_space (const ringbuffer_t * rb)
{
size_t w, r;
w = rb->write_ptr;
r = rb->read_ptr;
if (w > r) {
return w - r;
} else {
return (w - r + rb->size) & rb->size_mask;
}
}
/* Return the number of bytes available for writing. This is the
number of bytes in front of the write pointer and behind the read
pointer. */
static size_t
ringbuffer_write_space (const ringbuffer_t * rb)
{
size_t w, r;
w = rb->write_ptr;
r = rb->read_ptr;
if (w > r) {
return ((r - w + rb->size) & rb->size_mask) - 1;
} else if (w < r) {
return (r - w) - 1;
} else {
return rb->size - 1;
}
}
/* The copying data reader. Copy at most `cnt' bytes from `rb' to
`dest'. Returns the actual number of bytes copied. */
static size_t
ringbuffer_read (ringbuffer_t * rb, char *dest, size_t cnt)
{
size_t free_cnt;
size_t cnt2;
size_t to_read;
size_t n1, n2;
if ((free_cnt = ringbuffer_read_space (rb)) == 0) {
return 0;
}
to_read = cnt > free_cnt ? free_cnt : cnt;
cnt2 = rb->read_ptr + to_read;
if (cnt2 > rb->size) {
n1 = rb->size - rb->read_ptr;
n2 = cnt2 & rb->size_mask;
} else {
n1 = to_read;
n2 = 0;
}
memcpy (dest, &(rb->buf[rb->read_ptr]), n1);
rb->read_ptr = (rb->read_ptr + n1) & rb->size_mask;
if (n2) {
memcpy (dest + n1, &(rb->buf[rb->read_ptr]), n2);
rb->read_ptr = (rb->read_ptr + n2) & rb->size_mask;
}
return to_read;
}
/* The copying data reader w/o read pointer advance. Copy at most
`cnt' bytes from `rb' to `dest'. Returns the actual number of bytes
copied. */
static size_t
ringbuffer_peek (ringbuffer_t * rb, char *dest, size_t cnt)
{
size_t free_cnt;
size_t cnt2;
size_t to_read;
size_t n1, n2;
size_t tmp_read_ptr;
tmp_read_ptr = rb->read_ptr;
if ((free_cnt = ringbuffer_read_space (rb)) == 0) {
return 0;
}
to_read = cnt > free_cnt ? free_cnt : cnt;
cnt2 = tmp_read_ptr + to_read;
if (cnt2 > rb->size) {
n1 = rb->size - tmp_read_ptr;
n2 = cnt2 & rb->size_mask;
} else {
n1 = to_read;
n2 = 0;
}
memcpy (dest, &(rb->buf[tmp_read_ptr]), n1);
tmp_read_ptr = (tmp_read_ptr + n1) & rb->size_mask;
if (n2) {
memcpy (dest + n1, &(rb->buf[tmp_read_ptr]), n2);
}
return to_read;
}
/* The copying data writer. Copy at most `cnt' bytes to `rb' from
`src'. Returns the actual number of bytes copied. */
static size_t
ringbuffer_write (ringbuffer_t * rb, const char *src, size_t cnt)
{
size_t free_cnt;
size_t cnt2;
size_t to_write;
size_t n1, n2;
if ((free_cnt = ringbuffer_write_space (rb)) == 0) {
return 0;
}
to_write = cnt > free_cnt ? free_cnt : cnt;
cnt2 = rb->write_ptr + to_write;
if (cnt2 > rb->size) {
n1 = rb->size - rb->write_ptr;
n2 = cnt2 & rb->size_mask;
} else {
n1 = to_write;
n2 = 0;
}
memcpy (&(rb->buf[rb->write_ptr]), src, n1);
rb->write_ptr = (rb->write_ptr + n1) & rb->size_mask;
if (n2) {
memcpy (&(rb->buf[rb->write_ptr]), src + n1, n2);
rb->write_ptr = (rb->write_ptr + n2) & rb->size_mask;
}
return to_write;
}
/* Advance the read pointer `cnt' places. */
static void
ringbuffer_read_advance (ringbuffer_t * rb, size_t cnt)
{
size_t tmp = (rb->read_ptr + cnt) & rb->size_mask;
rb->read_ptr = tmp;
}
/* Advance the write pointer `cnt' places. */
static void
ringbuffer_write_advance (ringbuffer_t * rb, size_t cnt)
{
size_t tmp = (rb->write_ptr + cnt) & rb->size_mask;
rb->write_ptr = tmp;
}
/* The non-copying data reader. `vec' is an array of two places. Set
the values at `vec' to hold the current readable data at `rb'. If
the readable data is in one segment the second segment has zero
length. */
static void
ringbuffer_get_read_vector (const ringbuffer_t * rb,
ringbuffer_data_t * vec)
{
size_t free_cnt;
size_t cnt2;
size_t w, r;
w = rb->write_ptr;
r = rb->read_ptr;
if (w > r) {
free_cnt = w - r;
} else {
free_cnt = (w - r + rb->size) & rb->size_mask;
}
cnt2 = r + free_cnt;
if (cnt2 > rb->size) {
/* Two part vector: the rest of the buffer after the current write
ptr, plus some from the start of the buffer. */
vec[0].buf = &(rb->buf[r]);
vec[0].len = rb->size - r;
vec[1].buf = rb->buf;
vec[1].len = cnt2 & rb->size_mask;
} else {
/* Single part vector: just the rest of the buffer */
vec[0].buf = &(rb->buf[r]);
vec[0].len = free_cnt;
vec[1].len = 0;
}
}
/* The non-copying data writer. `vec' is an array of two places. Set
the values at `vec' to hold the current writeable data at `rb'. If
the writeable data is in one segment the second segment has zero
length. */
static void
ringbuffer_get_write_vector (const ringbuffer_t * rb,
ringbuffer_data_t * vec)
{
size_t free_cnt;
size_t cnt2;
size_t w, r;
w = rb->write_ptr;
r = rb->read_ptr;
if (w > r) {
free_cnt = ((r - w + rb->size) & rb->size_mask) - 1;
} else if (w < r) {
free_cnt = (r - w) - 1;
} else {
free_cnt = rb->size - 1;
}
cnt2 = w + free_cnt;
if (cnt2 > rb->size) {
/* Two part vector: the rest of the buffer after the current write
ptr, plus some from the start of the buffer. */
vec[0].buf = &(rb->buf[w]);
vec[0].len = rb->size - w;
vec[1].buf = rb->buf;
vec[1].len = cnt2 & rb->size_mask;
} else {
vec[0].buf = &(rb->buf[w]);
vec[0].len = free_cnt;
vec[1].len = 0;
}
}
#endif // __ring_buffer__
/************************** END ring-buffer.h **************************/
/*******************************************************************************
* GUI : Abstract Graphic User Interface
* Provides additional mechanisms to synchronize widgets and zones. Widgets
* should both reflect the value of a zone and allow to change this value.
******************************************************************************/
class uiItem;
class GUI;
struct clist;
typedef void (*uiCallback)(FAUSTFLOAT val, void* data);
struct uiItemBase
{
uiItemBase(GUI* ui, FAUSTFLOAT* zone)
{
assert(ui);
assert(zone);
}
virtual ~uiItemBase()
{}
virtual void modifyZone(FAUSTFLOAT v) = 0;
virtual void modifyZone(double date, FAUSTFLOAT v) {}
virtual double cache() = 0;
virtual void reflectZone() = 0;
};
// Declared as 'static' to avoid code duplication at link time
static void deleteClist(clist* cl);
struct clist : public std::list<uiItemBase*>
{
virtual ~clist()
{
deleteClist(this);
}
};
static void createUiCallbackItem(GUI* ui, FAUSTFLOAT* zone, uiCallback foo, void* data);
typedef std::map<FAUSTFLOAT*, clist*> zmap;
typedef std::map<FAUSTFLOAT*, ringbuffer_t*> ztimedmap;
class GUI : public UI
{
private:
static std::list<GUI*> fGuiList;
zmap fZoneMap;
bool fStopped;
public:
GUI():fStopped(false)
{
fGuiList.push_back(this);
}
virtual ~GUI()
{
// delete all items
for (auto& it : fZoneMap) {
delete it.second;
}
// suppress 'this' in static fGuiList
fGuiList.remove(this);
}
// -- registerZone(z,c) : zone management
void registerZone(FAUSTFLOAT* z, uiItemBase* c)
{
if (fZoneMap.find(z) == fZoneMap.end()) fZoneMap[z] = new clist();
fZoneMap[z]->push_back(c);
}
void updateZone(FAUSTFLOAT* z)
{
FAUSTFLOAT v = *z;
clist* cl = fZoneMap[z];
for (auto& c : *cl) {
if (c->cache() != v) c->reflectZone();
}
}
void updateAllZones()
{
for (auto& m : fZoneMap) {
updateZone(m.first);
}
}
static void updateAllGuis()
{
for (auto& g : fGuiList) {
g->updateAllZones();
}
}
static void runAllGuis()
{
for (auto& g : fGuiList) {
g->run();
}
}
void addCallback(FAUSTFLOAT* zone, uiCallback foo, void* data)
{
createUiCallbackItem(this, zone, foo, data);
}
virtual void show() {};
virtual bool run() { return false; };
virtual void stop() { fStopped = true; }
bool stopped() { return fStopped; }
// -- widget's layouts
virtual void openTabBox(const char* label) {};
virtual void openHorizontalBox(const char* label) {}
virtual void openVerticalBox(const char* label) {}
virtual void closeBox() {}
// -- active widgets
virtual void addButton(const char* label, FAUSTFLOAT* zone) {}
virtual void addCheckButton(const char* label, FAUSTFLOAT* zone) {}
virtual void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) {}
virtual void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) {}
virtual void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) {}
// -- passive widgets
virtual void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) {}
virtual void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) {}
// -- soundfiles
virtual void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) {}
// -- metadata declarations
virtual void declare(FAUSTFLOAT*, const char*, const char*) {}
// Static global for timed zones, shared between all UI that will set timed values
static ztimedmap gTimedZoneMap;
};
/**
* User Interface Item: abstract definition
*/
template <typename REAL>
class uiTypedItem : public uiItemBase
{
protected:
GUI* fGUI;
REAL* fZone;
REAL fCache;
uiTypedItem(GUI* ui, REAL* zone):uiItemBase(ui, static_cast<FAUSTFLOAT*>(zone)),
fGUI(ui), fZone(zone), fCache(REAL(-123456.654321))
{
ui->registerZone(zone, this);
}
public:
virtual ~uiTypedItem()
{}
void modifyZone(REAL v)
{
fCache = v;
if (*fZone != v) {
*fZone = v;
fGUI->updateZone(fZone);
}
}
double cache() { return fCache; }
};
class uiItem : public uiTypedItem<FAUSTFLOAT> {
protected:
uiItem(GUI* ui, FAUSTFLOAT* zone):uiTypedItem<FAUSTFLOAT>(ui, zone)
{}
public:
virtual ~uiItem()
{}
void modifyZone(FAUSTFLOAT v)
{
fCache = v;
if (*fZone != v) {
*fZone = v;
fGUI->updateZone(fZone);
}
}
};
/**
* Base class for items with a converter
*/
struct uiConverter {
ValueConverter* fConverter;
uiConverter(MetaDataUI::Scale scale, FAUSTFLOAT umin, FAUSTFLOAT umax, FAUSTFLOAT fmin, FAUSTFLOAT fmax)
{
// Select appropriate converter according to scale mode
if (scale == MetaDataUI::kLog) {
fConverter = new LogValueConverter(umin, umax, fmin, fmax);
} else if (scale == MetaDataUI::kExp) {
fConverter = new ExpValueConverter(umin, umax, fmin, fmax);
} else {
fConverter = new LinearValueConverter(umin, umax, fmin, fmax);
}
}
virtual ~uiConverter()
{
delete fConverter;
}
};
/**
* User Interface item owned (and so deleted) by external code
*/
class uiOwnedItem : public uiItem {
protected:
uiOwnedItem(GUI* ui, FAUSTFLOAT* zone):uiItem(ui, zone)
{}
public:
virtual ~uiOwnedItem()
{}
virtual void reflectZone() {}
};
/**
* Callback Item
*/
class uiCallbackItem : public uiItem {
protected:
uiCallback fCallback;
void* fData;
public:
uiCallbackItem(GUI* ui, FAUSTFLOAT* zone, uiCallback foo, void* data)
: uiItem(ui, zone), fCallback(foo), fData(data) {}
virtual void reflectZone()
{
FAUSTFLOAT v = *fZone;
fCache = v;
fCallback(v, fData);
}
};
/**
* For timestamped control
*/
struct DatedControl {
double fDate;
FAUSTFLOAT fValue;
DatedControl(double d = 0., FAUSTFLOAT v = FAUSTFLOAT(0)):fDate(d), fValue(v) {}
};
/**
* Base class for timed items
*/
class uiTimedItem : public uiItem
{
protected:
bool fDelete;
public:
using uiItem::modifyZone;
uiTimedItem(GUI* ui, FAUSTFLOAT* zone):uiItem(ui, zone)
{
if (GUI::gTimedZoneMap.find(fZone) == GUI::gTimedZoneMap.end()) {
GUI::gTimedZoneMap[fZone] = ringbuffer_create(8192);
fDelete = true;
} else {
fDelete = false;
}
}
virtual ~uiTimedItem()
{
ztimedmap::iterator it;
if (fDelete && ((it = GUI::gTimedZoneMap.find(fZone)) != GUI::gTimedZoneMap.end())) {
ringbuffer_free((*it).second);
GUI::gTimedZoneMap.erase(it);
}
}
virtual void modifyZone(double date, FAUSTFLOAT v)
{
size_t res;
DatedControl dated_val(date, v);
if ((res = ringbuffer_write(GUI::gTimedZoneMap[fZone], (const char*)&dated_val, sizeof(DatedControl))) != sizeof(DatedControl)) {
std::cerr << "ringbuffer_write error DatedControl" << std::endl;
}
}
};
/**
* Allows to group a set of zones
*/
class uiGroupItem : public uiItem
{
protected:
std::vector<FAUSTFLOAT*> fZoneMap;
public:
uiGroupItem(GUI* ui, FAUSTFLOAT* zone):uiItem(ui, zone)
{}
virtual ~uiGroupItem()
{}
virtual void reflectZone()
{
FAUSTFLOAT v = *fZone;
fCache = v;
// Update all zones of the same group
for (auto& it : fZoneMap) {
*it = v;
}
}
void addZone(FAUSTFLOAT* zone) { fZoneMap.push_back(zone); }
};
// Can not be defined as method in the classes
static void createUiCallbackItem(GUI* ui, FAUSTFLOAT* zone, uiCallback foo, void* data)
{
new uiCallbackItem(ui, zone, foo, data);
}
static void deleteClist(clist* cl)
{
/*
for (auto& it : *cl) {
uiOwnedItem* owned = dynamic_cast<uiOwnedItem*>(it);
// owned items are deleted by external code
if (!owned) {
delete it;
}
}
*/
}
#endif
/************************** END GUI.h **************************/
/************************** BEGIN JSONUI.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef FAUST_JSONUI_H
#define FAUST_JSONUI_H
#include <vector>
#include <map>
#include <string>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <algorithm>
/*******************************************************************************
* JSONUI : Faust User Interface
* This class produce a complete JSON decription of the DSP instance.
******************************************************************************/
template <typename REAL>
class JSONUIReal : public PathBuilder, public Meta, public UIReal<REAL>
{
protected:
std::stringstream fUI;
std::stringstream fMeta;
std::vector<std::pair <std::string, std::string> > fMetaAux;
std::string fVersion; // Compiler version
std::string fCompileOptions; // Compilation options
std::vector<std::string> fLibraryList;
std::vector<std::string> fIncludePathnames;
std::string fName;
std::string fFileName;
std::string fExpandedCode;
std::string fSHAKey;
int fDSPSize; // In bytes
std::map<std::string, int> fPathTable;
bool fExtended;
char fCloseUIPar;
char fCloseMetaPar;
int fTab;
int fInputs, fOutputs, fSRIndex;
void tab(int n, std::ostream& fout)
{
fout << '\n';
while (n-- > 0) {
fout << '\t';
}
}
std::string flatten(const std::string& src)
{
std::string dst;
for (size_t i = 0; i < src.size(); i++) {
switch (src[i]) {
case '\n':
case '\t':
break;
default:
dst += src[i];
break;
}
}
return dst;
}
void addMeta(int tab_val, bool quote = true)
{
if (fMetaAux.size() > 0) {
tab(tab_val, fUI); fUI << "\"meta\": [";
std::string sep = "";
for (size_t i = 0; i < fMetaAux.size(); i++) {
fUI << sep;
tab(tab_val + 1, fUI); fUI << "{ \"" << fMetaAux[i].first << "\": \"" << fMetaAux[i].second << "\" }";
sep = ",";
}
tab(tab_val, fUI); fUI << ((quote) ? "],": "]");
fMetaAux.clear();
}
}
int getAddressIndex(const std::string& path)
{
return (fPathTable.find(path) != fPathTable.end()) ? fPathTable[path] : -1;
}
public:
JSONUIReal(const std::string& name,
const std::string& filename,
int inputs,
int outputs,
int sr_index,
const std::string& sha_key,
const std::string& dsp_code,
const std::string& version,
const std::string& compile_options,
const std::vector<std::string>& library_list,
const std::vector<std::string>& include_pathnames,
int size,
const std::map<std::string, int>& path_table)
{
init(name, filename, inputs, outputs, sr_index, sha_key, dsp_code, version, compile_options, library_list, include_pathnames, size, path_table);
}
JSONUIReal(const std::string& name, const std::string& filename, int inputs, int outputs)
{
init(name, filename, inputs, outputs, -1, "", "", "", "", std::vector<std::string>(), std::vector<std::string>(), -1, std::map<std::string, int>());
}
JSONUIReal(int inputs, int outputs)
{
init("", "", inputs, outputs, -1, "", "","", "", std::vector<std::string>(), std::vector<std::string>(), -1, std::map<std::string, int>());
}
JSONUIReal()
{
init("", "", -1, -1, -1, "", "", "", "", std::vector<std::string>(), std::vector<std::string>(), -1, std::map<std::string, int>());
}
virtual ~JSONUIReal() {}
void setInputs(int inputs) { fInputs = inputs; }
void setOutputs(int outputs) { fOutputs = outputs; }
void setSRIndex(int sr_index) { fSRIndex = sr_index; }
// Init may be called multiple times so fMeta and fUI are reinitialized
void init(const std::string& name,
const std::string& filename,
int inputs,
int outputs,
int sr_index,
const std::string& sha_key,
const std::string& dsp_code,
const std::string& version,
const std::string& compile_options,
const std::vector<std::string>& library_list,
const std::vector<std::string>& include_pathnames,
int size,
const std::map<std::string, int>& path_table,
bool extended = false)
{
fTab = 1;
fExtended = extended;
if (fExtended) {
fUI << std::setprecision(std::numeric_limits<REAL>::max_digits10);
fMeta << std::setprecision(std::numeric_limits<REAL>::max_digits10);
}
// Start Meta generation
fMeta.str("");
tab(fTab, fMeta); fMeta << "\"meta\": [";
fCloseMetaPar = ' ';
// Start UI generation
fUI.str("");
tab(fTab, fUI); fUI << "\"ui\": [";
fCloseUIPar = ' ';
fTab += 1;
fName = name;
fFileName = filename;
fInputs = inputs;
fOutputs = outputs;
fSRIndex = sr_index;
fExpandedCode = dsp_code;
fSHAKey = sha_key;
fDSPSize = size;
fPathTable = path_table;
fVersion = version;
fCompileOptions = compile_options;
fLibraryList = library_list;
fIncludePathnames = include_pathnames;
}
// -- widget's layouts
virtual void openGenericGroup(const char* label, const char* name)
{
pushLabel(label);
fUI << fCloseUIPar;
tab(fTab, fUI); fUI << "{";
fTab += 1;
tab(fTab, fUI); fUI << "\"type\": \"" << name << "\",";
tab(fTab, fUI); fUI << "\"label\": \"" << label << "\",";
addMeta(fTab);
tab(fTab, fUI); fUI << "\"items\": [";
fCloseUIPar = ' ';
fTab += 1;
}
virtual void openTabBox(const char* label)
{
openGenericGroup(label, "tgroup");
}
virtual void openHorizontalBox(const char* label)
{
openGenericGroup(label, "hgroup");
}
virtual void openVerticalBox(const char* label)
{
openGenericGroup(label, "vgroup");
}
virtual void closeBox()
{
popLabel();
fTab -= 1;
tab(fTab, fUI); fUI << "]";
fTab -= 1;
tab(fTab, fUI); fUI << "}";
fCloseUIPar = ',';
}
// -- active widgets
virtual void addGenericButton(const char* label, const char* name)
{
std::string path = buildPath(label);
fUI << fCloseUIPar;
tab(fTab, fUI); fUI << "{";
fTab += 1;
tab(fTab, fUI); fUI << "\"type\": \"" << name << "\",";
tab(fTab, fUI); fUI << "\"label\": \"" << label << "\",";
if (fPathTable.size() > 0) {
tab(fTab, fUI); fUI << "\"address\": \"" << path << "\",";
tab(fTab, fUI); fUI << "\"index\": " << getAddressIndex(path) << ((fMetaAux.size() > 0) ? "," : "");
} else {
tab(fTab, fUI); fUI << "\"address\": \"" << path << "\"" << ((fMetaAux.size() > 0) ? "," : "");
}
addMeta(fTab, false);
fTab -= 1;
tab(fTab, fUI); fUI << "}";
fCloseUIPar = ',';
}
virtual void addButton(const char* label, REAL* zone)
{
addGenericButton(label, "button");
}
virtual void addCheckButton(const char* label, REAL* zone)
{
addGenericButton(label, "checkbox");
}
virtual void addGenericEntry(const char* label, const char* name, REAL init, REAL min, REAL max, REAL step)
{
std::string path = buildPath(label);
fUI << fCloseUIPar;
tab(fTab, fUI); fUI << "{";
fTab += 1;
tab(fTab, fUI); fUI << "\"type\": \"" << name << "\",";
tab(fTab, fUI); fUI << "\"label\": \"" << label << "\",";
tab(fTab, fUI); fUI << "\"address\": \"" << path << "\",";
if (fPathTable.size() > 0) {
tab(fTab, fUI); fUI << "\"index\": " << getAddressIndex(path) << ",";
}
addMeta(fTab);
tab(fTab, fUI); fUI << "\"init\": " << init << ",";
tab(fTab, fUI); fUI << "\"min\": " << min << ",";
tab(fTab, fUI); fUI << "\"max\": " << max << ",";
tab(fTab, fUI); fUI << "\"step\": " << step;
fTab -= 1;
tab(fTab, fUI); fUI << "}";
fCloseUIPar = ',';
}
virtual void addVerticalSlider(const char* label, REAL* zone, REAL init, REAL min, REAL max, REAL step)
{
addGenericEntry(label, "vslider", init, min, max, step);
}
virtual void addHorizontalSlider(const char* label, REAL* zone, REAL init, REAL min, REAL max, REAL step)
{
addGenericEntry(label, "hslider", init, min, max, step);
}
virtual void addNumEntry(const char* label, REAL* zone, REAL init, REAL min, REAL max, REAL step)
{
addGenericEntry(label, "nentry", init, min, max, step);
}
// -- passive widgets
virtual void addGenericBargraph(const char* label, const char* name, REAL min, REAL max)
{
std::string path = buildPath(label);
fUI << fCloseUIPar;
tab(fTab, fUI); fUI << "{";
fTab += 1;
tab(fTab, fUI); fUI << "\"type\": \"" << name << "\",";
tab(fTab, fUI); fUI << "\"label\": \"" << label << "\",";
tab(fTab, fUI); fUI << "\"address\": \"" << path << "\",";
if (fPathTable.size() > 0) {
tab(fTab, fUI); fUI << "\"index\": " << getAddressIndex(path) << ",";
}
addMeta(fTab);
tab(fTab, fUI); fUI << "\"min\": " << min << ",";
tab(fTab, fUI); fUI << "\"max\": " << max;
fTab -= 1;
tab(fTab, fUI); fUI << "}";
fCloseUIPar = ',';
}
virtual void addHorizontalBargraph(const char* label, REAL* zone, REAL min, REAL max)
{
addGenericBargraph(label, "hbargraph", min, max);
}
virtual void addVerticalBargraph(const char* label, REAL* zone, REAL min, REAL max)
{
addGenericBargraph(label, "vbargraph", min, max);
}
virtual void addSoundfile(const char* label, const char* url, Soundfile** zone)
{
std::string path = buildPath(label);
fUI << fCloseUIPar;
tab(fTab, fUI); fUI << "{";
fTab += 1;
tab(fTab, fUI); fUI << "\"type\": \"" << "soundfile" << "\",";
tab(fTab, fUI); fUI << "\"label\": \"" << label << "\"" << ",";
tab(fTab, fUI); fUI << "\"url\": \"" << url << "\"" << ",";
tab(fTab, fUI); fUI << "\"address\": \"" << path << "\"" << ((fPathTable.size() > 0) ? "," : "");
if (fPathTable.size() > 0) {
tab(fTab, fUI); fUI << "\"index\": " << getAddressIndex(path);
}
fTab -= 1;
tab(fTab, fUI); fUI << "}";
fCloseUIPar = ',';
}
// -- metadata declarations
virtual void declare(REAL* zone, const char* key, const char* val)
{
fMetaAux.push_back(std::make_pair(key, val));
}
// Meta interface
virtual void declare(const char* key, const char* value)
{
fMeta << fCloseMetaPar;
// fName found in metadata
if ((strcmp(key, "name") == 0) && (fName == "")) fName = value;
// fFileName found in metadata
if ((strcmp(key, "filename") == 0) && (fFileName == "")) fFileName = value;
tab(fTab, fMeta); fMeta << "{ " << "\"" << key << "\"" << ": " << "\"" << value << "\" }";
fCloseMetaPar = ',';
}
std::string JSON(bool flat = false)
{
fTab = 0;
std::stringstream JSON;
if (fExtended) {
JSON << std::setprecision(std::numeric_limits<REAL>::max_digits10);
}
JSON << "{";
fTab += 1;
tab(fTab, JSON); JSON << "\"name\": \"" << fName << "\",";
tab(fTab, JSON); JSON << "\"filename\": \"" << fFileName << "\",";
if (fVersion != "") { tab(fTab, JSON); JSON << "\"version\": \"" << fVersion << "\","; }
if (fCompileOptions != "") { tab(fTab, JSON); JSON << "\"compile_options\": \"" << fCompileOptions << "\","; }
if (fLibraryList.size() > 0) {
tab(fTab, JSON);
JSON << "\"library_list\": [";
for (size_t i = 0; i < fLibraryList.size(); i++) {
JSON << "\"" << fLibraryList[i] << "\"";
if (i < (fLibraryList.size() - 1)) JSON << ",";
}
JSON << "],";
}
if (fIncludePathnames.size() > 0) {
tab(fTab, JSON);
JSON << "\"include_pathnames\": [";
for (size_t i = 0; i < fIncludePathnames.size(); i++) {
JSON << "\"" << fIncludePathnames[i] << "\"";
if (i < (fIncludePathnames.size() - 1)) JSON << ",";
}
JSON << "],";
}
if (fDSPSize != -1) { tab(fTab, JSON); JSON << "\"size\": " << fDSPSize << ","; }
if (fSHAKey != "") { tab(fTab, JSON); JSON << "\"sha_key\": \"" << fSHAKey << "\","; }
if (fExpandedCode != "") { tab(fTab, JSON); JSON << "\"code\": \"" << fExpandedCode << "\","; }
tab(fTab, JSON); JSON << "\"inputs\": " << fInputs << ",";
tab(fTab, JSON); JSON << "\"outputs\": " << fOutputs << ",";
if (fSRIndex != -1) { tab(fTab, JSON); JSON << "\"sr_index\": " << fSRIndex << ","; }
tab(fTab, fMeta); fMeta << "],";
tab(fTab, fUI); fUI << "]";
fTab -= 1;
if (fCloseMetaPar == ',') { // If "declare" has been called, fCloseMetaPar state is now ','
JSON << fMeta.str() << fUI.str();
} else {
JSON << fUI.str();
}
tab(fTab, JSON); JSON << "}";
return (flat) ? flatten(JSON.str()) : JSON.str();
}
};
// Externally available class using FAUSTFLOAT
struct JSONUI : public JSONUIReal<FAUSTFLOAT>, public UI
{
JSONUI(const std::string& name,
const std::string& filename,
int inputs,
int outputs,
int sr_index,
const std::string& sha_key,
const std::string& dsp_code,
const std::string& version,
const std::string& compile_options,
const std::vector<std::string>& library_list,
const std::vector<std::string>& include_pathnames,
int size,
const std::map<std::string, int>& path_table):
JSONUIReal<FAUSTFLOAT>(name, filename,
inputs, outputs,
sr_index,
sha_key, dsp_code,
version, compile_options,
library_list, include_pathnames,
size, path_table)
{}
JSONUI(const std::string& name, const std::string& filename, int inputs, int outputs):
JSONUIReal<FAUSTFLOAT>(name, filename, inputs, outputs)
{}
JSONUI(int inputs, int outputs):JSONUIReal<FAUSTFLOAT>(inputs, outputs)
{}
JSONUI():JSONUIReal<FAUSTFLOAT>()
{}
virtual void openTabBox(const char* label)
{
JSONUIReal<FAUSTFLOAT>::openTabBox(label);
}
virtual void openHorizontalBox(const char* label)
{
JSONUIReal<FAUSTFLOAT>::openHorizontalBox(label);
}
virtual void openVerticalBox(const char* label)
{
JSONUIReal<FAUSTFLOAT>::openVerticalBox(label);
}
virtual void closeBox()
{
JSONUIReal<FAUSTFLOAT>::closeBox();
}
// -- active widgets
virtual void addButton(const char* label, FAUSTFLOAT* zone)
{
JSONUIReal<FAUSTFLOAT>::addButton(label, zone);
}
virtual void addCheckButton(const char* label, FAUSTFLOAT* zone)
{
JSONUIReal<FAUSTFLOAT>::addCheckButton(label, zone);
}
virtual void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step)
{
JSONUIReal<FAUSTFLOAT>::addVerticalSlider(label, zone, init, min, max, step);
}
virtual void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step)
{
JSONUIReal<FAUSTFLOAT>::addHorizontalSlider(label, zone, init, min, max, step);
}
virtual void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step)
{
JSONUIReal<FAUSTFLOAT>::addNumEntry(label, zone, init, min, max, step);
}
// -- passive widgets
virtual void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max)
{
JSONUIReal<FAUSTFLOAT>::addHorizontalBargraph(label, zone, min, max);
}
virtual void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max)
{
JSONUIReal<FAUSTFLOAT>::addVerticalBargraph(label, zone, min, max);
}
// -- soundfiles
virtual void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone)
{
JSONUIReal<FAUSTFLOAT>::addSoundfile(label, filename, sf_zone);
}
// -- metadata declarations
virtual void declare(FAUSTFLOAT* zone, const char* key, const char* val)
{
JSONUIReal<FAUSTFLOAT>::declare(zone, key, val);
}
virtual void declare(const char* key, const char* val)
{
JSONUIReal<FAUSTFLOAT>::declare(key, val);
}
virtual ~JSONUI() {}
};
#endif // FAUST_JSONUI_H
/************************** END JSONUI.h **************************/
// for polyphonic synths
#ifdef NVOICES
/************************** BEGIN poly-dsp.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef __poly_dsp__
#define __poly_dsp__
#include <stdio.h>
#include <string>
#include <cmath>
#include <algorithm>
#include <ostream>
#include <sstream>
#include <vector>
#include <limits.h>
#include <float.h>
#include <assert.h>
/************************** BEGIN dsp-combiner.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2019 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef __dsp_combiner__
#define __dsp_combiner__
#include <string.h>
#include <string>
#include <assert.h>
#include <sstream>
// Base class and common code for binary combiners
class dsp_binary_combiner : public dsp {
protected:
dsp* fDSP1;
dsp* fDSP2;
void buildUserInterfaceAux(UI* ui_interface, const char* name)
{
ui_interface->openTabBox(name);
ui_interface->openVerticalBox("DSP1");
fDSP1->buildUserInterface(ui_interface);
ui_interface->closeBox();
ui_interface->openVerticalBox("DSP2");
fDSP2->buildUserInterface(ui_interface);
ui_interface->closeBox();
ui_interface->closeBox();
}
FAUSTFLOAT** allocateChannels(int num, int buffer_size)
{
FAUSTFLOAT** channels = new FAUSTFLOAT*[num];
for (int chan = 0; chan < num; chan++) {
channels[chan] = new FAUSTFLOAT[buffer_size];
memset(channels[chan], 0, sizeof(FAUSTFLOAT) * buffer_size);
}
return channels;
}
void deleteChannels(FAUSTFLOAT** channels, int num)
{
for (int chan = 0; chan < num; chan++) {
delete [] channels[chan];
}
delete [] channels;
}
public:
dsp_binary_combiner(dsp* dsp1, dsp* dsp2):fDSP1(dsp1), fDSP2(dsp2)
{}
virtual ~dsp_binary_combiner()
{
delete fDSP1;
delete fDSP2;
}
virtual int getSampleRate()
{
return fDSP1->getSampleRate();
}
virtual void init(int sample_rate)
{
fDSP1->init(sample_rate);
fDSP2->init(sample_rate);
}
virtual void instanceInit(int sample_rate)
{
fDSP1->instanceInit(sample_rate);
fDSP2->instanceInit(sample_rate);
}
virtual void instanceConstants(int sample_rate)
{
fDSP1->instanceConstants(sample_rate);
fDSP2->instanceConstants(sample_rate);
}
virtual void instanceResetUserInterface()
{
fDSP1->instanceResetUserInterface();
fDSP2->instanceResetUserInterface();
}
virtual void instanceClear()
{
fDSP1->instanceClear();
fDSP2->instanceClear();
}
virtual void metadata(Meta* m)
{
fDSP1->metadata(m);
fDSP2->metadata(m);
}
};
// Combine two 'compatible' DSP in sequence
class dsp_sequencer : public dsp_binary_combiner {
private:
FAUSTFLOAT** fDSP1Outputs;
public:
dsp_sequencer(dsp* dsp1, dsp* dsp2, int buffer_size = 4096):dsp_binary_combiner(dsp1, dsp2)
{
fDSP1Outputs = allocateChannels(fDSP1->getNumOutputs(), buffer_size);
}
virtual ~dsp_sequencer()
{
deleteChannels(fDSP1Outputs, fDSP1->getNumOutputs());
}
virtual int getNumInputs() { return fDSP1->getNumInputs(); }
virtual int getNumOutputs() { return fDSP2->getNumOutputs(); }
virtual void buildUserInterface(UI* ui_interface)
{
buildUserInterfaceAux(ui_interface, "Sequencer");
}
virtual dsp* clone()
{
return new dsp_sequencer(fDSP1->clone(), fDSP2->clone());
}
virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs)
{
fDSP1->compute(count, inputs, fDSP1Outputs);
fDSP2->compute(count, fDSP1Outputs, outputs);
}
virtual void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { compute(count, inputs, outputs); }
};
// Combine two DSP in parallel
class dsp_parallelizer : public dsp_binary_combiner {
private:
FAUSTFLOAT** fDSP2Inputs;
FAUSTFLOAT** fDSP2Outputs;
public:
dsp_parallelizer(dsp* dsp1, dsp* dsp2, int buffer_size = 4096):dsp_binary_combiner(dsp1, dsp2)
{
fDSP2Inputs = new FAUSTFLOAT*[fDSP2->getNumInputs()];
fDSP2Outputs = new FAUSTFLOAT*[fDSP2->getNumOutputs()];
}
virtual ~dsp_parallelizer()
{
delete [] fDSP2Inputs;
delete [] fDSP2Outputs;
}
virtual int getNumInputs() { return fDSP1->getNumInputs() + fDSP2->getNumInputs(); }
virtual int getNumOutputs() { return fDSP1->getNumOutputs() + fDSP2->getNumOutputs(); }
virtual void buildUserInterface(UI* ui_interface)
{
buildUserInterfaceAux(ui_interface, "Parallelizer");
}
virtual dsp* clone()
{
return new dsp_parallelizer(fDSP1->clone(), fDSP2->clone());
}
virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs)
{
fDSP1->compute(count, inputs, outputs);
// Shift inputs/outputs channels for fDSP2
for (int chan = 0; chan < fDSP2->getNumInputs(); chan++) {
fDSP2Inputs[chan] = inputs[fDSP1->getNumInputs() + chan];
}
for (int chan = 0; chan < fDSP2->getNumOutputs(); chan++) {
fDSP2Outputs[chan] = outputs[fDSP1->getNumOutputs() + chan];
}
fDSP2->compute(count, fDSP2Inputs, fDSP2Outputs);
}
virtual void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { compute(count, inputs, outputs); }
};
// Combine two 'compatible' DSP in splitter
class dsp_splitter : public dsp_binary_combiner {
private:
FAUSTFLOAT** fDSP1Outputs;
FAUSTFLOAT** fDSP2Inputs;
public:
dsp_splitter(dsp* dsp1, dsp* dsp2, int buffer_size = 4096):dsp_binary_combiner(dsp1, dsp2)
{
fDSP1Outputs = allocateChannels(fDSP1->getNumOutputs(), buffer_size);
fDSP2Inputs = new FAUSTFLOAT*[fDSP2->getNumInputs()];
}
virtual ~dsp_splitter()
{
deleteChannels(fDSP1Outputs, fDSP1->getNumOutputs());
delete [] fDSP2Inputs;
}
virtual int getNumInputs() { return fDSP1->getNumInputs(); }
virtual int getNumOutputs() { return fDSP2->getNumOutputs(); }
virtual void buildUserInterface(UI* ui_interface)
{
buildUserInterfaceAux(ui_interface, "Splitter");
}
virtual dsp* clone()
{
return new dsp_splitter(fDSP1->clone(), fDSP2->clone());
}
virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs)
{
fDSP1->compute(count, inputs, fDSP1Outputs);
for (int chan = 0; chan < fDSP2->getNumInputs(); chan++) {
fDSP2Inputs[chan] = fDSP1Outputs[chan % fDSP1->getNumOutputs()];
}
fDSP2->compute(count, fDSP2Inputs, outputs);
}
};
// Combine two 'compatible' DSP in merger
class dsp_merger : public dsp_binary_combiner {
private:
FAUSTFLOAT** fDSP1Inputs;
FAUSTFLOAT** fDSP1Outputs;
FAUSTFLOAT** fDSP2Inputs;
void mix(int count, FAUSTFLOAT* dst, FAUSTFLOAT* src)
{
for (int frame = 0; frame < count; frame++) {
dst[frame] += src[frame];
}
}
public:
dsp_merger(dsp* dsp1, dsp* dsp2, int buffer_size = 4096):dsp_binary_combiner(dsp1, dsp2)
{
fDSP1Inputs = allocateChannels(fDSP1->getNumInputs(), buffer_size);
fDSP1Outputs = allocateChannels(fDSP1->getNumOutputs(), buffer_size);
fDSP2Inputs = new FAUSTFLOAT*[fDSP2->getNumInputs()];
}
virtual ~dsp_merger()
{
deleteChannels(fDSP1Inputs, fDSP1->getNumInputs());
deleteChannels(fDSP1Outputs, fDSP1->getNumOutputs());
delete [] fDSP2Inputs;
}
virtual int getNumInputs() { return fDSP1->getNumInputs(); }
virtual int getNumOutputs() { return fDSP2->getNumOutputs(); }
virtual void buildUserInterface(UI* ui_interface)
{
buildUserInterfaceAux(ui_interface, "Merge");
}
virtual dsp* clone()
{
return new dsp_merger(fDSP1->clone(), fDSP2->clone());
}
virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs)
{
fDSP1->compute(count, fDSP1Inputs, fDSP1Outputs);
memset(fDSP2Inputs, 0, sizeof(FAUSTFLOAT*) * fDSP2->getNumInputs());
for (int chan = 0; chan < fDSP1->getNumOutputs(); chan++) {
int mchan = chan % fDSP2->getNumInputs();
if (fDSP2Inputs[mchan]) {
mix(count, fDSP2Inputs[mchan], fDSP1Outputs[chan]);
} else {
fDSP2Inputs[mchan] = fDSP1Outputs[chan];
}
}
fDSP2->compute(count, fDSP2Inputs, outputs);
}
};
// Combine two 'compatible' DSP in a recursive way
class dsp_recursiver : public dsp_binary_combiner {
private:
FAUSTFLOAT** fDSP1Inputs;
FAUSTFLOAT** fDSP1Outputs;
FAUSTFLOAT** fDSP2Inputs;
FAUSTFLOAT** fDSP2Outputs;
public:
dsp_recursiver(dsp* dsp1, dsp* dsp2):dsp_binary_combiner(dsp1, dsp2)
{
fDSP1Inputs = allocateChannels(fDSP1->getNumInputs(), 1);
fDSP1Outputs = allocateChannels(fDSP1->getNumOutputs(), 1);
fDSP2Inputs = allocateChannels(fDSP2->getNumInputs(), 1);
fDSP2Outputs = allocateChannels(fDSP2->getNumOutputs(), 1);
}
virtual ~dsp_recursiver()
{
deleteChannels(fDSP1Inputs, fDSP1->getNumInputs());
deleteChannels(fDSP1Outputs, fDSP1->getNumOutputs());
deleteChannels(fDSP2Inputs, fDSP2->getNumInputs());
deleteChannels(fDSP2Outputs, fDSP2->getNumOutputs());
}
virtual int getNumInputs() { return fDSP1->getNumInputs() - fDSP2->getNumOutputs(); }
virtual int getNumOutputs() { return fDSP1->getNumOutputs(); }
virtual void buildUserInterface(UI* ui_interface)
{
buildUserInterfaceAux(ui_interface, "Recursiver");
}
virtual dsp* clone()
{
return new dsp_recursiver(fDSP1->clone(), fDSP2->clone());
}
virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs)
{
for (int frame = 0; (frame < count); frame++) {
for (int chan = 0; chan < fDSP2->getNumOutputs(); chan++) {
fDSP1Inputs[chan][0] = fDSP2Outputs[chan][0];
}
for (int chan = 0; chan < fDSP1->getNumInputs() - fDSP2->getNumOutputs(); chan++) {
fDSP1Inputs[chan + fDSP2->getNumOutputs()][0] = inputs[chan][frame];
}
fDSP1->compute(1, fDSP1Inputs, fDSP1Outputs);
for (int chan = 0; chan < fDSP1->getNumOutputs(); chan++) {
outputs[chan][frame] = fDSP1Outputs[chan][0];
}
for (int chan = 0; chan < fDSP2->getNumInputs(); chan++) {
fDSP2Inputs[chan][0] = fDSP1Outputs[chan][0];
}
fDSP2->compute(1, fDSP2Inputs, fDSP2Outputs);
}
}
virtual void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { compute(count, inputs, outputs); }
};
#ifndef __dsp_algebra_api__
#define __dsp_algebra_api__
// DSP algebra API
/*
Each operation takes two DSP as parameters, returns the combined DSPs, or null if failure with an error message.
*/
static dsp* createDSPSequencer(dsp* dsp1, dsp* dsp2, std::string& error)
{
if (dsp1->getNumOutputs() != dsp2->getNumInputs()) {
std::stringstream error_aux;
error_aux << "Connection error int dsp_sequencer : the number of outputs ("
<< dsp1->getNumOutputs() << ") of A "
<< "must be equal to the number of inputs (" << dsp2->getNumInputs() << ") of B" << std::endl;
error = error_aux.str();
return nullptr;
} else {
return new dsp_sequencer(dsp1, dsp2);
}
}
static dsp* createDSPParallelizer(dsp* dsp1, dsp* dsp2, std::string& error)
{
return new dsp_parallelizer(dsp1, dsp2);
}
static dsp* createDSPSplitter(dsp* dsp1, dsp* dsp2, std::string& error)
{
if (dsp1->getNumOutputs() == 0) {
error = "Connection error in dsp_splitter : the first expression has no outputs\n";
return nullptr;
} else if (dsp2->getNumInputs() == 0) {
error = "Connection error in dsp_splitter : the second expression has no inputs\n";
return nullptr;
} else if (dsp2->getNumInputs() % dsp1->getNumOutputs() != 0) {
std::stringstream error_aux;
error_aux << "Connection error in dsp_splitter : the number of outputs (" << dsp1->getNumOutputs()
<< ") of the first expression should be a divisor of the number of inputs ("
<< dsp2->getNumInputs()
<< ") of the second expression" << std::endl;
error = error_aux.str();
return nullptr;
} else if (dsp2->getNumInputs() == dsp1->getNumOutputs()) {
return new dsp_sequencer(dsp1, dsp2);
} else {
return new dsp_splitter(dsp1, dsp2);
}
}
static dsp* createDSPMerger(dsp* dsp1, dsp* dsp2, std::string& error)
{
if (dsp1->getNumOutputs() == 0) {
error = "Connection error in dsp_merger : the first expression has no outputs\n";
return nullptr;
} else if (dsp2->getNumInputs() == 0) {
error = "Connection error in dsp_merger : the second expression has no inputs\n";
return nullptr;
} else if (dsp1->getNumOutputs() % dsp2->getNumInputs() != 0) {
std::stringstream error_aux;
error_aux << "Connection error in dsp_merger : the number of outputs (" << dsp1->getNumOutputs()
<< ") of the first expression should be a multiple of the number of inputs ("
<< dsp2->getNumInputs()
<< ") of the second expression" << std::endl;
error = error_aux.str();
return nullptr;
} else if (dsp2->getNumInputs() == dsp1->getNumOutputs()) {
return new dsp_sequencer(dsp1, dsp2);
} else {
return new dsp_merger(dsp1, dsp2);
}
}
static dsp* createDSPRecursiver(dsp* dsp1, dsp* dsp2, std::string& error)
{
if ((dsp2->getNumInputs() > dsp1->getNumOutputs()) || (dsp2->getNumOutputs() > dsp1->getNumInputs())) {
std::stringstream error_aux;
error_aux << "Connection error in : dsp_recursiver" << std::endl;
if (dsp2->getNumInputs() > dsp1->getNumOutputs()) {
error_aux << "The number of outputs " << dsp1->getNumOutputs()
<< " of the first expression should be greater or equal to the number of inputs ("
<< dsp2->getNumInputs()
<< ") of the second expression" << std::endl;
}
if (dsp2->getNumOutputs() > dsp1->getNumInputs()) {
error_aux << "The number of inputs " << dsp1->getNumInputs()
<< " of the first expression should be greater or equal to the number of outputs ("
<< dsp2->getNumOutputs()
<< ") of the second expression" << std::endl;
}
error = error_aux.str();
return nullptr;
} else {
return new dsp_recursiver(dsp1, dsp2);
}
}
#endif
#endif
/************************** END dsp-combiner.h **************************/
/************************** BEGIN proxy-dsp.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef __proxy_dsp__
#define __proxy_dsp__
#include <vector>
#include <map>
/************************** BEGIN JSONUIDecoder.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2003-2020 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef __JSONUIDecoder__
#define __JSONUIDecoder__
#include <vector>
#include <map>
#include <utility>
#include <cstdlib>
#include <sstream>
#include <functional>
/************************** BEGIN CGlue.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2018 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef CGLUE_H
#define CGLUE_H
/************************** BEGIN CInterface.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2018 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef CINTERFACE_H
#define CINTERFACE_H
#ifndef FAUSTFLOAT
#define FAUSTFLOAT float
#endif
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
struct Soundfile;
/*******************************************************************************
* UI, Meta and MemoryManager structures for C code.
******************************************************************************/
// -- widget's layouts
typedef void (* openTabBoxFun) (void* ui_interface, const char* label);
typedef void (* openHorizontalBoxFun) (void* ui_interface, const char* label);
typedef void (* openVerticalBoxFun) (void* ui_interface, const char* label);
typedef void (* closeBoxFun) (void* ui_interface);
// -- active widgets
typedef void (* addButtonFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone);
typedef void (* addCheckButtonFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone);
typedef void (* addVerticalSliderFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step);
typedef void (* addHorizontalSliderFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step);
typedef void (* addNumEntryFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step);
// -- passive widgets
typedef void (* addHorizontalBargraphFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max);
typedef void (* addVerticalBargraphFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max);
// -- soundfiles
typedef void (* addSoundfileFun) (void* ui_interface, const char* label, const char* url, struct Soundfile** sf_zone);
typedef void (* declareFun) (void* ui_interface, FAUSTFLOAT* zone, const char* key, const char* value);
typedef struct {
void* uiInterface;
openTabBoxFun openTabBox;
openHorizontalBoxFun openHorizontalBox;
openVerticalBoxFun openVerticalBox;
closeBoxFun closeBox;
addButtonFun addButton;
addCheckButtonFun addCheckButton;
addVerticalSliderFun addVerticalSlider;
addHorizontalSliderFun addHorizontalSlider;
addNumEntryFun addNumEntry;
addHorizontalBargraphFun addHorizontalBargraph;
addVerticalBargraphFun addVerticalBargraph;
addSoundfileFun addSoundfile;
declareFun declare;
} UIGlue;
typedef void (* metaDeclareFun) (void* ui_interface, const char* key, const char* value);
typedef struct {
void* metaInterface;
metaDeclareFun declare;
} MetaGlue;
/***************************************
* Interface for the DSP object
***************************************/
typedef char dsp_imp;
typedef dsp_imp* (* newDspFun) ();
typedef void (* destroyDspFun) (dsp_imp* dsp);
typedef int (* getNumInputsFun) (dsp_imp* dsp);
typedef int (* getNumOutputsFun) (dsp_imp* dsp);
typedef void (* buildUserInterfaceFun) (dsp_imp* dsp, UIGlue* ui);
typedef int (* getSampleRateFun) (dsp_imp* dsp);
typedef void (* initFun) (dsp_imp* dsp, int sample_rate);
typedef void (* classInitFun) (int sample_rate);
typedef void (* instanceInitFun) (dsp_imp* dsp, int sample_rate);
typedef void (* instanceConstantsFun) (dsp_imp* dsp, int sample_rate);
typedef void (* instanceResetUserInterfaceFun) (dsp_imp* dsp);
typedef void (* instanceClearFun) (dsp_imp* dsp);
typedef void (* computeFun) (dsp_imp* dsp, int len, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs);
typedef void (* metadataFun) (MetaGlue* meta);
/***************************************
* DSP memory manager functions
***************************************/
typedef void* (* allocateFun) (void* manager_interface, size_t size);
typedef void (* destroyFun) (void* manager_interface, void* ptr);
typedef struct {
void* managerInterface;
allocateFun allocate;
destroyFun destroy;
} MemoryManagerGlue;
#ifdef __cplusplus
}
#endif
#endif
/************************** END CInterface.h **************************/
#ifdef __cplusplus
extern "C" {
#endif
/*******************************************************************************
* UI glue code
******************************************************************************/
class UIFloat
{
public:
UIFloat() {}
virtual ~UIFloat() {}
// -- widget's layouts
virtual void openTabBox(const char* label) = 0;
virtual void openHorizontalBox(const char* label) = 0;
virtual void openVerticalBox(const char* label) = 0;
virtual void closeBox() = 0;
// -- active widgets
virtual void addButton(const char* label, float* zone) = 0;
virtual void addCheckButton(const char* label, float* zone) = 0;
virtual void addVerticalSlider(const char* label, float* zone, float init, float min, float max, float step) = 0;
virtual void addHorizontalSlider(const char* label, float* zone, float init, float min, float max, float step) = 0;
virtual void addNumEntry(const char* label, float* zone, float init, float min, float max, float step) = 0;
// -- passive widgets
virtual void addHorizontalBargraph(const char* label, float* zone, float min, float max) = 0;
virtual void addVerticalBargraph(const char* label, float* zone, float min, float max) = 0;
// -- soundfiles
virtual void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) = 0;
// -- metadata declarations
virtual void declare(float* zone, const char* key, const char* val) {}
};
static void openTabBoxGlueFloat(void* cpp_interface, const char* label)
{
UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface);
ui_interface->openTabBox(label);
}
static void openHorizontalBoxGlueFloat(void* cpp_interface, const char* label)
{
UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface);
ui_interface->openHorizontalBox(label);
}
static void openVerticalBoxGlueFloat(void* cpp_interface, const char* label)
{
UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface);
ui_interface->openVerticalBox(label);
}
static void closeBoxGlueFloat(void* cpp_interface)
{
UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface);
ui_interface->closeBox();
}
static void addButtonGlueFloat(void* cpp_interface, const char* label, float* zone)
{
UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface);
ui_interface->addButton(label, zone);
}
static void addCheckButtonGlueFloat(void* cpp_interface, const char* label, float* zone)
{
UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface);
ui_interface->addCheckButton(label, zone);
}
static void addVerticalSliderGlueFloat(void* cpp_interface, const char* label, float* zone, float init, float min, float max, float step)
{
UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface);
ui_interface->addVerticalSlider(label, zone, init, min, max, step);
}
static void addHorizontalSliderGlueFloat(void* cpp_interface, const char* label, float* zone, float init, float min, float max, float step)
{
UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface);
ui_interface->addHorizontalSlider(label, zone, init, min, max, step);
}
static void addNumEntryGlueFloat(void* cpp_interface, const char* label, float* zone, float init, float min, float max, float step)
{
UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface);
ui_interface->addNumEntry(label, zone, init, min, max, step);
}
static void addHorizontalBargraphGlueFloat(void* cpp_interface, const char* label, float* zone, float min, float max)
{
UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface);
ui_interface->addHorizontalBargraph(label, zone, min, max);
}
static void addVerticalBargraphGlueFloat(void* cpp_interface, const char* label, float* zone, float min, float max)
{
UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface);
ui_interface->addVerticalBargraph(label, zone, min, max);
}
static void addSoundfileGlueFloat(void* cpp_interface, const char* label, const char* url, Soundfile** sf_zone)
{
UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface);
ui_interface->addSoundfile(label, url, sf_zone);
}
static void declareGlueFloat(void* cpp_interface, float* zone, const char* key, const char* value)
{
UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface);
ui_interface->declare(zone, key, value);
}
class UIDouble
{
public:
UIDouble() {}
virtual ~UIDouble() {}
// -- widget's layouts
virtual void openTabBox(const char* label) = 0;
virtual void openHorizontalBox(const char* label) = 0;
virtual void openVerticalBox(const char* label) = 0;
virtual void closeBox() = 0;
// -- active widgets
virtual void addButton(const char* label, double* zone) = 0;
virtual void addCheckButton(const char* label, double* zone) = 0;
virtual void addVerticalSlider(const char* label, double* zone, double init, double min, double max, double step) = 0;
virtual void addHorizontalSlider(const char* label, double* zone, double init, double min, double max, double step) = 0;
virtual void addNumEntry(const char* label, double* zone, double init, double min, double max, double step) = 0;
// -- passive widgets
virtual void addHorizontalBargraph(const char* label, double* zone, double min, double max) = 0;
virtual void addVerticalBargraph(const char* label, double* zone, double min, double max) = 0;
// -- soundfiles
virtual void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) = 0;
// -- metadata declarations
virtual void declare(double* zone, const char* key, const char* val) {}
};
static void openTabBoxGlueDouble(void* cpp_interface, const char* label)
{
UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface);
ui_interface->openTabBox(label);
}
static void openHorizontalBoxGlueDouble(void* cpp_interface, const char* label)
{
UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface);
ui_interface->openHorizontalBox(label);
}
static void openVerticalBoxGlueDouble(void* cpp_interface, const char* label)
{
UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface);
ui_interface->openVerticalBox(label);
}
static void closeBoxGlueDouble(void* cpp_interface)
{
UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface);
ui_interface->closeBox();
}
static void addButtonGlueDouble(void* cpp_interface, const char* label, double* zone)
{
UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface);
ui_interface->addButton(label, zone);
}
static void addCheckButtonGlueDouble(void* cpp_interface, const char* label, double* zone)
{
UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface);
ui_interface->addCheckButton(label, zone);
}
static void addVerticalSliderGlueDouble(void* cpp_interface, const char* label, double* zone, double init, double min, double max, double step)
{
UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface);
ui_interface->addVerticalSlider(label, zone, init, min, max, step);
}
static void addHorizontalSliderGlueDouble(void* cpp_interface, const char* label, double* zone, double init, double min, double max, double step)
{
UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface);
ui_interface->addHorizontalSlider(label, zone, init, min, max, step);
}
static void addNumEntryGlueDouble(void* cpp_interface, const char* label, double* zone, double init, double min, double max, double step)
{
UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface);
ui_interface->addNumEntry(label, zone, init, min, max, step);
}
static void addHorizontalBargraphGlueDouble(void* cpp_interface, const char* label, double* zone, double min, double max)
{
UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface);
ui_interface->addHorizontalBargraph(label, zone, min, max);
}
static void addVerticalBargraphGlueDouble(void* cpp_interface, const char* label, double* zone, double min, double max)
{
UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface);
ui_interface->addVerticalBargraph(label, zone, min, max);
}
static void addSoundfileGlueDouble(void* cpp_interface, const char* label, const char* url, Soundfile** sf_zone)
{
UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface);
ui_interface->addSoundfile(label, url, sf_zone);
}
static void declareGlueDouble(void* cpp_interface, double* zone, const char* key, const char* value)
{
UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface);
ui_interface->declare(zone, key, value);
}
static void buildUIGlue(UIGlue* glue, UI* ui_interface, bool is_double)
{
glue->uiInterface = ui_interface;
if (is_double) {
glue->openTabBox = reinterpret_cast<openTabBoxFun>(openTabBoxGlueDouble);
glue->openHorizontalBox = reinterpret_cast<openHorizontalBoxFun>(openHorizontalBoxGlueDouble);
glue->openVerticalBox = reinterpret_cast<openVerticalBoxFun>(openVerticalBoxGlueDouble);
glue->closeBox = reinterpret_cast<closeBoxFun>(closeBoxGlueDouble);
glue->addButton = reinterpret_cast<addButtonFun>(addButtonGlueDouble);
glue->addCheckButton = reinterpret_cast<addCheckButtonFun>(addCheckButtonGlueDouble);
glue->addVerticalSlider = reinterpret_cast<addVerticalSliderFun>(addVerticalSliderGlueDouble);
glue->addHorizontalSlider = reinterpret_cast<addHorizontalSliderFun>(addHorizontalSliderGlueDouble);
glue->addNumEntry = reinterpret_cast<addNumEntryFun>(addNumEntryGlueDouble);
glue->addHorizontalBargraph = reinterpret_cast<addHorizontalBargraphFun>(addHorizontalBargraphGlueDouble);
glue->addVerticalBargraph = reinterpret_cast<addVerticalBargraphFun>(addVerticalBargraphGlueDouble);
glue->addSoundfile = reinterpret_cast<addSoundfileFun>(addSoundfileGlueDouble);
glue->declare = reinterpret_cast<declareFun>(declareGlueDouble);
} else {
glue->openTabBox = reinterpret_cast<openTabBoxFun>(openTabBoxGlueFloat);
glue->openHorizontalBox = reinterpret_cast<openHorizontalBoxFun>(openHorizontalBoxGlueFloat);
glue->openVerticalBox = reinterpret_cast<openVerticalBoxFun>(openVerticalBoxGlueFloat);
glue->closeBox = reinterpret_cast<closeBoxFun>(closeBoxGlueFloat);
glue->addButton = reinterpret_cast<addButtonFun>(addButtonGlueFloat);
glue->addCheckButton = reinterpret_cast<addCheckButtonFun>(addCheckButtonGlueFloat);
glue->addVerticalSlider = reinterpret_cast<addVerticalSliderFun>(addVerticalSliderGlueFloat);
glue->addHorizontalSlider = reinterpret_cast<addHorizontalSliderFun>(addHorizontalSliderGlueFloat);
glue->addNumEntry = reinterpret_cast<addNumEntryFun>(addNumEntryGlueFloat);
glue->addHorizontalBargraph = reinterpret_cast<addHorizontalBargraphFun>(addHorizontalBargraphGlueFloat);
glue->addVerticalBargraph = reinterpret_cast<addVerticalBargraphFun>(addVerticalBargraphGlueFloat);
glue->addSoundfile = reinterpret_cast<addSoundfileFun>(addSoundfileGlueFloat);
glue->declare = reinterpret_cast<declareFun>(declareGlueFloat);
}
}
class UITemplate
{
private:
void* fCPPInterface;
public:
UITemplate(void* cpp_interface):fCPPInterface(cpp_interface)
{}
virtual ~UITemplate() {}
// -- widget's layouts
virtual void openTabBox(const char* label)
{
openTabBoxGlueFloat(fCPPInterface, label);
}
virtual void openHorizontalBox(const char* label)
{
openHorizontalBoxGlueFloat(fCPPInterface, label);
}
virtual void openVerticalBox(const char* label)
{
openVerticalBoxGlueFloat(fCPPInterface, label);
}
virtual void closeBox()
{
closeBoxGlueFloat(fCPPInterface);
}
// float version
// -- active widgets
virtual void addButton(const char* label, float* zone)
{
addButtonGlueFloat(fCPPInterface, label, zone);
}
virtual void addCheckButton(const char* label, float* zone)
{
addCheckButtonGlueFloat(fCPPInterface, label, zone);
}
virtual void addVerticalSlider(const char* label, float* zone, float init, float min, float max, float step)
{
addVerticalSliderGlueFloat(fCPPInterface, label, zone, init, min, max, step);
}
virtual void addHorizontalSlider(const char* label, float* zone, float init, float min, float max, float step)
{
addHorizontalSliderGlueFloat(fCPPInterface, label, zone, init, min, max, step);
}
virtual void addNumEntry(const char* label, float* zone, float init, float min, float max, float step)
{
addNumEntryGlueFloat(fCPPInterface, label, zone, init, min, max, step);
}
// -- passive widgets
virtual void addHorizontalBargraph(const char* label, float* zone, float min, float max)
{
addHorizontalBargraphGlueFloat(fCPPInterface, label, zone, min, max);
}
virtual void addVerticalBargraph(const char* label, float* zone, float min, float max)
{
addVerticalBargraphGlueFloat(fCPPInterface, label, zone, min, max);
}
// -- metadata declarations
virtual void declare(float* zone, const char* key, const char* val)
{
declareGlueFloat(fCPPInterface, zone, key, val);
}
// double version
virtual void addButton(const char* label, double* zone)
{
addButtonGlueDouble(fCPPInterface, label, zone);
}
virtual void addCheckButton(const char* label, double* zone)
{
addCheckButtonGlueDouble(fCPPInterface, label, zone);
}
virtual void addVerticalSlider(const char* label, double* zone, double init, double min, double max, double step)
{
addVerticalSliderGlueDouble(fCPPInterface, label, zone, init, min, max, step);
}
virtual void addHorizontalSlider(const char* label, double* zone, double init, double min, double max, double step)
{
addHorizontalSliderGlueDouble(fCPPInterface, label, zone, init, min, max, step);
}
virtual void addNumEntry(const char* label, double* zone, double init, double min, double max, double step)
{
addNumEntryGlueDouble(fCPPInterface, label, zone, init, min, max, step);
}
// -- soundfiles
virtual void addSoundfile(const char* label, const char* url, Soundfile** sf_zone)
{
addSoundfileGlueFloat(fCPPInterface, label, url, sf_zone);
}
// -- passive widgets
virtual void addHorizontalBargraph(const char* label, double* zone, double min, double max)
{
addHorizontalBargraphGlueDouble(fCPPInterface, label, zone, min, max);
}
virtual void addVerticalBargraph(const char* label, double* zone, double min, double max)
{
addVerticalBargraphGlueDouble(fCPPInterface, label, zone, min, max);
}
// -- metadata declarations
virtual void declare(double* zone, const char* key, const char* val)
{
declareGlueDouble(fCPPInterface, zone, key, val);
}
};
/*******************************************************************************
* Meta glue code
******************************************************************************/
static void declareMetaGlue(void* cpp_interface, const char* key, const char* value)
{
Meta* meta_interface = static_cast<Meta*>(cpp_interface);
meta_interface->declare(key, value);
}
static void buildMetaGlue(MetaGlue* glue, Meta* meta)
{
glue->metaInterface = meta;
glue->declare = declareMetaGlue;
}
/*******************************************************************************
* Memory manager glue code
******************************************************************************/
static void* allocateMemoryManagerGlue(void* cpp_interface, size_t size)
{
dsp_memory_manager* manager_interface = static_cast<dsp_memory_manager*>(cpp_interface);
return manager_interface->allocate(size);
}
static void destroyMemoryManagerGlue(void* cpp_interface, void* ptr)
{
dsp_memory_manager* manager_interface = static_cast<dsp_memory_manager*>(cpp_interface);
manager_interface->destroy(ptr);
}
static void buildManagerGlue(MemoryManagerGlue* glue, dsp_memory_manager* manager)
{
glue->managerInterface = manager;
glue->allocate = allocateMemoryManagerGlue;
glue->destroy = destroyMemoryManagerGlue;
}
#ifdef __cplusplus
}
#endif
#endif
/************************** END CGlue.h **************************/
#ifdef _WIN32
#include <windows.h>
#define snprintf _snprintf
#endif
//-------------------------------------------------------------------
// Decode a dsp JSON description and implement 'buildUserInterface'
//-------------------------------------------------------------------
#define REAL_UI(ui_interface) reinterpret_cast<UIReal<REAL>*>(ui_interface)
#define REAL_ADR(offset) reinterpret_cast<REAL*>(&memory_block[offset])
#define REAL_EXT_ADR(offset) reinterpret_cast<FAUSTFLOAT*>(&memory_block[offset])
#define SOUNDFILE_ADR(offset) reinterpret_cast<Soundfile**>(&memory_block[offset])
typedef std::function<void(double)> ReflectFunction;
typedef std::function<double()> ModifyFunction;
struct ExtZoneParam {
virtual void reflectZone() = 0;
virtual void modifyZone() = 0;
virtual void setReflectZoneFun(ReflectFunction reflect) = 0;
virtual void setModifyZoneFun(ModifyFunction modify) = 0;
virtual ~ExtZoneParam()
{}
};
template <typename REAL>
struct JSONUIDecoderReal {
struct ZoneParam : public ExtZoneParam {
REAL fZone;
int fIndex;
ReflectFunction fReflect;
ModifyFunction fModify;
#if defined(TARGET_OS_IPHONE) || defined(WIN32)
ZoneParam(int index, ReflectFunction reflect = nullptr, ModifyFunction modify = nullptr)
:fIndex(index), fReflect(reflect), fModify(modify)
{}
void reflectZone() { if (fReflect) fReflect(fZone); }
void modifyZone() { if (fModify) fZone = fModify(); }
#else
ZoneParam(int index, ReflectFunction reflect = [](REAL value) {}, ModifyFunction modify = []() { return REAL(-1); })
:fIndex(index), fReflect(reflect), fModify(modify)
{}
void reflectZone() { fReflect(fZone); }
void modifyZone() { fZone = fModify(); }
#endif
void setReflectZoneFun(ReflectFunction reflect) { fReflect = reflect; }
void setModifyZoneFun(ModifyFunction modify) { fModify = modify; }
};
typedef std::vector<ExtZoneParam*> controlMap;
std::string fName;
std::string fFileName;
std::string fJSON;
std::string fVersion;
std::string fCompileOptions;
std::map<std::string, std::string> fMetadata;
std::vector<itemInfo> fUiItems;
std::vector<std::string> fLibraryList;
std::vector<std::string> fIncludePathnames;
Soundfile** fSoundfiles;
int fNumInputs, fNumOutputs, fSRIndex;
int fSoundfileItems;
int fDSPSize;
controlMap fPathInputTable; // [path, ZoneParam]
controlMap fPathOutputTable; // [path, ZoneParam]
bool isInput(const std::string& type)
{
return (type == "vslider" || type == "hslider" || type == "nentry" || type == "button" || type == "checkbox");
}
bool isOutput(const std::string& type) { return (type == "hbargraph" || type == "vbargraph"); }
bool isSoundfile(const std::string& type) { return (type == "soundfile"); }
std::string getString(std::map<std::string, std::pair<std::string, double> >& map, const std::string& key)
{
return (map.find(key) != map.end()) ? map[key].first : "";
}
int getInt(std::map<std::string, std::pair<std::string, double> >& map, const std::string& key)
{
return (map.find(key) != map.end()) ? int(map[key].second) : -1;
}
void setReflectZoneFun(int index, ReflectFunction fun)
{
fPathInputTable[index]->setReflectZoneFun(fun);
}
void setModifyZoneFun(int index, ModifyFunction fun)
{
fPathOutputTable[index]->setModifyZoneFun(fun);
}
JSONUIDecoderReal(const std::string& json)
{
fJSON = json;
const char* p = fJSON.c_str();
std::map<std::string, std::pair<std::string, double> > meta_data1;
std::map<std::string, std::vector<std::string> > meta_data2;
parseJson(p, meta_data1, fMetadata, meta_data2, fUiItems);
// meta_data1 contains <name : val>, <inputs : val>, <ouputs : val> pairs etc...
fName = getString(meta_data1, "name");
fFileName = getString(meta_data1, "filename");
fVersion = getString(meta_data1, "version");
fCompileOptions = getString(meta_data1, "compile_options");
if (meta_data2.find("library_list") != meta_data2.end()) {
fLibraryList = meta_data2["library_list"];
}
if (meta_data2.find("include_pathnames") != meta_data2.end()) {
fIncludePathnames = meta_data2["include_pathnames"];
}
fDSPSize = getInt(meta_data1, "size");
fNumInputs = getInt(meta_data1, "inputs");
fNumOutputs = getInt(meta_data1, "outputs");
fSRIndex = getInt(meta_data1, "sr_index");
fSoundfileItems = 0;
for (auto& it : fUiItems) {
std::string type = it.type;
if (isSoundfile(type)) {
fSoundfileItems++;
}
}
fSoundfiles = new Soundfile*[fSoundfileItems];
// Prepare the fPathTable and init zone
for (auto& it : fUiItems) {
std::string type = it.type;
// Meta data declaration for input items
if (isInput(type)) {
ZoneParam* param = new ZoneParam(it.index);
fPathInputTable.push_back(param);
param->fZone = it.init;
}
// Meta data declaration for output items
else if (isOutput(type)) {
ZoneParam* param = new ZoneParam(it.index);
fPathOutputTable.push_back(param);
param->fZone = REAL(0);
}
}
}
virtual ~JSONUIDecoderReal()
{
delete [] fSoundfiles;
for (auto& it : fPathInputTable) {
delete it;
}
for (auto& it : fPathOutputTable) {
delete it;
}
}
void metadata(Meta* m)
{
for (auto& it : fMetadata) {
m->declare(it.first.c_str(), it.second.c_str());
}
}
void metadata(MetaGlue* m)
{
for (auto& it : fMetadata) {
m->declare(m->metaInterface, it.first.c_str(), it.second.c_str());
}
}
void resetUserInterface()
{
int item = 0;
for (auto& it : fUiItems) {
if (isInput(it.type)) {
static_cast<ZoneParam*>(fPathInputTable[item++])->fZone = it.init;
}
}
}
void resetUserInterface(char* memory_block, Soundfile* defaultsound = nullptr)
{
for (auto& it : fUiItems) {
int offset = it.index;
if (isInput(it.type)) {
*REAL_ADR(offset) = it.init;
} else if (isSoundfile(it.type)) {
if (*SOUNDFILE_ADR(offset) == nullptr) {
*SOUNDFILE_ADR(offset) = defaultsound;
}
}
}
}
int getSampleRate(char* memory_block)
{
return *reinterpret_cast<int*>(&memory_block[fSRIndex]);
}
void buildUserInterface(UI* ui_interface)
{
// MANDATORY: to be sure floats or double are correctly parsed
char* tmp_local = setlocale(LC_ALL, nullptr);
if (tmp_local != NULL) {
tmp_local = strdup(tmp_local);
}
setlocale(LC_ALL, "C");
int countIn = 0;
int countOut = 0;
int countSound = 0;
for (auto& it : fUiItems) {
std::string type = it.type;
REAL init = REAL(it.init);
REAL min = REAL(it.min);
REAL max = REAL(it.max);
REAL step = REAL(it.step);
// Meta data declaration for input items
if (isInput(type)) {
for (size_t i = 0; i < it.meta.size(); i++) {
REAL_UI(ui_interface)->declare(&static_cast<ZoneParam*>(fPathInputTable[countIn])->fZone, it.meta[i].first.c_str(), it.meta[i].second.c_str());
}
}
// Meta data declaration for output items
else if (isOutput(type)) {
for (size_t i = 0; i < it.meta.size(); i++) {
REAL_UI(ui_interface)->declare(&static_cast<ZoneParam*>(fPathOutputTable[countOut])->fZone, it.meta[i].first.c_str(), it.meta[i].second.c_str());
}
}
// Meta data declaration for group opening or closing
else {
for (size_t i = 0; i < it.meta.size(); i++) {
REAL_UI(ui_interface)->declare(0, it.meta[i].first.c_str(), it.meta[i].second.c_str());
}
}
if (type == "hgroup") {
REAL_UI(ui_interface)->openHorizontalBox(it.label.c_str());
} else if (type == "vgroup") {
REAL_UI(ui_interface)->openVerticalBox(it.label.c_str());
} else if (type == "tgroup") {
REAL_UI(ui_interface)->openTabBox(it.label.c_str());
} else if (type == "vslider") {
REAL_UI(ui_interface)->addVerticalSlider(it.label.c_str(), &static_cast<ZoneParam*>(fPathInputTable[countIn])->fZone, init, min, max, step);
} else if (type == "hslider") {
REAL_UI(ui_interface)->addHorizontalSlider(it.label.c_str(), &static_cast<ZoneParam*>(fPathInputTable[countIn])->fZone, init, min, max, step);
} else if (type == "checkbox") {
REAL_UI(ui_interface)->addCheckButton(it.label.c_str(), &static_cast<ZoneParam*>(fPathInputTable[countIn])->fZone);
} else if (type == "soundfile") {
REAL_UI(ui_interface)->addSoundfile(it.label.c_str(), it.url.c_str(), &fSoundfiles[countSound]);
} else if (type == "hbargraph") {
REAL_UI(ui_interface)->addHorizontalBargraph(it.label.c_str(), &static_cast<ZoneParam*>(fPathOutputTable[countOut])->fZone, min, max);
} else if (type == "vbargraph") {
REAL_UI(ui_interface)->addVerticalBargraph(it.label.c_str(), &static_cast<ZoneParam*>(fPathOutputTable[countOut])->fZone, min, max);
} else if (type == "nentry") {
REAL_UI(ui_interface)->addNumEntry(it.label.c_str(), &static_cast<ZoneParam*>(fPathInputTable[countIn])->fZone, init, min, max, step);
} else if (type == "button") {
REAL_UI(ui_interface)->addButton(it.label.c_str(), &static_cast<ZoneParam*>(fPathInputTable[countIn])->fZone);
} else if (type == "close") {
REAL_UI(ui_interface)->closeBox();
}
if (isInput(type)) {
countIn++;
} else if (isOutput(type)) {
countOut++;
} else if (isSoundfile(type)) {
countSound++;
}
}
if (tmp_local != NULL) {
setlocale(LC_ALL, tmp_local);
free(tmp_local);
}
}
void buildUserInterface(UI* ui_interface, char* memory_block)
{
// MANDATORY: to be sure floats or double are correctly parsed
char* tmp_local = setlocale(LC_ALL, nullptr);
if (tmp_local != NULL) {
tmp_local = strdup(tmp_local);
}
setlocale(LC_ALL, "C");
for (auto& it : fUiItems) {
std::string type = it.type;
int offset = it.index;
REAL init = REAL(it.init);
REAL min = REAL(it.min);
REAL max = REAL(it.max);
REAL step = REAL(it.step);
// Meta data declaration for input items
if (isInput(type)) {
for (size_t i = 0; i < it.meta.size(); i++) {
REAL_UI(ui_interface)->declare(REAL_ADR(offset), it.meta[i].first.c_str(), it.meta[i].second.c_str());
}
}
// Meta data declaration for output items
else if (isOutput(type)) {
for (size_t i = 0; i < it.meta.size(); i++) {
REAL_UI(ui_interface)->declare(REAL_ADR(offset), it.meta[i].first.c_str(), it.meta[i].second.c_str());
}
}
// Meta data declaration for group opening or closing
else {
for (size_t i = 0; i < it.meta.size(); i++) {
REAL_UI(ui_interface)->declare(0, it.meta[i].first.c_str(), it.meta[i].second.c_str());
}
}
if (type == "hgroup") {
REAL_UI(ui_interface)->openHorizontalBox(it.label.c_str());
} else if (type == "vgroup") {
REAL_UI(ui_interface)->openVerticalBox(it.label.c_str());
} else if (type == "tgroup") {
REAL_UI(ui_interface)->openTabBox(it.label.c_str());
} else if (type == "vslider") {
REAL_UI(ui_interface)->addVerticalSlider(it.label.c_str(), REAL_ADR(offset), init, min, max, step);
} else if (type == "hslider") {
REAL_UI(ui_interface)->addHorizontalSlider(it.label.c_str(), REAL_ADR(offset), init, min, max, step);
} else if (type == "checkbox") {
REAL_UI(ui_interface)->addCheckButton(it.label.c_str(), REAL_ADR(offset));
} else if (type == "soundfile") {
REAL_UI(ui_interface)->addSoundfile(it.label.c_str(), it.url.c_str(), SOUNDFILE_ADR(offset));
} else if (type == "hbargraph") {
REAL_UI(ui_interface)->addHorizontalBargraph(it.label.c_str(), REAL_ADR(offset), min, max);
} else if (type == "vbargraph") {
REAL_UI(ui_interface)->addVerticalBargraph(it.label.c_str(), REAL_ADR(offset), min, max);
} else if (type == "nentry") {
REAL_UI(ui_interface)->addNumEntry(it.label.c_str(), REAL_ADR(offset), init, min, max, step);
} else if (type == "button") {
REAL_UI(ui_interface)->addButton(it.label.c_str(), REAL_ADR(offset));
} else if (type == "close") {
REAL_UI(ui_interface)->closeBox();
}
}
if (tmp_local != NULL) {
setlocale(LC_ALL, tmp_local);
free(tmp_local);
}
}
void buildUserInterface(UIGlue* ui_interface, char* memory_block)
{
// MANDATORY: to be sure floats or double are correctly parsed
char* tmp_local = setlocale(LC_ALL, nullptr);
if (tmp_local != NULL) {
tmp_local = strdup(tmp_local);
}
setlocale(LC_ALL, "C");
for (auto& it : fUiItems) {
std::string type = it.type;
int offset = it.index;
REAL init = REAL(it.init);
REAL min = REAL(it.min);
REAL max = REAL(it.max);
REAL step = REAL(it.step);
// Meta data declaration for input items
if (isInput(type)) {
for (size_t i = 0; i < it.meta.size(); i++) {
ui_interface->declare(ui_interface->uiInterface, REAL_EXT_ADR(offset), it.meta[i].first.c_str(), it.meta[i].second.c_str());
}
}
// Meta data declaration for output items
else if (isOutput(type)) {
for (size_t i = 0; i < it.meta.size(); i++) {
ui_interface->declare(ui_interface->uiInterface, REAL_EXT_ADR(offset), it.meta[i].first.c_str(), it.meta[i].second.c_str());
}
}
// Meta data declaration for group opening or closing
else {
for (size_t i = 0; i < it.meta.size(); i++) {
ui_interface->declare(ui_interface->uiInterface, 0, it.meta[i].first.c_str(), it.meta[i].second.c_str());
}
}
if (type == "hgroup") {
ui_interface->openHorizontalBox(ui_interface->uiInterface, it.label.c_str());
} else if (type == "vgroup") {
ui_interface->openVerticalBox(ui_interface->uiInterface, it.label.c_str());
} else if (type == "tgroup") {
ui_interface->openTabBox(ui_interface->uiInterface, it.label.c_str());
} else if (type == "vslider") {
ui_interface->addVerticalSlider(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset), init, min, max, step);
} else if (type == "hslider") {
ui_interface->addHorizontalSlider(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset), init, min, max, step);
} else if (type == "checkbox") {
ui_interface->addCheckButton(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset));
} else if (type == "soundfile") {
ui_interface->addSoundfile(ui_interface->uiInterface, it.label.c_str(), it.url.c_str(), SOUNDFILE_ADR(offset));
} else if (type == "hbargraph") {
ui_interface->addHorizontalBargraph(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset), min, max);
} else if (type == "vbargraph") {
ui_interface->addVerticalBargraph(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset), min, max);
} else if (type == "nentry") {
ui_interface->addNumEntry(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset), init, min, max, step);
} else if (type == "button") {
ui_interface->addButton(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset));
} else if (type == "close") {
ui_interface->closeBox(ui_interface->uiInterface);
}
}
if (tmp_local != NULL) {
setlocale(LC_ALL, tmp_local);
free(tmp_local);
}
}
bool hasCompileOption(const std::string& option)
{
std::istringstream iss(fCompileOptions);
std::string token;
while (std::getline(iss, token, ' ')) {
if (token == option) return true;
}
return false;
}
};
// Templated decoder
struct JSONUITemplatedDecoder
{
virtual ~JSONUITemplatedDecoder()
{}
virtual void metadata(Meta* m) = 0;
virtual void metadata(MetaGlue* glue) = 0;
virtual int getDSPSize() = 0;
virtual std::string getName() = 0;
virtual std::string getLibVersion() = 0;
virtual std::string getCompileOptions() = 0;
virtual std::vector<std::string> getLibraryList() = 0;
virtual std::vector<std::string> getIncludePathnames() = 0;
virtual int getNumInputs() = 0;
virtual int getNumOutputs() = 0;
virtual int getSampleRate(char* memory_block) = 0;
virtual void setReflectZoneFun(int index, ReflectFunction fun) = 0;
virtual void setModifyZoneFun(int index, ModifyFunction fun) = 0;
virtual std::vector<ExtZoneParam*>& getInputControls() = 0;
virtual std::vector<ExtZoneParam*>& getOutputControls() = 0;
virtual void resetUserInterface(char* memory_block, Soundfile* defaultsound = nullptr) = 0;
virtual void buildUserInterface(UI* ui_interface) = 0;
virtual void buildUserInterface(UI* ui_interface, char* memory_block) = 0;
virtual void buildUserInterface(UIGlue* ui_interface, char* memory_block) = 0;
virtual bool hasCompileOption(const std::string& option) = 0;
};
// Float templated decoder
struct JSONUIFloatDecoder : public JSONUIDecoderReal<float>, public JSONUITemplatedDecoder
{
JSONUIFloatDecoder(const std::string& json):JSONUIDecoderReal<float>(json)
{}
void metadata(Meta* m) { JSONUIDecoderReal<float>::metadata(m); }
void metadata(MetaGlue* glue) { JSONUIDecoderReal<float>::metadata(glue); }
int getDSPSize() { return fDSPSize; }
std::string getName() { return fName; }
std::string getLibVersion() { return fVersion; }
std::string getCompileOptions() { return fCompileOptions; }
std::vector<std::string> getLibraryList() { return fLibraryList; }
std::vector<std::string> getIncludePathnames() { return fIncludePathnames; }
int getNumInputs() { return fNumInputs; }
int getNumOutputs() { return fNumOutputs; }
int getSampleRate(char* memory_block) { return JSONUIDecoderReal<float>::getSampleRate(memory_block); }
void setReflectZoneFun(int index, ReflectFunction fun)
{
JSONUIDecoderReal<float>::setReflectZoneFun(index, fun);
}
void setModifyZoneFun(int index, ModifyFunction fun)
{
JSONUIDecoderReal<float>::setModifyZoneFun(index, fun);
}
std::vector<ExtZoneParam*>& getInputControls()
{
return fPathInputTable;
}
std::vector<ExtZoneParam*>& getOutputControls()
{
return fPathOutputTable;
}
void resetUserInterface(char* memory_block, Soundfile* defaultsound = nullptr)
{
JSONUIDecoderReal<float>::resetUserInterface(memory_block, defaultsound);
}
void buildUserInterface(UI* ui_interface)
{
JSONUIDecoderReal<float>::buildUserInterface(ui_interface);
}
void buildUserInterface(UI* ui_interface, char* memory_block)
{
JSONUIDecoderReal<float>::buildUserInterface(ui_interface, memory_block);
}
void buildUserInterface(UIGlue* ui_interface, char* memory_block)
{
JSONUIDecoderReal<float>::buildUserInterface(ui_interface, memory_block);
}
bool hasCompileOption(const std::string& option) { return JSONUIDecoderReal<float>::hasCompileOption(option); }
};
// Double templated decoder
struct JSONUIDoubleDecoder : public JSONUIDecoderReal<double>, public JSONUITemplatedDecoder
{
JSONUIDoubleDecoder(const std::string& json):JSONUIDecoderReal<double>(json)
{}
void metadata(Meta* m) { JSONUIDecoderReal<double>::metadata(m); }
void metadata(MetaGlue* glue) { JSONUIDecoderReal<double>::metadata(glue); }
int getDSPSize() { return fDSPSize; }
std::string getName() { return fName; }
std::string getLibVersion() { return fVersion; }
std::string getCompileOptions() { return fCompileOptions; }
std::vector<std::string> getLibraryList() { return fLibraryList; }
std::vector<std::string> getIncludePathnames() { return fIncludePathnames; }
int getNumInputs() { return fNumInputs; }
int getNumOutputs() { return fNumOutputs; }
int getSampleRate(char* memory_block) { return JSONUIDecoderReal<double>::getSampleRate(memory_block); }
void setReflectZoneFun(int index, ReflectFunction fun)
{
JSONUIDecoderReal<double>::setReflectZoneFun(index, fun);
}
void setModifyZoneFun(int index, ModifyFunction fun)
{
JSONUIDecoderReal<double>::setModifyZoneFun(index, fun);
}
std::vector<ExtZoneParam*>& getInputControls()
{
return fPathInputTable;
}
std::vector<ExtZoneParam*>& getOutputControls()
{
return fPathOutputTable;
}
void resetUserInterface(char* memory_block, Soundfile* defaultsound = nullptr)
{
JSONUIDecoderReal<double>::resetUserInterface(memory_block, defaultsound);
}
void buildUserInterface(UI* ui_interface)
{
JSONUIDecoderReal<double>::buildUserInterface(ui_interface);
}
void buildUserInterface(UI* ui_interface, char* memory_block)
{
JSONUIDecoderReal<double>::buildUserInterface(ui_interface, memory_block);
}
void buildUserInterface(UIGlue* ui_interface, char* memory_block)
{
JSONUIDecoderReal<double>::buildUserInterface(ui_interface, memory_block);
}
bool hasCompileOption(const std::string& option) { return JSONUIDecoderReal<double>::hasCompileOption(option); }
};
// FAUSTFLOAT templated decoder
struct JSONUIDecoder : public JSONUIDecoderReal<FAUSTFLOAT>
{
JSONUIDecoder(const std::string& json):JSONUIDecoderReal<FAUSTFLOAT>(json)
{}
};
// Generic factory
static JSONUITemplatedDecoder* createJSONUIDecoder(const std::string& json)
{
JSONUIDecoder decoder(json);
if (decoder.hasCompileOption("-double")) {
return new JSONUIDoubleDecoder(json);
} else {
return new JSONUIFloatDecoder(json);
}
}
#endif
/************************** END JSONUIDecoder.h **************************/
//----------------------------------------------------------------
// Proxy dsp definition created from the DSP JSON description
// This class allows a 'proxy' dsp to control a real dsp
// possibly running somewhere else.
//----------------------------------------------------------------
class proxy_dsp : public dsp {
private:
JSONUIDecoder* fDecoder;
int fSampleRate;
public:
proxy_dsp():fDecoder(nullptr), fSampleRate(-1)
{}
proxy_dsp(const std::string& json)
{
init(json);
}
void init(const std::string& json)
{
fDecoder = new JSONUIDecoder(json);
fSampleRate = -1;
}
proxy_dsp(dsp* dsp)
{
JSONUI builder(dsp->getNumInputs(), dsp->getNumOutputs());
dsp->metadata(&builder);
dsp->buildUserInterface(&builder);
fSampleRate = dsp->getSampleRate();
fDecoder = new JSONUIDecoder(builder.JSON());
}
virtual ~proxy_dsp()
{
delete fDecoder;
}
virtual int getNumInputs() { return fDecoder->fNumInputs; }
virtual int getNumOutputs() { return fDecoder->fNumOutputs; }
virtual void buildUserInterface(UI* ui) { fDecoder->buildUserInterface(ui); }
// To possibly implement in a concrete proxy dsp
virtual void init(int sample_rate)
{
instanceInit(sample_rate);
}
virtual void instanceInit(int sample_rate)
{
instanceConstants(sample_rate);
instanceResetUserInterface();
instanceClear();
}
virtual void instanceConstants(int sample_rate) { fSampleRate = sample_rate; }
virtual void instanceResetUserInterface() { fDecoder->resetUserInterface(); }
virtual void instanceClear() {}
virtual int getSampleRate() { return fSampleRate; }
virtual proxy_dsp* clone() { return new proxy_dsp(fDecoder->fJSON); }
virtual void metadata(Meta* m) { fDecoder->metadata(m); }
virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) {}
virtual void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) {}
};
#endif
/************************** END proxy-dsp.h **************************/
/************************** BEGIN JSONControl.h **************************/
/************************************************************************
FAUST Architecture File
Copyright (C) 2019 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************/
#ifndef __JSON_CONTROL__
#define __JSON_CONTROL__
#include <string>
#ifndef FAUSTFLOAT
#define FAUSTFLOAT float
#endif
struct JSONControl {
virtual std::string getJSON() { return ""; }
virtual void setParamValue(const std::string& path, FAUSTFLOAT value) {}
virtual FAUSTFLOAT getParamValue(const std::string& path) { return 0; }
virtual ~JSONControl()
{}
};
#endif
/************************** END JSONControl.h **************************/
#define kActiveVoice 0
#define kFreeVoice -1
#define kReleaseVoice -2
#define kNoVoice -3
#define VOICE_STOP_LEVEL 0.0005 // -70 db
#define MIX_BUFFER_SIZE 4096
// endsWith(<str>,<end>) : returns true if <str> ends with <end>
static double midiToFreq(double note)
{
return 440.0 * std::pow(2.0, (note-69.0)/12.0);
}
/**
* Allows to control zones in a grouped manner.
*/
class GroupUI : public GUI, public PathBuilder
{
private:
std::map<std::string, uiGroupItem*> fLabelZoneMap;
void insertMap(std::string label, FAUSTFLOAT* zone)
{
if (!MapUI::endsWith(label, "/gate")
&& !MapUI::endsWith(label, "/freq")
&& !MapUI::endsWith(label, "/gain")) {
// Groups all controller except 'freq', 'gate', and 'gain'
if (fLabelZoneMap.find(label) != fLabelZoneMap.end()) {
fLabelZoneMap[label]->addZone(zone);
} else {
fLabelZoneMap[label] = new uiGroupItem(this, zone);
}
}
}
uiCallbackItem* fPanic;
public:
GroupUI(FAUSTFLOAT* zone, uiCallback cb, void* arg)
{
fPanic = new uiCallbackItem(this, zone, cb, arg);
}
virtual ~GroupUI()
{
// 'fPanic' is kept and deleted in GUI, so do not delete here
}
// -- widget's layouts
void openTabBox(const char* label)
{
pushLabel(label);
}
void openHorizontalBox(const char* label)
{
pushLabel(label);
}
void openVerticalBox(const char* label)
{
pushLabel(label);
}
void closeBox()
{
popLabel();
}
// -- active widgets
void addButton(const char* label, FAUSTFLOAT* zone)
{
insertMap(buildPath(label), zone);
}
void addCheckButton(const char* label, FAUSTFLOAT* zone)
{
insertMap(buildPath(label), zone);
}
void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step)
{
insertMap(buildPath(label), zone);
}
void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step)
{
insertMap(buildPath(label), zone);
}
void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step)
{
insertMap(buildPath(label), zone);
}
// -- passive widgets
void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT fmin, FAUSTFLOAT fmax)
{
insertMap(buildPath(label), zone);
}
void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT fmin, FAUSTFLOAT fmax)
{
insertMap(buildPath(label), zone);
}
};
/**
* One voice of polyphony.
*/
struct dsp_voice : public MapUI, public decorator_dsp {
int fNote; // Playing note actual pitch
int fDate; // KeyOn date
int fRelease; // Current number of samples used in release mode to detect end of note
int fMinRelease; // Max of samples used in release mode to detect end of note
FAUSTFLOAT fLevel; // Last audio block level
std::vector<std::string> fGatePath; // Paths of 'gate' control
std::vector<std::string> fGainPath; // Paths of 'gain' control
std::vector<std::string> fFreqPath; // Paths of 'freq' control
dsp_voice(dsp* dsp):decorator_dsp(dsp)
{
dsp->buildUserInterface(this);
fNote = kFreeVoice;
fLevel = FAUSTFLOAT(0);
fDate = 0;
fMinRelease = dsp->getSampleRate()/2; // One 1/2 sec used in release mode to detect end of note
extractPaths(fGatePath, fFreqPath, fGainPath);
}
virtual ~dsp_voice()
{}
void extractPaths(std::vector<std::string>& gate, std::vector<std::string>& freq, std::vector<std::string>& gain)
{
// Keep gain, freq and gate labels
std::map<std::string, FAUSTFLOAT*>::iterator it;
for (it = getMap().begin(); it != getMap().end(); it++) {
std::string path = (*it).first;
if (endsWith(path, "/gate")) {
gate.push_back(path);
} else if (endsWith(path, "/freq")) {
freq.push_back(path);
} else if (endsWith(path, "/gain")) {
gain.push_back(path);
}
}
}
// MIDI velocity [0..127]
void keyOn(int pitch, int velocity, bool trigger)
{
keyOn(pitch, float(velocity)/127.f, trigger);
}
// Normalized MIDI velocity [0..1]
void keyOn(int pitch, float velocity, bool trigger)
{
// So that DSP state is always re-initialized
fDSP->instanceClear();
for (size_t i = 0; i < fFreqPath.size(); i++) {
setParamValue(fFreqPath[i], midiToFreq(pitch));
}
for (size_t i = 0; i < fGatePath.size(); i++) {
setParamValue(fGatePath[i], FAUSTFLOAT(1));
}
for (size_t i = 0; i < fGainPath.size(); i++) {
setParamValue(fGainPath[i], velocity);
}
fNote = pitch;
}
void keyOff(bool hard = false)
{
// No use of velocity for now...
for (size_t i = 0; i < fGatePath.size(); i++) {
setParamValue(fGatePath[i], FAUSTFLOAT(0));
}
if (hard) {
// Immediately stop voice
fNote = kFreeVoice;
} else {
// Release voice
fRelease = fMinRelease;
fNote = kReleaseVoice;
}
}
};
/**
* A group of voices.
*/
struct dsp_voice_group {
GroupUI fGroups;
std::vector<dsp_voice*> fVoiceTable; // Individual voices
dsp* fVoiceGroup; // Voices group to be used for GUI grouped control
FAUSTFLOAT fPanic;
bool fVoiceControl;
bool fGroupControl;
dsp_voice_group(uiCallback cb, void* arg, bool control, bool group)
:fGroups(&fPanic, cb, arg),
fVoiceGroup(0), fPanic(FAUSTFLOAT(0)),
fVoiceControl(control), fGroupControl(group)
{}
virtual ~dsp_voice_group()
{
for (size_t i = 0; i < fVoiceTable.size(); i++) {
delete fVoiceTable[i];
}
delete fVoiceGroup;
}
void addVoice(dsp_voice* voice)
{
fVoiceTable.push_back(voice);
}
void clearVoices()
{
fVoiceTable.clear();
}
void init()
{
// Groups all uiItem for a given path
fVoiceGroup = new proxy_dsp(fVoiceTable[0]);
fVoiceGroup->buildUserInterface(&fGroups);
for (size_t i = 0; i < fVoiceTable.size(); i++) {
fVoiceTable[i]->buildUserInterface(&fGroups);
}
}
void instanceResetUserInterface()
{
for (size_t i = 0; i < fVoiceTable.size(); i++) {
fVoiceTable[i]->instanceResetUserInterface();
}
}
void buildUserInterface(UI* ui_interface)
{
if (fVoiceTable.size() > 1) {
ui_interface->openTabBox("Polyphonic");
// Grouped voices UI
ui_interface->openVerticalBox("Voices");
ui_interface->addButton("Panic", &fPanic);
fVoiceGroup->buildUserInterface(ui_interface);
ui_interface->closeBox();
// If not grouped, also add individual voices UI
if (!fGroupControl) {
for (size_t i = 0; i < fVoiceTable.size(); i++) {
char buffer[32];
snprintf(buffer, 32, ((fVoiceTable.size() < 8) ? "Voice%ld" : "V%ld"), long(i+1));
ui_interface->openHorizontalBox(buffer);
fVoiceTable[i]->buildUserInterface(ui_interface);
ui_interface->closeBox();
}
}
ui_interface->closeBox();
} else {
fVoiceTable[0]->buildUserInterface(ui_interface);
}
}
};
/**
* Base class for MIDI controllable DSP.
*/
#ifdef EMCC
#endif
class dsp_poly : public decorator_dsp, public midi, public JSONControl {
protected:
#ifdef EMCC
MapUI fMapUI;
std::string fJSON;
midi_handler fMIDIHandler;
MidiUI fMIDIUI;
#endif
public:
#ifdef EMCC
dsp_poly(dsp* dsp):decorator_dsp(dsp), fMIDIUI(&fMIDIHandler)
{
JSONUI jsonui(getNumInputs(), getNumOutputs());
buildUserInterface(&jsonui);
fJSON = jsonui.JSON(true);
buildUserInterface(&fMapUI);
buildUserInterface(&fMIDIUI);
}
#else
dsp_poly(dsp* dsp):decorator_dsp(dsp)
{}
#endif
virtual ~dsp_poly() {}
// Reimplemented for EMCC
#ifdef EMCC
virtual int getNumInputs() { return decorator_dsp::getNumInputs(); }
virtual int getNumOutputs() { return decorator_dsp::getNumOutputs(); }
virtual void buildUserInterface(UI* ui_interface) { decorator_dsp::buildUserInterface(ui_interface); }
virtual int getSampleRate() { return decorator_dsp::getSampleRate(); }
virtual void init(int sample_rate) { decorator_dsp::init(sample_rate); }
virtual void instanceInit(int sample_rate) { decorator_dsp::instanceInit(sample_rate); }
virtual void instanceConstants(int sample_rate) { decorator_dsp::instanceConstants(sample_rate); }
virtual void instanceResetUserInterface() { decorator_dsp::instanceResetUserInterface(); }
virtual void instanceClear() { decorator_dsp::instanceClear(); }
virtual dsp_poly* clone() { return new dsp_poly(fDSP->clone()); }
virtual void metadata(Meta* m) { decorator_dsp::metadata(m); }
// Additional API
std::string getJSON()
{
return fJSON;
}
virtual void setParamValue(const std::string& path, FAUSTFLOAT value)
{
fMapUI.setParamValue(path, value);
GUI::updateAllGuis();
}
virtual FAUSTFLOAT getParamValue(const std::string& path) { return fMapUI.getParamValue(path); }
virtual void computeJS(int count, uintptr_t inputs, uintptr_t outputs)
{
decorator_dsp::compute(count, reinterpret_cast<FAUSTFLOAT**>(inputs),reinterpret_cast<FAUSTFLOAT**>(outputs));
}
#endif
virtual MapUI* keyOn(int channel, int pitch, int velocity)
{
return midi::keyOn(channel, pitch, velocity);
}
virtual void keyOff(int channel, int pitch, int velocity)
{
midi::keyOff(channel, pitch, velocity);
}
virtual void keyPress(int channel, int pitch, int press)
{
midi::keyPress(channel, pitch, press);
}
virtual void chanPress(int channel, int press)
{
midi::chanPress(channel, press);
}
virtual void ctrlChange(int channel, int ctrl, int value)
{
midi::ctrlChange(channel, ctrl, value);
}
virtual void ctrlChange14bits(int channel, int ctrl, int value)
{
midi::ctrlChange14bits(channel, ctrl, value);
}
virtual void pitchWheel(int channel, int wheel)
{
#ifdef EMCC
fMIDIUI.pitchWheel(0., channel, wheel);
GUI::updateAllGuis();
#else
midi::pitchWheel(channel, wheel);
#endif
}
virtual void progChange(int channel, int pgm)
{
midi::progChange(channel, pgm);
}
// Group API
virtual void setGroup(bool group) {}
virtual bool getGroup() { return false; }
};
/**
* Polyphonic DSP: groups a set of DSP to be played together or triggered by MIDI.
*
* All voices are preallocated by cloning the single DSP voice given at creation time.
* Dynamic voice allocation is done in 'getFreeVoice'
*/
class mydsp_poly : public dsp_voice_group, public dsp_poly {
private:
FAUSTFLOAT** fMixBuffer;
int fDate;
FAUSTFLOAT mixCheckVoice(int count, FAUSTFLOAT** outputBuffer, FAUSTFLOAT** mixBuffer)
{
FAUSTFLOAT level = 0;
for (int i = 0; i < getNumOutputs(); i++) {
FAUSTFLOAT* mixChannel = mixBuffer[i];
FAUSTFLOAT* outChannel = outputBuffer[i];
for (int j = 0; j < count; j++) {
level = std::max<FAUSTFLOAT>(level, (FAUSTFLOAT)fabs(outChannel[j]));
mixChannel[j] += outChannel[j];
}
}
return level;
}
void mixVoice(int count, FAUSTFLOAT** outputBuffer, FAUSTFLOAT** mixBuffer)
{
for (int i = 0; i < getNumOutputs(); i++) {
FAUSTFLOAT* mixChannel = mixBuffer[i];
FAUSTFLOAT* outChannel = outputBuffer[i];
for (int j = 0; j < count; j++) {
mixChannel[j] += outChannel[j];
}
}
}
void clearOutput(int count, FAUSTFLOAT** mixBuffer)
{
for (int i = 0; i < getNumOutputs(); i++) {
memset(mixBuffer[i], 0, count * sizeof(FAUSTFLOAT));
}
}
int getPlayingVoice(int pitch)
{
int voice_playing = kNoVoice;
int oldest_date_playing = INT_MAX;
for (size_t i = 0; i < fVoiceTable.size(); i++) {
if (fVoiceTable[i]->fNote == pitch) {
// Keeps oldest playing voice
if (fVoiceTable[i]->fDate < oldest_date_playing) {
oldest_date_playing = fVoiceTable[i]->fDate;
voice_playing = int(i);
}
}
}
return voice_playing;
}
// Always returns a voice
int getFreeVoice()
{
int voice = kNoVoice;
// Looks for the first available voice
for (size_t i = 0; i < fVoiceTable.size(); i++) {
if (fVoiceTable[i]->fNote == kFreeVoice) {
voice = int(i);
goto result;
}
}
{
// Otherwise steal one
int voice_release = kNoVoice;
int voice_playing = kNoVoice;
int oldest_date_release = INT_MAX;
int oldest_date_playing = INT_MAX;
// Scan all voices
for (size_t i = 0; i < fVoiceTable.size(); i++) {
if (fVoiceTable[i]->fNote == kReleaseVoice) {
// Keeps oldest release voice
if (fVoiceTable[i]->fDate < oldest_date_release) {
oldest_date_release = fVoiceTable[i]->fDate;
voice_release = int(i);
}
} else {
// Otherwise keeps oldest playing voice
if (fVoiceTable[i]->fDate < oldest_date_playing) {
oldest_date_playing = fVoiceTable[i]->fDate;
voice_playing = int(i);
}
}
}
// Then decide which one to steal
if (oldest_date_release != INT_MAX) {
std::cout << "Steal release voice : voice_date " << fVoiceTable[voice_release]->fDate << " cur_date = " << fDate << " voice = " << voice_release << std::endl;
voice = voice_release;
goto result;
} else if (oldest_date_playing != INT_MAX) {
std::cout << "Steal playing voice : voice_date " << fVoiceTable[voice_playing]->fDate << " cur_date = " << fDate << " voice = " << voice_playing << std::endl;
voice = voice_playing;
goto result;
} else {
assert(false);
return kNoVoice;
}
}
result:
fVoiceTable[voice]->fDate = fDate++;
fVoiceTable[voice]->fNote = kActiveVoice;
return voice;
}
static void panic(FAUSTFLOAT val, void* arg)
{
if (val == FAUSTFLOAT(1)) {
static_cast<mydsp_poly*>(arg)->allNotesOff(true);
}
}
bool checkPolyphony()
{
if (fVoiceTable.size() > 0) {
return true;
} else {
std::cout << "DSP is not polyphonic...\n";
return false;
}
}
public:
/**
* Constructor.
*
* @param dsp - the dsp to be used for one voice. Beware: mydsp_poly will use and finally delete the pointer.
* @param nvoices - number of polyphony voices, should be at least 1
* @param control - whether voices will be dynamically allocated and controlled (typically by a MIDI controler).
* If false all voices are always running.
* @param group - if true, voices are not individually accessible, a global "Voices" tab will automatically dispatch
* a given control on all voices, assuming GUI::updateAllGuis() is called.
* If false, all voices can be individually controlled.
* setGroup/getGroup methods can be used to set/get the group state.
*
*/
mydsp_poly(dsp* dsp,
int nvoices,
bool control = false,
bool group = true)
: dsp_voice_group(panic, this, control, group), dsp_poly(dsp) // dsp parameter is deallocated by ~dsp_poly
{
fDate = 0;
// Create voices
assert(nvoices > 0);
for (int i = 0; i < nvoices; i++) {
addVoice(new dsp_voice(dsp->clone()));
}
// Init audio output buffers
fMixBuffer = new FAUSTFLOAT*[getNumOutputs()];
for (int i = 0; i < getNumOutputs(); i++) {
fMixBuffer[i] = new FAUSTFLOAT[MIX_BUFFER_SIZE];
}
dsp_voice_group::init();
}
virtual ~mydsp_poly()
{
for (int i = 0; i < getNumOutputs(); i++) {
delete[] fMixBuffer[i];
}
delete[] fMixBuffer;
}
// DSP API
void buildUserInterface(UI* ui_interface)
{
dsp_voice_group::buildUserInterface(ui_interface);
}
void init(int sample_rate)
{
decorator_dsp::init(sample_rate);
fVoiceGroup->init(sample_rate);
fPanic = FAUSTFLOAT(0);
// Init voices
for (size_t i = 0; i < fVoiceTable.size(); i++) {
fVoiceTable[i]->init(sample_rate);
}
}
void instanceInit(int samplingFreq)
{
instanceConstants(samplingFreq);
instanceResetUserInterface();
instanceClear();
}
void instanceConstants(int sample_rate)
{
decorator_dsp::instanceConstants(sample_rate);
fVoiceGroup->instanceConstants(sample_rate);
// Init voices
for (size_t i = 0; i < fVoiceTable.size(); i++) {
fVoiceTable[i]->instanceConstants(sample_rate);
}
}
void instanceResetUserInterface()
{
decorator_dsp::instanceResetUserInterface();
fVoiceGroup->instanceResetUserInterface();
fPanic = FAUSTFLOAT(0);
for (size_t i = 0; i < fVoiceTable.size(); i++) {
fVoiceTable[i]->instanceResetUserInterface();
}
}
void instanceClear()
{
decorator_dsp::instanceClear();
fVoiceGroup->instanceClear();
for (size_t i = 0; i < fVoiceTable.size(); i++) {
fVoiceTable[i]->instanceClear();
}
}
virtual mydsp_poly* clone()
{
return new mydsp_poly(fDSP->clone(), int(fVoiceTable.size()), fVoiceControl, fGroupControl);
}
void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs)
{
assert(count <= MIX_BUFFER_SIZE);
// First clear the outputs
clearOutput(count, outputs);
if (fVoiceControl) {
// Mix all playing voices
for (size_t i = 0; i < fVoiceTable.size(); i++) {
dsp_voice* voice = fVoiceTable[i];
if (voice->fNote != kFreeVoice) {
voice->compute(count, inputs, fMixBuffer);
// Mix it in result
voice->fLevel = mixCheckVoice(count, fMixBuffer, outputs);
// Check the level to possibly set the voice in kFreeVoice again
voice->fRelease -= count;
if ((voice->fNote == kReleaseVoice)
&& (voice->fRelease < 0)
&& (voice->fLevel < VOICE_STOP_LEVEL)) {
voice->fNote = kFreeVoice;
}
}
}
} else {
// Mix all voices
for (size_t i = 0; i < fVoiceTable.size(); i++) {
fVoiceTable[i]->compute(count, inputs, fMixBuffer);
mixVoice(count, fMixBuffer, outputs);
}
}
}
void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs)
{
compute(count, inputs, outputs);
}
// Terminate all active voices, gently or immediately (depending of 'hard' value)
void allNotesOff(bool hard = false)
{
for (size_t i = 0; i < fVoiceTable.size(); i++) {
fVoiceTable[i]->keyOff(hard);
}
}
// Additional polyphonic API
MapUI* newVoice()
{
int voice = getFreeVoice();
// So that DSP state is always re-initialized
fVoiceTable[voice]->instanceClear();
return fVoiceTable[voice];
}
void deleteVoice(MapUI* voice)
{
std::vector<dsp_voice*>::iterator it = find(fVoiceTable.begin(), fVoiceTable.end(), reinterpret_cast<dsp_voice*>(voice));
if (it != fVoiceTable.end()) {
(*it)->keyOff();
} else {
std::cout << "Voice not found\n";
}
}
// Group API
void setGroup(bool group) { fGroupControl = group; }
bool getGroup() { return fGroupControl; }
// MIDI API
MapUI* keyOn(int channel, int pitch, int velocity)
{
if (checkPolyphony()) {
int voice = getFreeVoice();
fVoiceTable[voice]->keyOn(pitch, velocity, true);
return fVoiceTable[voice];
} else {
return 0;
}
}
void keyOff(int channel, int pitch, int velocity = 127)
{
if (checkPolyphony()) {
int voice = getPlayingVoice(pitch);
if (voice != kNoVoice) {
fVoiceTable[voice]->keyOff();
} else {
std::cout << "Playing pitch = " << pitch << " not found\n";
}
}
}
void ctrlChange(int channel, int ctrl, int value)
{
if (ctrl == ALL_NOTES_OFF || ctrl == ALL_SOUND_OFF) {
allNotesOff();
}
}
};
/**
* Polyphonic DSP with an integrated effect. fPolyDSP will respond to MIDI messages.
*/
class dsp_poly_effect : public dsp_poly {
private:
dsp_poly* fPolyDSP;
public:
dsp_poly_effect(dsp_poly* dsp1, dsp* dsp2)
:dsp_poly(dsp2), fPolyDSP(dsp1)
{}
virtual ~dsp_poly_effect()
{
// dsp_poly_effect is also a decorator_dsp, which will free fPolyDSP
}
// MIDI API
MapUI* keyOn(int channel, int pitch, int velocity)
{
return fPolyDSP->keyOn(channel, pitch, velocity);
}
void keyOff(int channel, int pitch, int velocity)
{
fPolyDSP->keyOff(channel, pitch, velocity);
}
void keyPress(int channel, int pitch, int press)
{
fPolyDSP->keyPress(channel, pitch, press);
}
void chanPress(int channel, int press)
{
fPolyDSP->chanPress(channel, press);
}
void ctrlChange(int channel, int ctrl, int value)
{
fPolyDSP->ctrlChange(channel, ctrl, value);
}
void ctrlChange14bits(int channel, int ctrl, int value)
{
fPolyDSP->ctrlChange14bits(channel, ctrl, value);
}
void pitchWheel(int channel, int wheel)
{
fPolyDSP->pitchWheel(channel, wheel);
}
void progChange(int channel, int pgm)
{
fPolyDSP->progChange(channel, pgm);
}
// Group API
void setGroup(bool group)
{
fPolyDSP->setGroup(group);
}
bool getGroup()
{
return fPolyDSP->getGroup();
}
};
/**
* Polyphonic DSP factory class. Helper code to support polyphonic DSP source with an integrated effect.
*/
struct dsp_poly_factory : public dsp_factory {
dsp_factory* fProcessFactory;
dsp_factory* fEffectFactory;
std::string getEffectCode(const std::string& dsp_content)
{
std::stringstream effect_code;
effect_code << "adapt(1,1) = _; adapt(2,2) = _,_; adapt(1,2) = _ <: _,_; adapt(2,1) = _,_ :> _;";
effect_code << "adaptor(F,G) = adapt(outputs(F),inputs(G)); dsp_code = environment{ " << dsp_content << " };";
effect_code << "process = adaptor(dsp_code.process, dsp_code.effect) : dsp_code.effect;";
return effect_code.str();
}
dsp_poly_factory(dsp_factory* process_factory = NULL,
dsp_factory* effect_factory = NULL):
fProcessFactory(process_factory)
,fEffectFactory(effect_factory)
{}
virtual ~dsp_poly_factory()
{}
virtual std::string getName() { return fProcessFactory->getName(); }
virtual std::string getSHAKey() { return fProcessFactory->getSHAKey(); }
virtual std::string getDSPCode() { return fProcessFactory->getDSPCode(); }
virtual std::string getCompileOptions() { return fProcessFactory->getCompileOptions(); }
virtual std::vector<std::string> getLibraryList() { return fProcessFactory->getLibraryList(); }
virtual std::vector<std::string> getIncludePathnames() { return fProcessFactory->getIncludePathnames(); }
virtual void setMemoryManager(dsp_memory_manager* manager)
{
fProcessFactory->setMemoryManager(manager);
if (fEffectFactory) {
fEffectFactory->setMemoryManager(manager);
}
}
virtual dsp_memory_manager* getMemoryManager() { return fProcessFactory->getMemoryManager(); }
/* Create a new polyphonic DSP instance with global effect, to be deleted with C++ 'delete'
*
* @param nvoices - number of polyphony voices, should be at least 1
* @param control - whether voices will be dynamically allocated and controlled (typically by a MIDI controler).
* If false all voices are always running.
* @param group - if true, voices are not individually accessible, a global "Voices" tab will automatically dispatch
* a given control on all voices, assuming GUI::updateAllGuis() is called.
* If false, all voices can be individually controlled.
*/
dsp_poly* createPolyDSPInstance(int nvoices, bool control, bool group)
{
dsp_poly* dsp_poly = new mydsp_poly(fProcessFactory->createDSPInstance(), nvoices, control, group);
if (fEffectFactory) {
// the 'dsp_poly' object has to be controlled with MIDI, so kept separated from new dsp_sequencer(...) object
return new dsp_poly_effect(dsp_poly, new dsp_sequencer(dsp_poly, fEffectFactory->createDSPInstance()));
} else {
return new dsp_poly_effect(dsp_poly, dsp_poly);
}
}
/* Create a new DSP instance, to be deleted with C++ 'delete' */
dsp* createDSPInstance()
{
return fProcessFactory->createDSPInstance();
}
};
#endif // __poly_dsp__
/************************** END poly-dsp.h **************************/
#endif
#ifdef HAS_MAIN
#include "WM8978.h"
#endif
/******************************************************************************
*******************************************************************************
VECTOR INTRINSICS
*******************************************************************************
*******************************************************************************/
/********************END ARCHITECTURE SECTION (part 1/2)****************/
/**************************BEGIN USER SECTION **************************/
#ifndef FAUSTFLOAT
#define FAUSTFLOAT float
#endif
#include <algorithm>
#include <cmath>
class mydspSIG0 {
private:
int iRec1[2];
public:
int getNumInputsmydspSIG0() {
return 0;
}
int getNumOutputsmydspSIG0() {
return 1;
}
int getInputRatemydspSIG0(int channel) {
int rate;
switch ((channel)) {
default: {
rate = -1;
break;
}
}
return rate;
}
int getOutputRatemydspSIG0(int channel) {
int rate;
switch ((channel)) {
case 0: {
rate = 0;
break;
}
default: {
rate = -1;
break;
}
}
return rate;
}
void instanceInitmydspSIG0(int sample_rate) {
for (int l1 = 0; (l1 < 2); l1 = (l1 + 1)) {
iRec1[l1] = 0;
}
}
void fillmydspSIG0(int count, float* table) {
for (int i = 0; (i < count); i = (i + 1)) {
iRec1[0] = (iRec1[1] + 1);
table[i] = std::sin((0.0245436933f * float((iRec1[0] + -1))));
iRec1[1] = iRec1[0];
}
}
};
static mydspSIG0* newmydspSIG0() { return (mydspSIG0*)new mydspSIG0(); }
static void deletemydspSIG0(mydspSIG0* dsp) { delete dsp; }
static float ftbl0mydspSIG0[256];
#ifndef FAUSTCLASS
#define FAUSTCLASS mydsp
#endif
#ifdef __APPLE__
#define exp10f __exp10f
#define exp10 __exp10
#endif
class mydsp : public dsp {
private:
FAUSTFLOAT fEntry0;
float fRec0[2];
FAUSTFLOAT fEntry1;
float fRec3[2];
float fRec2[2];
int fSampleRate;
public:
void metadata(Meta* m) {
m->declare("basics.lib/name", "Faust Basic Element Library");
m->declare("basics.lib/version", "0.1");
m->declare("filename", "untitled.dsp");
m->declare("maths.lib/author", "GRAME");
m->declare("maths.lib/copyright", "GRAME");
m->declare("maths.lib/license", "LGPL with exception");
m->declare("maths.lib/name", "Faust Math Library");
m->declare("maths.lib/version", "2.3");
m->declare("name", "untitled");
m->declare("oscillators.lib/name", "Faust Oscillator Library");
m->declare("oscillators.lib/version", "0.1");
m->declare("platform.lib/name", "Embedded Platform Library");
m->declare("platform.lib/version", "0.1");
m->declare("signals.lib/name", "Faust Signal Routing Library");
m->declare("signals.lib/version", "0.0");
}
virtual int getNumInputs() {
return 0;
}
virtual int getNumOutputs() {
return 1;
}
virtual int getInputRate(int channel) {
int rate;
switch ((channel)) {
default: {
rate = -1;
break;
}
}
return rate;
}
virtual int getOutputRate(int channel) {
int rate;
switch ((channel)) {
case 0: {
rate = 1;
break;
}
default: {
rate = -1;
break;
}
}
return rate;
}
static void classInit(int sample_rate) {
mydspSIG0* sig0 = newmydspSIG0();
sig0->instanceInitmydspSIG0(sample_rate);
sig0->fillmydspSIG0(256, ftbl0mydspSIG0);
deletemydspSIG0(sig0);
}
virtual void instanceConstants(int sample_rate) {
fSampleRate = sample_rate;
}
virtual void instanceResetUserInterface() {
fEntry0 = FAUSTFLOAT(1.0f);
fEntry1 = FAUSTFLOAT(440.0f);
}
virtual void instanceClear() {
for (int l0 = 0; (l0 < 2); l0 = (l0 + 1)) {
fRec0[l0] = 0.0f;
}
for (int l2 = 0; (l2 < 2); l2 = (l2 + 1)) {
fRec3[l2] = 0.0f;
}
for (int l3 = 0; (l3 < 2); l3 = (l3 + 1)) {
fRec2[l3] = 0.0f;
}
}
virtual void init(int sample_rate) {
classInit(sample_rate);
instanceInit(sample_rate);
}
virtual void instanceInit(int sample_rate) {
instanceConstants(sample_rate);
instanceResetUserInterface();
instanceClear();
}
virtual mydsp* clone() {
return new mydsp();
}
virtual int getSampleRate() {
return fSampleRate;
}
virtual void buildUserInterface(UI* ui_interface) {
ui_interface->openVerticalBox("untitled");
ui_interface->addNumEntry("freq", &fEntry1, 440.0f, 20.0f, 20000.0f, 0.00999999978f);
ui_interface->addNumEntry("gain", &fEntry0, 1.0f, 0.0f, 1.0f, 0.00999999978f);
ui_interface->closeBox();
}
virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) {
FAUSTFLOAT* output0 = outputs[0];
float fSlow0 = (0.00100000005f * float(fEntry0));
float fSlow1 = (0.00100000005f * float(fEntry1));
for (int i = 0; (i < count); i = (i + 1)) {
fRec0[0] = (fSlow0 + (0.999000013f * fRec0[1]));
fRec3[0] = (fSlow1 + (0.999000013f * fRec3[1]));
float fTemp0 = (fRec2[1] + (2.08333331e-05f * fRec3[0]));
fRec2[0] = (fTemp0 - std::floor(fTemp0));
output0[i] = FAUSTFLOAT((fRec0[0] * ftbl0mydspSIG0[int((256.0f * fRec2[0]))]));
fRec0[1] = fRec0[0];
fRec3[1] = fRec3[0];
fRec2[1] = fRec2[0];
}
}
};
/***************************END USER SECTION ***************************/
/*******************BEGIN ARCHITECTURE SECTION (part 2/2)***************/
untitled::untitled(int sample_rate, int buffer_size)
{
fUI = new MapUI();
fAudio = new esp32audio(sample_rate, buffer_size);
#ifdef NVOICES
int nvoices = NVOICES;
mydsp_poly* dsp_poly = new mydsp_poly(new mydsp(), nvoices, true, true);
fDSP = dsp_poly;
#else
fDSP = new mydsp();
#endif
fDSP->buildUserInterface(fUI);
fAudio->init("esp32", fDSP);
}
untitled::~untitled()
{
delete fDSP;
delete fUI;
delete fAudio;
}
bool untitled::start()
{
return fAudio->start();
}
void untitled::stop()
{
fAudio->stop();
}
void untitled::setParamValue(const std::string& path, float value)
{
fUI->setParamValue(path, value);
}
float untitled::getParamValue(const std::string& path)
{
return fUI->getParamValue(path);
}
/********************END ARCHITECTURE SECTION (part 2/2)****************/
#endif
#endif
<file_sep># ttgo-audio-synth
simple synth based on TTGO Audio PCB, Faust DSP, and AppleMIDI
<file_sep>
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#define APPLEMIDI_INITIATOR
#include <AppleMIDI.h>// V2.1.0
USING_NAMESPACE_APPLEMIDI
#include <NeoPixelBus.h>// V2.5.7
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <WM8978.h> //https://github.com/CelliesProjects/wm8978-esp32/ V1.0
#include "untitled.h"
#define I2C_SCL 18
#define I2C_SDA 19
#define I2S_BCK 33
#define I2S_WS 25
#define I2S_DOUT 26
#define I2S_DIN 27
#define I2S_MCLKPIN 0
#define I2S_MFREQ (24 * 1000 * 1000)
untitled* DSP = new untitled(48000, 32);
double gfrequency = 0;
double gvelocity = 0;
char ssid[] = "YOUR_WIFI_SSID";
char pass[] = "<PASSWORD>";
int show_debug = 0;
// NEOPIXEL SETUP
#define PIN 22
#define NUMPIXELS 19
//C1
#define LOWEST_NOTE 24
#include <ETH.h>
#include <ESPmDNS.h>
static bool eth_connected = false;
static double midiToFreq(double note)
{
return 440.0 * std::pow(2.0, (note - 69.0) / 12.0);
}
void WiFiEvent(WiFiEvent_t event)
{
switch (event) {
case SYSTEM_EVENT_ETH_START:
Serial.println("ETH Started");
//set eth hostname here
ETH.setHostname("esp32-ethernet");
break;
case SYSTEM_EVENT_ETH_CONNECTED:
Serial.println("ETH Connected");
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.print("ETH MAC: ");
Serial.print(ETH.macAddress());
Serial.print(", IPv4: ");
Serial.print(ETH.localIP());
if (ETH.fullDuplex()) {
Serial.print(", FULL_DUPLEX");
}
Serial.print(", ");
Serial.print(ETH.linkSpeed());
Serial.println("Mbps");
eth_connected = true;
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
Serial.println("ETH Disconnected");
eth_connected = false;
break;
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH Stopped");
eth_connected = false;
break;
default:
break;
}
}
bool ETH_startup()
{
WiFi.onEvent(WiFiEvent);
ETH.begin();
Serial.println(F("Getting IP address..."));
while (!eth_connected)
delay(100);
return true;
}
NeoPixelBus<NeoGrbFeature, NeoEsp32Rmt0800KbpsMethod> pixels (NUMPIXELS, PIN);
unsigned long t0 = millis();
bool isConnected = false;
APPLEMIDI_CREATE_INSTANCE(WiFiUDP, MIDI, "ESP32", DEFAULT_CONTROL_PORT);
void setAllLeds(int v)
{
for (int i = 0; i < NUMPIXELS; i++)
{
pixels.SetPixelColor(i, RgbColor(v, v, v));
}
pixels.Show();
}
// ====================================================================================
// Event handlers for incoming MIDI messages
// ====================================================================================
void OnAppleMidiConnected(const ssrc_t & ssrc, const char* name) {
isConnected = true;
Serial.print(F("Connected to session "));
Serial.println(name);
}
void OnAppleMidiDisconnected(const ssrc_t & ssrc) {
isConnected = false;
Serial.println(F("Disconnected"));
}
void OnAppleMidiError(const ssrc_t& ssrc, int32_t err) {
Serial.print (F("Exception "));
Serial.print (err);
Serial.print (F(" from ssrc 0x"));
Serial.println(ssrc, HEX);
switch (err)
{
case Exception::NoResponseFromConnectionRequestException:
Serial.println(F("xxx:yyy did't respond to the connection request. Check the address and port, and any firewall or router settings. (time)"));
break;
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void OnAppleMidiNoteOn(byte channel, byte note, byte velocity) {
/*
Serial.print(F("Incoming NoteOn from channel:"));
Serial.print(channel);
Serial.print(F(" note:"));
Serial.print(note);
Serial.print(F(" velocity:"));
Serial.print(velocity);
Serial.println();
*/
int i = note - LOWEST_NOTE;
if (i < 0)
{
i = 0;
}
if (show_debug)
{
Serial.println(i);
}
if (i < NUMPIXELS)
{
pixels.SetPixelColor(i, RgbColor(50, 40, 30));
pixels.Show();
}
gfrequency = midiToFreq(note);
gvelocity = 1;
DSP->setParamValue("freq", gfrequency);
//DSP->setParamValue("gate", gvelocity);
//DSP->setParamValue("/gate", gvelocity);
//DSP->setParamValue("/synth/gate", gvelocity);
DSP->setParamValue("gain", gvelocity);
//Serial.println(gfrequency);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void OnAppleMidiNoteOff(byte channel, byte note, byte velocity) {
/*
Serial.print(F("Incoming NoteOff from channel:"));
Serial.print(channel);
Serial.print(F(" note:"));
Serial.print(note);
Serial.print(F(" velocity:"));
Serial.print(velocity);
Serial.println();
*/
int i = note - LOWEST_NOTE;
if (i < 0)
{
i = 0;
}
if (i < NUMPIXELS)
{
pixels.SetPixelColor(i, RgbColor(0, 0, 0));
pixels.Show();
}
if (gfrequency != midiToFreq(note))
{
//we received a note on message from a different note in the meantime...
return;
}
gvelocity = 0;
//DSP->setParamValue("gate", gvelocity);
//DSP->setParamValue("/gate", gvelocity);
//DSP->setParamValue("/synth/gate", gvelocity);
DSP->setParamValue("gain", gvelocity);
}
void OnAppleMidiByte(const ssrc_t & ssrc, byte data) {
Serial.print(F("raw MIDI: "));
Serial.println(data);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void setup()
{
// Serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
//pinMode(TRANSISTOR_PIN, OUTPUT);
Serial.print(F("Getting IP address..."));
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(F("."));
}
Serial.println(F(""));
Serial.println(F("WiFi connected"));
Serial.println();
Serial.print(F("IP address is "));
Serial.println(WiFi.localIP());
// SETUP NeoPixel
pixels.Begin();
delay(10);
pixels.Show();
Serial.println(F("OK, now make sure you an rtpMIDI session that is Enabled"));
Serial.print(F("Add device named ESP32 with Host/Port "));
Serial.print(WiFi.localIP());
Serial.println(F(":5004"));
WM8978 wm8978;
if (!wm8978.begin(I2C_SDA, I2C_SCL)) {
ESP_LOGE(TAG, "Error setting up dac. System halted");
while (1) delay(100);
}
/* Setup wm8978 MCLK on gpio - for example M5Stack Node needs this clock on gpio 0 */
double retval = wm8978.setPinMCLK(I2S_MCLKPIN, I2S_MFREQ);
if (!retval)
ESP_LOGE(TAG, "Could not set %.2fMHz clock signal on GPIO %i", I2S_MFREQ / (1000.0 * 1000.0), I2S_MCLKPIN);
else
ESP_LOGI(TAG, "Set %.2fMHz clock signal on GPIO %i", retval / (1000.0 * 1000.0), I2S_MCLKPIN);
wm8978.setHPvol(40, 40);
//wm8978.spkVolSet(60); // [0-63]
DSP->setParamValue("gain", 0);
DSP->start();
MDNS.begin(AppleMIDI.getName());
MIDI.begin(1); // listen on channel 1
AppleMIDI.setHandleConnected(OnAppleMidiConnected);
AppleMIDI.setHandleDisconnected(OnAppleMidiDisconnected);
AppleMIDI.setHandleError(OnAppleMidiError);
MDNS.addService("apple-midi", "udp", AppleMIDI.getPort());
MIDI.setHandleNoteOn(OnAppleMidiNoteOn);
MIDI.setHandleNoteOff(OnAppleMidiNoteOff);
//AppleMIDI.setHandleReceivedMidi(OnAppleMidiByte);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void loop()
{
// Listen to incoming notes
MIDI.read();
//AppleMIDI.sendNoteOn(note, velocity, channel);
//AppleMIDI.sendNoteOff(note, velocity, channel);
}
| 67f241bbd5780e9fe788831f1324d744243ea9cf | [
"Markdown",
"C++"
]
| 3 | C++ | renebohne/ttgo-audio-synth | 2486b6463787caab3442709af24cb4200573d8a1 | 04084cea9036534d8f07e3f7398c68886c8d5932 |
refs/heads/master | <repo_name>clementBro/Toc-Eat<file_sep>/Scroll2 - Copie/app/src/main/java/com/example/oli/scroll2/Adaptater.java
package com.example.oli.scroll2;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by Oli on 11/01/2017.
*/
public class Adaptater extends FragmentPagerAdapter {
final int PAGE_COUNT = 4;
private String tabTitles[] = new String[] { "Mes posts", "Chercher", "Profil", "Chat"};
public Adaptater (FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return PAGE_COUNT;
}
@Override
public BlankFragment getItem(int position) {
return BlankFragment.newInstance(position + 1);
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
| e8c46d3b9cb4c5423d425381f6a6c6441d20ce95 | [
"Java"
]
| 1 | Java | clementBro/Toc-Eat | 95cb379cefb92f62df05643a034ff5514a1f26cb | 7d49876c712a0fa28edc30f9b6d635a9cc35fc6c |
refs/heads/master | <repo_name>laefad/Shaverma<file_sep>/scripts/script_reviews.js
"use strict";
document.addEventListener("DOMContentLoaded", function() {
initStarRating();
});
function initStarRating()
{
let starDivs = document.querySelectorAll(".star_rating");
starDivs.forEach( (elem) => {
let labels = elem.querySelectorAll("label");
labels = [...labels];
labels.reduce( (prevLabels, label) => {
let inputId = label.getAttribute("for");
let input = elem.querySelector("#" + inputId);
let anotherInputs = [...elem.querySelectorAll("input")].filter( (e) => e != input );
label.addEventListener("mouseenter", () => {
if ( label.classList.contains("active")
|| label.classList.contains("selected"))
return;
else {
label.classList.add("active");
prevLabels.forEach( prevLabel => {
prevLabel.classList.add("active");
});
}
});
label.addEventListener("mouseleave", () => {
if (label.classList.contains("active")) {
label.classList.remove("active");
prevLabels.forEach( prevLabel => {
prevLabel.classList.remove("active");
});
}
});
label.addEventListener("click", () => {
if (label.classList.contains("selected"))
input.checked = false;
anotherInputs.forEach( i => {
i.checked = false;
});
labels.forEach( el => {
el.classList.remove("selected");
});
label.classList.add("selected");
prevLabels.forEach( prevLabel => {
prevLabel.classList.add("selected");
});
});
return prevLabels.concat(label);
}, []);
});
}<file_sep>/scripts/script_about.js
"use strict";
document.addEventListener("DOMContentLoaded", function() {
initSlider();
});
function initSlider() {
let slider = document.querySelector("#images_about");
let slides = ["imgs/about/img_1.jpg", "imgs/about/img_2.jpg", "imgs/about/img_3.jpg", "imgs/about/img_4.jpg"];
let inputs = slider.querySelector("#selectors")
.querySelectorAll("input");
inputs = [...inputs];
let i = 0;
const setBackground = img => {
slider.style.background = `url(${img})`;
slider.style.backgroundSize = "cover";
}
const changeChecked = j => {
inputs[i].checked = false;
i = j % slides.length;
inputs[i].checked = true;
}
const styleF = () => {
changeChecked(i + 1);
setBackground(slides[i]);
}
changeChecked(0);
let timer = setInterval( styleF, 3000);
inputs.forEach( (input, j) => {
input.addEventListener("click", () => {
clearInterval(timer);
changeChecked(j);
setBackground(slides[i]);
timer = setInterval( styleF, 3000);
});
});
} | ace7c973d3b5241b4926a869b75795fe933e1246 | [
"JavaScript"
]
| 2 | JavaScript | laefad/Shaverma | adc79642097b8d00ca2bff1b6a6b39b0f6871886 | 1c9406ef7959b2ced818f2add1127e6aca3f9e95 |
refs/heads/master | <file_sep>package eu.appbucket.sandbox.myq.processor;
import eu.appbucket.sandbox.myq.record.Record;
import org.apache.commons.math3.geometry.euclidean.twod.Line;
import org.apache.commons.math3.geometry.euclidean.twod.Vector2D;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation;
import org.apache.commons.math3.stat.descriptive.moment.Variance;
import org.apache.commons.math3.stat.regression.SimpleRegression;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.Assert;
import java.util.*;
public class UnderstandApacheMathLibraryTest {
private SimpleRegression regression;
@Before
public void setup() {
regression = new SimpleRegression(true);
}
@Test
@Ignore
public void testRegression() {
regression.addData(0,0);
regression.addData(1, 1);
System.out.println(regression.getSlopeStdErr()); // ???
System.out.println(regression.getRSquare()); // R square
System.out.println(regression.getMeanSquareError()); // ???
System.out.println(regression.getRegressionSumSquares()); // ???
System.out.println(regression.getSumSquaredErrors()); // ???
System.out.println(regression.getTotalSumSquares()); // ???
}
@Test
public void testRegressionWithRealData() {
regression.addData(1410768337, 25);
regression.addData(1410768461, 26);
regression.addData(1410769032, 36);
regression.addData(1410769626, 44);
regression.addData(1410769697, 45);
regression.addData(1410769708, 45);
regression.addData(1410769711, 45);
regression.addData(1410769824, 46);
regression.addData(1410769858, 46);
regression.addData(1410770225, 52);
regression.addData(1410770531, 50);
regression.addData(1410770883, 58);
regression.addData(1410771027, 60);
regression.addData(1410771364, 61);
regression.addData(1410772306, 272);
regression.addData(1410773742, 88);
regression.addData(1410774516, 92);
regression.addData(1410774760, 92);
regression.addData(1410775099, 93);
regression.addData(1410775856, 96);
regression.addData(1410775984, 97);
regression.addData(1410776757, 102);
regression.addData(1410777156, 105);
regression.addData(1410777180, 106);
regression.addData(1410777430, 112);
regression.addData(1410777634, 100);
regression.addData(1410777837, 115);
regression.addData(1410777881, 168);
regression.addData(1410777912, 116);
regression.addData(1410778418, 121);
regression.addData(1410778520, 122);
regression.addData(1410779608, 131);
System.out.println("y = ax + b"); // ???
System.out.println("a: " + regression.getSlope());
System.out.println("b: " + regression.getIntercept());
}
// http://www.mathsisfun.com/data/standard-deviation.html
@Test
public void testVariances() {
Variance variance = new Variance(false);
double varianceValue = variance.evaluate(new double[]{206, 76, -224, 36, -94});
System.out.println(varianceValue);
Assert.assertEquals(21704d, varianceValue, 0d);
}
// http://www.mathsisfun.com/data/standard-deviation.html
@Test
public void testStandardDeviationOfDogs() {
StandardDeviation standardDeviation = new StandardDeviation(false);
double standardDeviationValue = standardDeviation.evaluate(new double[]{206, 76, -224, 36, -94});
System.out.println(standardDeviationValue);
Assert.assertEquals(147d, standardDeviationValue, 0.5d);
}
@Test
public void testStandardDeviationOfSimpleNumber() {
StandardDeviation standardDeviation = new StandardDeviation(false);
System.out.println(standardDeviation.evaluate(new double[]{1,1,2}));
}
// http://www.mathsisfun.com/data/standard-deviation.html
@Test
public void testMeanDogs() {
DescriptiveStatistics stats = new DescriptiveStatistics();
stats.addValue(600d);
stats.addValue(470d);
stats.addValue(170d);
stats.addValue(430d);
stats.addValue(300d);
System.out.println(stats.getMean());
Assert.assertEquals(394d, stats.getMean(), 0d);
}
// http://www.mathsisfun.com/data/standard-deviation.html
@Test
public void testThresholdOfDogs() {
DescriptiveStatistics stats = new DescriptiveStatistics();
stats.addValue(600d);
stats.addValue(470d);
stats.addValue(170d);
stats.addValue(430d);
stats.addValue(300d);
double mean = stats.getMean();
StandardDeviation standardDeviation = new StandardDeviation(false);
double standardDeviationValue = standardDeviation.evaluate(new double[]{206, 76, -224, 36, -94});
Assert.assertFalse(valueFitsTheThreshold(600d, mean, standardDeviationValue));
Assert.assertTrue(valueFitsTheThreshold(470d, mean, standardDeviationValue));
Assert.assertFalse(valueFitsTheThreshold(170d, mean, standardDeviationValue));
Assert.assertTrue(valueFitsTheThreshold(430d, mean, standardDeviationValue));
Assert.assertTrue(valueFitsTheThreshold(300d, mean, standardDeviationValue));
}
private static boolean valueFitsTheThreshold(double valueToTest, double mean, double standardDeviation) {
double minThreshold = mean - standardDeviation;
double maxThreshold = mean + standardDeviation;
if(valueToTest > minThreshold && valueToTest < maxThreshold) {
return true;
}
return false;
}
@Test
public void testDistanceBetweenRegressionLineAndPointOnTheLine() {
Vector2D pointNotOnTheLine = new Vector2D(0,0);
Set<Vector2D> observations = new HashSet<Vector2D>();
observations.add(new Vector2D(0, 0));
observations.add(new Vector2D(1, 1));
double distance = calculateDistanceBetweenPointAndObservations(pointNotOnTheLine, observations);
System.out.println("Distance: " + distance);
Assert.assertEquals(0, distance, 0.01d);
}
@Test
public void testDistanceBetweenRegressionLineAndPointWhereLineInterceptIsAvailable() {
Vector2D pointNotOnTheLine = new Vector2D(0,1);
Set<Vector2D> observations = new HashSet<Vector2D>();
observations.add(new Vector2D(0, 0));
observations.add(new Vector2D(1, 1));
double distance = calculateDistanceBetweenPointAndObservations(pointNotOnTheLine, observations);
System.out.println("Distance: " + distance);
Assert.assertEquals(Math.sqrt(2) / 2, distance, 0.01d);
}
@Test
public void testDistanceBetweenRegressionLineAndPointWhereLineInterceptIsNotAvailable() {
Vector2D pointNotOnTheLine = new Vector2D(0,1);
Set<Vector2D> observations = new HashSet<Vector2D>();
observations.add(new Vector2D(1, 0));
observations.add(new Vector2D(1, 1));
double distance = calculateDistanceBetweenPointAndObservations(pointNotOnTheLine, observations);
System.out.println("Distance: " + distance);
Assert.assertEquals(1d, distance, 0.01d);
}
private double calculateDistanceBetweenPointAndObservations(Vector2D point, Set<Vector2D> observations) {
double distance = 0;
if(areAllObservationsOnVerticalLine(observations)) {
Vector2D observation = observations.iterator().next();
distance = Math.abs(observation.getX() - point.getX());
} else {
SimpleRegression regression = new SimpleRegression(true);
for(Vector2D observation: observations) {
regression.addData(observation.getX(), observation.getY());
}
Line line = buildLineFromRegression(regression);
distance = line.distance(point);
}
return distance;
}
private boolean areAllObservationsOnVerticalLine(Set<Vector2D> observations) {
double firstObservationX = observations.iterator().next().getX();
for(Vector2D point: observations) {
if(point.getX() != firstObservationX) {
return false;
}
}
return true;
}
private Line buildLineFromRegression(SimpleRegression regression) {
Vector2D linePoint1 = new Vector2D(0, findYForXOnLine(0, regression.getSlope(), regression.getIntercept()));
Vector2D linePoint2 = new Vector2D(1, findYForXOnLine(1, regression.getSlope(), regression.getIntercept()));
Line line = new Line(linePoint1, linePoint2, 0);
return line;
}
private double findYForXOnLine(double x, double slope, double intercept) {
double y = intercept + slope * x;
return y;
}
@Test
public void testMarkingOfPointsAsInvalidBecauseAreAboveCalculatedThreshold() {
// valid observations points
Vector2D validRegressionPoint1 = new Vector2D(0,0);
Vector2D validRegressionPoint2 = new Vector2D(1,1);
Vector2D validRegressionPoint3 = new Vector2D(2,2);
// point to measure the variation
Vector2D validTestPoint1 = new Vector2D(0,1);
Vector2D validTestPoint2 = new Vector2D(2,1);
Vector2D validTestPoint3 = new Vector2D(2,3);
Vector2D validTestPoint4 = new Vector2D(4,3);
// point which should be out of threshold
Vector2D invalidTestPoint1 = new Vector2D(0,3);
Vector2D invalidTestPoint2 = new Vector2D(4,1);
// calculate their distance from regression line
Set<Vector2D> observations = new HashSet<Vector2D>();
observations.add(validRegressionPoint1);
observations.add(validRegressionPoint2);
observations.add(validRegressionPoint3);
double validTestPoint1Distance = calculateDistanceBetweenPointAndObservations(validTestPoint1, observations);
double validTestPoint2Distance = calculateDistanceBetweenPointAndObservations(validTestPoint2, observations);
double validTestPoint3Distance = calculateDistanceBetweenPointAndObservations(validTestPoint3, observations);
Assert.assertEquals(Math.sqrt(2) / 2, validTestPoint1Distance, 0.01d);
Assert.assertEquals(Math.sqrt(2) / 2, validTestPoint2Distance, 0.01d);
Assert.assertEquals(Math.sqrt(2) / 2, validTestPoint3Distance, 0.01d);
double invalidTestPoint1Distance = calculateDistanceBetweenPointAndObservations(invalidTestPoint1, observations);
double invalidTestPoint2Distance = calculateDistanceBetweenPointAndObservations(invalidTestPoint2, observations);
Assert.assertEquals(3 * Math.sqrt(2) / 2, invalidTestPoint1Distance, 0.01d);
Assert.assertEquals(3 * Math.sqrt(2) / 2, invalidTestPoint2Distance, 0.01d);
// calculate variation
StandardDeviation standardDeviation = new StandardDeviation(false);
double margin = standardDeviation.evaluate(new double[]{validTestPoint1Distance, validTestPoint2Distance, validTestPoint3Distance, invalidTestPoint1Distance, invalidTestPoint2Distance});
DescriptiveStatistics stats = new DescriptiveStatistics();
stats.addValue(validTestPoint1Distance);
stats.addValue(validTestPoint2Distance);
stats.addValue(validTestPoint3Distance);
stats.addValue(invalidTestPoint1Distance);
stats.addValue(invalidTestPoint2Distance);
double mean = stats.getMean();
double maxMargin = mean + margin;
double minMargin = mean - margin;
System.out.println("min = " + minMargin);
System.out.println("max = " + maxMargin);
// decide which points are out of the standard variation threshold
System.out.println(validTestPoint1Distance);
Assert.assertTrue(validTestPoint1Distance > minMargin && validTestPoint1Distance < maxMargin);
System.out.println(validTestPoint2Distance);
Assert.assertTrue(validTestPoint2Distance > minMargin && validTestPoint2Distance < maxMargin);
System.out.println(validTestPoint3Distance);
Assert.assertTrue(validTestPoint3Distance > minMargin && validTestPoint3Distance < maxMargin);
Assert.assertTrue(invalidTestPoint1Distance < minMargin || invalidTestPoint1Distance > maxMargin);
Assert.assertTrue(invalidTestPoint2Distance < minMargin || invalidTestPoint2Distance > maxMargin);
}
private class Point {
private double x;
private double y;
public void setX(double x) { this.x = x; }
public void setY(double y) { this.y = y; }
public double getX() { return x; }
public double getY() { return y; }
public String toString() {
return "Point{" +
"x=" + x +
", y=" + y +
'}';
}
}
private class Store {
private Set<Point> data = new LinkedHashSet<Point>();
private void addData(double x, double y) {
Point point = new Point();
point.setX(x);
point.setY(y);
data.add(point);
}
public Set<Point> getData() {
return data;
}
}
@Test
public void testRealData() {
Store store = new Store();
store.addData(1410768337, 25);
store.addData(1410768461, 26);
store.addData(1410769032, 36);
store.addData(1410769626, 44);
store.addData(1410769697, 45);
store.addData(1410769708, 45);
store.addData(1410769711, 45);
store.addData(1410769824, 46);
store.addData(1410769858, 46);
store.addData(1410770225, 52);
store.addData(1410770531, 50);
store.addData(1410770883, 58);
store.addData(1410771027, 60);
store.addData(1410771364, 61);
store.addData(1410772306, 272);
store.addData(1410773742, 88);
store.addData(1410774516, 92);
store.addData(1410774760, 92);
store.addData(1410775099, 93);
store.addData(1410775856, 96);
store.addData(1410775984, 97);
store.addData(1410776757, 102);
store.addData(1410777156, 105);
store.addData(1410777180, 106);
store.addData(1410777430, 112);
store.addData(1410777634, 100);
store.addData(1410777837, 115);
store.addData(1410777881, 168);
store.addData(1410777912, 116);
store.addData(1410778418, 121);
store.addData(1410778520, 122);
store.addData(1410779608, 131);
SimpleRegression regression = new SimpleRegression(true);
for(Point point: store.getData()) {
regression.addData(point.getX(), point.getY());
}
DescriptiveStatistics stats = new DescriptiveStatistics();
double [] distances = new double[store.getData().size()];
int i = 0;
for(Point point: store.getData()) {
double distanceFromTheMean = findDistanceBetweenRegressionLineAndPoint(regression, point);
stats.addValue(distanceFromTheMean);
distances[i++] = distanceFromTheMean;
System.out.println(point + ", point.distance = " + distanceFromTheMean);
}
double mean = stats.getMean();
System.out.println("distance.mean = " + mean);
StandardDeviation standardDeviation = new StandardDeviation(false);
double deviation = standardDeviation.evaluate(distances);
System.out.println("distance.deviation = " + deviation);
double margin = mean + deviation;
System.out.println("distance.margin = " + margin);
for(Point point: store.getData()) {
double distance = findDistanceBetweenRegressionLineAndPoint(regression, point);
if(distance < margin) {
System.out.println(point + " is Valid, point.distance = " + distance + ", distance.margin = " + margin);
} else {
System.out.println(point + " is Invalid, point.distance = " + distance + ", distance.margin = " + margin);
Assert.assertTrue(point.getY() == 272 || point.getY() == 168);
}
}
}
private double findDistanceBetweenRegressionLineAndPoint(SimpleRegression regression, Point point) {
double predictedY = regression.predict(point.getX());
double distance = Math.abs(Math.abs(point.getY()) - Math.abs(predictedY));
return distance;
}
private class Sample {
private List<Record> records = new ArrayList<Record>();
int i = 1;
private void addRecord(long timeStamp, int servicedNumber) {
Record record = new Record();
record.setTimeStamp(timeStamp * 1000);
record.setServedTicket(servicedNumber);
record.setId(i++);
records.add(record);
}
public List<Record> getRecords() {
return records;
}
}
@Test
public void testCalculateRegressionForFilteredOutData() {
Sample sample = new Sample();
sample.addRecord(1410768337, 25);
sample.addRecord(1410768461, 26);
sample.addRecord(1410769032, 36);
sample.addRecord(1410769626, 44);
sample.addRecord(1410769697, 45);
sample.addRecord(1410769708, 45);
sample.addRecord(1410769711, 45);
sample.addRecord(1410769824, 46);
sample.addRecord(1410769858, 46);
sample.addRecord(1410770225, 52);
sample.addRecord(1410770531, 50);
sample.addRecord(1410770883, 58);
sample.addRecord(1410771027, 60);
sample.addRecord(1410771364, 61);
sample.addRecord(1410772334, 50);
sample.addRecord(1410773742, 88);
sample.addRecord(1410774516, 92);
sample.addRecord(1410774760, 92);
sample.addRecord(1410775099, 93);
sample.addRecord(1410775856, 96);
sample.addRecord(1410775984, 97);
sample.addRecord(1410776757, 102);
sample.addRecord(1410777156, 105);
sample.addRecord(1410777180, 106);
sample.addRecord(1410777430, 112);
sample.addRecord(1410777634, 100);
sample.addRecord(1410777837, 115);
sample.addRecord(1410777881, 168);
sample.addRecord(1410777912, 116);
sample.addRecord(1410778418, 121);
sample.addRecord(1410778520, 122);
sample.addRecord(1410779608, 131);
sample.addRecord(1410780069, 134);
sample.addRecord(1410780523, 144);
sample.addRecord(1410780554, 145);
sample.addRecord(1410780752, 146);
sample.addRecord(1410780824, 149);
sample.addRecord(1410783252, 159);
sample.addRecord(1410783625, 172);
sample.addRecord(1410783695, 172);
sample.addRecord(1410784422, 178);
sample.addRecord(1410784432, 162);
sample.addRecord(1410785910, 195);
sample.addRecord(1410786081, 196);
sample.addRecord(1410786710, 204);
sample.addRecord(1410786806, 205);
sample.addRecord(1410786864, 206);
sample.addRecord(1410786920, 252);
sample.addRecord(1410788000, 211);
sample.addRecord(1410788736, 218);
sample.addRecord(1410789960, 229);
sample.addRecord(1410790145, 231);
sample.addRecord(1410790630, 233);
sample.addRecord(1410793777, 254);
sample.addRecord(1410794530, 261);
sample.addRecord(1410794576, 263);
sample.addRecord(1410798064, 299);
sample.addRecord(1410798307, 294);
sample.addRecord(1410799129, 299);
sample.addRecord(1410804578, 370);
sample.addRecord(1410804599, 361);
sample.addRecord(1410804617, 362);
sample.addRecord(1410809081, 400);
sample.addRecord(1410809138, 400);
SimpleRegression regression = new SimpleRegression(true);
for(Record point: sample.getRecords()) {
regression.addData(point.getTimeStamp(), point.getServedTicket());
}
System.out.print("filtered slope = " + regression.getSlope() + ", intercept = " + regression.getIntercept());
}
@Test
public void testCalculateRegressionForData() {
Sample sample = new Sample();
sample.addRecord(1410849840, 9);
sample.addRecord(1410857340, 32);
sample.addRecord(1410860700, 47);
sample.addRecord(1410861000, 47);
sample.addRecord(1410864480, 69);
sample.addRecord(1410865920, 79);
sample.addRecord(1410865980, 100);
sample.addRecord(1410866940, 84);
sample.addRecord(1410867780, 90);
sample.addRecord(1410869640, 113);
sample.addRecord(1410876540, 172);
sample.addRecord(1410876600, 174);
sample.addRecord(1410878940, 210);
sample.addRecord(1410879000, 212);
sample.addRecord(1410879120, 214);
sample.addRecord(1410879720, 217);
sample.addRecord(1410880260, 223);
sample.addRecord(1410887040, 200);
sample.addRecord(1410887040, 200);
sample.addRecord(1410891960, 320);
sample.addRecord(1410893640, 302);
sample.addRecord(1410893640, 310);
sample.addRecord(1410893700, 360);
sample.addRecord(1410895440, 340);
sample.addRecord(1410895500, 338);
sample.addRecord(1410895500, 320);
sample.addRecord(1410895560, 338);
SimpleRegression regression = new SimpleRegression(true);
for(Record point: sample.getRecords()) {
regression.addData(point.getTimeStamp(), point.getServedTicket());
}
System.out.print("actual slope = " + regression.getSlope() + ", intercept = " + regression.getIntercept());
}
}
<file_sep>package eu.appbucket.sandbox.myq.processor;
import eu.appbucket.sandbox.myq.record.Flag;
import eu.appbucket.sandbox.myq.record.Record;
import org.apache.commons.math3.stat.descriptive.rank.Median;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class OutOfRangeRecordProcessorImpl implements RecordProcessor {
private Set<Record> recordsCache;
private Record currentRecord;
private RecordProcessor nextRecordProcessor;
private long timeBase;
private List<Record> recordsToBeMarked;
double timeToServedTicketMedian;
public OutOfRangeRecordProcessorImpl(long timeBase) {
recordsCache = new HashSet<Record>();
this.timeBase=timeBase;
}
@Override
public void setSuccessor(RecordProcessor successor) {
nextRecordProcessor = successor;
}
@Override
public void processRecords(List<Record> recordsToBeMarked) {
this.recordsToBeMarked = recordsToBeMarked;
calculateTimeToServedTicketMedian();
List<Record> markedRecords = this.markRecords(recordsToBeMarked);
if(nextRecordProcessor != null) {
nextRecordProcessor.processRecords(markedRecords);
}
}
private void calculateTimeToServedTicketMedian() {
Median median = new Median();
double [] deltas = new double[recordsToBeMarked.size()];
int i = 0;
double timeDurationFromTimeBaseToRecordTimestamp;
for(Record record: recordsToBeMarked) {
timeDurationFromTimeBaseToRecordTimestamp = record.getTimeStamp() - timeBase;
deltas[i++] = timeDurationFromTimeBaseToRecordTimestamp / record.getServedTicket();
}
timeToServedTicketMedian = median.evaluate(deltas);
}
private List<Record> markRecords(List<Record> records) {
for(Record record: records) {
if(!record.isValid())
continue;
currentRecord = record;
markCurrentRecord();
}
return records;
}
private void markCurrentRecord() {
if(isRecordValueOutOfRange()) {
currentRecord.setFlag(Flag.DELTA_VALUE_NOT_IN_RANGE);
} else {
currentRecord.setFlag(Flag.VALID);
}
}
private boolean isRecordValueOutOfRange() {
double maxCutOffDelta = timeToServedTicketMedian * 1.5;
double minCutOffDelta = timeToServedTicketMedian / 1.5;
double deltaDurationToServedTicket = Math.abs(currentRecord.getTimeStamp() - timeBase) / currentRecord.getServedTicket();
if(deltaDurationToServedTicket > maxCutOffDelta ||
deltaDurationToServedTicket < minCutOffDelta) {
return true;
}
return false;
}
}
<file_sep>package eu.appbucket.sandbox.myq.record;
public enum Flag {
VALID,
UNEXPECTED_VALUE,
DUPLICATE_ENTRY,
SERVED_TICKET_HIGHER_THEN_USER_TICKET,
DELTA_VALUE_NOT_IN_RANGE
}
<file_sep>package eu.appbucket.sandbox.myq.processor;
import eu.appbucket.sandbox.myq.record.Flag;
import eu.appbucket.sandbox.myq.record.Record;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation;
import org.apache.commons.math3.stat.regression.SimpleRegression;
import java.util.ArrayList;
import java.util.List;
public class OutOfTrendRecordProcessorImpl implements RecordProcessor {
private List<Point> points = new ArrayList<Point>();
private SimpleRegression regression = new SimpleRegression(true);
private double distanceMean;
private double distanceDeviation;
private int MARGIN_100_PERCENT = 1;
private int MARGIN_50_PERCENT = 2;
private int MARGIN_25_PERCENT = 4;
private RecordProcessor nextRecordProcessor;
private class Point {
private Record record;
public Point(Record record) {
this.record = record;
x = record.getTimeStamp() / 1000;
y = record.getServedTicket();
}
private double x;
private double y;
private double distanceToRegressionLine;
public void setDistanceToRegressionLine(double distanceToRegressionLine) { this.distanceToRegressionLine = distanceToRegressionLine; }
public double getDistanceToRegressionLine() { return distanceToRegressionLine; }
public double getX() { return x; }
public double getY() { return y; }
public Record getRecord() { return record; }
public String toString() {
return "Point{" +
"x=" + x +
", y=" + y +
", flag=" + record.getFlag() +
'}';
}
}
public void setSuccessor(RecordProcessor successor) {
this.nextRecordProcessor = successor;
}
@Override
public void processRecords(List<Record> recordsToBeMarked) {
List<Record> markedRecords = this.markRecords(recordsToBeMarked);
if(nextRecordProcessor != null) {
nextRecordProcessor.processRecords(markedRecords);
}
}
protected List<Record> markRecords(List<Record> records) {
convertRecordsToPoints(records);
calculateStandardRegression();
calculatePointsDistancesToRegressionLine();
calculateDistanceMean();
calculatedDeviationOfDistances();
setRecordsFlags();
return records;
}
private void convertRecordsToPoints(List<Record> records) {
for(Record record: records) {
if(!record.isValid())
continue;
points.add(new Point(record));
}
}
private void calculateStandardRegression() {
for(Point point: points) {
regression.addData(point.getX(), point.getY());
}
}
private void calculatePointsDistancesToRegressionLine() {
double distanceToRegressionLine;
for(Point point: points) {
distanceToRegressionLine = findDistanceBetweenRegressionLineAndPoint(point);
point.setDistanceToRegressionLine(distanceToRegressionLine);
}
}
private void calculateDistanceMean() {
DescriptiveStatistics stats = new DescriptiveStatistics();
int i = 0;
for(Point point: points) {
stats.addValue(point.getDistanceToRegressionLine());
}
distanceMean = stats.getMean();
}
private double findDistanceBetweenRegressionLineAndPoint(Point point) {
double predictedY = regression.predict(point.getX());
double distance = Math.abs(Math.abs(point.getY()) - Math.abs(predictedY));
return distance;
}
private void calculatedDeviationOfDistances() {
StandardDeviation standardDeviation = new StandardDeviation(false);
int i = 0;
double[] distances = new double[points.size()];
for(Point point: points) {
distances[i++] = point.getDistanceToRegressionLine();
}
distanceDeviation = standardDeviation.evaluate(distances);
}
private void setRecordsFlags() {
int marginDivider = MARGIN_50_PERCENT;
double acceptableDistanceMargin = (distanceMean + distanceDeviation) / marginDivider;
for(Point point: points) {
if(point.getDistanceToRegressionLine() > acceptableDistanceMargin) {
point.getRecord().setFlag(Flag.UNEXPECTED_VALUE);
}
}
}
}
<file_sep>package eu.appbucket.sandbox.myq.processor;
import eu.appbucket.sandbox.myq.record.Flag;
import eu.appbucket.sandbox.myq.record.Record;
import org.junit.Before;
import org.junit.Test;
import org.junit.Assert;
import java.util.ArrayList;
import java.util.List;
public class DuplicateRecordProcessorImplTest {
private DuplicatedRecordProcessorImpl marker;
@Before
public void setup() {
marker = new DuplicatedRecordProcessorImpl();
}
@Test
public void singleRecordIsValid() {
List<Record> inputSample = buildSingleRecordSample();
List<Record> markedSample = marker.markRecords(inputSample);
Assert.assertEquals(Flag.VALID, markedSample.get(0).getFlag());
}
private List<Record> buildSingleRecordSample() {
List<Record> sample = new ArrayList<Record>();
Record record = new Record();
sample.add(record);
return sample;
}
@Test
public void uniqueRecordsAreValid() {
List<Record> inputSample = buildUniqueRecordsSample();
List<Record> markedSample = marker.markRecords(inputSample);
Assert.assertEquals("Record 1", Flag.VALID, markedSample.get(0).getFlag());
Assert.assertEquals("Record 2", Flag.VALID, markedSample.get(1).getFlag());
}
private List<Record> buildUniqueRecordsSample() {
List<Record> sample = new ArrayList<Record>();
Record uniqueRecord1 = new Record();
uniqueRecord1.setServedTicket(10);
uniqueRecord1.setUserTicket(1);
Record uniqueRecord2 = new Record();
uniqueRecord2.setServedTicket(20);
uniqueRecord2.setUserTicket(2);
sample.add(uniqueRecord1);
sample.add(uniqueRecord2);
return sample;
}
@Test
public void duplicatedRecordsAreInvalid() {
List<Record> inputSample = buildDuplicatedRecordsSample();
List<Record> markedSample = marker.markRecords(inputSample);
Assert.assertEquals("Original Record 1 expected to be valid", Flag.VALID, markedSample.get(0).getFlag());
Assert.assertEquals("Duplicated Record 2 expected to be invalid", Flag.DUPLICATE_ENTRY, markedSample.get(1).getFlag());
}
private List<Record> buildDuplicatedRecordsSample() {
List<Record> sample = new ArrayList<Record>();
Record duplicateRecord = new Record();
duplicateRecord.setServedTicket(10);
duplicateRecord.setUserTicket(1);
sample.add(duplicateRecord);
duplicateRecord = new Record();
duplicateRecord.setServedTicket(10);
duplicateRecord.setUserTicket(1);
sample.add(duplicateRecord);
return sample;
}
}
<file_sep>package eu.appbucket.sandbox.myq.processor;
import eu.appbucket.sandbox.myq.record.Flag;
import eu.appbucket.sandbox.myq.record.Record;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class OutOfTrendRecordProcessorImplTest {
private OutOfTrendRecordProcessorImpl marker;
@Before
public void setup() {
marker = new OutOfTrendRecordProcessorImpl();
}
private class Sample {
private List<Record> records = new ArrayList<Record>();
int i = 1;
private void addRecord(long timeStamp, int servicedNumber) {
Record record = new Record();
record.setTimeStamp(timeStamp);
record.setServedTicket(servicedNumber);
record.setId(i++);
records.add(record);
}
public List<Record> getRecords() {
return records;
}
}
@Test
public void testSampleOfData() {
Sample sample = new Sample();
sample.addRecord(1410768337, 25);
sample.addRecord(1410768461, 26);
sample.addRecord(1410769032, 36);
sample.addRecord(1410769626, 44);
sample.addRecord(1410769697, 45);
sample.addRecord(1410769708, 45);
sample.addRecord(1410769711, 45);
sample.addRecord(1410769824, 46);
sample.addRecord(1410769858, 46);
sample.addRecord(1410770225, 52);
sample.addRecord(1410770531, 50);
sample.addRecord(1410770883, 58);
sample.addRecord(1410771027, 60);
sample.addRecord(1410771364, 61);
sample.addRecord(1410772306, 272);
sample.addRecord(1410772334, 88);
sample.addRecord(1410773742, 92);
sample.addRecord(1410774516, 92);
sample.addRecord(1410774760, 93);
sample.addRecord(1410775099, 96);
sample.addRecord(1410775856, 97);
sample.addRecord(1410775984, 102);
sample.addRecord(1410776757, 105);
sample.addRecord(1410777156, 106);
sample.addRecord(1410777180, 112);
sample.addRecord(1410777430, 100);
sample.addRecord(1410777634, 115);
sample.addRecord(1410777837, 168);
sample.addRecord(1410777881, 116);
sample.addRecord(1410777912, 121);
sample.addRecord(1410778418, 122);
sample.addRecord(1410778520, 122);
sample.addRecord(1410779608, 131);
sample.addRecord(1410780069, 134);
sample.addRecord(1410780523, 144);
sample.addRecord(1410780554, 145);
sample.addRecord(1410780752, 146);
sample.addRecord(1410780806, 236);
sample.addRecord(1410780824, 149);
sample.addRecord(1410783252, 159);
sample.addRecord(1410783625, 172);
sample.addRecord(1410783695, 172);
sample.addRecord(1410784422, 178);
sample.addRecord(1410784432, 162);
sample.addRecord(1410785910, 195);
sample.addRecord(1410786081, 196);
sample.addRecord(1410786710, 204);
sample.addRecord(1410786806, 205);
sample.addRecord(1410786864, 206);
sample.addRecord(1410786920, 252);
sample.addRecord(1410788000, 211);
sample.addRecord(1410788736, 218);
sample.addRecord(1410789960, 229);
sample.addRecord(1410790145, 231);
sample.addRecord(1410790630, 233);
sample.addRecord(1410793777, 254);
sample.addRecord(1410794530, 261);
sample.addRecord(1410794576, 263);
sample.addRecord(1410798064, 299);
sample.addRecord(1410798307, 294);
sample.addRecord(1410799129, 299);
sample.addRecord(1410804578, 370);
sample.addRecord(1410804599, 361);
sample.addRecord(1410804617, 362);
sample.addRecord(1410809081, 400);
sample.addRecord(1410809138, 400);
sample.addRecord(1410815541, 21);
List<Record> records = sample.getRecords();
marker.markRecords(records);
for(Record record: records) {
System.out.println(record);
if(record.getTimeStamp() == 1410772306
|| record.getTimeStamp() == 1410777837
|| record.getTimeStamp() == 1410780806
|| record.getTimeStamp() == 1410786920
|| record.getTimeStamp() == 1410804578
|| record.getTimeStamp() == 1410815541) {
Assert.assertEquals(record.toString() + ": " + record.getTimeStamp(),Flag.UNEXPECTED_VALUE, record.getFlag());
}
}
}
}
<file_sep>package eu.appbucket.sandbox.myq.estimator;
import eu.appbucket.sandbox.myq.record.Record;
import java.util.List;
/**
* Created by adambednarski on 08/06/2015.
*/
public class VotingBasedEstimator {
public Integer estimateCurrentServedNumber(List<Record> records) {
Record lastRecord = records.get(records.size() - 1);
return lastRecord.getServedTicket();
}
}
<file_sep>package eu.appbucket.sandbox.myq.processor;
import eu.appbucket.sandbox.myq.record.Flag;
import eu.appbucket.sandbox.myq.record.Record;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class OutOfRangeRecordProcessorImplTest {
private OutOfRangeRecordProcessorImpl processor;
@Before
public void setup() {
processor = new OutOfRangeRecordProcessorImpl(0);
}
@Test
public void test() {
List<Record> recordsToBeMarked = new ArrayList<Record>();
Record record1 = new Record();
record1.setDate(new Date(100));
record1.setServedTicket(1);
recordsToBeMarked.add(record1);
Record record2 = new Record();
record2.setDate(new Date(200));
record2.setServedTicket(2);
recordsToBeMarked.add(record2);
Record record3 = new Record();
record3.setDate(new Date(300));
record3.setServedTicket(3);
recordsToBeMarked.add(record3);
Record record4 = new Record();
record4.setDate(new Date(800));
record4.setServedTicket(4);
recordsToBeMarked.add(record4);
processor.processRecords(recordsToBeMarked);
Assert.assertEquals("Record 1", Flag.VALID, recordsToBeMarked.get(0).getFlag());
Assert.assertEquals("Record 2", Flag.VALID, recordsToBeMarked.get(1).getFlag());
Assert.assertEquals("Record 3", Flag.VALID, recordsToBeMarked.get(2).getFlag());
Assert.assertEquals("Record 4", Flag.DELTA_VALUE_NOT_IN_RANGE, recordsToBeMarked.get(3).getFlag());
}
}
| 35e612fd42124af6025d365ac7c69f01ba37c7ec | [
"Java"
]
| 8 | Java | abednarski79/sandbox | bc929555c0c54647c48afffbe231675a2cfdd319 | 2824e509af1737b53270b8ae92f8463b9c9e945d |
refs/heads/master | <repo_name>pablolibo/oslo.messaging<file_sep>/oslo_messaging/server.py
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright 2013 Red Hat, Inc.
# Copyright 2013 New Dream Network, LLC (DreamHost)
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
__all__ = [
'ExecutorLoadFailure',
'MessageHandlingServer',
'MessagingServerError',
'ServerListenError',
]
import functools
import inspect
import logging
import threading
import traceback
from oslo_service import service
from oslo_utils import timeutils
from stevedore import driver
from oslo_messaging._drivers import base as driver_base
from oslo_messaging import exceptions
LOG = logging.getLogger(__name__)
class MessagingServerError(exceptions.MessagingException):
"""Base class for all MessageHandlingServer exceptions."""
class ExecutorLoadFailure(MessagingServerError):
"""Raised if an executor can't be loaded."""
def __init__(self, executor, ex):
msg = 'Failed to load executor "%s": %s' % (executor, ex)
super(ExecutorLoadFailure, self).__init__(msg)
self.executor = executor
self.ex = ex
class ServerListenError(MessagingServerError):
"""Raised if we failed to listen on a target."""
def __init__(self, target, ex):
msg = 'Failed to listen on target "%s": %s' % (target, ex)
super(ServerListenError, self).__init__(msg)
self.target = target
self.ex = ex
class _OrderedTask(object):
"""A task which must be executed in a particular order.
A caller may wait for this task to complete by calling
`wait_for_completion`.
A caller may run this task with `run_once`, which will ensure that however
many times the task is called it only runs once. Simultaneous callers will
block until the running task completes, which means that any caller can be
sure that the task has completed after run_once returns.
"""
INIT = 0 # The task has not yet started
RUNNING = 1 # The task is running somewhere
COMPLETE = 2 # The task has run somewhere
# We generate a log message if we wait for a lock longer than
# LOG_AFTER_WAIT_SECS seconds
LOG_AFTER_WAIT_SECS = 30
def __init__(self, name):
"""Create a new _OrderedTask.
:param name: The name of this task. Used in log messages.
"""
super(_OrderedTask, self).__init__()
self._name = name
self._cond = threading.Condition()
self._state = self.INIT
def _wait(self, condition, warn_msg):
"""Wait while condition() is true. Write a log message if condition()
has not become false within LOG_AFTER_WAIT_SECS.
"""
with timeutils.StopWatch(duration=self.LOG_AFTER_WAIT_SECS) as w:
logged = False
while condition():
wait = None if logged else w.leftover()
self._cond.wait(wait)
if not logged and w.expired():
LOG.warn(warn_msg)
LOG.debug(''.join(traceback.format_stack()))
# Only log once. After than we wait indefinitely without
# logging.
logged = True
def wait_for_completion(self, caller):
"""Wait until this task has completed.
:param caller: The name of the task which is waiting.
"""
with self._cond:
self._wait(lambda: self._state != self.COMPLETE,
'%s has been waiting for %s to complete for longer '
'than %i seconds'
% (caller, self._name, self.LOG_AFTER_WAIT_SECS))
def run_once(self, fn):
"""Run a task exactly once. If it is currently running in another
thread, wait for it to complete. If it has already run, return
immediately without running it again.
:param fn: The task to run. It must be a callable taking no arguments.
It may optionally return another callable, which also takes
no arguments, which will be executed after completion has
been signaled to other threads.
"""
with self._cond:
if self._state == self.INIT:
self._state = self.RUNNING
# Note that nothing waits on RUNNING, so no need to notify
# We need to release the condition lock before calling out to
# prevent deadlocks. Reacquire it immediately afterwards.
self._cond.release()
try:
post_fn = fn()
finally:
self._cond.acquire()
self._state = self.COMPLETE
self._cond.notify_all()
if post_fn is not None:
# Release the condition lock before calling out to prevent
# deadlocks. Reacquire it immediately afterwards.
self._cond.release()
try:
post_fn()
finally:
self._cond.acquire()
elif self._state == self.RUNNING:
self._wait(lambda: self._state == self.RUNNING,
'%s has been waiting on another thread to complete '
'for longer than %i seconds'
% (self._name, self.LOG_AFTER_WAIT_SECS))
class _OrderedTaskRunner(object):
"""Mixin for a class which executes ordered tasks."""
def __init__(self, *args, **kwargs):
super(_OrderedTaskRunner, self).__init__(*args, **kwargs)
# Get a list of methods on this object which have the _ordered
# attribute
self._tasks = [name
for (name, member) in inspect.getmembers(self)
if inspect.ismethod(member) and
getattr(member, '_ordered', False)]
self.init_task_states()
def init_task_states(self):
# Note that we don't need to lock this. Once created, the _states dict
# is immutable. Get and set are (individually) atomic operations in
# Python, and we only set after the dict is fully created.
self._states = {task: _OrderedTask(task) for task in self._tasks}
@staticmethod
def decorate_ordered(fn, state, after):
@functools.wraps(fn)
def wrapper(self, *args, **kwargs):
# Store the states we started with in case the state wraps on us
# while we're sleeping. We must wait and run_once in the same
# epoch. If the epoch ended while we were sleeping, run_once will
# safely do nothing.
states = self._states
# Wait for the given preceding state to complete
if after is not None:
states[after].wait_for_completion(state)
# Run this state
states[state].run_once(lambda: fn(self, *args, **kwargs))
return wrapper
def ordered(after=None):
"""A method which will be executed as an ordered task. The method will be
called exactly once, however many times it is called. If it is called
multiple times simultaneously it will only be called once, but all callers
will wait until execution is complete.
If `after` is given, this method will not run until `after` has completed.
:param after: Optionally, another method decorated with `ordered`. Wait for
the completion of `after` before executing this method.
"""
if after is not None:
after = after.__name__
def _ordered(fn):
# Set an attribute on the method so we can find it later
setattr(fn, '_ordered', True)
state = fn.__name__
return _OrderedTaskRunner.decorate_ordered(fn, state, after)
return _ordered
class MessageHandlingServer(service.ServiceBase, _OrderedTaskRunner):
"""Server for handling messages.
Connect a transport to a dispatcher that knows how to process the
message using an executor that knows how the app wants to create
new tasks.
"""
def __init__(self, transport, dispatcher, executor='blocking'):
"""Construct a message handling server.
The dispatcher parameter is a callable which is invoked with context
and message dictionaries each time a message is received.
The executor parameter controls how incoming messages will be received
and dispatched. By default, the most simple executor is used - the
blocking executor.
:param transport: the messaging transport
:type transport: Transport
:param dispatcher: a callable which is invoked for each method
:type dispatcher: callable
:param executor: name of message executor - for example
'eventlet', 'blocking'
:type executor: str
"""
self.conf = transport.conf
self.transport = transport
self.dispatcher = dispatcher
self.executor = executor
try:
mgr = driver.DriverManager('oslo.messaging.executors',
self.executor)
except RuntimeError as ex:
raise ExecutorLoadFailure(self.executor, ex)
self._executor_cls = mgr.driver
self._executor_obj = None
super(MessageHandlingServer, self).__init__()
@ordered()
def start(self):
"""Start handling incoming messages.
This method causes the server to begin polling the transport for
incoming messages and passing them to the dispatcher. Message
processing will continue until the stop() method is called.
The executor controls how the server integrates with the applications
I/O handling strategy - it may choose to poll for messages in a new
process, thread or co-operatively scheduled coroutine or simply by
registering a callback with an event loop. Similarly, the executor may
choose to dispatch messages in a new thread, coroutine or simply the
current thread.
"""
try:
listener = self.dispatcher._listen(self.transport)
except driver_base.TransportDriverError as ex:
raise ServerListenError(self.target, ex)
executor = self._executor_cls(self.conf, listener, self.dispatcher)
executor.start()
self._executor_obj = executor
if self.executor == 'blocking':
# N.B. This will be executed unlocked and unordered, so
# we can't rely on the value of self._executor_obj when this runs.
# We explicitly pass the local variable.
return lambda: executor.execute()
@ordered(after=start)
def stop(self):
"""Stop handling incoming messages.
Once this method returns, no new incoming messages will be handled by
the server. However, the server may still be in the process of handling
some messages, and underlying driver resources associated to this
server are still in use. See 'wait' for more details.
"""
self._executor_obj.stop()
@ordered(after=stop)
def wait(self):
"""Wait for message processing to complete.
After calling stop(), there may still be some existing messages
which have not been completely processed. The wait() method blocks
until all message processing has completed.
Once it's finished, the underlying driver resources associated to this
server are released (like closing useless network connections).
"""
try:
self._executor_obj.wait()
finally:
# Close listener connection after processing all messages
self._executor_obj.listener.cleanup()
self._executor_obj = None
self.init_task_states()
def reset(self):
"""Reset service.
Called in case service running in daemon mode receives SIGHUP.
"""
# TODO(sergey.vilgelm): implement this method
pass
| ee30ef5a2eeff73f17efa0c016e31dc332dc56c1 | [
"Python"
]
| 1 | Python | pablolibo/oslo.messaging | d3bb45fe34c6fcdef0b896d5f4ed172d5dee4985 | aa1e072c14bb75c6958ff9ae1bc4536f351232c6 |
refs/heads/master | <repo_name>Yisaer/SHU-GameZone<file_sep>/GameZone/src/test/com/GameZone/Dao/CreditDaoTest.java
package com.GameZone.Dao;
import com.GameZone.Entity.Credit;
import org.apache.ibatis.annotations.Param;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
/**
* Created by Yisa on 2017/6/24.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml"})
public class CreditDaoTest {
// Credit GetCreditByUid(@Param("userId") int userId);
// void UpdateCredit(Credit credit);
// List<Credit> getCreditList();
// void InsertCredit(Credit credit);
@Resource
private CreditDao creditDao;
@Test
public void getCreditByUid() throws Exception {
Credit credit = creditDao.GetCreditByUid(2);
System.out.println(credit);
}
@Test
public void updateCredit() throws Exception {
Credit credit = new Credit(2,60);
creditDao.UpdateCredit(credit);
System.out.println("Success");
}
@Test
public void getCreditList() throws Exception {
List<Credit> Creditlist = creditDao.getCreditList();
for(Credit c :Creditlist){
System.out.println(c);
}
}
@Test
public void insertCredit() throws Exception {
Credit credit = new Credit(2,50);
creditDao.InsertCredit(credit);
System.out.println("Success");
}
}<file_sep>/README.md
## SHU-GameZone
init<file_sep>/GameZone/src/main/java/com/GameZone/Entity/User.java
package com.GameZone.Entity;
/**
* Created by Yisa on 2017/6/22.
*/
public class User {
private int userId;
private String username;
private String password;
private String sex;
private String email;
private String url;
public User(Integer userId, String username, String password, String sex, String email, String url) {
this.userId = userId;
this.username = username;
this.password = <PASSWORD>;
this.sex = sex;
this.email = email;
this.url = url;
}
public User(String username, String password, String sex, String email, String url) {
this.username = username;
this.password = <PASSWORD>;
this.sex = sex;
this.email = email;
this.url = url;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getUseriId() {
return userId;
}
public void setUseriId(int useriId) {
this.userId = useriId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User(String username, String password, String sex, String email) {
this.username = username;
this.password = <PASSWORD>;
this.sex = sex;
this.email = email;
}
@Override
public String toString() {
return "username="+username+" email="+email;
}
public User(Integer userId, String username, String password, String sex, String email) {
this.userId = userId;
this.username = username;
this.password = <PASSWORD>;
this.sex = sex;
this.email = email;
}
}
<file_sep>/GameZone/target/GameZone/WEB-INF/classes/jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://172.16.31.10:3306/GameZone?useUnicode=true&characterEncoding=utf-8
username=root
password=<PASSWORD>
<file_sep>/GameZone/src/main/java/com/GameZone/Dao/UserDao.java
package com.GameZone.Dao;
import com.GameZone.Entity.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Created by Yisa on 2017/6/22.
*/
public interface UserDao {
void AddUser( User user);
void DeleteUser(@Param("userId") int userId);
List<User> queryAll();
void UpdateUser(User user);
User getUserById(@Param("userId") int userId);
}
<file_sep>/GameZone/src/test/com/GameZone/Service/UserServiceTest.java
package com.GameZone.Service;
import com.GameZone.Entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
/**
* Created by Yisa on 2017/6/24.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml","classpath:spring/spring-service.xml"})
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void registerUser() throws Exception {
User user = new User("Tom","Tompass","male","Tomemail");
boolean Success = userService.RegisterUser(user);
if(Success){
System.out.println("Success");
}
else{
System.out.println("Fail");
}
}
@Test
public void getUserList() throws Exception {
List<User> userList = userService.getUserList();
for(User u :userList){
System.out.println(u.toString());
}
}
@Test
public void updateUser() throws Exception {
int uid = 3;
User user = userService.getUserByUid(uid);
user.setEmail("<EMAIL>");
boolean Success = userService.UpdateUser(user);
if(Success){
System.out.println("Success");
}
else{
System.out.println("Fail");
}
}
@Test
public void deleteUserByUid() throws Exception {
int uid = 2;
boolean Succes = userService.DeleteUserByUid(uid);
if(Succes){
System.out.println("Succes");
}
else{
System.out.println("Fail");
}
}
@Test
public void getUserByUid() throws Exception{
int uid = 3;
User user = userService.getUserByUid(uid);
System.out.println(user.toString());
}
} | 7614ddb138da2694e3f4f3bd2d9d385c0ad2fca8 | [
"Markdown",
"Java",
"INI"
]
| 6 | Java | Yisaer/SHU-GameZone | 258adf29a034529e5d647078502345c30a4b3bc4 | ae95039315e5bde95c721736032ed2ba7db436ad |
refs/heads/master | <file_sep>SPOTIFY_ID=the-oauth-client-id
SPOTIFY_SECRET=the-oauth-client-secret
# You can generate the SECRET_TOKEN any way you please, but we suggest:
# openssl rand -base64 32
SECRET_TOKEN=generate-random-string-of-at-least-32-bytes
<file_sep>package main
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/url"
"github.com/labstack/echo"
"github.com/labstack/echo-contrib/session"
"github.com/zmb3/spotify"
"golang.org/x/oauth2"
)
const (
// SessionKey is used to retrieve the session from store
SessionKey = "mixtape-session"
)
// Login a user by redirecting them to Spotify to initiate the authorization
// code flow. It depends on the following environment variables having been
// set:
//
// SPOTIFY_ID - the oauth2 client ID
// SPOTIFY_SECRET - the oauth2 client secret
func Login(ctx echo.Context) error {
sess, err := session.Get(SessionKey, ctx)
if err != nil {
return err
}
if _, hasToken := sess.Values["access_token"]; hasToken {
return redirectWithTokens(ctx)
}
auth := newAuthenticator(ctx)
state, err := newState()
if err != nil {
return err
}
sess.Values["auth_state"] = state
err = sess.Save(ctx.Request(), ctx.Response())
if err != nil {
return err
}
authURL := auth.AuthURL(state)
return ctx.Redirect(http.StatusFound, authURL)
}
// Callback after authentication/authorization is complete and the Spotify
// server redirects back to the redirect URI with an authorization code
func Callback(ctx echo.Context) error {
sess, err := session.Get(SessionKey, ctx)
if err != nil {
return err
}
var state string
if val := sess.Values["auth_state"]; val != nil {
state = val.(string)
delete(sess.Values, "auth_state")
}
auth := newAuthenticator(ctx)
token, err := auth.Token(state, ctx.Request())
if err != nil {
return err
}
sess.Values["access_token"] = token
err = sess.Save(ctx.Request(), ctx.Response())
if err != nil {
return err
}
return redirectWithTokens(ctx)
}
// Logout an authenticated user, destroying the existing session
func Logout(ctx echo.Context) error {
sess, err := session.Get(SessionKey, ctx)
if err != nil {
return err
}
// This forces gorilla to delete the session safely, no matter what kind of
// session store is being used
sess.Options.MaxAge = -1
err = sess.Save(ctx.Request(), ctx.Response())
if err != nil {
return nil
}
return ctx.Redirect(http.StatusFound, "/")
}
func newState() (string, error) {
var state string
randBytes := make([]byte, 32)
_, err := rand.Read(randBytes)
if err != nil {
return state, err
}
state = base64.StdEncoding.EncodeToString(randBytes)
return state, nil
}
func newAuthenticator(ctx echo.Context) spotify.Authenticator {
redirectURI := &url.URL{
Scheme: ctx.Scheme(),
Host: ctx.Request().Host,
Path: "auth/callback",
}
return spotify.NewAuthenticator(
redirectURI.String(),
spotify.ScopeUserReadPrivate,
)
}
func redirectWithTokens(ctx echo.Context) error {
sess, err := session.Get(SessionKey, ctx)
if err != nil {
return err
}
t, ok := sess.Values["access_token"]
if !ok {
return errors.New("session access_token is not set")
}
token := t.(*oauth2.Token)
// No doubt there's all kinds of encoding and stuff we're missing here
fragment := fmt.Sprintf(
"/#access_token=%s&refresh_token=%s",
token.AccessToken,
token.RefreshToken)
return ctx.Redirect(http.StatusFound, fragment)
}
<file_sep>FROM golang:1.10.3
EXPOSE 8088
ENV DEP_VERSION=v0.5.0
RUN apt-get update && \
apt-get install -y curl && \
curl -LO https://github.com/golang/dep/releases/download/$DEP_VERSION/dep-linux-amd64 && \
chmod a+x dep-linux-amd64 && \
mv dep-linux-amd64 /usr/local/bin/dep && \
rm -rf /var/lib/apt/lists/*
# We don't absolutely NEED the ginkgo binary to run the test suite, but it's
# nice to have
RUN go get -u github.com/onsi/ginkgo/ginkgo
RUN go get -u github.com/onsi/gomega/...
WORKDIR /go/src/github.com/therevels/mixtape
# Generate a self-signed cert for development
RUN go run $(go env GOROOT)/src/crypto/tls/generate_cert.go --host localhost
COPY Gopkg.toml Gopkg.toml
COPY Gopkg.lock Gopkg.lock
RUN dep ensure -vendor-only
COPY . .
# This is for development purposes only. Eventually we'll want CI/CD to build
# a leaner release image
RUN go build -o dist/mixtape ./...
CMD "dist/mixtape"
<file_sep>version: '3'
services:
web:
build: .
ports:
- "8088:8088"
environment:
- SPOTIFY_ID
- SPOTIFY_SECRET
- COOKIE_SECRET
<file_sep>mixtape [ ](https://app.codeship.com/projects/303334)
=======
Configuration
-------------
1. You must register your application (including redirect URI) with Spotify in your [developer dashboard](https://developer.spotify.com/dashboard/applications).
2. Configure the following environment variables:
- `SPOTIFY_ID` - the client ID
- `SPOTIFY_SECRET` - the client secret
Local development
------------------
1. Clone the repo:
```console
git clone [email protected]:mixtape.git $GOPATH/src/github.com/therevels/mixtape
```
2. Copy the example `.env` file and edit the environment variables (see [configuration instructions](#configuration)\):
```console
cp .env.example .env
vim .env
```
3. Build the image locally:
```console
docker-compose build
```
4. Start the app containers locally:
```console
docker-compose up
```
5. Visit https://localhost:8088 in a browser
<file_sep>package main
import (
"encoding/gob"
"os"
"github.com/gorilla/sessions"
"github.com/labstack/echo"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/middleware"
"golang.org/x/oauth2"
)
func main() {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// TODO: research config for encryption in gorilla sessions
secret := os.Getenv("SECRET_TOKEN")
e.Use(session.Middleware(sessions.NewCookieStore([]byte(secret))))
// Permit serializing the oauth2.Token type to the session
gob.Register(&oauth2.Token{})
// Routing
e.File("/", "static/index.html")
e.GET("/auth/login", Login)
e.GET("/auth/callback", Callback)
e.GET("/auth/logout", Logout)
e.Logger.Fatal(e.StartTLS(":8088", "cert.pem", "key.pem"))
}
<file_sep>package main_test
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"time"
"github.com/gorilla/sessions"
"github.com/labstack/echo"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/quasoft/memstore"
"golang.org/x/oauth2"
. "github.com/therevels/mixtape"
)
var _ = Describe("Auth", func() {
var origClientID, clientID string
var req *http.Request
var rec *httptest.ResponseRecorder
var e *echo.Echo
var ctx echo.Context
var store sessions.Store
var sess *sessions.Session
BeforeEach(func() {
origClientID = os.Getenv("SPOTIFY_ID")
clientID = "my-test-client-id"
os.Setenv("SPOTIFY_ID", clientID)
e = echo.New()
rec = httptest.NewRecorder()
store = memstore.NewMemStore(
[]byte("authkey123"),
[]byte("enckey12341234567890123456789012"),
)
})
AfterEach(func() {
os.Setenv("SPOTIFY_ID", origClientID)
})
Describe("Login", func() {
BeforeEach(func() {
req = httptest.NewRequest(echo.GET, "https://example.com:443/auth/login", nil)
ctx = e.NewContext(req, rec)
ctx.Set("_session_store", store)
})
Context("when not logged in", func() {
It("redirects with a 302", func() {
Expect(Login(ctx)).To(Succeed())
Expect(rec.Code).To(Equal(http.StatusFound))
})
It("redirects to Spotify authorization endpoint", func() {
Login(ctx)
loc, err := rec.Result().Location()
Expect(err).ToNot(HaveOccurred())
Expect(loc.Scheme).To(Equal("https"))
Expect(loc.Host).To(Equal("accounts.spotify.com"))
Expect(loc.Path).To(Equal("/authorize"))
})
It("includes client ID in redirect", func() {
Login(ctx)
loc, _ := rec.Result().Location()
Expect(loc.Query().Get("client_id")).To(Equal(clientID))
})
It("includes redirect URI", func() {
Login(ctx)
loc, _ := rec.Result().Location()
Expect(loc.Query().Get("redirect_uri")).To(Equal("https://example.com:443/auth/callback"))
})
It("includes the auth scopes", func() {
Login(ctx)
loc, _ := rec.Result().Location()
Expect(loc.Query().Get("scope")).To(Equal("user-read-private"))
})
It("includes unique session state", func() {
Expect(Login(ctx)).To(Succeed())
loc, _ := rec.Result().Location()
state := loc.Query().Get("state")
sess, err := store.Get(req, SessionKey)
Expect(err).ToNot(HaveOccurred())
sessState := sess.Values["auth_state"].(string)
Expect(state).To(Equal(sessState))
})
})
Context("when logged in", func() {
var accessToken, refreshToken string
BeforeEach(func() {
sess, _ = store.Get(req, SessionKey)
accessToken = "existing-access-token"
refreshToken = "existing-refresh-token"
sess.Values["access_token"] = &oauth2.Token{
AccessToken: accessToken,
TokenType: "Bearer",
RefreshToken: refreshToken,
Expiry: time.Now().Add(time.Hour),
}
})
AfterEach(func() {
delete(sess.Values, "access_token")
})
It("redirects to root", func() {
Expect(Login(ctx)).To(Succeed())
Expect(rec.Code).To(Equal(http.StatusFound))
loc, _ := rec.Result().Location()
Expect(loc.Path).To(Equal("/"))
fragment := fmt.Sprintf("access_token=%s&refresh_token=%s", accessToken, refreshToken)
Expect(loc.Fragment).To(Equal(fragment))
})
})
})
Describe("Callback", func() {
var code, state string
Context("with authorization code", func() {
BeforeEach(func() {
code = "my-authorization-code"
state = "my-redirect-state"
callbackURL := fmt.Sprintf("https://example.com/auth/callback?code=%s&state=%s", code, state)
req = httptest.NewRequest(echo.GET, callbackURL, nil)
ctx = e.NewContext(req, rec)
ctx.Set("_session_store", store)
sess, _ = store.Get(req, SessionKey)
})
Context("when there is no session state", func() {
It("returns an error", func() {
err := Callback(ctx)
Expect(err).To(HaveOccurred())
Expect(err).To(MatchError("spotify: redirect state parameter doesn't match"))
})
})
Context("when session state is invalid", func() {
BeforeEach(func() {
sess.Values["auth_state"] = "some-completely-different-value"
})
AfterEach(func() {
delete(sess.Values, "state")
})
It("returns an error", func() {
err := Callback(ctx)
Expect(err).To(HaveOccurred())
Expect(err).To(MatchError("spotify: redirect state parameter doesn't match"))
})
})
PContext("when session state is valid", func() {
BeforeEach(func() {
sess.Values["auth_state"] = state
})
// TODO: ideally this would have full test coverage, but between
// the spotify and oauth2 libraries, the abstractions do not make it
// easily testable (no way to inject server URLs, etc)
It("exchanges the authorization code for an access token", func() {})
It("stores the tokens in the session", func() {})
})
})
Context("without authorization code", func() {
BeforeEach(func() {
callbackURL := "https://example.com/auth/callback"
req = httptest.NewRequest(echo.GET, callbackURL, nil)
ctx = e.NewContext(req, rec)
ctx.Set("_session_store", store)
})
It("returns an error", func() {
err := Callback(ctx)
Expect(err).To(HaveOccurred())
Expect(err).To(MatchError("spotify: didn't get access code"))
})
})
})
Describe("Logout", func() {
BeforeEach(func() {
req = httptest.NewRequest(echo.GET, "https://example.com/auth/logout", nil)
ctx = e.NewContext(req, rec)
ctx.Set("_session_store", store)
})
Context("when logged in", func() {
var accessToken, refreshToken string
BeforeEach(func() {
sess, _ = store.Get(req, SessionKey)
accessToken = "existing-access-token"
refreshToken = "existing-refresh-token"
sess.Values["access_token"] = &oauth2.Token{
AccessToken: accessToken,
TokenType: "Bearer",
RefreshToken: refreshToken,
Expiry: time.Now().Add(time.Hour),
}
})
AfterEach(func() {
delete(sess.Values, "access_token")
})
It("has no errors", func() {
Expect(Logout(ctx)).To(Succeed())
})
It("redirects to the landing page", func() {
Logout(ctx)
Expect(rec.Code).To(Equal(http.StatusFound))
loc, _ := rec.Result().Location()
Expect(loc.String()).To(Equal("/"))
})
It("invalidates the existing session", func() {
Logout(ctx)
Expect(sess.Values["access_token"]).To(BeNil())
})
})
Context("when not logged in", func() {
It("redirects to the landing page", func() {
Expect(Logout(ctx)).To(Succeed())
Expect(rec.Code).To(Equal(http.StatusFound))
loc, _ := rec.Result().Location()
Expect(loc.String()).To(Equal("/"))
})
})
})
})
| 3d8c8ca4f215e91f812dcc1d0fcce600b7c2b036 | [
"YAML",
"Markdown",
"Go",
"Dockerfile",
"Shell"
]
| 7 | Shell | therevels/mixtape | ec27bfc41288225d59104a6b380207daa226fef7 | aa3782a17cfa14eee8e52180353ac5e38a133ff3 |
refs/heads/main | <file_sep>const assert = require('chai').assert;
const {soma, subtracao, divisao, multiplicacao} = require('../src/operacoes')
describe('Testes com operações', () => {
it('Soma', () => {
assert.equal(soma(1, 1), 2, '1 + 1 deve ser 2');
assert.notEqual(soma(1, 1), 3, '1 + 1 não deve ser 3');
})
it('Subtracao', () => {
assert.equal(subtracao(1, 1), 0, '1 - 1 deve ser 0');
})
it('Multiplicacao', () => {
assert.equal(multiplicacao(2, 2), 4, '2 * 2 deve ser 4');
})
describe('Testes com Divisão', () => {
it('Divisao', () => {
assert.equal(divisao(2, 2), 1, '2 / 2 deve ser 1');
})
it('Divisao por zero', () => {
assert.equal(divisao(2, 0), 'invalido', 'Não pode dividir por zero');
})
})
})
<file_sep>function lista (){
const resultado = []
for (let i = 1; i <= 50; i++){
if (i % 3 === 0) {
resultado.push('Fizz')
} else if (i % 5 === 0){
resultado.push('Buzz')
} else {
resultado.push(i)
}
}
return resultado
}
function div3 (){
}
module.exports = lista
<file_sep>const assert = require('chai').assert;
const lista = require('../src/fizzbuzz')
describe ('listagem', () => {
it ('testa se lista numeros', () => {
assert.equal(lista().length, 50, 'deve retornar um array de 50 numeros' )
})
})
describe ('divisao por 3', () =>{
it ('testa se é fizz', () =>{
const resultado = lista();
assert.equal(resultado[2], 'Fizz', 'Divisivel por 3 vira fizz')
assert.equal(resultado[0], 1, 'não Divisivel por 3 não muda')
})
})
describe ('divisao por 5', () =>{
it ('testa o buzz', () => {
const resultado = lista();
assert.equal(resultado[4], 'Buzz', 'Divisivel por 5 vira buzz')
assert.equal(resultado[3], 4, 'outros numeros não mudam')
})
})
describe ('funcao divisivel por 3 esta restrita', () =>{
it ('testa funcao divisao por 3', () => {
try {
div3()
} catch (error) {
assert.equal(error.message, 'div3 is not defined', 'função está restrita')
}
})
})
| 9f2fe51aaef88a85d174437104c20e1d518d7cee | [
"JavaScript"
]
| 3 | JavaScript | hugocgc/Exercicios-TDD | 5215ff2a5ebdc3669bf379706756bb1f31f12c61 | 0485fa7b3a27ab261e29660a2084f80457180aae |
refs/heads/master | <repo_name>zvadaadam/parking-prediction<file_sep>/parkingprediction/dataset/base_dataset.py
import pandas as pd
from sklearn.model_selection import train_test_split
class DatasetBase(object):
"""
Base class for datasets operation.
"""
def __init__(self, config):
self.config = config
self.df = pd.DataFrame()
self.train_df = pd.DataFrame()
self.test_df = pd.DataFrame()
def load_dataset(self):
raise NotImplemented
def split_dataset(self, test_size=None):
if test_size is None:
test_size = self.config.test_size()
train, test = train_test_split(self.df, test_size=test_size, random_state=42, shuffle=False)
self.train_df = train
self.test_df = test
def train_dataset(self):
return self.train_df
def test_dataset(self):
return self.test_df
<file_sep>/parkingprediction/trainer/main_trainer.py
import os, sys
import tensorflow as tf
from parkingprediction.dataset.parking_dataset import ParkingDataset
from parkingprediction.model.cnn_model import RNNModel
from parkingprediction.trainer.parking_trainer import ParkingTrainer
def main_train(config):
dataset = SignalDataset(config)
session = tf.Session()
# TODO: init the right model from config
model = CNNModel(config)
trainer = Trainer(session, model, dataset, config)
trainer.train()
if __name__ == '__main__':
from parkingprediction.config.config_reader import ConfigReader
sys.path.append(os.path.abspath('../../'))
config_path = '/Users/adamzvada/Documents/hackathon/iotea/ParkingPrediction/config/test.yml'
main_train(ConfigReader(config_path))
<file_sep>/parkingprediction/trainer/base_trainer.py
import os
import tensorflow as tf
from tqdm import trange
from parkingprediction.trainer.tensor_iterator import TensorIterator
#from parkingprediction.utils.tensor_logger import TensorLogger
class BaseTrain(object):
"""
Base class for Tensorflow Training
"""
def __init__(self, session, model, dataset, config):
"""
Initializer fot BaseTraing object
:param tf.Session session: tensorflow session
:param BaseModel model: tensorflow model
:param BaseDataset dataset: dataset object
:param ConfigReader config: config reader object
"""
self.session = session
self.model = model
self.dataset = dataset
self.config = config
self.iterator = TensorIterator(dataset, model, session, config)
#self.logger = TensorLogger(log_path=self.config.tensorboard_path(), session=self.session)
def train(self):
"""
Main training method.
It creates tf.Dataset iterator from the Dataset and builds the tensorflow model.
It runs the training epoches while logging the progress to Tensorboard.
It has the capabilities to restore and save trained models.
"""
model_train_inputs, train_handle = self.iterator.create_dataset_iterator(mode='train')
_, test_handle = self.iterator.create_dataset_iterator(mode='test')
self.train_handle = train_handle
self.test_handle = test_handle
self.model.build_model(model_train_inputs)
self.init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
self.session.run(self.init)
self.model.init_saver(max_to_keep=2)
# restore latest checkpoint model
self.model.load(self.session, self.config.restore_trained_model())
# tqdm progress bar looping through all epoches
t_epoches = trange(self.model.cur_epoch_tensor.eval(self.session), self.config.num_epoches() + 1, 1,
desc=f'Training {self.config.model_name()}')
for cur_epoch in t_epoches:
# run epoch training
train_output = self.train_epoch(cur_epoch)
# run model on test set
test_output = self.test_step()
self.log_progress(train_output, num_iteration=cur_epoch * self.config.num_iterations(), mode='train')
self.log_progress(test_output, num_iteration=cur_epoch * self.config.num_iterations(), mode='test')
self.update_progress_bar(t_epoches, train_output, test_output)
# increase epoche counter
self.session.run(self.model.increment_cur_epoch_tensor)
self.model.save(self.session, write_meta_graph=False)
# finale save model - creates checkpoint
self.model.save(self.session, write_meta_graph=True)
def train_epoch(self, cur_epoche):
"""
Method to be overridden for training epoche.
:param int cur_epoche: index of current epoch
"""
raise NotImplementedError
def train_step(self):
"""
Method to be overridden for training step.
"""
raise NotImplementedError
def test_step(self):
"""
Method to be overridden for training step.
"""
raise NotImplementedError
def log_progress(self, input, num_iteration, mode):
"""
Method to be overridden for logging the training progress to Tensorboard
"""
raise NotImplementedError
def update_progress_bar(self, t_bar, train_output, test_output):
"""
Method to be overridden for updating tqdm progress bar
"""
raise NotImplementedError
<file_sep>/parkingprediction/dataset/parking_dataset.py
import numpy as np
import pandas as pd
import holidays
import requests
from tqdm import tqdm
from datetime import datetime
from parkingprediction.dataset.base_dataset import DatasetBase
class ParkingDataset(DatasetBase):
def __init__(self, config):
super(ParkingDataset, self).__init__(config)
self.load_dataset()
def load_dataset(self):
self.df = self.create_dataset()
self.split_dataset()
def create_dataset(self, csv_path=None):
if csv_path == None:
csv_path = self.config.csv_path()
print(csv_path)
df = pd.read_csv(csv_path)
df = df.drop(columns='value1')
df = df.set_index('created')
df = df.drop(columns='id')
df.index = pd.to_datetime(df.index)
df = df.groupby(pd.Grouper(freq='h')).mean()
df = self.update_external_features(df)
return df
def update_external_features(self, df):
weather_features = self.get_weather()
days_features = self.get_days_of_week()
temp_feature = [weather[0] for weather in weather_features]
df['temperature'] = temp_feature
pressure_feature = [weather[1] for weather in weather_features]
df['pressure'] = pressure_feature
mo = []
tue = []
wen = []
thr = []
fr = []
sat = []
sun = []
holiday = []
for days in days_features:
mo.append(days[0])
tue.append(days[1])
wen.append(days[2])
thr.append(days[3])
fr.append(days[4])
sat.append(days[5])
sun.append(days[6])
holiday.append(days[7])
df['monday'] = mo
df['tuesday'] = tue
df['wednesday'] = wen
df['thursday'] = thr
df['friday'] = fr
df['saturday'] = sat
df['sunday'] = sun
df['holiday'] = holiday
return df
def get_weather(self, start="2018-01-01", end="2018-12-31"):
datelist = pd.date_range(start=start, end=end).tolist()
return_dict = {}
for i in datelist:
START_DATE = i.strftime('%Y%m%d')
END_DATE = i.strftime('%Y%m%d')
URL = "https://api.weather.com/v1/geocode/50.12/14.54/observations/historical.json?apiKey=<KEY>&startDate={}&endDate={}&units=m".format(
START_DATE, END_DATE)
r = requests.get(URL)
observations = r.json()['observations']
for i in observations:
dt_object = datetime.fromtimestamp(i['valid_time_gmt'])
t = (i['temp'], i['pressure'])
return_dict[str(dt_object)] = t
datelist = pd.date_range(start="2018-01-01", end="2018-12-31").tolist()
timelist = []
for i in datelist:
for h in range(0, 24):
datestr = i.strftime('%Y-%m-%d')
timelist.append("{} {:02d}:00:00".format(datestr, h))
return_list = []
prev_val = None
for t in timelist:
if t in return_dict:
return_list.append(return_dict[t])
prev_val = return_dict[t]
else:
return_list.append(prev_val)
return return_list
def get_days_of_week(self, start="2018-01-01", end="2018-12-31"):
cz_holidays = holidays.CZ()
date_list = pd.date_range(start=start, end=end).tolist()
output_list = []
for d in date_list:
weekday = int(d.strftime('%w'))
for _ in range(0, 24):
output_list.append(
[int(weekday == 1), int(weekday == 2), int(weekday == 3), int(weekday == 4), int(weekday == 5),
int(weekday == 6), int(weekday == 0), int(d in cz_holidays)])
return output_list
def normalization(self, coef):
coef_norm = coef - coef.mean()
coef_norm = coef_norm / coef_norm.max()
return coef_norm
if __name__ == '__main__':
from parkingprediction.config.config_reader import ConfigReader
dataset = ParkingDataset(ConfigReader())
print(dataset.train_df)<file_sep>/parkingprediction/trainer/parking_trainer.py
from parkingprediction.trainer.base_trainer import BaseTrain
class ParkingTrainer(BaseTrain):
def __init__(self, session, model, dataset, config):
super(ParkingTrainer, self).__init__(session, model, dataset, config)
def train_epoch(self, cur_epoche):
num_iterations = self.config.num_iterations()
mean_loss = 0
mean_acc = 0
for i in range(num_iterations):
loss, acc = self.train_step()
mean_loss += loss
mean_acc += acc
mean_loss /= num_iterations
mean_acc /= num_iterations
return mean_loss, mean_acc
def train_step(self):
_, loss, acc = self.session.run([self.model.opt, self.model.loss, self.model.acc], feed_dict={
self.iterator.handle_placeholder: self.train_handle
})
self.session.run(self.model.increment_global_step_tensor)
return loss, acc
def test_step(self):
loss, acc = self.session.run([self.model.loss, self.model.acc], feed_dict={
self.iterator.handle_placeholder: self.test_handle
})
return loss, acc
def log_progress(self, input, num_iteration, mode):
summaries_dict = {
'loss': input[0],
'acc': input[1],
}
self.logger.log_scalars(num_iteration, summarizer=mode, summaries_dict=summaries_dict)
def update_progress_bar(self, t_bar, train_output, test_output):
t_bar.set_postfix(
train_loss='{:05.3f}'.format(train_output[0]),
train_acc='{:05.3f}'.format(train_output[1]),
test_loss='{:05.3f}'.format(test_output[0]),
test_acc='{:05.3f}'.format(test_output[1]),
)
<file_sep>/parkingprediction/trainer/tensor_iterator.py
import numpy as np
import tensorflow as tf
from sklearn.preprocessing import OneHotEncoder
class TensorIterator(object):
def __init__(self, dataset, model, session, config):
self.dataset = dataset
self.model = model
self.session = session
self.config = config
self.handle_placeholder = tf.placeholder(tf.string, shape=[])
def create_dataset_iterator(self, mode='train'):
dataset = tf.data.Dataset.from_tensor_slices((self.model.x, self.model.y))
# TODO: Add shuffling
dataset = dataset.batch(self.config.batch_size()).repeat()
dataset_iterator = dataset.make_initializable_iterator()
generic_iterator = tf.data.Iterator.from_string_handle(self.handle_placeholder, dataset.output_types,
dataset.output_shapes, dataset.output_classes)
dataset_handle = self.session.run(dataset_iterator.string_handle())
x, y = generic_iterator.get_next()
inputs = {
'x': x,
'y': y
}
if mode == 'train':
df = self.dataset.train_dataset()
else:
df = self.dataset.test_dataset()
coef, label = self.reshape_data(df['coef'], df['label'])
feed = {
self.model.x: coef,
self.model.y: label
}
self.session.run(dataset_iterator.initializer, feed_dict=feed)
return inputs, dataset_handle
def reshape_data(self, x, y):
coef = np.array(x.values.tolist())
coef = np.expand_dims(coef, axis=3)
labels = np.expand_dims(y, axis=1)
onehot_encoder = OneHotEncoder(sparse=False)
onehot_encoded_label = onehot_encoder.fit_transform(labels)
return coef, onehot_encoded_label
<file_sep>/requirements.txt
tensorflow
numpy
scikit-learn
click
tqdm
PyYAML
pandas
click
holidays
requests<file_sep>/parkingprediction/config/config_reader.py
import os
import yaml
## define custom tag handler
def join(loader, node):
seq = loader.construct_sequence(node)
return ''.join([str(i) for i in seq])
class ConfigReader(object):
def __init__(self, config_path='/Users/adamzvada/Documents/hackathon/iotea/ParkingPrediction/config/test.yml'):
self.ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
yaml.add_constructor('!join', join)
with open(config_path, 'r') as f:
config = yaml.load(f)
self.info = config['info']
self.dataset = config['dataset']
self.hyperparams = config['hyperparams']
self.wavelet = config['wavelet']
self.model = config['model']
def model_name(self):
return self.info['model_name']
# --DATASET--
def csv_path(self):
path = self.dataset['csv_path']
return self._absolute_path(path)
def num_samples(self):
return self.dataset['num_samples']
def sample_rate(self):
return self.dataset['sample_rate']
def max_period(self):
return self.dataset['max_period']
def stochastic_ratio(self):
return self.dataset['stochastic_ratio']
def signal_length(self):
return self.dataset['signal_length']
def test_size(self):
return self.dataset['test_size']
def coef_preprocess(self):
return self.dataset['coef_preprocess']
# --HYPERPARAMETERS--
def feature_size(self):
return self.hyperparams['feature_size']
def batch_size(self):
return self.hyperparams['batch_size']
def num_layers(self):
return self.hyperparams['num_layers']
def num_classes(self):
return self.hyperparams['num_classes']
def num_epoches(self):
return self.hyperparams['num_epoches']
def num_iterations(self):
return self.hyperparams['num_iterations']
# --WAVELET--
def wavelet_name(self):
return self.wavelet['name']
def max_scale(self):
return self.wavelet['max_scale']
# --MODEL--
def tensorboard_path(self):
path = self.model['tensorboard_path']
return self._absolute_path(path)
def trained_model_path(self):
path = self.model['trained_path']
return self._absolute_path(path)
def model_description(self):
return self.model['model_description']
def restore_trained_model(self):
path = self.model['restore_trained_model']
if path == None:
return None
return self._absolute_path(path)
def _absolute_path(self, path):
if not os.path.isabs(path):
return os.path.join(self.ROOT_DIR, path)
return path
if __name__ == '__main__':
config = ConfigReader()
print(config.model_description())
print(config.trained_path())
| d222bdf99d7bce36876a42ba8e8493d8ff1c38a5 | [
"Python",
"Text"
]
| 8 | Python | zvadaadam/parking-prediction | a6ce5e11d4c9767aaefaace50a15fe1382143c71 | 39ac03e64834526adff4b185bc0d9c6b6e3c3a39 |
refs/heads/master | <file_sep>drop database if exists spotify_cal;
create database spotify_cal;
\connect spotify_cal;
CREATE TABLE users (
ID SERIAL PRIMARY KEY,
username VARCHAR UNIQUE,
password VARCHAR
);
CREATE TABLE events (
ID SERIAL PRIMARY KEY,
date date,
start_time VARCHAR,
end_time VARCHAR,
description VARCHAR,
user_id INTEGER REFERENCES users(ID)
);
INSERT INTO users (username, password )
VALUES('Hansusana', '<PASSWORD>');
<file_sep>var express = require('express');
var router = express.Router();
const db = require('../db/queries');
/* GET events listing. */
router.get('/all', db.getAllEvents);
router.post('/create', db.createEvent);
module.exports = router;
<file_sep>let db = require("./index");
const getAllEvents = (req, res, next) => {
db.any('SELECT * FROM events').then( data => {
res.json(data).status(200);
})
.catch( err => {
console.log(err);
});
}
const createEvent = (req, res, next) => {
let startTime = req.body.startTime;
let endTime = req.body.endTime;
let descriptionInput = req.body.descriptionInput;
db.any('INSERT INTO events (date, start_time, end_time, description) VALUES (${date}, ${startTime}, ${endTime}, ${descriptionInput})', {date: date, start_time: startTime, end_time: endTime, description: descriptionInput})
.then( data => {
res.json(data).status(200);
})
.catch( err => {
console.log(err);
});
}
module.exports = {
getAllEvents,
createEvent
}<file_sep>import React, { Component } from 'react';
import { CSSTransitionGroup } from 'react-transition-group'
class Events extends Component {
render() {
const {selectedMonthEvents, selectedDay, removeEvent} = this.props;
// const {currentSelectedDay} = this.props.selectedDay;
// const monthEvents = this.props.selectedMonthEvents;
// const removeEvent = this.props.removeEvent;
const monthEventsRendered = selectedMonthEvents.map((event, i) => {
return (
<div
key={event.title}
className="event-container"
onClick={() => removeEvent(i)}
>
<CSSTransitionGroup
component="div"
className="animated-time"
transitionName="time"
transitionAppear={true}
transitionAppearTimeout={500}
transitionEnterTimeout={500}
transitionLeaveTimeout={500}
>
<div className="event-time event-attribute">
{event.date.format("HH:mm")}
</div>
</CSSTransitionGroup>
<CSSTransitionGroup
component="div"
className="animated-title"
transitionName="title"
transitionAppear={true}
transitionAppearTimeout={500}
transitionEnterTimeout={500}
transitionLeaveTimeout={500}
>
<div className="event-title event-attribute">{event.title}</div>
</CSSTransitionGroup>
</div>
);
});
const dayEventsRendered = [];
for (var i = 0; i < monthEventsRendered.length; i++) {
if (selectedMonthEvents[i].date.isSame(selectedDay, "day")) {
dayEventsRendered.push(monthEventsRendered[i]);
}
}
return (
<div className="day-events">
{dayEventsRendered}
</div>
);
}
}
export default Events; | 2a8b321a2163a36c80955c9cc150777d455b9493 | [
"JavaScript",
"SQL"
]
| 4 | SQL | susanahan/spotify_calendar | 04dae9cfc0c5c1c47d0a51163823441b66d84621 | ba55cd4cad254934352c81e04870c6df8971dfd3 |
refs/heads/master | <repo_name>zakariaelas/gemochat<file_sep>/frontend/src/components/InterviewerRoom/MeetingInformation/JobDetail.js
import React from 'react';
import PropTypes from 'prop-types';
import { Box, Typography } from '@material-ui/core';
const JobDetail = (props) => {
return (
<Box pt={2}>
<Typography variant="h5" paragraph>
Full Stack Developer
</Typography>
<Typography variant="body1" paragraph>
We are looking for a highly skilled computer programmer who is
comfortable with both front and back end programming. Full
Stack Developers are responsible for developing and designing
front end web architecture, ensuring the responsiveness of
applications and working alongside graphic designers for web
design features, among other duties. Full Stack Developers
will be required to see out a project from conception to final
product, requiring good organizational skills and attention to
detail.
</Typography>
<Typography variant="h6" paragraph>
Requirements
</Typography>
<ul>
<li>
<Typography>Degree in Computer Science</Typography>
</li>
<li>
<Typography>
Proficiency with fundamental front end languages such as
HTML, CSS and JavaScript
</Typography>
</li>
<li>
<Typography>
Familiarity with JavaScript frameworks such as Angular JS,
React and Amber
</Typography>
</li>
<li>
<Typography>
Familiarity with database technology such as MySQL, Oracle
and MongoDB.
</Typography>
</li>
</ul>
</Box>
);
};
export default JobDetail;
<file_sep>/backend/errors/ApplicationNotFound.js
const CustomError = require('./CustomError');
class ApplicationNotFound extends CustomError {
name = 'ApplicationNotFound';
status = 404;
constructor(message = 'Application not found') {
super(message);
}
}
module.exports = ApplicationNotFound;
<file_sep>/frontend/src/hooks/useInterview.js
import { useQuery } from 'react-query';
import api from '../api';
const useInterview = (key, config = {}) => {
const { data, ...options } = useQuery(
['interview', { key }],
api.getInterviewNormalized,
config,
);
return [data, { ...options }];
};
export default useInterview;
<file_sep>/frontend/src/components/InterviewerRoom/QuestionsList/QuestionItem/QuestionItemAvatar.js
import React from 'react';
import {
ListItemAvatar,
makeStyles,
Avatar,
Box,
} from '@material-ui/core';
import { Check } from '@material-ui/icons';
const useStyles = makeStyles((theme) => ({
avatar: {
width: 30,
height: 30,
color: 'white',
backgroundColor: theme.palette.primary.light,
border: `1px solid ${theme.palette.primary.light}`,
},
ListItemAvatar: {
minWidth: 0,
marginRight: theme.spacing(0.75),
},
circle: {
borderRadius: '50%',
border: `1px solid ${theme.palette.primary.dark}`,
color: theme.palette.primary.dark,
width: 30,
height: 30,
lineHeight: '30px',
textAlign: 'center',
fontSize: theme.spacing(0.875),
},
}));
const QuestionItemAvatar = ({ isScored, index }) => {
const classes = useStyles();
return (
<>
{isScored ? (
<ListItemAvatar classes={{ root: classes.ListItemAvatar }}>
<Avatar classes={{ root: classes.avatar }}>
<Check color="inherit" fontSize="small" />
</Avatar>
</ListItemAvatar>
) : (
<Box mr={0.75} className={classes.circle}>
{index + 1}
</Box>
)}
</>
);
};
export default QuestionItemAvatar;
<file_sep>/frontend/src/ui/Spinners/LoadingSpinner.js
import { CircularProgress, makeStyles } from '@material-ui/core';
import React from 'react';
const useStyles = makeStyles((theme) => ({
container: (props) => ({
minHeight: props.minHeight || '50vh',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
}),
spinnerBox: {
transform: 'translate(-50%, -50%)',
},
}));
const LoadingSpinner = ({ minHeight, ...props }) => {
const classes = useStyles({ minHeight });
return (
<div className={classes.container}>
<div className={classes.spinnerBox}>
<CircularProgress thickness={4} {...props} disableShrink />
</div>
</div>
);
};
export default LoadingSpinner;
<file_sep>/backend/api/routes/users.js
const express = require('express');
const router = express.Router();
const { createUser, updateProfile } = require('../controllers/users');
const { validateSignUp, validateUpdateUser } = require('../validators/users');
const { sanitizeReqBody } = require('../validators/sanitizers');
const { loginRequired } = require('../middleware/auth');
router
.route('/')
.post(validateSignUp, sanitizeReqBody, createUser)
.put(loginRequired, validateUpdateUser, sanitizeReqBody, updateProfile);
module.exports = router;
<file_sep>/backend/errors/CustomError.js
class CustomError extends Error {
name = 'CustomError';
constructor(message) {
super(message);
}
serializeError() {
return { message: this.message, status: this.status };
}
}
module.exports = CustomError;
<file_sep>/frontend/src/ui/SimpleTabs/SimpleTabs.js
import { withStyles, Tabs } from '@material-ui/core';
const SimpleTabs = withStyles((theme) => ({
indicator: {
backgroundColor: theme.palette.primary.main,
height: 3,
},
}))(Tabs);
export default SimpleTabs;
<file_sep>/backend/utils/helpers.js
const NUMERICAL_RATINGS = require('../enums/numericalRatings');
const RATINGS = require('../enums/ratings');
// Utility function used to get the closest rating to the numerical score generated
// e.g: Used to convert a 4.2666 to a 'Yes'
const getClosestRatingToNumericalScore = (score) => {
const arr = Object.values(NUMERICAL_RATINGS);
const closest = arr.reduce((acc, curr) =>
Math.abs(acc - score) < Math.abs(curr - score) ? acc : curr,
);
return Object.keys(NUMERICAL_RATINGS).find(
(key) => NUMERICAL_RATINGS[key] === closest,
);
};
const generateScorecardRatingFromQuestions = (questions) => {
let attributes = {};
for (let i = 0; i < questions.length; i++) {
let { rating, note } = questions[i];
// Continue to next iteration if there is no attribute or not scored
if (!questions[i].attributes || rating === RATINGS.NO_DECISION) continue;
// Iterate through question attributes and compute weighted sum for each.
for (let j = 0; j < questions[i].attributes.length; j++) {
let { attribute_name, attribute_id, weight = 1 } = questions[
i
].attributes[j];
// if the attribute is seen for the first time, add it to the attributes map.
if (!attributes[attribute_id])
attributes[attribute_id] = {
weighted_sum: 0,
sumOfWeights: 0,
note: '',
attribute_name,
};
attributes[attribute_id].weighted_sum +=
NUMERICAL_RATINGS[rating] * weight;
attributes[attribute_id].sumOfWeights += weight;
attributes[attribute_id].note += note ? note + '\n' : '';
}
}
for (const [
key,
{ attribute_name, note, weighted_sum, sumOfWeights },
] of Object.entries(attributes)) {
attributes[key] = {
attribute_id: key,
attribute_name,
note,
rating: getClosestRatingToNumericalScore(weighted_sum / sumOfWeights),
};
}
return attributes;
};
module.exports = {
getClosestRatingToNumericalScore,
generateScorecardRatingFromQuestions,
};
<file_sep>/frontend/src/components/AuthenticatedApp/AuthenticatedApp.js
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Interviews from '../../pages/Interviews/Interviews';
import Profile from '../../pages/Profile/Profile';
import InterviewDetails from '../../pages/InterviewDetails/InterviewDetails';
import AppLayout from '../../ui/AppLayout';
import NotFound from '../../pages/NotFound/NotFound';
import Interview from '../../pages/Interview/Interview';
import { ErrorBoundary } from 'react-error-boundary';
import ErrorDialogFallback from '../ErrorDialogFallback/ErrorDialogFallback';
import AssessmentPage from '../../pages/AssessmentPage/AssessmentPage';
const AuthenticatedApp = () => {
return (
<ErrorBoundary FallbackComponent={ErrorDialogFallback}>
<Switch>
<Route
exact
path="/logout"
render={() => {
localStorage.removeItem('token');
window.location.href = `${process.env.PUBLIC_URL}/`;
}}
/>
<Route
exact
path={[
'/',
'/profile',
'/interviews/:key/details',
'/:key/assessment',
]}
>
<AppLayout>
<Route label="Interviews" exact path="/" isTab>
<Interviews label="Interviews" exact path="/" isTab />
</Route>
<Route label="Profile" exact path="/profile" isTab>
<Profile />
</Route>
<Route
exact
isTab={false}
path="/interviews/:key/details"
>
<InterviewDetails />
</Route>
<Route exact isTab={false} path="/:key/assessment">
<AssessmentPage />
</Route>
</AppLayout>
</Route>
<Route exact path="/:key">
<Interview />
</Route>
<Route path="*">
<NotFound />
</Route>
</Switch>
</ErrorBoundary>
);
};
export default AuthenticatedApp;
<file_sep>/frontend/src/components/InterviewerRoom/RoomQuestions/RoomQuestions.js
import React, { useMemo } from 'react';
import {
Paper,
Box,
Typography,
makeStyles,
Tooltip,
Grid,
} from '@material-ui/core';
import QuestionsStepper from './QuestionsStepper';
import { InfoOutlined } from '@material-ui/icons';
import useInterviewStateContext from '../../../hooks/useInterviewStateContext';
import { INTERVIEW_STEP } from '../../../constants';
const useStyles = makeStyles((theme) => ({
paper: {
background: theme.palette.blueGrey[100],
},
title: {
color: theme.palette.blueGrey[400],
textTransform: 'uppercase',
letterSpacing: '-1px',
fontSize: '1.1rem',
},
icon: {
color: theme.palette.blueGrey[400],
},
tooltip: {
fontSize: theme.spacing(0.8),
},
}));
const RoomQuestions = () => {
const classes = useStyles();
const { interviewStep } = useInterviewStateContext();
return useMemo(() => {
if (interviewStep === INTERVIEW_STEP.ASSESSMENT) return null;
return (
<Grid item lg={12}>
<Paper elevation={0}>
<Box px={1} py={0.5}>
<Box display="flex" alignItems="center">
<Box mr={0.75}>
<Typography className={classes.title} variant="h6">
Interview Questions
</Typography>
</Box>
<Tooltip
classes={{ tooltip: classes.tooltip }}
interactive
leaveDelay={500}
placement="right"
title="You can use the arrow keys on your keyboard to navigate the questions"
>
<InfoOutlined className={classes.icon} />
</Tooltip>
</Box>
<QuestionsStepper />
</Box>
</Paper>
</Grid>
);
}, [interviewStep, classes]);
};
export default RoomQuestions;
<file_sep>/backend/api.js
const express = require('express');
const app = express();
const morgan = require('morgan');
const helmet = require('helmet');
const apiRoutes = require('./api/index');
const logger = require('./utils/logger');
if (typeof jest === 'undefined')
app.use(
morgan(':method :url :status :res[content-length] - :response-time ms', {
stream: logger.stream,
}),
);
app.use(helmet());
app.use(express.json());
app.use('/api', apiRoutes);
module.exports = app;
<file_sep>/backend/main.js
const api = require('./api');
const config = require('./config');
const logger = require('./utils/logger');
const server = require('http').Server(api);
require('./subscribers');
server.listen(config.port, function () {
logger.info(`Server is starting on port ${config.port}`);
});
<file_sep>/frontend/src/components/AudioTrack/AudioTrack.js
import { useRef, useEffect } from 'react';
const AudioTrack = ({ track }) => {
const audioEl = useRef();
useEffect(() => {
audioEl.current = track.attach();
document.body.appendChild(audioEl.current);
return () => track.detach().forEach((el) => el.remove());
}, [track]);
return null;
};
export default AudioTrack;
<file_sep>/frontend/src/components/InterviewerRoom/QuestionsList/QuestionListConnected.js
import React from 'react';
import useInterviewStateContext from '../../../hooks/useInterviewStateContext';
import QuestionList from './QuestionList';
const QuestionListConnected = (props) => {
const {
interview: { questions: questionIds },
updateQuestionIds,
} = useInterviewStateContext();
return (
<QuestionList
questionIds={questionIds}
updateQuestionIds={updateQuestionIds}
/>
);
};
export default QuestionListConnected;
<file_sep>/backend/api/middleware/auth.js
const passport = require('passport');
const jwt = require('jsonwebtoken');
const { ExtractJwt, Strategy: JwtStrategy } = require('passport-jwt');
const config = require('../../config/');
const { ForbiddenError, CredentialsError } = require('../../errors/');
const db = require('../../db');
const ROLES = require('../../enums/roles');
const jwtStrategy = new JwtStrategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.jwt.secret,
},
(jwt_payload, done) => {
done(null, jwt_payload);
},
);
passport.use(jwtStrategy);
const jwtOptions = {
expiresIn: config.jwt.expirationTime,
};
const createToken = (user) => {
return jwt.sign(user, config.jwt.secret, jwtOptions);
};
const requireAuthWithPredicate = (pred) => (req, res, next) => {
passport.authenticate('jwt', { session: false }, async (err, payload) => {
try {
if (err) throw err;
if (!payload) return next(new CredentialsError('Please log in'));
const { id } = payload;
const user = await db.User.findById(id);
const predCheck = await pred.check(user, req);
if (predCheck) {
req.user = user;
return next();
} else return next(new ForbiddenError(pred.message));
} catch (e) {
next(e);
}
})(req, res, next);
};
module.exports = {
createToken,
requireAuthWithPredicate,
loginRequired: requireAuthWithPredicate({ check: () => true }),
ensureCorrectUser: requireAuthWithPredicate({
check: (user, req) => user._id.toString() === req.params.uid,
message: 'Needs permission',
}),
ensureInterviewer: requireAuthWithPredicate({
check: (user, req) => user.role === ROLES.INTERVIEWER,
message: 'Needs permission',
}),
};
<file_sep>/frontend/src/components/ParticipantTracks/ParticipantTracks.js
import React from 'react';
import usePublications from '../../hooks/usePublications';
import Publication from '../Publication/Publication';
const ParticipantTracks = ({ participant }) => {
const publications = usePublications(participant);
return (
<>
{publications.map((publication) => (
<Publication
key={publication.kind}
participant={participant}
publication={publication}
/>
))}
</>
);
};
export default ParticipantTracks;
<file_sep>/frontend/src/components/VideoProvider/index.js
import React, { createContext } from 'react';
import useHandleRoomDisconnectionErrors from './useHandleRoomDisconnectionErrors/useHandleRoomDisconnectionErrors';
import useHandleOnDisconnect from './useHandleOnDisconnect/useHandleOnDisconnect';
import useHandleTrackPublicationFailed from './useHandleTrackPublicationFailed/useHandleTrackPublicationFailed';
import useLocalTracks from './useLocalTracks/useLocalTracks';
import useRoom from './useRoom/useRoom';
export const VideoContext = createContext(null);
export function VideoProvider({
options,
children,
onError = () => {},
onDisconnect = () => {},
}) {
const onErrorCallback = (error) => {
console.log(`ERROR: ${error.message}`, error);
onError(error);
};
const {
localTracks,
getLocalVideoTrack,
getLocalAudioTrack,
isAcquiringLocalTracks,
} = useLocalTracks();
const audioTrack = localTracks.find(
(track) => track.kind === 'audio',
);
const videoTrack = localTracks.find(
(track) => track.kind === 'video',
);
const { room, isConnecting, connect } = useRoom(
localTracks,
onErrorCallback,
options,
);
// Register onError and onDisconnect callback functions.
useHandleRoomDisconnectionErrors(room, onError);
useHandleTrackPublicationFailed(room, onError);
useHandleOnDisconnect(room, onDisconnect);
return (
<VideoContext.Provider
value={{
room,
localTracks,
audioTrack,
videoTrack,
isConnecting,
onError: onErrorCallback,
onDisconnect,
getLocalVideoTrack,
getLocalAudioTrack,
connect,
isAcquiringLocalTracks,
}}
>
{children}
</VideoContext.Provider>
);
}
<file_sep>/backend/services/interviews.js
const db = require('../db');
const redisClient = require('redis').createClient();
const _ = require('lodash');
const { v4: uuidv4 } = require('uuid');
const { InterviewNotFound } = require('../errors');
const STATUS = require('../enums/interviewStatus');
const RATINGS = require('../enums/ratings');
const { generateScorecardRatingFromQuestions } = require('../utils/helpers');
const { greenhouseChannel } = require('../subscribers/channels');
const faker = require('faker');
const harvestService = require('./harvest');
const getInterviews = async (id) => {
const interviews = await db.Interview.find({ interviewer: id }).sort({
date: 'desc',
});
return interviews;
};
const createInterview = async (data) => {
const key = uuidv4();
const { application_id } = data;
const {
candidate_id,
job_id,
job_name,
} = await harvestService.getApplication(application_id);
let { questions, scorecard } = await db.Job.findOne({ job_id });
questions = questions.map((q) => q.toObject());
scorecard = scorecard.map((s) => s.toObject());
const interview = await db.Interview.create({
key,
...data,
questions,
scorecard,
candidate_id,
candidate_name: faker.name.findName(),
job_id,
job_name,
});
return interview;
};
const getInterview = async (key) => {
let interview = await db.Interview.findOne({
key,
});
if (!interview) throw new InterviewNotFound();
return interview;
};
const isInterviewValid = async (key) => {
const interview = await db.Interview.findOne({ key });
return !!interview;
};
const isInterviewerOfInterview = async (userId, key) => {
const interview = await db.Interview.findOne({ key });
return interview && interview.interviewer.toString() === userId;
};
const submitAssessment = async (key, data) => {
let status = STATUS.AWAITING_ASSESSMENT;
const { overall_rating } = data;
if (overall_rating && overall_rating !== RATINGS.NO_DECISION)
status = STATUS.COMPLETED;
// As we push in a new array with every submission. We need to preserve the attributes ids
// This is important because this will preserve the question attribute mappings.
// If the following line is removed, on each submission, new ids get assigned to attributes .. thus breaking the question mappings.
data.scorecard = data.scorecard.map((s) => ({ ...s, _id: s.id }));
let interview = await db.Interview.findOneAndUpdate(
{ key },
{ $set: { ...data, status } },
{ new: true },
).populate({ path: 'interviewer', select: 'displayName' });
// Once the overall rating is submitted, we publish a message to redis so that our scraping worker can submit to greenhouse
if (status === STATUS.COMPLETED) {
redisClient.publish(
`${greenhouseChannel}`,
JSON.stringify({
type: 'submit_assessment',
...interview.toObject(),
interviewer: interview.interviewer.displayName,
}),
);
}
return interview;
};
const getInterviewScoresFromQuestions = async (key, questions) => {
const attributesMap = generateScorecardRatingFromQuestions(questions);
// Return an array of scores instead of an object
const attributes = _.values(attributesMap);
return attributes;
};
const getCandidateInformation = async (key) => {
let interview = await db.Interview.findOne({
key,
});
if (!interview) throw new InterviewNotFound();
const { keyed_custom_fields } = await harvestService.getApplication(
interview.application_id,
);
return {
candidate_name: interview.candidate_name,
keyed_custom_fields,
};
};
module.exports = {
createInterview,
isInterviewValid,
getInterview,
submitAssessment,
getInterviews,
getInterviewScoresFromQuestions,
isInterviewerOfInterview,
getCandidateInformation,
};
<file_sep>/frontend/src/components/InterviewStateProvider/schemas/interview.js
import { schema } from 'normalizr';
import { questions } from './questions';
import { scorecard } from './scorecard';
export const interview = new schema.Entity('interview', {
questions: [questions],
scorecard: [scorecard],
});
<file_sep>/frontend/src/components/UnauthenticatedApp/UnauthenticatedApp.js
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Login from '../../pages/Login/Login';
import Interview from '../../pages/Interview/Interview';
import NotFound from '../../pages/NotFound/NotFound';
const UnauthenticatedApp = () => {
return (
<Switch>
<Route exact path={['/', '/login']}>
<Login />
</Route>
<Route exact path="/:key">
<Interview />
</Route>
<Route path="*">
<NotFound />
</Route>
</Switch>
);
};
export default UnauthenticatedApp;
<file_sep>/frontend/src/hooks/useVideoContext.js
import { useContext } from 'react';
import { VideoContext } from '../components/VideoProvider';
const useVideoContext = (props) => {
const context = useContext(VideoContext);
if (!context) {
throw new Error(
'useVideoContext must be used within a VideoProvider',
);
}
return context;
};
export default useVideoContext;
<file_sep>/frontend/src/hooks/useTwilioAccessToken.js
import { useState } from 'react';
import { useQuery } from 'react-query';
import api from '../api';
const useTwilioAccessToken = (display_name, key) => {
const [token, setToken] = useState('');
const options = useQuery(
['accessToken', { display_name, key }],
api.getAccessToken,
{
onSuccess: (data = {}) => {
setToken(data.accessToken);
},
},
);
return [token, options];
};
export default useTwilioAccessToken;
<file_sep>/backend/api/controllers/scorecards.js
const harvestService = require('../../services/harvest');
// This route is not yet consumed by our frontend, but it can be used to fetch a scorecard template from an application
const getScorecards = async (req, res, next) => {
try {
const { applicationId } = req.params;
const scorecards = await harvestService.getHarvestScorecards(applicationId);
return res.json(scorecards);
} catch (err) {
next(err);
}
};
module.exports = {
getScorecards,
};
<file_sep>/frontend/src/components/InterviewerRoom/QuestionsList/QuestionItem/QuestionItemCall.js
import React, { useCallback } from 'react';
import useQuestionItemStyles from './useQuestionItemStyles';
import QuestionItemAvatar from './QuestionItemAvatar';
import { Box, ListItem, ListItemText } from '@material-ui/core';
import { DragIndicator } from '@material-ui/icons';
import { RATINGS } from '../../../../constants';
import useInterviewStateContext from '../../../../hooks/useInterviewStateContext';
const Component = React.memo(
React.forwardRef(
({ handleClick, question, index, dragHandle, ...props }, ref) => {
const classes = useQuestionItemStyles();
const isScored =
question.rating && question.rating !== RATINGS.NO_DECISION;
return (
<Box {...props} ref={ref} className={classes.mainBox}>
<Box display="flex" alignItems="center">
<Box className={classes.icon} {...dragHandle}>
<DragIndicator color="primary" />
</Box>
<ListItem
classes={{ root: classes.listItemRoot }}
button
onClick={handleClick}
>
<QuestionItemAvatar index={index} isScored={isScored} />
<ListItemText
primary={`${question.text}`}
primaryTypographyProps={{
className: classes.listItemTextPrimary,
}}
/>
</ListItem>
</Box>
</Box>
);
},
),
);
const QuestionItemCall = ({ index, questionId, ...props }, ref) => {
const {
questions,
setSelectedQuestionIndex,
} = useInterviewStateContext();
const question = questions[questionId];
const handleClick = useCallback(() => {
setSelectedQuestionIndex(index);
}, [setSelectedQuestionIndex, index]);
return (
<Component
question={question}
index={index}
handleClick={handleClick}
ref={ref}
{...props}
/>
);
};
export default React.forwardRef(QuestionItemCall);
<file_sep>/backend/services/users.js
const db = require('../db');
const CredentialsError = require('../errors/CredentialsError');
const bcrypt = require('bcrypt');
const createUser = async (data) => {
try {
const user = await db.User.create(data);
return user;
} catch (err) {
throw err;
}
};
const updateProfile = async (userId, data) => {
const user = await db.User.findOne({ _id: userId });
const isMatch = await user.comparePassword(data.password);
if (!isMatch) throw new CredentialsError();
const newPassword = await bcrypt.hash(data.newPassword, 10);
delete data.newPassword;
const newUser = await db.User.findOneAndUpdate(
{ _id: userId },
{ $set: { ...data, password: <PASSWORD> } },
{ new: true },
);
return newUser;
};
module.exports = {
createUser,
updateProfile,
};
<file_sep>/backend/.env.example
NODE_ENV=development
PORT=
DATABASE_URL=
JWT_SECRET=
JWT_EXPIRATION_TIME=
TWILIO_ACCOUNT_SID=
TWILIO_API_KEY_SID=
TWILIO_API_KEY_SECRET=
TWILIO_MAX_ALLOWED_SESSION_DURATION=
HARVEST_API_KEY=
GREENHOUSE_EMAIL=
GREENHOUSE_PASSWORD=<file_sep>/frontend/src/components/NewInterview/InterviewKey.js
import React, { useRef } from 'react';
import {
makeStyles,
Divider,
Tooltip,
IconButton,
Box,
InputBase,
Paper,
Button,
DialogContent,
DialogActions,
} from '@material-ui/core';
import { FileCopy } from '@material-ui/icons';
import snackbar from '../../ui/Snackbar';
import { Link } from 'react-router-dom';
const useStyles = makeStyles((theme) => ({
input: {
flex: 1,
marginLeft: theme.spacing(1),
},
divider: {
height: 28,
margin: 4,
},
}));
const InterviewKey = ({ interviewKey, handleClose }) => {
const classes = useStyles();
const inputRef = useRef(null);
const handleCopy = (e) => {
inputRef.current.focus();
inputRef.current.select();
document.execCommand('copy');
snackbar.success('Copied to clipboard !');
};
return (
<>
<DialogContent>
<Paper
elevation={2}
component="form"
className={classes.root}
>
<Box p={0.5} display="flex" alignItems="center">
<InputBase
className={classes.input}
value={`${window.location.host}/${interviewKey}`}
inputRef={inputRef}
readOnly
/>
<Divider
className={classes.divider}
orientation="vertical"
/>
<Tooltip title="Copy to clipboard" placement="bottom">
<IconButton
onClick={handleCopy}
color="primary"
aria-label="copy"
>
<FileCopy />
</IconButton>
</Tooltip>
</Box>
</Paper>
</DialogContent>
<Box mt={1}>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button
component={Link}
to={`/${interviewKey}`}
color="primary"
>
Start
</Button>
</DialogActions>
</Box>
</>
);
};
export default InterviewKey;
<file_sep>/frontend/src/components/RoomSkeleton/RoomSkeleton.js
import React from 'react';
import { Box, Grid, makeStyles } from '@material-ui/core';
import { Skeleton } from '@material-ui/lab';
const useStyles = makeStyles((theme) => ({
root: {
backgroundColor: 'white',
borderRadius: theme.spacing(0.25),
margin: 0,
},
}));
const RoomSkeleton = () => {
const classes = useStyles();
return (
<Box p={0.5}>
<Grid container spacing={1}>
<Grid spacing={1} container item lg={8}>
<Grid item lg={12}>
<Skeleton
classes={{ root: classes.root }}
variant="rect"
animation="wave"
width="100%"
height="20vh"
/>
</Grid>
<Grid item lg={12}>
<Skeleton
classes={{ root: classes.root }}
variant="rect"
animation="wave"
width="100%"
height="75vh"
/>
</Grid>
</Grid>
<Grid item lg={4}>
<Skeleton
classes={{ root: classes.root }}
variant="rect"
animation="wave"
width={507}
height="100%"
/>
</Grid>
</Grid>
</Box>
);
};
export default RoomSkeleton;
<file_sep>/backend/db/models/job.js
const mongoose = require('mongoose');
const questionSchema = require('./question');
const attributeSchema = require('./attribute');
const jobSchema = new mongoose.Schema(
{
job_id: {
type: String,
required: true,
},
questions: [questionSchema],
scorecard: [attributeSchema],
},
{ timestamps: true },
);
jobSchema.index({ job_id: 1 });
const Job = new mongoose.model('Job', jobSchema);
module.exports = Job;
<file_sep>/backend/errors/InterviewNotFound.js
const CustomError = require('./CustomError');
class InterviewNotFound extends CustomError {
name = 'InterviewNotFound';
status = 404;
constructor(message = 'Interview not found') {
super(message);
}
}
module.exports = InterviewNotFound;
<file_sep>/backend/api/validators/sanitizers.js
const { matchedData } = require('express-validator');
const sanitizeReqBody = (req, res, next) => {
req.body = matchedData(req, {
locations: ['body'],
includeOptionals: false,
});
next();
};
const capitalizeString = (value) =>
value
.split(' ')
.map((w) => `${w.charAt(0).toUpperCase()}${w.slice(1)}`)
.join(' ');
module.exports = {
sanitizeReqBody,
capitalizeString,
};
<file_sep>/README.md
# 💼 Gemochat
Gemochat is a web application that enables standard, consistent, and fast candidate evaluation for external interviewers by leveraging the interviewing experience the Gemography team has spent years fine-tuning. The application provides real-time questions that map to specific attributes on scorecards and makes use of the Twilio Programmable Video API to provide live video calls.
# 📖 Table of Contents
- [1. Installation](#️-installation)
- [2. Features](#-features)
- [2.1 Twilio API](#twilio-api)
- [2.2 Core Business Logic](#core-business-logic)
- [2.3 Integration](#integration)
- [2.3.1 Interview Assessment Submission](#interview-assessment-submission)
- [2.3.2 Interviewers' Interviews](#interviewers-interviews)
- [2.4 Admin Platform](#admin-platform)
- [3. Improvements and Future Work](#-improvements-and-future-work)
- [4. Feature requests](#-feature-requests)
## ⚒️ Installation
Use git to clone the gemochat repository locally
with HTTPS:
```bash
git clone [email protected]:zakariaelas/gemochat.git
```
with SSH:
```bash
git clone [email protected]:zakariaelas/gemochat.git
```
Futhermore, you will need the following software installed on your computer:
- [Node.js](https://nodejs.org/en/download/)
- [MongoDB](https://docs.mongodb.com/manual/installation/)
- [Redis](https://redis.io/download)
Once you change directories to `backend` or `frontend`, you will need to install all dependencies.
```bash
cd backend
npm install
cd ../frontend
npm install
```
Following is a list of env variables necessary to spin up the server and for all features to work:
```bash
NODE_ENV=development
PORT=
DATABASE_URL=
JWT_SECRET=
JWT_EXPIRATION_TIME=
TWILIO_ACCOUNT_SID=
TWILIO_API_KEY_SID=
TWILIO_API_KEY_SECRET=
TWILIO_MAX_ALLOWED_SESSION_DURATION=
HARVEST_API_KEY=
GREENHOUSE_EMAIL=
GREENHOUSE_PASSWORD=
```
These can also be found in the `.env.example` file.
In order to help you get started quickly, you can make use of a seed script. The repo comes with two JSON files that you can leverage to add or remove seed data. The two files are located under the following paths:
`./backend/db/seeds/users.json` and `./backend/db/seeds/jobs.json`
In order to run the seed script, execute the following command:
```bash
npm run seed
```
This will create users from the `users.json` file located in `./backend/db/seeds/users.json`, jobs from the `jobs.json` file located in `./backend/db/seeds/jobs.json`, and a dummy interview. The interview is hardcoded and mapped to the "Playground job", it also uses **Akram Saouri's** application for the playground job. The idea is to provide a quick interview for testing. Feel free to delete it and add a custom one through the app's interface.
`users.json` and `jobs.json` come with a default user and job.
The user has the following credentials:
```bash
email: <EMAIL>
password: <PASSWORD>
```
The job is the "Playground job" I had access to during my internship.
If you want to programmatically create users and jobs quickly, you can import the `createJobs` and `createUsers` functions from the `./backend/db/seeds/jobs.js` and `./backend/db/seeds/users.js` files respectively, and call them from additional scripts or files.
## 💡 Features
The app's **main** features will be discussed in this section. I believe it would be best to break this down into what I think are the **building blocks** of the application.
### Twilio API
In order to power the app with real-time video and audio streaming capabilities, we have used the Twilio Programmable Video service.
Once we generate an access token from our application server, it can then be consumed by our React application to start a WebRTC Peer Connection through the Twilio Video JS sdk. I came across an open source Github [repo](https://github.com/twilio/twilio-video-app-react) from the Twilio team that implements a small video chat app. I found it particularly useful because it does align with what we need and also uses Material UI. Modifications where made accordingly to fit the context of our application.
### Core Business Logic
The added value of this project lies in the interviewing experience. We tried to optimize the experience by providing support for different steps or stages of the interview.
**During The Interview**
During the interview, interviewers are provided with a set of questions to ask the candidate. Based on their answer, they can assign one score from the following: *strong no*, *no*, *mixed*, *yes*, *strong yes*. These ratings were used to stay in sync with what is already available and used in greenhouse.
Furthermore, adjacent to each question, a text field that can be used to take notes. These notes should capture whatever goes beyond a simple score (follow up questions, discussions, etc) starting from when the question was asked, until when the interviewer decides to move to the next question. Basically, each set of notes is mapped to a specific question.
On the right hand side, you will be able to see, browse, and reorder the questions in the "Questions" tab.
**End of The Interview**
Hopefully, at this stage, the candidate's answers to the questions have helped build strong opinion about the interview. As soon as you click the hang up button, the **assessment** phase starts.
You will be prompted to fill out a scorecard, which is a standard way to assess candidates and mitigate interviewer bias. The scorecard contains a set of attributes, where each can be scored following the same rating scale as before.
To fill out the scorecard, you can use the **"Generate ratings"** button. This will use the ratings you have filled on the questions, as well as any notes taken, and will automatically score + compile notes for the relevant attributes. Each question is in fact, mapped to a set of attributes, each with a predetermined weight. We then compute the weighted average for each attribute and determine the ratings accordingly. The question-to-attribute mappings take place through an admin platform (not yet implemented).
Once the scorecard is filled, you can choose your overall recommendation of the interview. This is arguably the most important input from the interviewer, as this is what represents the final decision whether the candidate advances to the next stage or not.
### Integration
The company uses Greenhouse as its main recruiting software so we wanted to keep this as our single source of truth and try to integrate Gemochat with it.
### Interview Assessment Submission
Ideally, we want to be able to submit the scorecard + overall rating to Greenhouse. I believe there are 3 main options:
**Option 1: Use the Harvest API to submit scorecard or final interview decision**
Unfortunately, the Harvest API (built by Greenhouse) does not support submission of interview scorecard nor final decision.
**Option 2: Create custom_fields through the Harvest API (just like Eval)**
Just like there is a "Backend quiz" attribute on each application on greenhouse for example, we could add an "{Interview type} overall rating" custom field to capture the most important information of the assessment. However, this was a bit difficult to achieve because of the way custom fields work.
If a custom field was to be created through the following route
```
POST https://harvest.greenhouse.io/v1/custom_fields
```
It would be added to **ALL** applications on greenhouse, including the real ones coming from authentic candidates, not just the "Playground Job" (we don't want this behavior). Then we'll have to fill it accordingly through this route:
```
PATCH https://harvest.greenhouse.io/v1/applications/{id}
```
**Option 3: Use a headless browser**
By using a headless browser, we could load relevant web pages on greenhouse and fill the scorecard, as well as the overall recommendation. Theoretically speaking, this would work great. However, in the future, any changes to the Greenhouse website might break our code. In addition, this would be very slow compared to hitting an endpoint if it was supported.
### Solution
The solution I ended up going for was based on **Option 3**. I used Puppeteer as a headless browser to target the relevant pages, fill the scorecard, fill the final decision, and finally submit the assessment. As a preventative measure in case things go wrong, all interview assessments are saved on Gemochat as well.
In order to try and deal with the performance issues, I have used redis as a pub/sub implementation to publish a message once interviewers submit their assessment. On the other side, our web scraper worker subscribes to this type of messages, and when received, starts its work. This would allow us to easily split the application into two services if performance becomes an issue. One service would simply deal with incoming requests, and another would do the "heavy" work that comes with scraping. Currently, there is only one service, but I hope this helps prepare for any future changes in case performance becomes a problem.
### Interviewers' Interviews
The way things work currently, each interviewer can add his or her own interview. All they have to provide is the following:
```bash
{
interview_type: String,
application_id: String,
date: Date,
}
```
The `application_id` is then used to hit the following Harvest API [route](https://developers.greenhouse.io/harvest.html#get-retrieve-application):
```
GET https://harvest.greenhouse.io/v1/applications/{id}
```
The response is then used to get the `job_id`, `job_name`, and `candidate_id`. These are important for our web scraper to work correctly.
I am well aware that this is not ideal. I believe that, as potential improvement, you can use **webhooks** from the scheduling software that you use or greenhouse to hit a Gemochat endpoint. This endpoint would simply add an interview given a date, an interview_type, and an application_id.
### Admin Platform
Currently, jobs are simply created through our seed script. An admin platform can be used to create jobs, scorecards, questions and their mappings, and perhaps manage interviewers.
## 🧠 Improvements and Future Work
Following is a recap on what has already been mentioned and further improvements that can be brought to the software:
### Better Test Coverage
I have only written a couple dozens of test cases to try and give the software some amount of reliability. However, there are probably a lot of features to be tested more extensively. The scraper service feels like one of those things that should be heavily tested to overcome its frail nature.
### Better Authentication System
I believe it would be best to use the company's auth system, if existing, to login to Gemochat. It would be cumbersome for interviewers, who work at the company, and possibly have an Eval (or other platforms) account to have to create a new one.
### Admin Platform
Just like we discussed in a different section, this is an important part of the system.
### Webhooks Integration
I see it as a good solution to the shortcomings of *Interviewers' Interviews*. I believe Greenhouse also supports a variety of webhooks, that can be used in combination with MixMax's webhooks to achieve the intended behavior.
### Screensharing
The current solution does not support streaming the media devices, however, this should be feasible through the Twilio Video API. You can get inspired from this [code](https://github.com/twilio/twilio-video-app-react/blob/master/src/hooks/useScreenShareToggle/useScreenShareToggle.tsx).
## 🤔 Feature Requests
Feature requests are features that were suggested by other engineers during different demo calls. These features are considered *nice-to-have* but are not a priority.
### On demand recording of audio/video
The idea is to record a short but specific audio/video clip of the interview. Use cases include interviewers recording candidate's answers to some questions. I have looked into this a tiny bit, and i have stumbled across an interesting [library](https://github.com/muaz-khan/RecordRTC) that can be used to implement this.
### Addition of Questions and Mappings by Interviewers
At the moment, questions and their mappins are added through the back office. Ideally, we would like interviewers to be able to add their own questions as well and map them to specific attributes. The only concern is that this feature ends up re-introducing the bias we have tried to eliminate 😅. One thing worth thinking about is having interviewers request to add questions and perhaps an admin validating them before the interview, or increasing the amount of questions and let interviewers craft their own interview from a specific and pre-determined set of questions.
<file_sep>/frontend/src/hooks/useParticipants.js
import { useState, useEffect } from 'react';
import useVideoContext from './useVideoContext';
const useParticipants = () => {
const { room } = useVideoContext();
// room has a property "participants" of type Map<ParticipantSID, RemoteParticipant>
// we are only concerned with the values of the Map object
const [participants, setParticipants] = useState(
Array.from(room.participants.values()),
);
useEffect(() => {
const participantConnected = (participant) =>
setParticipants((prevParticipants) => [
...prevParticipants,
participant,
]);
const participantDisconnected = (participant) =>
setParticipants((prevParticipants) =>
prevParticipants.filter((p) => p !== participant),
);
room.on('participantConnected', participantConnected);
room.on('participantDisconnected', participantDisconnected);
return () => {
room.off('participantConnected', participantConnected);
room.off('participantDisconnected', participantDisconnected);
};
}, [room]);
return participants;
};
export default useParticipants;
<file_sep>/frontend/src/components/MeetingNotes/MeetingNotes.js
import React from 'react';
import {
Box,
Typography,
Paper,
makeStyles,
} from '@material-ui/core';
import MUIRichTextEditor from 'mui-rte';
import { convertToRaw } from 'draft-js';
import { useParams } from 'react-router-dom';
import RichTextEditor from '../../ui/RichTextEditor';
import { useFormikContext } from 'formik';
const useStyles = makeStyles((theme) => ({
paper: {
height: '100%',
},
title: {
color: '#829AB1',
textTransform: 'uppercase',
letterSpacing: '-1px',
fontSize: '1.1rem',
},
}));
const MeetingNotes = (props) => {
const classes = useStyles();
const { key } = useParams();
return (
<Paper className={classes.paper} elevation={0}>
<Box
height="100%"
display="flex"
flexDirection="column"
py={1}
pl={3}
pr={1}
>
<Typography className={classes.title} variant="h6" paragraph>
Meeting Notes
</Typography>
<Typography paragraph variant="body2" color="textSecondary">
Use this space to take notes during the interview. All
changes are saved automatically.
</Typography>
<Box flex="1" pb={2}>
<RichTextEditor name="notes" hash={`notes-${key}`} />
</Box>
</Box>
</Paper>
);
};
export default MeetingNotes;
<file_sep>/frontend/src/components/Controls/EndCallButton/EndCallButton.js
import React from 'react';
import { ROLES } from '../../../constants';
import EndCallButtonInterviewee from './EndCallButtonInterviewee';
import EndCallButtonInterviewer from './EndCallButtonInterviewer';
import { useAuth } from '../../AuthProvider/AuthProvider';
const EndCallButton = () => {
const { user } = useAuth();
if (user.role === ROLES.INTERVIEWER)
return <EndCallButtonInterviewer />;
else {
return <EndCallButtonInterviewee />;
}
};
export default EndCallButton;
<file_sep>/backend/api/validators/users.js
const validate = require('./validate');
const { body } = require('express-validator');
const { capitalizeString } = require('./sanitizers');
const validateSignUp = validate([
body('displayName')
.exists()
.isString()
.trim()
.notEmpty()
.customSanitizer(capitalizeString)
.withMessage('Invalid full name'),
body('email')
.exists()
.withMessage('Email is required')
.isEmail()
.withMessage('Email must be a valid email')
.trim(),
body('password')
.exists()
.isString()
.isLength({ min: 8, max: 20 })
.withMessage('Password must contain at least 8 characters'),
]);
const validateUpdateUser = validate([
body('displayName')
.exists()
.isString()
.trim()
.notEmpty()
.customSanitizer(capitalizeString)
.withMessage('Invalid full name'),
body('email')
.exists()
.withMessage('Email is required')
.isEmail()
.withMessage('Email must be a valid email')
.trim(),
body('password')
.exists()
.isString()
.notEmpty()
.withMessage('Invalid password'),
body('newPassword')
.exists()
.isString()
.isLength({ min: 8, max: 20 })
.withMessage('Password must contain at least 8 characters'),
]);
module.exports = {
validateSignUp,
validateUpdateUser,
};
<file_sep>/frontend/src/pages/Profile/Profile.js
import React from 'react';
import {
Box,
Paper,
Typography,
makeStyles,
} from '@material-ui/core';
import ProfileForm from './ProfileForm';
import useUpdateProfile from './useUpdateProfile';
import { useAuth } from '../../components/AuthProvider/AuthProvider';
const useStyles = makeStyles((theme) => ({
title: {
fontFamily: 'Roboto',
fontSize: theme.spacing(2),
fontWeight: 500,
},
}));
const Profile = () => {
const classes = useStyles();
const [updateProfile, { isLoading }] = useUpdateProfile();
const { user } = useAuth();
return (
<Box display="flex" justifyContent={['stretch', 'center']}>
<Box flex={[1, 0.45]}>
<Paper elevation={0}>
<Box py={[1.5, 3.5]} px={[2, 6]}>
<Typography className={classes.title} variant="h6">
Change your profile
</Typography>
<Box mt={1.5}>
<ProfileForm
initialValues={{
displayName: user.displayName,
email: user.email,
password: '',
newPassword: '',
confirmationPassword: '',
}}
onSubmit={async (values) => {
await updateProfile(values);
}}
isLoading={isLoading}
/>
</Box>
</Box>
</Paper>
</Box>
</Box>
);
};
export default Profile;
<file_sep>/frontend/src/components/InterviewStateProvider/actions/index.js
import {
UPDATE_QUESTION,
UPDATE_SCORECARD,
SET_INTERVIEW_QUESTIONS,
SET_SELECTED_QUESTION,
LOAD_INTERVIEW,
UPDATE_ATTRIBUTES,
UPDATE_INTERVIEW_STEP,
UPDATE_INTERVIEW,
UPDATE_QUESTION_IDS,
} from '../actionTypes';
export const loadInterviewAction = (dispatch, payload) => {
dispatch({ type: LOAD_INTERVIEW, payload });
};
export const updateQuestionAction = (
dispatch,
questionId,
payload,
) => {
dispatch({ type: UPDATE_QUESTION, questionId, payload });
};
export const updateAttributeAction = (
dispatch,
attributeId,
payload,
) => {
dispatch({
type: UPDATE_SCORECARD,
attributeId,
payload,
});
};
export const setInterviewQuestionsAction = (dispatch, questions) => {
dispatch({
type: SET_INTERVIEW_QUESTIONS,
questions,
});
};
export const setSelectedQuestionIndexAction = (
dispatch,
questionIndex,
) => {
dispatch({
type: SET_SELECTED_QUESTION,
questionIndex,
});
};
export const updateAttributesAction = (dispatch, attributes) => {
dispatch({ type: UPDATE_ATTRIBUTES, attributes });
};
export const updateInterviewStepAction = (
dispatch,
interviewStep,
) => {
dispatch({ type: UPDATE_INTERVIEW_STEP, interviewStep });
};
export const updateQuestionIdsAction = (dispatch, questionIds) => {
dispatch({ type: UPDATE_QUESTION_IDS, questionIds });
};
export const updateInterviewAction = (dispatch, payload) => {
dispatch({ type: UPDATE_INTERVIEW, payload });
};
<file_sep>/frontend/src/components/PeerMeeting/PeerMeeting.js
import React, { useRef, useEffect } from 'react';
import useVideoContext from '../../hooks/useVideoContext';
import useRoomState from '../../hooks/useRoomState';
import VideoStates from '../../ui/VideoStates';
import { Box, makeStyles } from '@material-ui/core';
import MainParticipant from '../MainParticipant/MainParticipant';
import Controls from '../Controls/Controls';
import { useParams } from 'react-router-dom';
import useTwilioAccessToken from '../../hooks/useTwilioAccessToken';
const useStyles = makeStyles((theme) => ({
videoContainer: {
borderRadius: 10,
background: '#000',
},
}));
const PeerMeeting = ({ displayName }) => {
const classes = useStyles();
const { key } = useParams();
const [token] = useTwilioAccessToken(displayName, key);
const { room, connect, isConnecting } = useVideoContext();
const roomState = useRoomState();
const isDisconnected = roomState === 'disconnected';
const cleanUpCallbackRef = useRef(() => {});
useEffect(() => {
if (room && room.disconnect)
cleanUpCallbackRef.current = () => {
room.disconnect();
};
}, [room]);
useEffect(() => {
if (token) connect(token);
}, [token]);
useEffect(() => {
return () => {
cleanUpCallbackRef.current();
};
}, []);
return (
<Box
display="flex"
flexDirection="column"
justifyContent="center"
minHeight="557px"
minWidth="864px"
position="relative"
color="#fff"
className={classes.videoContainer}
>
<VideoStates loading={isConnecting} disabled={isDisconnected}>
<MainParticipant />
<Controls />
</VideoStates>
</Box>
);
};
export default PeerMeeting;
<file_sep>/backend/scraper/submitAssessment.js
const config = require('../config');
const RATINGS = require('../enums/ratings');
const puppeteer = require('puppeteer');
const _ = require('lodash');
const OVERALL_RATINGS = {
[RATINGS.STRONG_NO]: 1,
[RATINGS.NO]: 2,
[RATINGS.YES]: 3,
[RATINGS.STRONG_YES]: 4,
};
const NUMERICAL_RATINGS = {
[RATINGS.STRONG_NO]: 1,
[RATINGS.NO]: 2,
[RATINGS.YES]: 3,
[RATINGS.STRONG_YES]: 4,
[RATINGS.MIXED]: 5,
};
const submitAssessment = async ({
candidate_id,
application_id,
interviewer,
interview_type,
overall_rating,
scorecard,
}) => {
const BASE_URL = `https://app2.greenhouse.io`;
const browser = await puppeteer.launch();
const page = await browser.newPage();
const APPLICATION_URL = `${BASE_URL}/people/${candidate_id}?application_id=${application_id}&src=search`;
await page.goto(APPLICATION_URL, { headless: false });
await page.type('#user_email', config.greenhouse.email);
await page.click('#submit_email_button');
await page.waitForSelector('#user_password', { visible: true });
await page.waitForSelector('#submit_password_button', { visible: true });
await page.type('#user_password', config.greenhouse.password);
await page.click('#submit_password_button');
await page.waitForNavigation();
const interviewStageId = await page
.$(`tr[name="${interview_type}"]`)
.then((element) => {
element.click();
return element;
})
.then((element) =>
page.evaluate((node) => node.getAttribute('stage_id'), element),
);
const scorecardHref = await page
.waitForSelector(
`tr[stage_id="${interviewStageId}"] td[title="View Interview Kit"]`,
)
.then((element) =>
page.evaluate((node) => node.getAttribute('href'), element),
);
const scorecardLink = `${BASE_URL}${scorecardHref}&new=true#scorecard`;
await page.goto(scorecardLink);
await page.waitForSelector(
`li[data-rating-id="${OVERALL_RATINGS[overall_rating]}"]`,
{
visible: true,
},
);
const scorecardRatings = scorecard.reduce(
(acc, curr) => ({
...acc,
[curr.name]: { ...curr },
}),
{},
);
// page.on('console', (msg) => {
// for (let i = 0; i < msg._args.length; ++i)
// console.log(`${i}: ${msg._args[i]}`);
// });
await page.evaluate(
(attributesMap, NUMERICAL_RATINGS, RATINGS) => {
const attributes = document.querySelectorAll(
'table.scorecard-attributes-table td.name',
);
for (const attributeNode of attributes) {
const assessmentAttribute = attributesMap[attributeNode.innerText];
const has_rating =
assessmentAttribute &&
assessmentAttribute.rating !== RATINGS.NO_DECISION;
if (!assessmentAttribute || !has_rating) continue;
const rating = assessmentAttribute.rating;
const ratingNode = attributeNode.nextElementSibling.firstElementChild.querySelector(
`span[data-rating-id="${NUMERICAL_RATINGS[rating]}"]`,
);
ratingNode.click();
}
},
scorecardRatings,
NUMERICAL_RATINGS,
RATINGS,
);
await page.click(`li[data-rating-id="${OVERALL_RATINGS[overall_rating]}"]`);
await page.click('#s2id_scorecard_interviewer_id');
await page.type('#s2id_autogen1_search', interviewer);
await page.waitFor(3500);
await page.type('#s2id_autogen1_search', String.fromCharCode(13));
await page.waitFor('#submit_scorecard_button');
await page.focus('#submit_scorecard_button');
await page.keyboard.type('\n');
await page.close();
await browser.close();
console.log('done');
};
module.exports = submitAssessment;
<file_sep>/frontend/src/pages/AssessmentPage/AssessmentPage.js
import React from 'react';
import { Box, Grid } from '@material-ui/core';
import InterviewStateProvider from '../../components/InterviewStateProvider/InterviewStateProvider';
import Assessment from '../../components/Assessment/Assessment';
import MeetingInformation from '../../components/InterviewerRoom/MeetingInformation/MeetingInformation';
const AssessmentPage = () => {
return (
<InterviewStateProvider>
<Box p={0.5}>
<Grid container spacing={1}>
<Grid spacing={1} container item lg={8}>
<Grid item lg={12}>
<Assessment />
</Grid>
</Grid>
<Grid item lg={4}>
<MeetingInformation />
</Grid>
</Grid>
</Box>
</InterviewStateProvider>
);
};
export default AssessmentPage;
<file_sep>/backend/api/routes/scorecards.js
const router = require('express').Router();
const { getScorecards } = require('../controllers/scorecards');
router.get('/:applicationId', getScorecards);
module.exports = router;
<file_sep>/frontend/src/ui/Spinners/LoadingContainer.js
import React from 'react';
import LoadingSpinner from './LoadingSpinner';
const LoadingContainer = ({ isLoading, children, ...props }) => {
return <>{isLoading ? <LoadingSpinner {...props} /> : children}</>;
};
export default LoadingContainer;
<file_sep>/frontend/src/components/AuthProvider/AuthProvider.js
import React, { createContext, useState, useContext } from 'react';
import { jwtVerifyAndDecode } from '../../utils';
import useLogin from './useLogin';
const getInitialState = () => {
const token = jwtVerifyAndDecode(localStorage.token);
return token.isValid
? {
isAuthenticated: true,
...token.payload,
}
: {
isAuthenticated: false,
role: 'guest',
};
};
const AuthContext = createContext(null);
export const AuthProvider = ({ children }) => {
const [{ isAuthenticated, ...user }, setState] = useState(
getInitialState(),
);
const [
loginMutation,
{ isLoading, isSuccess, isError },
] = useLogin();
const setUser = (data) => {
localStorage.setItem('token', data.token);
setState({
isAuthenticated: true,
...data,
});
};
const login = async (credentials) => {
const data = await loginMutation(credentials);
if (data) setUser(data);
};
return (
<AuthContext.Provider
value={{
user,
isAuthenticated,
login,
setUser,
isLoading,
isSuccess,
isError,
}}
>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
<file_sep>/frontend/src/components/Controls/EndCallButton/EndCallButtonInterviewee.js
import React from 'react';
import useVideoContext from '../../../hooks/useVideoContext';
import { Tooltip, IconButton, makeStyles } from '@material-ui/core';
import { CallEnd } from '@material-ui/icons';
const useStyles = makeStyles((theme) => ({
endCallButton: {
backgroundColor: 'hsl(354, 85%, 44%)',
'&:hover': {
backgroundColor: 'hsl(356, 75%, 53%)',
},
},
}));
const EndCallButtonInterviewee = (props) => {
const { room } = useVideoContext();
const classes = useStyles();
return (
<Tooltip title="End Call" placement="top">
<IconButton
className={classes.endCallButton}
color="inherit"
onClick={() => {
room.disconnect();
}}
>
<CallEnd />
</IconButton>
</Tooltip>
);
};
export default EndCallButtonInterviewee;
<file_sep>/frontend/src/hooks/useDialog.js
import { useState, useCallback } from 'react';
const useDialog = (initialState = false) => {
const [open, setDialogOpen] = useState(initialState);
const handleClose = useCallback(() => {
setDialogOpen(false);
}, []);
const handleOpen = useCallback(() => {
setDialogOpen(true);
}, []);
return [open, { handleClose, handleOpen, setDialogOpen }];
};
export default useDialog;
<file_sep>/frontend/src/components/LocalAudioLevelIndicator/LocalAudioLevelIndicator.js
import React from 'react';
import AudioLevelIndicator from '../AudioLevelIndicator/AudioLevelIndicator';
import useVideoContext from '../../hooks/useVideoContext';
export default function LocalAudioLevelIndicator() {
const { audioTrack } = useVideoContext();
return <AudioLevelIndicator size={30} audioTrack={audioTrack} />;
}
<file_sep>/frontend/src/components/Scorecard/Attribute.js
import React, { useState, useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import {
Box,
Typography,
Link,
TextField,
makeStyles,
} from '@material-ui/core';
import Ratings from '../Ratings/Ratings';
import { useFormikContext } from 'formik';
import _ from 'lodash';
import useInterviewStateContext from '../../hooks/useInterviewStateContext';
const useStyles = makeStyles((theme) => ({
attribute: {
'&:hover $link': {
visibility: 'visible',
},
},
link: {
visibility: 'hidden',
},
}));
const Attribute = ({ attributeId }) => {
const classes = useStyles();
const [open, setOpen] = useState(false);
const { scorecard, updateAttribute } = useInterviewStateContext();
const onChangeRating = useCallback(
(rating) => {
updateAttribute(attributeId, { rating });
},
[updateAttribute, attributeId],
);
const onChangeNote = useCallback(
(ev) => {
const note = ev.target.value;
updateAttribute(attributeId, { note });
},
[updateAttribute, attributeId],
);
const attribute = scorecard[attributeId];
return (
<Box
borderBottom="1px solid #D9E2EC"
display="flex"
justifyContent="space-between"
py={0.5}
pl={2}
mb={1}
className={classes.attribute}
>
<Typography variant="body2">{attribute.name}</Typography>
<Box display="flex">
<Box className={classes.link} mr={1}>
<Link
onClick={() => {
setOpen((open) => !open);
}}
>
{open ? 'Close' : 'Add'} note
</Link>
</Box>
<Box>
<Ratings
value={attribute.rating}
onChange={onChangeRating}
/>
{open && (
<Box mt={0.5}>
<Typography
style={{
fontWeight: 400,
color: 'hsl(210, 22%, 49%)',
}}
color="textSecondary"
variant="body2"
gutterBottom
>
Please Explain:
</Typography>
<TextField
value={attribute.note}
multiline={true}
rows={3}
variant="outlined"
fullWidth
onChange={onChangeNote}
/>
</Box>
)}
</Box>
</Box>
</Box>
);
};
export default React.memo(Attribute);
<file_sep>/frontend/src/pages/NotFound/NotFound.js
import React from 'react';
import { Typography, Box, Button } from '@material-ui/core';
import { Link } from 'react-router-dom';
const NotFound = () => (
<Box
pt={6}
display="flex"
flexDirection="column"
alignItems="center"
>
<Box mb={3}>
<Typography color="primary" variant="h1">
x_x
</Typography>
</Box>
<Typography variant="h3">404 not found...</Typography>
<Box mt={2}>
<Button color="primary" component={Link} to="/">
Homescreen
</Button>
</Box>
</Box>
);
export default NotFound;
<file_sep>/frontend/src/pages/Profile/ProfileForm.js
import React from 'react';
import { Form, withFormik } from 'formik';
import MuiFormikTextField from '../../ui/Formik/MuiFormikTextField';
import * as yup from 'yup';
import { Box } from '@material-ui/core';
import CircularProgressButton from '../../ui/Buttons/CircularProgressButton';
import ButtonPrimary from '../../ui/Buttons/ButtonPrimary';
const ProfileForm = ({ isLoading }) => {
return (
<Form>
<Box mb={1}>
<MuiFormikTextField
name="displayName"
label="Display Name"
margin="dense"
color="primary"
id="displayName"
InputLabelProps={{ shrink: true, htmlFor: 'displayName' }}
FormControlProps={{ fullWidth: true }}
withGemoStyles
/>
</Box>
<Box mb={1}>
<MuiFormikTextField
name="email"
label="Email"
margin="dense"
color="primary"
id="email"
InputLabelProps={{ shrink: true, htmlFor: 'email' }}
FormControlProps={{ fullWidth: true }}
withGemoStyles
/>
</Box>
<Box mb={1}>
<MuiFormikTextField
name="password"
label="Password"
type="<PASSWORD>"
color="primary"
margin="dense"
id="password"
InputLabelProps={{ shrink: true, htmlFor: 'password' }}
FormControlProps={{ fullWidth: true }}
withGemoStyles
/>
</Box>
<Box mb={1}>
<MuiFormikTextField
name="newPassword"
label="New Password"
type="<PASSWORD>"
color="primary"
margin="dense"
id="newPassword"
InputLabelProps={{ shrink: true, htmlFor: 'newPassword' }}
FormControlProps={{ fullWidth: true }}
withGemoStyles
/>
</Box>
<Box mb={2.5}>
<MuiFormikTextField
name="confirmationPassword"
label="Confirm Password"
type="<PASSWORD>"
color="primary"
margin="dense"
id="confirmationPassword"
InputLabelProps={{
shrink: true,
htmlFor: 'confirmationPassword',
}}
FormControlProps={{ fullWidth: true }}
withGemoStyles
/>
</Box>
<Box>
<CircularProgressButton isLoading={isLoading}>
<ButtonPrimary type="submit" fullWidth>
Save
</ButtonPrimary>
</CircularProgressButton>
</Box>
</Form>
);
};
yup.addMethod(yup.string, 'isSameAs', function (ref, end) {
return this.test({
name: 'isSameAs',
message: 'Passwords do not match',
exclusive: false,
test: function (v) {
return v === this.resolve(ref);
},
});
});
const validationSchema = yup.object().shape({
displayName: yup
.string()
.trim()
.nullable()
.required('You must enter a display name'),
email: yup
.string()
.email()
.trim()
.nullable()
.required('You must enter a valid e-mail'),
password: yup
.string()
.nullable()
.required('You must enter your password'),
newPassword: yup
.string()
.min(8, 'Password must be at least 8 characters')
.nullable()
.required('You must enter a password'),
confirmationPassword: yup
.string()
.nullable()
.required('Passwords do not match')
.isSameAs(yup.ref('newPassword')),
});
const formikOptions = {
mapPropsToValues: ({ initialValues }) => ({ ...initialValues }),
displayName: 'ProfileForm',
handleSubmit: (values, { setSubmitting, setFieldValue, props }) => {
values = validationSchema.cast(values);
props.onSubmit(values);
setFieldValue('password', '', false);
setFieldValue('confirmationPassword', '', false);
setFieldValue('newPassword', '', false);
},
validationSchema,
};
export default withFormik(formikOptions)(ProfileForm);
<file_sep>/backend/db/seeds/index.js
const jobSeeder = require('./jobs');
const userSeeder = require('./users');
const interviewSeeder = require('./interview');
const logger = require('../../utils/logger');
(async () => {
try {
const jobs = await jobSeeder.createJobs();
const users = await userSeeder.createUsers();
// Delete this call if you do not want to create an interview as part of the seeding script.
await Promise.all(
users.map((user) =>
interviewSeeder.createInterview(
{
job_id: '4451682002',
job_name: '<NAME>',
candidate_id: '27190588002',
application_id: '55033188002',
interview_type: 'Technical Interview',
},
user._id,
),
),
);
logger.info('SEEDING completed');
process.exit();
} catch (err) {
logger.log('error', err.message, { meta: err });
}
})();
<file_sep>/backend/api/controllers/auth.js
const { createToken } = require('../middleware/auth');
const authService = require('../../services/auth');
const login = async function (req, res, next) {
try {
const { email, password } = req.body;
// The call to authUser will throw an error if credentials do not match.
let { _id: id, role, displayName } = await authService.authUser(
email,
password,
);
let token = createToken({
id,
role,
email,
displayName,
});
return res.status(200).json({
id,
role,
email,
displayName,
token,
});
} catch (err) {
return next(err);
}
};
module.exports = {
login,
};
<file_sep>/backend/api/validators/interviews.js
const validate = require('./validate');
const { body, param } = require('express-validator');
const RATINGS = require('../../enums/ratings');
const { capitalizeString } = require('./sanitizers');
const validateCreateInterview = validate([
body('date').exists().isISO8601().withMessage('Invalid date'),
body('application_id')
.exists()
.isString()
.trim()
.notEmpty()
.withMessage('Invalid application_id'),
body('interview_type')
.exists()
.isString()
.trim()
.notEmpty()
.customSanitizer(capitalizeString)
.withMessage('Invalid interview type'),
]);
const validateQuestions = validate([
body('questions').exists().isArray().withMessage('Invalid questions'),
body('questions.*.note')
.exists()
.isString()
.trim()
.withMessage('Invalid question note'),
body('questions.*.rating')
.exists()
.customSanitizer((value) => (value ? value : RATINGS.NO_DECISION))
.isIn([
RATINGS.MIXED,
RATINGS.NO,
RATINGS.STRONG_NO,
RATINGS.STRONG_YES,
RATINGS.YES,
RATINGS.NO_DECISION,
])
.withMessage('Invalid question rating'),
]);
const validateKeyParam = validate([
param('key').exists().isString().withMessage('Invalid key'),
]);
const validateSubmitInterview = validate([
body('takeAways').exists().isString().withMessage('Invalid notes'),
body('questions').exists().isArray().withMessage('Invalid questions'),
// body('questions.*.id')
// .exists()
// .isString()
// .isMongoId()
// .withMessage('Invalid question id'),
body('questions.*.note')
.exists()
.isString()
.trim()
.withMessage('Invalid question note'),
body('questions.*.rating')
.exists()
.customSanitizer((value) => (value ? value : RATINGS.NO_DECISION))
.isIn([
RATINGS.MIXED,
RATINGS.NO,
RATINGS.STRONG_NO,
RATINGS.STRONG_YES,
RATINGS.YES,
RATINGS.NO_DECISION,
])
.withMessage('Invalid question rating'),
body('scorecard').exists().isArray().withMessage('Invalid questions'),
// body('scorecard.*.id')
// .exists()
// .isString()
// .isMongoId()
// .withMessage('Invalid scorecard id'),
body('scorecard.*.name')
.exists()
.isString()
.trim()
.withMessage('Invalid scorecard name'),
body('scorecard.*.type')
.exists()
.isString()
.trim()
.withMessage('Invalid scorecard type'),
body('scorecard.*.note')
.exists()
.isString()
.trim()
.withMessage('Invalid scorecard note'),
body('scorecard.*.rating')
.exists()
.customSanitizer((value) => (value ? value : RATINGS.NO_DECISION))
.isIn([
RATINGS.MIXED,
RATINGS.NO,
RATINGS.STRONG_NO,
RATINGS.STRONG_YES,
RATINGS.YES,
RATINGS.NO_DECISION,
])
.withMessage('Invalid scorecard rating'),
body('overall_rating')
.exists()
.customSanitizer((value) => (value ? value : RATINGS.NO_DECISION))
.isIn([
RATINGS.MIXED,
RATINGS.NO,
RATINGS.STRONG_NO,
RATINGS.STRONG_YES,
RATINGS.YES,
RATINGS.NO_DECISION,
])
.withMessage('Invalid overall rating'),
]);
module.exports = {
validateCreateInterview,
validateKeyParam,
validateSubmitInterview,
validateQuestions,
};
<file_sep>/frontend/src/components/LocalVideoPreview/LocalVideoPreview.js
import React from 'react';
import VideoTrack from '../VideoTrack/VideoTrack';
import Controls from '../Controls/Controls';
import useVideoContext from '../../hooks/useVideoContext';
import VideoStates from '../../ui/VideoStates';
const LocalVideoPreview = () => {
const { videoTrack, isAcquiringLocalTracks } = useVideoContext();
return (
<>
<VideoStates
loading={isAcquiringLocalTracks}
disabled={!videoTrack}
>
<VideoTrack track={videoTrack} />
</VideoStates>
<Controls />
</>
);
};
export default LocalVideoPreview;
<file_sep>/frontend/src/pages/Interviews/InterviewList/InterviewList.js
import React from 'react';
import InterviewItem from '../InterviewItem/InterviewItem';
import { Grid } from '@material-ui/core';
const InterviewList = ({ interviews, fallback }) => {
return (
<>
{interviews.length > 0 ? (
<Grid container spacing={3}>
{interviews.map((interview) => (
<Grid key={interview.id} item lg={4} sm={6} xs={12}>
<InterviewItem interview={interview} />
</Grid>
))}
</Grid>
) : (
fallback
)}
</>
);
};
export default InterviewList;
<file_sep>/frontend/src/components/Scorecard/ScorecardAttribute.js
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import {
ListItem,
ListItemText,
Collapse,
makeStyles,
Typography,
Box,
} from '@material-ui/core';
import { ExpandLess, ExpandMore } from '@material-ui/icons';
import Attribute from './Attribute';
const useStyles = makeStyles((theme) => ({
icon: {
cursor: 'pointer',
color: theme.palette.blueGrey[500],
transform: 'all .2s',
'&:hover': {
color: theme.palette.blueGrey[700],
},
},
typeTitle: {
fontWeight: 700,
},
collapse: {
paddingTop: theme.spacing(1),
},
}));
const ScorecardAttribute = ({ type, attributeIds = [] }) => {
const classes = useStyles();
return (
<Box mb={1.5}>
<Typography
variant="body2"
className={classes.typeTitle}
color="textSecondary"
gutterBottom
>
{type}
</Typography>
{attributeIds.map((attributeId) => (
<Attribute attributeId={attributeId} key={attributeId} />
))}
</Box>
);
};
export default React.memo(ScorecardAttribute);
<file_sep>/frontend/src/components/InterviewStateProvider/schemas/questions.js
import { schema } from 'normalizr';
export const questions = new schema.Entity('questions');
<file_sep>/backend/utils/logger.js
const winston = require('winston');
winston.addColors({ info: 'blue' });
const colorizer = winston.format.colorize();
const customFormat = winston.format.combine(
winston.format.label({
label: '[LOGGER]',
}),
winston.format.timestamp({
format: 'YY-MM-DD HH:MM:SS',
}),
winston.format.printf((info) => {
if (info.meta && info.meta instanceof Error) {
info.message = `${info.message} ${info.meta.stack}`;
}
return colorizer.colorize(
info.level,
`${info.label} [${info.timestamp}] [${info.level.toUpperCase()}]: ${
info.message
}`,
);
}),
);
const logger = winston.createLogger({
transports: [
new winston.transports.Console({
level: 'info',
format: customFormat,
}),
],
});
logger.stream = {
write: function (message, encoding) {
logger.info(message);
},
};
module.exports = logger;
<file_sep>/backend/scraper/index.js
const greenhouseScraper = {
submitAssessment: require('./submitAssessment'),
};
module.exports = greenhouseScraper;
<file_sep>/frontend/src/components/Scorecard/Scorecard.js
import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import { Box, makeStyles } from '@material-ui/core';
import _ from 'lodash';
import ScorecardAttribute from './ScorecardAttribute';
import useInterviewStateContext from '../../hooks/useInterviewStateContext';
const useStyles = makeStyles((theme) => ({
overflowY: {
overflowY: 'auto',
'&::-webkit-scrollbar-track': {
'-webkit-box-shadow': 'none',
backgroundColor: 'transparent',
},
'&::-webkit-scrollbar': {
width: 6,
backgroundColor: 'transparent',
},
'&::-webkit-scrollbar-thumb': {
backgroundColor: theme.palette.secondary.light,
border: `1px solid ${theme.palette.secondary.light}`,
borderRadius: 32,
},
},
}));
const Scorecard = ({ attributeTypes }) => {
const classes = useStyles();
return (
<Box pb={2} pr={1} className={classes.overflowY}>
{Object.keys(attributeTypes).map((type) => (
<ScorecardAttribute
type={type}
attributeIds={attributeTypes[type]}
key={type}
/>
))}
</Box>
);
};
export default React.memo(Scorecard);
<file_sep>/frontend/src/components/InterviewStateProvider/schemas/scorecard.js
import { schema } from 'normalizr';
export const scorecard = new schema.Entity('scorecard');
<file_sep>/frontend/src/pages/Login/LoginForm.js
import React from 'react';
import { Form, withFormik } from 'formik';
import MuiFormikTextField from '../../ui/Formik/MuiFormikTextField';
import * as yup from 'yup';
import { Box } from '@material-ui/core';
import CircularProgressButton from '../../ui/Buttons/CircularProgressButton';
import ButtonPrimary from '../../ui/Buttons/ButtonPrimary';
const LoginForm = ({ isLoading }) => {
return (
<Form>
<Box mb={1}>
<MuiFormikTextField
name="email"
variant="outlined"
label="Email"
margin="dense"
color="secondary"
id="email"
InputLabelProps={{ shrink: true, htmlFor: 'email' }}
FormControlProps={{ fullWidth: true }}
withGemoStyles
/>
</Box>
<Box mb={1}>
<MuiFormikTextField
name="password"
label="Password"
type="password"
variant="outlined"
color="secondary"
margin="dense"
id="password"
InputLabelProps={{ shrink: true, htmlFor: 'password' }}
FormControlProps={{ fullWidth: true }}
withGemoStyles
/>
</Box>
<Box mt={1.5}>
<CircularProgressButton isLoading={isLoading}>
<ButtonPrimary type="submit" fullWidth>
Sign in
</ButtonPrimary>
</CircularProgressButton>
</Box>
</Form>
);
};
const validationSchema = yup.object().shape({
email: yup
.string()
.trim()
.email('You must enter a valid email')
.nullable()
.required('You must enter an e-mail'),
password: yup
.string()
.nullable()
.required('You must enter a password'),
});
const formikOptions = {
mapPropsToValues: ({ initialValues }) => ({ ...initialValues }),
displayName: 'LoginForm',
enableReinitialize: true,
handleSubmit: (values, { setSubmitting, props }) => {
values = validationSchema.cast(values);
props.onSubmit(values);
setSubmitting(false);
},
validationSchema,
};
export default withFormik(formikOptions)(LoginForm);
<file_sep>/backend/subscribers/channels.js
module.exports = {
greenhouseChannel: 'greenhouseChannel#',
};
<file_sep>/frontend/src/components/Room/Room.js
import React, { useState } from 'react';
import RoomDoor from '../RoomDoor/RoomDoor';
import RoomDoorLayout from '../../ui/RoomDoorLayout';
import IntervieweeRoom from '../IntervieweeRoom/IntervieweeRoom';
import InterviewerRoom from '../InterviewerRoom/InterviewerRoom';
import InterviewStateProvider from '../InterviewStateProvider/InterviewStateProvider';
import { useAuth } from '../AuthProvider/AuthProvider';
const Room = (props) => {
const [joined, setJoined] = useState(false);
const { user, isAuthenticated } = useAuth();
const [displayName, setDisplayName] = useState(
isAuthenticated ? user.displayName : '',
);
const joinMeeting = () => {
setJoined(true);
};
return (
<>
{joined ? (
isAuthenticated ? (
<InterviewStateProvider>
<InterviewerRoom displayName={displayName} />
</InterviewStateProvider>
) : (
<IntervieweeRoom displayName={displayName} />
)
) : (
<RoomDoorLayout>
<RoomDoor
displayName={displayName}
setDisplayName={setDisplayName}
joinMeeting={joinMeeting}
/>
</RoomDoorLayout>
)}
</>
);
};
export default Room;
<file_sep>/frontend/src/pages/Interview/Interview.js
import React from 'react';
import useIsInterviewValid from '../../hooks/useIsInterviewValid';
import { useParams } from 'react-router-dom';
import Room from '../../components/Room/Room';
import NotValidInterview from './NotValidInterview';
import LoadingContainer from '../../ui/Spinners/LoadingContainer';
import { VideoProvider } from '../../components/VideoProvider';
const Interview = () => {
const { key } = useParams();
const [valid, { isLoading }] = useIsInterviewValid(key);
return (
<LoadingContainer isLoading={isLoading || valid === undefined}>
{valid ? (
<VideoProvider
onDisconnect={(room) => {
room.localParticipant.tracks.forEach(({ track }) => {
track.stop();
track.detach();
});
}}
>
<Room />
</VideoProvider>
) : (
<NotValidInterview key={key} />
)}
</LoadingContainer>
);
};
export default Interview;
<file_sep>/frontend/src/ui/Buttons/ButtonPrimary.js
import React from 'react';
import { withStyles, Button } from '@material-ui/core';
const ButtonPrimary = withStyles((theme) => ({
root: {
borderRadius: 50,
textTransform: 'capitalize',
fontWeight: 500,
backgroundColor: theme.palette.primary.main,
color: '#fff',
padding: `${theme.spacing(0.25)}px ${theme.spacing(1)}px`,
'&:hover': {
backgroundColor: theme.palette.primary.dark,
},
},
disabled: {
backgroundColor: '#f5f6fa',
},
}))((props) => <Button {...props} variant="outlined" />);
export default ButtonPrimary;
<file_sep>/frontend/src/utils/index.js
import jwtDecode from 'jwt-decode';
import { INTERVIEW_STATUS, INTERVIEW_STEP } from '../constants';
export const isMobile = (() => {
if (
typeof navigator === 'undefined' ||
typeof navigator.userAgent !== 'string'
) {
return false;
}
return /Mobile/.test(navigator.userAgent);
})();
export const jwtVerifyAndDecode = (token) => {
if (token) {
let jwt = jwtDecode(token);
let current_time = Date.now().valueOf() / 1000;
if (jwt.exp < current_time) {
localStorage.removeItem('token');
window.location.href = `${process.env.PUBLIC_URL}/`;
return { isValid: false };
} else return { isValid: true, payload: jwt };
}
return { isValid: false };
};
export const getInterviewStepFromStatus = (status) => {
switch (status) {
case INTERVIEW_STATUS.AWAITING_ASSESSMENT:
return INTERVIEW_STEP.ASSESSMENT;
case INTERVIEW_STATUS.COMPLETED:
return INTERVIEW_STEP.ASSESSMENT;
case INTERVIEW_STATUS.SCHEDULED:
return INTERVIEW_STEP.CALL;
default:
return '';
}
};
<file_sep>/backend/db/seeds/users.js
const db = require('../index');
var userSeed = require('./users.json');
const createUsers = async () => {
return await Promise.all(userSeed.users.map((user) => db.User.create(user)));
};
module.exports = {
createUsers,
};
<file_sep>/backend/services/harvest.js
/**
* This service is used to hit the Harvest API endpoints.
* Currently, this is used to submit an interview assessment to greenhouse.
* The getHarvestScorecards method is not yet used in our interface
*/
const config = require('../config');
const axios = require('axios');
const { ApplicationNotFound } = require('../errors/');
const token = Buffer.from(`${config.harvest.apiKey}:`).toString('base64');
axios.defaults.headers.common['Authorization'] = `Basic ${token}`;
const BASE_URL = `https://harvest.greenhouse.io/v1`;
const getHarvestScorecards = async (applicationId) => {
const response = await axios({
method: 'GET',
url: `${BASE_URL}/applications/${applicationId}/scorecards`,
});
const [harvestScorecard] = response.data;
const scorecards = harvestScorecard.attributes.map(({ name, type }) => ({
name,
type,
}));
const questions = harvestScorecard.questions.map(({ id, question }) => ({
id,
question,
}));
return { scorecards, questions };
};
const getApplication = async (applicationId) => {
try {
const response = await axios({
method: 'GET',
url: `${BASE_URL}/applications/${applicationId}/`,
});
const { candidate_id, jobs } = response.data;
// Always returns an array containing only one job.
const job = jobs[0];
return {
...response.data,
candidate_id,
job_name: job.name,
job_id: job.id,
};
} catch (err) {
if (err.response) {
// Then axios error
if (err.response.status === 404) {
throw new ApplicationNotFound();
}
}
throw err;
}
};
module.exports = {
getHarvestScorecards,
getApplication,
};
<file_sep>/frontend/src/App.js
import React, { Suspense } from 'react';
import { useAuth } from './components/AuthProvider/AuthProvider';
import FullPageSpinner from './ui/Spinners/FullPageSpinner';
const AuthenticatedApp = React.lazy(() =>
import('./components/AuthenticatedApp/AuthenticatedApp'),
);
const UnauthenticatedApp = React.lazy(() =>
import('./components/UnauthenticatedApp/UnauthenticatedApp'),
);
const App = () => {
const { isAuthenticated } = useAuth();
return (
<Suspense
fallback={
<FullPageSpinner size={36} thickness={4} disableShrink />
}
>
{isAuthenticated ? (
<AuthenticatedApp />
) : (
<UnauthenticatedApp />
)}
</Suspense>
);
};
export default App;
<file_sep>/frontend/src/pages/Interviews/InterviewFallback/InterviewFallback.js
import React from 'react';
import {
EventBusy,
Assignment,
AssignmentTurnedIn,
} from '@material-ui/icons';
import { makeStyles, Box, Typography } from '@material-ui/core';
import { INTERVIEW_STATUS } from '../../../constants';
const useStyles = makeStyles((theme) => ({
circle: {
borderRadius: '50%',
width: 80,
height: 80,
background: 'hsl(247deg 47% 41%)',
color: 'white',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
icon: {
fontSize: '2.5rem',
},
}));
const InterviewFallback = ({ filter }) => {
const classes = useStyles();
let fallbackByFilter;
switch (filter) {
case INTERVIEW_STATUS.AWAITING_ASSESSMENT:
fallbackByFilter = {
icon: <AssignmentTurnedIn />,
label: 'No awaiting assessments',
};
break;
case INTERVIEW_STATUS.COMPLETED:
fallbackByFilter = {
icon: <Assignment />,
label: 'Some assessments might be pending...',
};
break;
case INTERVIEW_STATUS.SCHEDULED:
fallbackByFilter = {
icon: <EventBusy />,
label: 'No scheduled interviews',
};
break;
default:
return <></>;
}
return (
<Box
minHeight="45vh"
display="flex"
alignItems="center"
flexDirection="column"
justifyContent="center"
>
<Box mb={1.5} className={classes.circle}>
{React.cloneElement(fallbackByFilter.icon, {
className: classes.icon,
})}
</Box>
<Typography variant="h6">{fallbackByFilter.label}</Typography>
</Box>
);
};
export default InterviewFallback;
<file_sep>/frontend/src/components/NewInterview/useCreateInterview.js
import React from 'react';
import PropTypes from 'prop-types';
import { useMutation } from 'react-query';
import api from '../../api';
const useCreateInterview = (props) => {
const [mutate, options] = useMutation(api.createInterview);
return [mutate, options];
};
export default useCreateInterview;
<file_sep>/frontend/src/components/Assessment/Assessment.js
import React from 'react';
import {
Typography,
Box,
makeStyles,
Paper,
Button,
Divider,
SvgIcon,
Link,
LinearProgress,
} from '@material-ui/core';
import TakeAways from './TakeAways/TakeAways';
import OverallRating from './OverallRating/OverallRating';
import Scorecard from '../Scorecard/Scorecard';
import { ReactComponent as MagicIcon } from '../../assets/magic.svg';
import useInterviewStateContext from '../../hooks/useInterviewStateContext';
import { useParams, useHistory } from 'react-router-dom';
import ButtonPrimary from '../../ui/Buttons/ButtonPrimary';
import CircularProgressButton from '../../ui/Buttons/CircularProgressButton';
const useStyles = makeStyles((theme) => ({
paper: {
border: `1px solid #D6D2F9`,
},
title: {
color: '#829AB1',
textTransform: 'uppercase',
letterSpacing: '-1px',
fontSize: '1.1rem',
},
label: {
fontWeight: 700,
color: '#102A43',
marginRight: theme.spacing(0.5),
},
helperText: {
color: theme.palette.blueGrey[500],
},
iconButton: {
border: `1px solid ${theme.palette.primary.main}`,
backgroundColor: theme.palette.primary.main,
padding: theme.spacing(0.375),
'&:hover': {
border: `1px solid ${theme.palette.primary.dark}`,
backgroundColor: theme.palette.primary.dark,
},
},
icon: {
fontSize: '1rem',
marginRight: theme.spacing(0.25),
},
link: {
color: theme.palette.primary.main,
cursor: 'pointer',
},
}));
const Assessment = () => {
const classes = useStyles();
const { key } = useParams();
const {
generateScores,
saveAssessment,
scorecardByType,
isLoadingScores,
isLoadingAssessment,
} = useInterviewStateContext();
const history = useHistory();
return (
<Paper className={classes.paper} elevation={0}>
<Box py={1} pl={3} pr={1}>
<Box>
<Typography
className={classes.title}
variant="h6"
paragraph
>
Assessment
</Typography>
<TakeAways />
<Box
display="flex"
alignItems="center"
justifyContent="space-between"
mb={0.5}
>
<Typography
variant="body1"
className={classes.label}
paragraph
>
Scorecard
</Typography>
<Box
display="flex"
alignItems="center"
component={Link}
onClick={() => generateScores(key)}
className={classes.link}
>
<SvgIcon className={classes.icon} color="primary">
<MagicIcon />
</SvgIcon>
Generate ratings
</Box>
</Box>
{isLoadingScores && <LinearProgress color="secondary" />}
<Scorecard attributeTypes={scorecardByType} />
<Typography variant="body1" className={classes.label}>
Overall Recommendation{' '}
<Typography
variant="body2"
component="span"
className={classes.helperText}
>
— Did the candidate pass the interview?
</Typography>
</Typography>
<OverallRating />
<Box my={2}>
<Divider />
</Box>
<Box textAlign="right" pb={1}>
<CircularProgressButton isLoading={isLoadingAssessment}>
<ButtonPrimary
type="submit"
onClick={async () => {
await saveAssessment();
history.push('/');
}}
>
Save
</ButtonPrimary>
</CircularProgressButton>
</Box>
</Box>
</Box>
</Paper>
);
};
export default Assessment;
<file_sep>/backend/api/controllers/twilio.js
const twilioService = require('../../services/twilio');
const interviewsService = require('../../services/interviews');
const { InterviewNotFound } = require('../../errors');
// This route is used to get the access token, which will later be used with the twilio js sdk to connect to the Twilio servers.
const getTwilioAccessToken = async (req, res, next) => {
try {
const { key, display_name } = req.query;
const isValid = await interviewsService.isInterviewValid(key);
if (!isValid) throw new InterviewNotFound();
const accessToken = await twilioService.getTwilioAccessToken(
display_name,
key,
);
return res.json({ accessToken });
} catch (err) {
next(err);
}
};
module.exports = {
getTwilioAccessToken,
};
<file_sep>/backend/config/index.js
const dotenv = require('dotenv');
dotenv.config();
module.exports = {
port: process.env.PORT,
databaseUrl: process.env.DATABASE_URL,
jwt: {
secret: process.env.JWT_SECRET,
expirationTime: process.env.JWT_EXPIRATION_TIME,
},
twilio: {
accountSid: process.env.TWILIO_ACCOUNT_SID,
apiKeySid: process.env.TWILIO_API_KEY_SID,
apiKeySecret: process.env.TWILIO_API_KEY_SECRET,
maxAllowedSessionDuration: process.env.TWILIO_MAX_ALLOWED_SESSION_DURATION,
},
harvest: {
apiKey: process.env.HARVEST_API_KEY,
},
greenhouse: {
email: process.env.GREENHOUSE_EMAIL,
password: <PASSWORD>,
},
};
<file_sep>/frontend/src/components/ErrorDialogFallback/ErrorDialogFallback.js
import React from 'react';
import {
Dialog,
DialogTitle,
DialogContentText,
DialogActions,
Button,
DialogContent,
} from '@material-ui/core';
import useDialog from '../../hooks/useDialog';
const ErrorDialogFallback = ({ error }) => {
const [open, { handleClose }] = useDialog(true);
return (
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="error-dialog-title"
aria-describedby="error-dialog-description"
maxWidth="xs"
>
<DialogTitle id="error-dialog-title">
Something happened...
</DialogTitle>
<DialogContent>
<DialogContentText id="error-dialog-description">
An error happened ... Please try refreshing the page. If the
error persists, please notify an admin
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="error">
Close
</Button>
</DialogActions>
</Dialog>
);
};
export default ErrorDialogFallback;
<file_sep>/frontend/src/components/Controls/ToggleVideoButton/ToggleVideoButton.js
import React from 'react';
import { Tooltip } from '@material-ui/core';
import { Videocam, VideocamOff } from '@material-ui/icons';
import useLocalVideoToggle from '../../../hooks/useLocalVideoToggle';
import ControlIconButton from '../../../ui/Buttons/ControlIconButton';
const ToggleVideoButton = (props) => {
const [isEnabled, toggleVideoEnabled] = useLocalVideoToggle();
return (
<Tooltip
placement="top"
title={isEnabled ? 'Turn off' : 'Turn on'}
>
<ControlIconButton color="inherit" onClick={toggleVideoEnabled}>
{isEnabled ? <Videocam /> : <VideocamOff />}
</ControlIconButton>
</Tooltip>
);
};
export default ToggleVideoButton;
<file_sep>/frontend/src/pages/Profile/useUpdateProfile.js
import { useMutation } from 'react-query';
import api from '../../api';
import snackbar from '../../ui/Snackbar';
import { useAuth } from '../../components/AuthProvider/AuthProvider';
const useUpdateProfile = () => {
const { setUser } = useAuth();
const [mutate, options] = useMutation(api.editProfile, {
onSuccess: (data) => {
snackbar.success('Profile updated');
setUser(data);
},
});
return [mutate, options];
};
export default useUpdateProfile;
<file_sep>/frontend/src/ui/RichTextEditor.js
import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import MUIRichTextEditor from 'mui-rte';
import { convertToRaw } from 'draft-js';
import _ from 'lodash';
const RichTextEditor = ({ hash, value, onChange }) => {
const saveToLocalStorage = useCallback(
_.debounce((state) => {
const contentState = convertToRaw(state.getCurrentContent());
onChange(JSON.stringify(contentState));
localStorage.setItem(hash, JSON.stringify(contentState));
}, 500),
[hash],
);
return (
<MUIRichTextEditor
toolbarButtonSize="small"
onChange={(state) => {
saveToLocalStorage(state);
}}
defaultValue={value}
controls={[
'title',
'bold',
'italic',
'underline',
'strikethrough',
'numberList',
'bulletList',
'quote',
]}
/>
);
};
RichTextEditor.propTypes = {
hash: PropTypes.string.isRequired,
};
export default RichTextEditor;
<file_sep>/backend/subscribers/index.js
const redis = require('redis');
const redisClient = redis.createClient();
const { greenhouseChannel } = require('./channels');
const greenhouseScraper = require('../scraper/');
redisClient.psubscribe(`${greenhouseChannel}*`);
redisClient.on('pmessage', async (pchannel, channel, msg) => {
if (channel.startsWith(greenhouseChannel)) {
const interview = JSON.parse(msg);
await greenhouseScraper.submitAssessment(interview);
}
return;
});
<file_sep>/backend/tests/api.test.js
const request = require('supertest');
const moment = require('moment');
const jwtDecode = require('jwt-decode');
const RATINGS = require('../enums/ratings');
const ROLES = require('../enums/roles');
const INTERVIEW_STATUS = require('../enums/interviewStatus');
const { v4: uuidv4 } = require('uuid');
let api;
let db;
let config;
let user_token = '';
let user_id = '';
let global_interview;
beforeAll(async () => {
process.env.DATABASE_URL = 'mongodb://localhost/gemochat_test_db';
api = require('../api');
config = require('../config');
db = require('../db');
});
describe('API UP', function () {
it('checks that the API is up and running', async () => {
const res = await request(api)
.get('/api')
.expect('Content-Type', /json/)
.expect(200);
const response = res.body;
expect(response.message).toBe('API is working !');
});
});
describe('User CRUD', () => {
describe('User Creation', () => {
describe('Valid Input', () => {
it('When users provide display name, email, and lengthy password, the account is created', async () => {
const requestBody = {
displayName: '<NAME>',
email: '<EMAIL>',
password: '<PASSWORD>',
};
const res = await request(api)
.post('/api/users/')
.send(requestBody)
.expect(200);
expect(res.body).toHaveProperty('token');
user_token = res.body.token;
user_id = res.body.id;
const token_payload = jwtDecode(res.body.token);
expect(token_payload).toHaveProperty('id');
expect(token_payload).not.toHaveProperty('password');
expect(token_payload.email).toBe(requestBody.email);
expect(token_payload.role).toBe(ROLES.INTERVIEWER);
expect(token_payload.displayName).toBe(requestBody.displayName);
expect(res.body).not.toHaveProperty('password');
});
});
describe('Wrong Input', () => {
it('When users provide a short password < 8 chars, should throw unprocessable entity error', async () => {
const requestBody = {
displayName: 'Short Pass',
email: '<EMAIL>',
password: '<PASSWORD>',
};
const res = await request(api)
.post('/api/users/')
.send(requestBody)
.expect(422);
expect(res.body).toHaveProperty('error');
expect(res.body.error).toHaveProperty('message');
});
});
});
describe('User (Profile) Update', () => {
describe('Valid Input', () => {
it('When users submit a display name, email, password, and new password >= 8 chars, should update a user', async () => {
const requestBody = {
displayName: '<NAME>',
email: '<EMAIL>',
password: '<PASSWORD>',
newPassword: '<PASSWORD>',
};
const res = await request(api)
.put(`/api/users/`)
.set('Authorization', `Bearer ${user_token}`)
.send(requestBody)
.expect(200);
expect(res.body).toHaveProperty('token');
const token_payload = jwtDecode(res.body.token);
expect(token_payload).toHaveProperty('id');
expect(token_payload).not.toHaveProperty('password');
expect(token_payload.email).toBe(requestBody.email);
expect(token_payload.role).toBe(ROLES.INTERVIEWER);
expect(token_payload.displayName).toBe(requestBody.displayName);
expect(res.body.email).toBe(requestBody.email);
expect(res.body.role).toBe(ROLES.INTERVIEWER);
expect(res.body.displayName).toBe(requestBody.displayName);
expect(res.body).not.toHaveProperty('password');
});
});
describe('Missing or Wrong Inputs', () => {
it('When users enter a wrong password, should throw a 401 error and not commit updates', async () => {
const requestBody = {
displayName: 'Should Not Happen',
email: '<EMAIL>',
password: '<PASSWORD>',
newPassword: '<PASSWORD>',
};
const res = await request(api)
.put(`/api/users/`)
.set('Authorization', `Bearer ${user_token}`)
.send(requestBody)
.expect(401);
expect(res.body).toHaveProperty('error');
expect(res.body.error).toHaveProperty('message');
});
it('When users enters an empty display name, should throw a 422 error and not commit updates', async () => {
const requestBody = {
displayName: '',
email: '<EMAIL>',
password: '<PASSWORD>',
newPassword: '<PASSWORD>',
};
const res = await request(api)
.put(`/api/users/`)
.set('Authorization', `Bearer ${user_token}`)
.send(requestBody)
.expect(422);
expect(res.body).toHaveProperty('error');
expect(res.body.error).toHaveProperty('message');
});
it('When users enters an empty email, should throw a 422 error and not commit updates', async () => {
const requestBody = {
displayName: 'Should Not Happen',
email: '',
password: '<PASSWORD>',
newPassword: '<PASSWORD>',
};
const res = await request(api)
.put(`/api/users/`)
.set('Authorization', `Bearer ${user_token}`)
.send(requestBody)
.expect(422);
expect(res.body).toHaveProperty('error');
expect(res.body.error).toHaveProperty('message');
});
});
});
});
describe('User Authentication', () => {
describe('Valid Credentials', () => {
it('checks that the user can login', async () => {
const body = {
email: '<EMAIL>',
password: '<PASSWORD>',
};
const res = await request(api)
.post('/api/auth/login')
.send(body)
.expect(200);
expect(res.body).toHaveProperty('token');
let token = jwtDecode(res.body.token);
expect(token).toHaveProperty('email');
expect(token).toHaveProperty('role');
expect(token).toHaveProperty('displayName');
expect(token).toHaveProperty('id');
const { displayName, email, role } = token;
expect(displayName).toBe('<NAME>');
expect(email).toBe(body.email);
expect(role).toBe(ROLES.INTERVIEWER);
});
});
describe('Wrong Credentials', () => {
it('checks that the user cannot login', async () => {
const body = {
email: '<EMAIL>',
password: '<PASSWORD>',
};
const res = await request(api)
.post('/api/auth/login')
.send(body)
.expect(401);
expect(res.body).toHaveProperty('error');
expect(res.body.error).toHaveProperty('message');
});
});
});
describe('Interview CRUD', () => {
describe('Create Interview', () => {
describe('Valid Input', () => {
it('When users enter an application_id and date, should create an interview', async () => {
const { createJobs } = require('../db/seeds/jobs');
await createJobs();
const interview = {
candidate_id: '52034186002',
date: moment()
.add(1, 'days')
.hours(11)
.minutes(0)
.seconds(0)
.millisecond(0)
.toISOString(),
job_id: '4451682002',
application_id: '57980652002',
interview_type: 'Technical Interview',
};
const body = {
date: interview.date,
application_id: interview.application_id,
interview_type: interview.interview_type,
};
const res = await request(api)
.post('/api/interviews/')
.set('Authorization', `Bearer ${user_token}`)
.send(body)
.expect(200);
global_interview = {
...res.body,
};
expect(res.body.candidate_id).toBe(interview.candidate_id);
expect(res.body.date).toBe(moment(interview.date).toISOString());
expect(res.body.job_id).toBe(interview.job_id);
expect(res.body.application_id).toBe(interview.application_id);
expect(res.body).toHaveProperty('key');
expect(res.body).toHaveProperty('candidate_name');
expect(res.body.status).toBe(INTERVIEW_STATUS.SCHEDULED);
expect(res.body.job_name).toBe('Playground Job');
});
});
describe('Wrong Input', () => {
it('When users enter a wrong application_id, should throw a 404 not found error', async () => {
const body = {
date: moment()
.add(1, 'days')
.hours(11)
.minutes(0)
.seconds(0)
.millisecond(0)
.toISOString(),
application_id: '185151561515',
interview_type: 'Technical Interview',
};
const res = await request(api)
.post('/api/interviews/')
.set('Authorization', `Bearer ${user_token}`)
.send(body)
.expect(404);
expect(res.body).toHaveProperty('error');
expect(res.body.error).toHaveProperty('message');
});
it('When users enter an empty application_id, should throw a 422 error', async () => {
const body = {
date: moment()
.add(1, 'days')
.hours(11)
.minutes(0)
.seconds(0)
.millisecond(0)
.toISOString(),
application_id: '',
interview_type: 'Technical Interview',
};
const res = await request(api)
.post('/api/interviews/')
.set('Authorization', `Bearer ${user_token}`)
.send(body)
.expect(422);
expect(res.body).toHaveProperty('error');
expect(res.body.error).toHaveProperty('message');
});
it('When users enter a wrong date format, should throw a 422 error', async () => {
const body = {
date: '2015-31-31',
application_id: '65416516',
};
const res = await request(api)
.post('/api/interviews/')
.set('Authorization', `Bearer ${user_token}`)
.send(body)
.expect(422);
expect(res.body).toHaveProperty('error');
expect(res.body.error).toHaveProperty('message');
});
it('When users enter an empty date, should throw a 422 error', async () => {
const body = {
date: '',
application_id: '65416516',
};
const res = await request(api)
.post('/api/interviews/')
.set('Authorization', `Bearer ${user_token}`)
.send(body)
.expect(422);
expect(res.body).toHaveProperty('error');
expect(res.body.error).toHaveProperty('message');
});
it('When users enter an empty interview_type, should throw a 422 error', async () => {
const body = {
date: moment()
.add(1, 'days')
.hours(11)
.minutes(0)
.seconds(0)
.millisecond(0)
.toISOString(),
application_id: '57980652002',
interview_type: '',
};
const res = await request(api)
.post('/api/interviews/')
.set('Authorization', `Bearer ${user_token}`)
.send(body)
.expect(422);
expect(res.body).toHaveProperty('error');
expect(res.body.error).toHaveProperty('message');
});
});
});
describe('Read Interview', () => {
describe('Valid input', () => {
it('When a user gets an interview by providing a key route param, should return that interview', async () => {
const res = await request(api)
.get(`/api/interviews/${global_interview.key}`)
.set('Authorization', `Bearer ${user_token}`)
.expect(200);
expect(res.body.candidate_id).toBe(global_interview.candidate_id);
expect(res.body.date).toBe(moment(global_interview.date).toISOString());
expect(res.body.job_id).toBe(global_interview.job_id);
expect(res.body.application_id).toBe(global_interview.application_id);
expect(res.body.interview_type).toBe(global_interview.interview_type);
expect(res.body).toHaveProperty('key');
expect(res.body).toHaveProperty('candidate_name');
expect(res.body.status).toBe(INTERVIEW_STATUS.SCHEDULED);
expect(res.body.job_name).toBe('Playground Job');
});
});
describe('Wrong input', () => {
it('When a user gets an interview by providing a invalid key route param, should throw 403 forbidden error', async () => {
const res = await request(api)
.get(`/api/interviews/${uuidv4()}`)
.set('Authorization', `Bearer ${user_token}`)
.expect(403);
expect(res.body).toHaveProperty('error');
expect(res.body.error).toHaveProperty('message');
});
});
});
describe('Interview Validity', () => {
describe('Valid Input', () => {
it('When given a correct interview key, should return true', async () => {
const res = await request(api)
.get(`/api/interviews/${global_interview.key}/valid`)
.set('Authorization', `Bearer ${user_token}`)
.expect(200);
expect(res.body).toHaveProperty('valid');
expect(res.body.valid).toBe(true);
});
});
describe('Wrong Input', () => {
it('When given a wrong interview key, should return false', async () => {
const res = await request(api)
.get(`/api/interviews/${uuidv4()}/valid`)
.set('Authorization', `Bearer ${user_token}`)
.expect(200);
expect(res.body).toHaveProperty('valid');
expect(res.body.valid).toBe(false);
});
});
});
describe('Interview Scores Generation', () => {
describe('Valid Input', () => {
it('When given a list of rated questions mapped to attributes, should generate scores for those attributes', async () => {
const {
questions,
ratingsByAttributeId,
} = require('./seeds/questions');
const res = await request(api)
.post(`/api/interviews/${global_interview.key}/scoring`)
.set('Authorization', `Bearer ${user_token}`)
.send({ questions })
.expect(200);
expect(res.body).toHaveProperty('attributes');
res.body.attributes.forEach((attribute) => {
expect(attribute).toHaveProperty('attribute_name');
expect(attribute).toHaveProperty('attribute_id');
expect(attribute).toHaveProperty('note');
expect(attribute).toHaveProperty('rating');
expect(attribute.rating).toBe(
ratingsByAttributeId[attribute.attribute_id],
);
});
});
});
});
describe('Submit Assessment', () => {
describe('Valid Input', () => {
it('When an interview is submitted with an empty overall_rating, should save the interview and update status to "AWAITING_ASSESSMENT"', async () => {
const { attributes, attributesByName } = require('./seeds/attributes');
const { questions } = require('./seeds/questions');
const body = {
takeAways: 'Great candidate !',
scorecard: attributes,
overall_rating: '',
questions,
};
const res = await request(api)
.post(`/api/interviews/${global_interview.key}/assessment`)
.set('Authorization', `Bearer ${user_token}`)
.send(body)
.expect(200);
expect(res.body).toHaveProperty('scorecard');
expect(res.body).toHaveProperty('questions');
expect(res.body.takeAways).toBe(body.takeAways);
res.body.scorecard.forEach((attribute) => {
const expectedAttribute = attributesByName[attribute.name];
expect(attribute.type).toBe(expectedAttribute.type);
expect(attribute.name).toBe(expectedAttribute.name);
expect(attribute.note).toBe(expectedAttribute.note);
expect(attribute.rating).toBe(expectedAttribute.rating);
});
expect(res.body.status).toBe(INTERVIEW_STATUS.AWAITING_ASSESSMENT);
});
it('When a scorecard, takeAways, and an overall rating is submitted, should update the interview and send a message to redis', async () => {
const { attributes, attributesByName } = require('./seeds/attributes');
const { questions } = require('./seeds/questions');
const body = {
takeAways: 'Great candidate !',
overall_rating: RATINGS.STRONG_YES,
scorecard: attributes,
questions,
};
const res = await request(api)
.post(`/api/interviews/${global_interview.key}/assessment`)
.set('Authorization', `Bearer ${user_token}`)
.send(body)
.expect(200);
expect(res.body).toHaveProperty('scorecard');
expect(res.body).toHaveProperty('questions');
expect(res.body.overall_rating).toBe(body.overall_rating);
expect(res.body.takeAways).toBe(body.takeAways);
res.body.scorecard.forEach((attribute) => {
const expectedAttribute = attributesByName[attribute.name];
expect(attribute.type).toBe(expectedAttribute.type);
expect(attribute.name).toBe(expectedAttribute.name);
expect(attribute.note).toBe(expectedAttribute.note);
expect(attribute.rating).toBe(expectedAttribute.rating);
});
expect(res.body.status).toBe(INTERVIEW_STATUS.COMPLETED);
});
});
});
});
describe('Twilio Access Token', () => {
describe('Valid Input', () => {
it('When an interview key and a display name are provided, should return an access token', async () => {
const queryParams = {
display_name: 'test user',
key: global_interview.key,
};
const res = await request(api)
.get(
`/api/twilio/token?key=${queryParams.key}&display_name=${queryParams.display_name}`,
)
.expect(200);
expect(res.body).toHaveProperty('accessToken');
let accessToken = jwtDecode(res.body.accessToken);
const { sub, iss, grants } = accessToken;
expect(sub).toBe(config.twilio.accountSid);
expect(iss).toBe(config.twilio.apiKeySid);
expect(grants).toHaveProperty('identity');
expect(grants).toHaveProperty('video');
expect(grants.identity).toBe(queryParams.display_name);
});
});
describe('Wrong Input', () => {
it('When a wrong key and a display name are provided, should throw a 404 error', async () => {
const body = {
display_name: '<NAME>',
key: uuidv4(),
};
const res = await request(api)
.get(`/api/twilio/token?key=${uuidv4()}&display_name=${'<NAME>'}`)
.expect(404);
expect(res.body).toHaveProperty('error');
expect(res.body.error).toHaveProperty('message');
});
});
});
afterAll(async (done) => {
db.connection.db.dropDatabase();
db.connection.close();
done();
});
<file_sep>/frontend/src/components/InterviewerRoom/MainBlock/MainBlock.js
import React, { useMemo } from 'react';
import { INTERVIEW_STEP } from '../../../constants';
import PeerMeeting from '../../PeerMeeting/PeerMeeting';
import Assessment from '../../Assessment/Assessment';
import useInterviewStateContext from '../../../hooks/useInterviewStateContext';
const components = {
[INTERVIEW_STEP.CALL]: PeerMeeting,
[INTERVIEW_STEP.ASSESSMENT]: Assessment,
fallback: () => <>Loading...</>,
};
const MainBlock = (props) => {
const { interviewStep } = useInterviewStateContext();
const Component = components[interviewStep || 'fallback'];
return useMemo(() => <Component {...props} />, [
interviewStep,
props,
]);
};
export default MainBlock;
<file_sep>/frontend/src/hooks/useLocalAudioToggle.js
import { useCallback } from 'react';
import useVideoContext from './useVideoContext';
import useIsTrackEnabled from './useIsTrackEnabled';
const useLocalAudioToggle = () => {
const { audioTrack } = useVideoContext();
const isEnabled = useIsTrackEnabled(audioTrack);
const toggleAudioEnabled = useCallback(() => {
if (audioTrack) {
audioTrack.isEnabled
? audioTrack.disable()
: audioTrack.enable();
}
}, [audioTrack]);
return [isEnabled, toggleAudioEnabled];
};
export default useLocalAudioToggle;
<file_sep>/backend/enums/numericalRatings.js
const RATINGS = require('./ratings');
module.exports = {
[RATINGS.STRONG_NO]: 1,
[RATINGS.NO]: 2,
[RATINGS.MIXED]: 3,
[RATINGS.YES]: 4,
[RATINGS.STRONG_YES]: 5,
};
<file_sep>/frontend/src/ui/FixedFab.js
import React from 'react';
import { styled, Fab } from '@material-ui/core';
const FixedFab = styled(Fab)((props) => ({
position: 'absolute',
right: props.right || 'auto',
bottom: props.bottom || 'auto',
left: props.left || 'auto',
top: props.top || 'auto',
}));
export default FixedFab;
<file_sep>/frontend/src/ui/Formik/MuiFormikTextField.js
import React from 'react';
import PropTypes from 'prop-types';
import { useField } from 'formik';
import { TextField } from '@material-ui/core';
import GemoTextField from '../GemoTextField';
//Re-usable component that couples MUI's textfield with Formik.
//This is necessary, because we need to make MUI's TextField component "aware" of Formik.
//One of the things that formik "injects" into the TextField component is the onChange handler.
//It is important to extract this coupling in a separate component in order to re-use it across different components
const MuiFormikTextField = ({ name, withGemoStyles, ...props }) => {
//makes use of formik v2 useField hook.
//Another alternative is to use formik's Field component.
const [field, meta] = useField(name);
const hasError = meta.touched && meta.error;
const errorMsg = hasError && meta.error;
return (
<>
{withGemoStyles ? (
<GemoTextField
error={!!hasError}
helperText={errorMsg}
{...field}
{...props}
/>
) : (
<TextField
error={!!hasError}
helperText={errorMsg}
{...field}
{...props}
/>
)}
</>
);
};
//Name prop is mandatory
MuiFormikTextField.propTypes = {
name: PropTypes.string.isRequired,
};
export default MuiFormikTextField;
<file_sep>/frontend/src/components/IntervieweeRoom/IntervieweeRoom.js
import React from 'react';
import RoomDoorLayout from '../../ui/RoomDoorLayout';
import { useParams } from 'react-router-dom';
import useTwilioAccessToken from '../../hooks/useTwilioAccessToken';
import PeerMeeting from '../PeerMeeting/PeerMeeting';
import { Box } from '@material-ui/core';
const IntervieweeRoom = ({ displayName }) => {
return (
<RoomDoorLayout>
<Box p={2}>
<PeerMeeting displayName={displayName} />
</Box>
</RoomDoorLayout>
);
};
export default IntervieweeRoom;
<file_sep>/frontend/src/components/InterviewStateProvider/useInterviewReducer/useInterviewReducer.js
import { useReducer, useCallback } from 'react';
import {
updateQuestionAction,
updateAttributeAction,
setInterviewQuestionsAction,
setSelectedQuestionIndexAction,
loadInterviewAction,
updateAttributesAction,
updateInterviewStepAction,
updateQuestionIdsAction,
updateInterviewAction,
} from '../actions';
import reducer from '../reducers';
const initialStateGlobal = {
interview: {
questions: [],
scorecard: [],
status: '',
},
scorecard: {},
scorecardByType: {},
questions: {},
selectedQuestionIndex: 0,
};
const useInterviewReducer = (initialState) => {
const [state, dispatch] = useReducer(
reducer,
initialState || initialStateGlobal,
);
const loadInterview = useCallback(
(interview) => {
loadInterviewAction(dispatch, interview);
},
[dispatch],
);
const updateQuestion = useCallback(
(questionId, question) => {
updateQuestionAction(dispatch, questionId, question);
},
[dispatch],
);
const updateQuestionIds = useCallback(
(questionIds) => {
updateQuestionIdsAction(dispatch, questionIds);
},
[dispatch],
);
const updateAttribute = useCallback(
(attributeId, attribute) => {
updateAttributeAction(dispatch, attributeId, attribute);
},
[dispatch],
);
const setInterviewQuestions = useCallback(
(questions) => {
setInterviewQuestionsAction(dispatch, questions);
},
[dispatch],
);
const setSelectedQuestionIndex = useCallback(
(questionIndex) => {
setSelectedQuestionIndexAction(dispatch, questionIndex);
},
[dispatch],
);
const updateAttributes = useCallback(
(attributes) => {
updateAttributesAction(dispatch, attributes);
},
[dispatch],
);
const updateInterviewStep = useCallback(
(interviewStep) => {
updateInterviewStepAction(dispatch, interviewStep);
},
[dispatch],
);
const updateInterview = useCallback(
(payload) => {
updateInterviewAction(dispatch, payload);
},
[dispatch],
);
return [
state,
dispatch,
{
loadInterview,
updateQuestion,
updateAttribute,
setInterviewQuestions,
setSelectedQuestionIndex,
updateAttributes,
updateInterviewStep,
updateQuestionIds,
updateInterview,
},
];
};
export default useInterviewReducer;
<file_sep>/frontend/src/components/InterviewStateProvider/InterviewStateProvider.js
import React, {
createContext,
useCallback,
useEffect,
useRef,
} from 'react';
import useGenerateScores from './useGenerateScores';
import _ from 'lodash';
import { useQuery } from 'react-query';
import useInterviewReducer from './useInterviewReducer/useInterviewReducer';
import { useParams, useHistory } from 'react-router-dom';
import api from '../../api';
import RoomSkeleton from '../RoomSkeleton/RoomSkeleton';
import { denormalize } from 'normalizr';
import { interview as interviewSchema } from './schemas/interview';
import useSaveAssessment from './useSaveAssessment';
import { INTERVIEW_STEP } from '../../constants';
/**
* Why normalize the API response?
* The idea here is that when we send an API request to generate the scores from the questions...
* ... We will need to look for every changed attribute in order to "patch" the calculated score.
* Normalization will solve this issue as we can simply access the attributes by their ids.
* Note however, that this problem is not relevant if we choose to fetch the scores automatically instead of waiting...
* ... for the user to trigger an action.
*
*/
export const InterviewStateContext = createContext(null);
export const InterviewStateProvider = ({ children }) => {
const { key } = useParams();
const history = useHistory();
const shouldSaveToLocalStorage = useRef(true);
const unloadHandlerRef = useRef(() => {});
const initialState = JSON.parse(
localStorage.getItem(`interview-${key}`),
);
const [state, dispatch, actions] = useInterviewReducer(
initialState,
);
const { isFetching, refetch } = useQuery(
['interview', { key }],
api.getInterviewNormalized,
{
onSuccess: (data) => {
actions.loadInterview(data);
},
enabled: false,
},
);
const [
generateScoresAPI,
{ isLoading: isLoadingScores },
] = useGenerateScores();
const [
saveAssessmentMutation,
{ isLoading: isLoadingSaveAssessment },
] = useSaveAssessment();
useEffect(() => {
if (!initialState) refetch();
}, [initialState]);
// Save the current state of the interview to local storage.
// Disruptions are expected in calls and users' intuition is probably to refresh the page
// The goal is not to lose the state of the interview (questions' scores etc.) on refresh
useEffect(() => {
unloadHandlerRef.current = () => {
if (shouldSaveToLocalStorage.current) {
localStorage.setItem(
`interview-${key}`,
JSON.stringify({
...state,
interviewStep: INTERVIEW_STEP.CALL,
}),
);
}
};
}, [state]);
useEffect(() => {
const unloadHandler = (ev) => {
unloadHandlerRef.current(ev);
};
window.addEventListener('beforeunload', unloadHandler);
return history.listen(() => {
unloadHandlerRef.current();
window.removeEventListener('beforeunload', unloadHandler);
});
}, []);
// Callback when an interviewer chooses to generate scores from questions.
const generateScores = useCallback(
async (key) => {
const questions = _.values(state.questions);
const { attributes } = await generateScoresAPI({
key,
data: { questions },
});
actions.updateAttributes(attributes);
},
[actions, generateScoresAPI, state.questions],
);
// Saving the assessment on the server.
// Denormalization needs to occur before sending the data.
const saveAssessment = useCallback(async () => {
const assessment = denormalize(
state.interview,
interviewSchema,
state,
);
await saveAssessmentMutation({
key: key,
data: assessment,
});
localStorage.removeItem(`interview-${key}`);
shouldSaveToLocalStorage.current = false;
});
return (
<InterviewStateContext.Provider
value={{
...state,
...actions,
isLoadingInterview: isFetching,
isLoadingScores,
isLoadingSaveAssessment,
generateScores,
saveAssessment,
}}
>
{isFetching ? <RoomSkeleton /> : children}
</InterviewStateContext.Provider>
);
};
export default InterviewStateProvider;
<file_sep>/frontend/src/components/AuthProvider/useLogin.js
import { useMutation } from 'react-query';
import api from '../../api';
const useLogin = () => {
const [mutate, options] = useMutation(api.login);
return [mutate, options];
};
export default useLogin;
<file_sep>/backend/errors/UnexpectedError.js
class UnexpectedError extends Error {
status = 500;
constructor(message = 'Something went wrong') {
super(message);
}
serializeError() {
return { message: this.message, status: this.status };
}
}
module.exports = UnexpectedError;
<file_sep>/backend/db/models/interview.js
const mongoose = require('mongoose');
const questionSchema = require('./question');
const attributeSchema = require('./attribute');
const RATINGS = require('../../enums/ratings');
const STATUS = require('../../enums/interviewStatus');
const interviewSchema = new mongoose.Schema(
{
// The interviewer's id
interviewer: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
// e.g: Technical Interview, Culture-Fit, etc.
interview_type: {
type: String,
required: true,
},
// The candidate's greenhouse id
candidate_id: {
type: String,
required: true,
},
// Fake name generated for privacy reasons.
candidate_name: {
type: String,
required: true,
},
// The date of the interview
date: {
type: Date,
required: true,
},
// Greenhouse job_id.
job_id: {
type: String,
required: true,
},
// Greenhouse job_name
job_name: {
type: String,
required: true,
},
// Greenhouse application_id
application_id: {
type: String,
required: true,
},
// Secure random uuid to identify each interview. This key can be shared with candidates.
key: {
type: String,
required: true,
},
takeAways: {
type: String,
default: '',
},
questions: [questionSchema],
scorecard: [attributeSchema],
overall_rating: {
type: String,
default: RATINGS.NO_DECISION,
enum: [
RATINGS.MIXED,
RATINGS.NO,
RATINGS.STRONG_NO,
RATINGS.STRONG_YES,
RATINGS.YES,
RATINGS.NO_DECISION,
],
},
status: {
type: String,
default: STATUS.SCHEDULED,
enum: [STATUS.SCHEDULED, STATUS.AWAITING_ASSESSMENT, STATUS.COMPLETED],
},
},
{ timestamps: true },
);
// Add indices on job_is and key for easy retrievals and "joins"
interviewSchema.index({ job_id: 1 });
interviewSchema.index({ key: 1 });
const Interview = new mongoose.model('Interview', interviewSchema);
module.exports = Interview;
<file_sep>/frontend/src/components/InterviewStateProvider/useSaveAssessment.js
import React from 'react';
import api from '../../api';
import { useMutation } from 'react-query';
const useSaveAssessment = () => {
const [mutate, options] = useMutation(api.submitAssessment);
return [mutate, options];
};
export default useSaveAssessment;
<file_sep>/frontend/src/ui/SimpleTabs/SimpleTab.js
import React from 'react';
import { withStyles, Tab } from '@material-ui/core';
const SimpleTab = withStyles((theme) => ({
root: {
textTransform: 'capitalize',
minWidth: 'fit-content',
color: '#828282',
fontWeight: 500,
padding: 0,
fontSize: theme.spacing(1.125),
marginRight: theme.spacing(2),
},
selected: {
color: theme.palette.primary.main,
},
}))((props) => <Tab disableRipple {...props} />);
export default SimpleTab;
<file_sep>/backend/services/twilio.js
const config = require('../config');
const AccessToken = require('twilio').jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;
const getTwilioAccessToken = async (identity, roomName) => {
const token = new AccessToken(
config.twilio.accountSid,
config.twilio.apiKeySid,
config.twilio.apiKeySecret,
{
ttl: config.twilio.maxAllowedSessionDuration,
},
);
token.identity = identity;
const videoGrant = new VideoGrant({ room: roomName });
token.addGrant(videoGrant);
return token.toJwt();
};
module.exports = {
getTwilioAccessToken,
};
<file_sep>/frontend/src/components/InterviewerRoom/MeetingInformation/CandidateInformation.js
import React, { useMemo } from 'react';
import { Box, Typography, makeStyles } from '@material-ui/core';
import { useQuery } from 'react-query';
import { useParams } from 'react-router-dom';
import api from '../../../api';
import LoadingContainer from '../../../ui/Spinners/LoadingContainer';
const useStyles = makeStyles((theme) => ({
capitalize: {
textTransform: 'capitalize',
},
}));
const useCandidateInformation = () => {
const { key } = useParams();
const { data, ...options } = useQuery(
['candidate', { key }],
api.getCandidateInformation,
{
initialStale: true,
initialData: {
keyed_custom_fields: {},
},
},
);
return [data, options];
};
const CandidateInformation = (props) => {
const classes = useStyles();
const [candidate, { isFetching }] = useCandidateInformation();
const custom_fields = useMemo(
() =>
Object.entries(candidate.keyed_custom_fields)
.filter(([k, v]) => v && v.value)
.reduce((acc, [k, v]) => {
return {
...acc,
[k]: v,
};
}, {}),
[candidate],
);
return (
<Box pt={2}>
<LoadingContainer isLoading={isFetching}>
<Typography variant="h5" paragraph>
{candidate.candidate_name}
</Typography>
{Object.keys(custom_fields).map((key) => (
<>
<Typography
className={classes.capitalize}
variant="body2"
color="textSecondary"
>
{custom_fields[key].name}
</Typography>
<Typography variant="body1" paragraph>
{custom_fields[key].type === 'multi_select'
? custom_fields[key].value.join(', ')
: custom_fields[key].value}
</Typography>
</>
))}
</LoadingContainer>
</Box>
);
};
export default CandidateInformation;
<file_sep>/backend/tests/seeds/attributes.js
// Test-only seed. The below attributes are scored to mimic a real-life scenario where an interview scores...
// ... different attributes.
const RATINGS = require('../../enums/ratings');
const _ = require('lodash');
let attributes = [
{
name: 'Version Control',
type: 'Software Engineering',
note: '',
rating: RATINGS.YES,
},
{
name: 'Understands French',
type: 'Culture-fit',
note: '',
rating: RATINGS.NO,
},
{
name: 'Understands English',
type: 'Culture-fit',
note: '',
rating: RATINGS.STRONG_YES,
},
{
name: 'Tool Knowledge',
type: 'Passion',
note: '',
rating: RATINGS.STRONG_YES,
},
{
name: 'Team work',
type: 'Culture-fit',
note: '',
rating: RATINGS.YES,
},
{
name: 'Startup mindset and product sense',
type: 'Culture-fit',
note: '',
rating: RATINGS.MIXED,
},
{
name: 'Speaks French',
type: 'Culture-fit',
note: '',
rating: RATINGS.STRONG_NO,
},
{
name: 'Speaks English',
type: 'Culture-fit',
note: '',
rating: RATINGS.STRONG_YES,
},
{
name: 'Self awareness and coacheability',
type: 'Culture-fit',
note: '',
rating: RATINGS.STRONG_YES,
},
{
name: 'Remote',
type: 'Culture-fit',
note: '',
rating: RATINGS.STRONG_YES,
},
{
name: 'Problem Decomposition',
type: 'Programming',
note: '',
rating: RATINGS.YES,
},
{
name: 'Platform Internals',
type: 'Passion',
note: '',
rating: RATINGS.STRONG_YES,
},
{
name: 'Languages Exposed to',
type: 'Passion',
note: '',
rating: RATINGS.YES,
},
{
name: 'Knowledge of upcoming technologies',
type: 'Passion',
note: '',
rating: RATINGS.YES,
},
{
name: 'Humbleness and eagerness to learn',
type: 'Culture-fit',
note: '',
rating: RATINGS.STRONG_YES,
},
{
name: 'Error Handling',
type: 'Programming',
note: '',
rating: RATINGS.YES,
},
{
name: 'Code Readability',
type: 'Programming',
note: '',
rating: RATINGS.YES,
},
{
name: 'Code Organization',
type: 'Programming',
note: '',
rating: RATINGS.YES,
},
{
name: 'Clear communication and idea structure',
type: 'Culture-fit',
note: '',
rating: RATINGS.YES,
},
{
name: 'Build Automation',
type: 'Software Engineering',
note: '',
rating: RATINGS.YES,
},
{
name: 'Books & Blogs',
type: 'Passion',
note: '',
rating: RATINGS.YES,
},
{
name: 'Autonomy and ownership ',
type: 'Culture-fit',
note: '',
rating: RATINGS.YES,
},
{
name: 'Automated Testing',
type: 'Software Engineering',
note: '',
rating: RATINGS.YES,
},
];
module.exports = {
attributes,
attributesByName: attributes.reduce(
(acc, curr) => ({
...acc,
[curr.name.trim()]: {
...curr,
name: curr.name.trim(),
type: curr.type.trim(),
},
}),
{},
),
};
<file_sep>/frontend/src/components/Controls/Controls.js
import React from 'react';
import { Box, makeStyles } from '@material-ui/core';
import ToggleAudioButton from './ToggleAudioButton/ToggleAudioButton';
import ToggleVideoButton from './ToggleVideoButton/ToggleVideoButton';
import useRoomState from '../../hooks/useRoomState';
import EndCallButton from './EndCallButton/EndCallButton';
const useStyles = makeStyles((theme) => ({
overlay: {
background:
'linear-gradient(180deg, rgba(255,255,255,0) 0%, rgba(28,27,27,0.5732844163055848) 100%)',
},
}));
const Controls = () => {
const classes = useStyles();
const roomState = useRoomState();
const isReconnecting = roomState === 'reconnecting';
return (
<Box
width="100%"
display="flex"
className={classes.overlay}
position="absolute"
justifyContent="center"
alignItems="center"
bottom={0}
borderRadius="10px"
py={0.5}
pb={1}
color="white"
>
<Box mr={1.5}>
<ToggleAudioButton disabled={isReconnecting} />
</Box>
<Box mr={1.5}>
<ToggleVideoButton disabled={isReconnecting} />
</Box>
{roomState !== 'disconnected' && (
<Box mr={1.5}>
<EndCallButton />
</Box>
)}
</Box>
);
};
Controls.propTypes = {};
export default Controls;
<file_sep>/frontend/src/ui/GemoTextField.js
import React from 'react';
import {
InputLabel,
TextField,
makeStyles,
FormControl,
withStyles,
} from '@material-ui/core';
const CustomTextField = withStyles((theme) => ({
root: {
marginTop: theme.spacing(1.25),
'& input:valid:focus + fieldset': {
borderWidth: 1,
},
'&.MuiFormHelperText-root.$': {
fontWeight: 500,
marginRight: 0,
},
},
}))((props) => <TextField {...props} variant="outlined" />);
const GemoTextField = ({
FormControlProps,
InputLabelProps,
label,
...props
}) => {
return (
<FormControl {...FormControlProps}>
<InputLabel {...InputLabelProps}>{label}</InputLabel>
<CustomTextField {...props} />
</FormControl>
);
};
export default GemoTextField;
<file_sep>/frontend/src/ui/Spinners/FullPageSpinner.js
import React from 'react';
import { makeStyles, CircularProgress } from '@material-ui/core';
const useStyles = makeStyles((theme) => ({
container: {
height: '100vh',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
spinnerBox: {
transform: 'translate(-50%, -50%)',
},
}));
const FullPageSpinner = (props) => {
const classes = useStyles();
return (
<div className={classes.container}>
<div className={classes.spinnerBox}>
<CircularProgress {...props} />
</div>
</div>
);
};
export default FullPageSpinner;
<file_sep>/backend/api/middleware/interviews.js
const { ForbiddenError } = require('../../errors');
const interviewsService = require('../../services/interviews');
const ensureCorrectInterviewer = async (req, res, next) => {
try {
const { key } = req.params;
const { id } = req.user;
const isInterviewerOfInterview = await interviewsService.isInterviewerOfInterview(
id,
key,
);
if (!isInterviewerOfInterview) throw new ForbiddenError();
return next();
} catch (err) {
next(err);
}
};
module.exports = {
ensureCorrectInterviewer,
};
<file_sep>/frontend/src/components/InterviewerRoom/MeetingInformation/MeetingInformation.js
import React, { useState } from 'react';
import {
Paper,
Tabs,
Box,
Tab,
Typography,
makeStyles,
} from '@material-ui/core';
import TabPanel from '../../../ui/TabPanel';
import JobDetail from './JobDetail';
import CandidateInformation from './CandidateInformation';
import {
HelpOutline,
PersonOutline,
WorkOutline,
} from '@material-ui/icons';
import QuestionListConnected from '../QuestionsList/QuestionListConnected';
const useStyles = makeStyles((theme) => ({
paper: {
position: 'sticky',
top: theme.spacing(0.5),
border: '1px solid #D6D2F9',
},
title: {
color: '#829AB1',
textTransform: 'uppercase',
letterSpacing: '-1px',
fontSize: '1.1rem',
},
}));
const MeetingInformation = () => {
const classes = useStyles();
const [value, setValue] = useState(0);
const handleChange = (_, value) => {
setValue(value);
};
return (
<Paper elevation={0} className={classes.paper}>
<Box
display="flex"
flexDirection="column"
py={1}
pl={1.5}
pr={1}
>
<Typography className={classes.title} variant="h6" paragraph>
Information
</Typography>
<Tabs
value={value}
indicatorColor="secondary"
onChange={handleChange}
textColor="primary"
variant="fullWidth"
>
<Tab icon={<HelpOutline />} label="Questions" />
<Tab icon={<PersonOutline />} label="Candidate" />
<Tab icon={<WorkOutline />} label="Job" />
</Tabs>
<TabPanel index={0} value={value}>
<QuestionListConnected />
</TabPanel>
<TabPanel index={1} value={value}>
<CandidateInformation />
</TabPanel>
<TabPanel index={2} value={value}>
<JobDetail />
</TabPanel>
</Box>
</Paper>
);
};
export default MeetingInformation;
<file_sep>/frontend/src/pages/Interviews/useInterviews.js
import { useQuery } from 'react-query';
import api from '../../api';
const useInterviews = () => {
const { data, ...options } = useQuery(
'interviews',
api.getInterviews,
{
initialStale: true,
initialData: {
interviews: [],
},
},
);
return [data.interviews, options];
};
export default useInterviews;
<file_sep>/frontend/src/pages/InterviewDetails/useInterviewDetails.js
import { useQuery } from 'react-query';
import api from '../../api';
const useInterviewDetails = (key) => {
const { data, ...options } = useQuery(
['interview', { key }],
api.getInterviewInformation,
{
initialData: {
questions: [],
scorecard: [],
},
initialStale: true,
},
);
return [data, { ...options }];
};
export default useInterviewDetails;
<file_sep>/frontend/src/theme.js
import {
createMuiTheme,
responsiveFontSizes,
} from '@material-ui/core';
let theme = createMuiTheme({
palette: {
type: 'light',
primary: {
main: 'hsl(247, 67%, 59%)',
dark: 'hsl(247, 68%, 54%)',
darkBlue: 'hsl(246, 65%, 9%)',
contrastText: '#fff',
},
secondary: {
light: 'hsl(247, 68%, 90%)',
main: 'rgb(143, 131, 239)',
},
blueGrey: {
50: 'hsl(210, 36%, 96%)',
100: 'hsl(212, 33%, 89%)',
200: 'hsl(210, 31%, 80%)',
300: 'hsl(211, 27%, 70%)',
400: 'hsl(209, 23%, 60%)',
500: 'hsl(210, 22%, 49%)',
600: 'hsl(209, 28%, 39%)',
700: 'hsl(209, 34%, 30%)',
800: 'hsl(211, 39%, 23%)',
900: 'hsl(209, 61%, 16%)',
},
},
spacing: 16,
typography: {
fontFamily: [
'Roboto',
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'"Helvetica Neue"',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"',
].join(','),
h1: {
fontFamily: 'Montserrat, sans-serif',
fontWeight: '700',
},
h2: {
fontFamily: 'Montserrat, sans-serif',
fontWeight: '700',
},
h3: {
fontFamily: 'Montserrat, sans-serif',
fontWeight: '700',
},
h4: {
fontFamily: 'Montserrat, sans-serif',
fontWeight: '700',
},
h5: {
fontFamily: 'Montserrat, sans-serif',
fontWeight: '700',
},
h6: {
fontFamily: 'Montserrat, sans-serif',
fontWeight: '700',
},
},
});
theme.overrides = {
MuiCssBaseline: {
'@global': {
body: {
backgroundColor: theme.palette.blueGrey[50],
},
},
},
MuiIconButton: {
sizeSmall: {
padding: theme.spacing(0.5),
},
},
MuiCircularProgress: {
circle: {
'stroke-linecap': 'round',
},
},
MuiFormHelperText: {
root: {
'&$error': {
marginLeft: 0,
fontWeight: 500,
},
},
error: {},
},
MUIRichTextEditor: {
root: {
height: '100%',
},
toolbar: {
padding: theme.spacing(0.25),
borderBottom: `1px solid ${theme.palette.blueGrey[100]}`,
backgroundColor: theme.palette.blueGrey[50],
},
container: {
height: '100%',
marginTop: 0,
border: `1px solid ${theme.palette.blueGrey[100]}`,
},
editorContainer: {
margin: 0,
padding: '18.5px 14px',
},
placeHolder: {
height: '100%',
position: 'static',
},
},
};
theme = responsiveFontSizes(theme);
export default theme;
<file_sep>/frontend/src/constants/index.js
export const INTERVIEW_STEP = {
CALL: 'call',
ASSESSMENT: 'assessment',
};
export const RATINGS = {
STRONG_NO: 'strong_no',
NO: 'np',
MIXED: 'mixed',
YES: 'yes',
STRONG_YES: 'strong_yes',
NO_DECISION: 'no_decision',
};
export const INTERVIEW_STATUS = {
SCHEDULED: 'scheduled',
AWAITING_ASSESSMENT: 'awaiting assessment',
COMPLETED: 'completed',
};
export const ROLES = {
INTERVIEWER: 'interviewer',
ADMIN: 'admin',
};
<file_sep>/frontend/src/api/login.js
import axiosInstance from './axiosInstance';
export const login = (data) => {
return axiosInstance({
method: 'POST',
url: '/auth/login',
data,
}).then((res) => res.data);
};
<file_sep>/frontend/src/ui/Navigation/NavTabs.js
import React, { useMemo, useState } from 'react';
import { withStyles, Tabs } from '@material-ui/core';
import { useLocation, Link } from 'react-router-dom';
import NavTab from './NavTab';
import useTabs from '../../hooks/useTabs';
const StyledTabs = withStyles((theme) => ({
root: {
flex: 1,
},
fixed: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
indicator: {
backgroundColor: 'white',
height: '5px',
},
}))(Tabs);
const NavTabs = ({ children }) => {
const location = useLocation();
const tabChildren = useMemo(() => {
return children.filter((child) => child.props.isTab);
}, [children]);
const initialSelectedTab = useMemo(() => {
const selectedTab = children.findIndex(
(tab) => tab.props.path === location.pathname,
);
return selectedTab !== -1 ? selectedTab : 0;
}, [location, children]);
const [tab, handleChange] = useTabs(initialSelectedTab);
return (
<StyledTabs centered value={tab} onChange={handleChange}>
{tabChildren.map((tab) => (
<NavTab
component={Link}
to={tab.props.path}
key={tab.props.label}
label={tab.props.label}
/>
))}
</StyledTabs>
);
};
export default NavTabs;
<file_sep>/frontend/src/components/InterviewerRoom/InterviewerRoom.js
import React from 'react';
import { Box, Grid } from '@material-ui/core';
import RoomQuestions from './RoomQuestions/RoomQuestions';
import MeetingInformation from './MeetingInformation/MeetingInformation';
import MainBlock from './MainBlock/MainBlock';
const InterviewerRoom = ({ displayName }) => {
return (
<Box p={0.5}>
<Grid container spacing={1}>
<Grid spacing={1} container item lg={8}>
<RoomQuestions />
<Grid item lg={12}>
<MainBlock displayName={displayName} />
</Grid>
</Grid>
<Grid item lg={4}>
<MeetingInformation />
</Grid>
</Grid>
</Box>
);
};
export default InterviewerRoom;
<file_sep>/frontend/src/components/InterviewerRoom/QuestionsList/QuestionItem.js
import React from 'react';
import useInterviewStateContext from '../../../hooks/useInterviewStateContext';
import { INTERVIEW_STEP } from '../../../constants';
import QuestionItemCall from './QuestionItem/QuestionItemCall';
import QuestionItemAssessment from './QuestionItem/QuestionItemAssessment';
const components = {
[INTERVIEW_STEP.CALL]: QuestionItemCall,
[INTERVIEW_STEP.ASSESSMENT]: QuestionItemAssessment,
};
const QuestionItem = (props, ref) => {
const { interviewStep } = useInterviewStateContext();
const Component = components[interviewStep];
return <Component ref={ref} {...props} />;
};
export default React.forwardRef(QuestionItem);
<file_sep>/backend/api/routes/twilio.js
const express = require('express');
const router = express.Router();
const { getTwilioAccessToken } = require('../controllers/twilio');
const { validateGetAccessToken } = require('../validators/twilio');
router.get('/token', validateGetAccessToken, getTwilioAccessToken);
module.exports = router;
<file_sep>/backend/errors/CredentialsError.js
const CustomError = require('./CustomError');
class CredentialsError extends CustomError {
name = 'CredentialsError';
status = 401;
constructor(message = 'Wrong credentials') {
super(message);
}
}
module.exports = CredentialsError;
| ffa4251835c33b282e6cccc9cd4261b31db66fa2 | [
"JavaScript",
"Markdown",
"Shell"
]
| 113 | JavaScript | zakariaelas/gemochat | 5236c4f36ae4e9280ebdfce76ac5c87aef7e8ba6 | c7cbf08b322e009bd9891efeb4b0ac80332f1aef |
refs/heads/master | <file_sep>//
// Created by 李寅斌 on 2019/2/27.
//
#include <gtest/gtest.h>
int add(int a, int b)
{
return a + b;
}
TEST(test, add)
{
EXPECT_EQ(add(2, 3), 5);
}<file_sep># cmake-learning
cmake learning
<file_sep>cmake_minimum_required(VERSION 2.8)
project(GTEST CXX)
include_directories(${PROJECT_SOURCE_DIR})
include_directories(${PROJECT_SOURCE_DIR}/third/googletest-release-1.8.1)
add_subdirectory(third)
add_subdirectory(src)<file_sep>
add_executable(test_g test.cc)
target_link_libraries(test_g gtest gtest_main)
<file_sep>cmake_minimum_required(VERSION 2.8.8)
if (POLICY CMP0048)
cmake_policy(SET CMP0048 NEW)
endif (POLICY CMP0048)
project(googletest-distribution)
set(GOOGLETEST_VERSION 1.9.0)
enable_testing()
include(CMakeDependentOption)
include(GNUInstallDirs)
#Note that googlemock target already builds googletest
option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON)
add_subdirectory( googlemock )
<file_sep>cmake_minimum_required(VERSION 2.8)
project(HELLO CXX)
message(STATUS "cmake and gtest")
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
add_executable(hello_world src/hello_world.cc)
| ec8aae14de037c6e8f4cbc44a6a187f54232fa3e | [
"Markdown",
"CMake",
"C++"
]
| 6 | C++ | kodo-0000/cmake-learning | 0114e3af82d2daaf4c936cb056a81220c7c3f998 | 38750bf340f26023d26e4e329652fde4a0b8c807 |
refs/heads/master | <file_sep>from flask import Flask
from flask_keystone import FlaskKeystone
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello World!"
@app.route('/<name>')
def hello_name(name):
return "Hello {}!".format(name)
if __name__ == "__main__":
# pragma: nocover
app1 = FlaskKeystone(app)
#app = app1.init_app(app)
#app = app.init_app()
app.run(host="0.0.0.0", port=8080)
<file_sep>Flask
flask-keystone==0.2
<file_sep>Steps
=====
1) Setup Keystone
2) Install Flask, Keystone client
3) Execute test to issue token
Setup Keystone
=================
$ sudo docker pull stephenhsu/keystone:9.1.0
$ sudo docker run -d -p 5000:5000 -p 35357:35357 --name mykeystone stephenhsu/keystone:9.1.0
$ sudo docker exec -it mykeystone bash
copy the /root/openrc
Install Flask, Keystone client
==============================
$ pip install Flask
$ pip install flask-keystone==0.2
or
$ pip install -r requirements.txt
Execute test to issue token
==============================
$ bash -x test/get_tokens.sh
| 98d12b5f741978593ea4942e4a2361a2e89b2f64 | [
"Markdown",
"Python",
"Text"
]
| 3 | Python | snivas/flask-keystone | 0c3f80b486ca37c17c92b769ef92f69d010efeed | a4533d9fb448a8597537088a6b32d80231ef9fee |
refs/heads/master | <file_sep>//
// Config.swift
// Perfect-App-Template
//
// Created by <NAME> on 2017-02-20.
// Copyright (C) 2017 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PerfectLib
import JSONConfig
import PerfectSession
import PerfectSessionPostgreSQL
import LocalAuthentication
import OAuth2
import StORM
import PostgresStORM
struct AppCredentials {
var clientid = ""
var clientsecret = ""
}
func config() {
#if os(Linux)
let fname = "./config/ApplicationConfigurationLinux.json"
#else
let fname = "./config/ApplicationConfiguration.json"
#endif
if let configData = JSONConfig(name: fname) {
if let dict = configData.getValues() {
// Required Values
httpPort = dict["httpport"] as? Int ?? httpPort
// Optional Values
if let i = dict["databasedebug"] {
if (i as? String ?? "") == "true" {
StORMdebug = true
}
}
if let i = dict["sslCertPath"] {
if !(i as? String ?? "").isEmpty {
sslCertPath = i as? String ?? ""
}
}
if let i = dict["sslKeyPath"] {
if !(i as? String ?? "").isEmpty {
sslKeyPath = i as? String ?? ""
}
}
if let i = dict["baseDomain"] {
if !(i as? String ?? "").isEmpty {
SessionConfig.cookieDomain = i as? String ?? SessionConfig.cookieDomain
}
}
// For ORM
PostgresConnector.host = dict["postgreshost"] as? String ?? "localhost"
PostgresConnector.username = dict["postgresuser"] as? String ?? ""
PostgresConnector.password = dict["<PASSWORD>"] as? String ?? ""
PostgresConnector.database = dict["postgresdbname"] as? String ?? ""
PostgresConnector.port = dict["postgresport"] as? Int ?? 5432
// For Sessions
PostgresSessionConnector.host = PostgresConnector.host
PostgresSessionConnector.port = PostgresConnector.port
PostgresSessionConnector.username = PostgresConnector.username
PostgresSessionConnector.password = <PASSWORD>
PostgresSessionConnector.database = PostgresConnector.database
PostgresSessionConnector.table = "sessions"
// Outbound email config
SMTPConfig.mailserver = dict["mailserver"] as? String ?? ""
SMTPConfig.mailuser = dict["mailuser"] as? String ?? ""
SMTPConfig.mailpass = dict["mailpass"] as? String ?? ""
SMTPConfig.mailfromaddress = dict["mailfromaddress"] as? String ?? ""
SMTPConfig.mailfromname = dict["mailfromname"] as? String ?? ""
// OAuth2 Config
if let i = dict["facebookAppID"] { FacebookConfig.appid = i as? String ?? "" }
if let i = dict["facebookSecret"] { FacebookConfig.secret = i as? String ?? "" }
if let i = dict["facebookEndpointAfterAuth"] { FacebookConfig.endpointAfterAuth = i as? String ?? "" }
if let i = dict["facebookRedirectAfterAuth"] { FacebookConfig.redirectAfterAuth = i as? String ?? "" }
if let i = dict["githubKey"] { GitHubConfig.appid = i as? String ?? "" }
if let i = dict["githubSecret"] { GitHubConfig.secret = i as? String ?? "" }
if let i = dict["githubEndpointAfterAuth"] { GitHubConfig.endpointAfterAuth = i as? String ?? "" }
if let i = dict["githubRedirectAfterAuth"] { GitHubConfig.redirectAfterAuth = i as? String ?? "" }
if let i = dict["googleKey"] { GoogleConfig.appid = i as? String ?? "" }
if let i = dict["googleSecret"] { GoogleConfig.secret = i as? String ?? "" }
if let i = dict["googleEndpointAfterAuth"] { GoogleConfig.endpointAfterAuth = i as? String ?? "" }
if let i = dict["googleRedirectAfterAuth"] { GoogleConfig.redirectAfterAuth = i as? String ?? "" }
if let i = dict["linkedinKey"] { LinkedinConfig.appid = i as? String ?? "" }
if let i = dict["linkedinSecret"] { LinkedinConfig.secret = i as? String ?? "" }
if let i = dict["linkedinEndpointAfterAuth"] { LinkedinConfig.endpointAfterAuth = i as? String ?? "" }
if let i = dict["linkedinRedirectAfterAuth"] { LinkedinConfig.redirectAfterAuth = i as? String ?? "" }
if let i = dict["slackKey"] { SlackConfig.appid = i as? String ?? "" }
if let i = dict["slackSecret"] { SlackConfig.secret = i as? String ?? "" }
if let i = dict["slackEndpointAfterAuth"] { SlackConfig.endpointAfterAuth = i as? String ?? "" }
if let i = dict["slackRedirectAfterAuth"] { SlackConfig.redirectAfterAuth = i as? String ?? "" }
if let i = dict["salesforceKey"] { SalesForceConfig.appid = i as? String ?? "" }
if let i = dict["salesforceSecret"] { SalesForceConfig.secret = i as? String ?? "" }
if let i = dict["salesforceEndpointAfterAuth"] { SalesForceConfig.endpointAfterAuth = i as? String ?? "" }
if let i = dict["salesforceRedirectAfterAuth"] { SalesForceConfig.redirectAfterAuth = i as? String ?? "" }
}
} else {
print("Unable to get Configuration")
}
}
<file_sep>//
// oAuth2ConvertToUser.swift
// PerfectAuthServer
//
// Created by <NAME> on 2017-07-19.
//
import SwiftMoment
import PerfectHTTP
import PerfectLogger
import LocalAuthentication
extension Handlers {
static func oAuth2ConvertToUser(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let contextAccountID = request.session?.userid ?? ""
let contextAuthenticated = !(request.session?.userid ?? "").isEmpty
if !contextAuthenticated { response.redirect(path: "/login") }
let user = Account()
guard let source = request.session?.data["loginType"] else {
response.redirect(path: "/")
response.completed()
return
}
do {
try user.find(["source": source, "remoteid": contextAccountID])
if user.id.isEmpty {
// no user, make one.
user.makeID()
user.usertype = .standard
user.source = source as? String ?? "unknown"
user.remoteid = contextAccountID // storing remote id so we can upgrade to user
user.detail["firstname"] = request.session?.data["firstName"] as? String ?? ""
user.detail["lastname"] = request.session?.data["lastName"] as? String ?? ""
try user.create()
request.session?.userid = user.id // storing new user id in session
} else {
// user exists, upgrade session to user.
request.session?.userid = user.id
}
} catch {
// no user
print("something wrong finding user: \(error)")
response.redirect(path: "/")
response.completed()
return
}
response.redirect(path: "/")
response.completed()
}
}
}
| f638154c95efc755ac89595b4b761958733a8ddd | [
"Swift"
]
| 2 | Swift | YoelL/Perfect-Authentication-Server | a55613ad476a606b1e729c8ed5d8d60d45b60c86 | 3210a6257007a0a0e1c35272afcc6cff8b614fa6 |
refs/heads/master | <file_sep><?php
session_start();
$numbers = array('00','01','02','03','04','05','06','07','08','09','10','11','12'); shuffle($numbers);
$colours = array('b','r','g','y'); shuffle($colours);
$cards = array('zzz'); //initialize the cards with +4
foreach($colours as $colour){
foreach($numbers as $number){
$cards[] = $colour . $number;
}
}
$cards = array_diff($cards, array('y00')); //remove y00
shuffle($cards); //shuffle the cards
shuffle($cards);
$players = array('player1','player2','player3','player4');
$game = array(
$players[0] => array_slice($cards,0*13,13),
$players[1] => array_slice($cards,1*13,13),
$players[2] => array_slice($cards,2*13,13),
$players[3] => array_slice($cards,3*13,13),
'colour' => '',
'team1_req' => 0,
'team2_req' => 0,
'team1_got' => 0,
'team2_got' => 0
);
//foreach($players as $player){
// rsort($game[$player]); //sort cards by color in descending order
//}
$_SESSION['game'] = $game;
print(json_encode($_SESSION['game']['player1']));<file_sep>okia
====
okia game
<file_sep>function newgame(){
$.get('php/newgame.php',function(r){
//$("#player1").html(r);
var div = $("#player1");
div.empty();
var cards = eval('('+ r +')');
for(var card in cards){
div.append('<img class="card" src="./img/'+ cards[card] +'.png" />');
}
var players = ['player2','player3','player4'];
for(var i in players){
$('#'+players[i]).html('<img class="card" src="./img/___.png" />');
}
for(var i in players){
for(var j=0;j<12;j++){
$('#'+players[i]).append('<img class="card stacked" src="./img/___.png" />');
}
}
});
}
function resetgame(){
var players = ['player1','player2','player3','player4'];
for(var i in players){
$('#'+players[i]).html('<img class="card" src="./img/___.png" />');
}
for(var i in players){
for(var j=0;j<12;j++){
$('#'+players[i]).append('<img class="card stacked" src="./img/___.png" />');
}
}
}
function create_account(){
$('#main').load('html/newplayer.html?_='+_t());
}
function forgot_pswd(){
$('#main').load('html/forgot_pswd.html?_='+_t());
}
function show_login(){
$('#main').load('html/login.html?_='+_t());
}
function _t(){
return (new Date()).getTime();
}
$(document).ready(function(){
$.get('html/game.html',function(r){
$("#main").html(r);
resetgame();
newgame();
});
//show_login();
});<file_sep>drop database if exists okia;
create database okia;
use okia;
create table player(
id varchar(20) not null primary key,
pswd varchar(32) not null,
name varchar(50) not null,
email varchar(100) not null unique,
is_online enum('0','1') not null default '0',
lastlogin datetime
);
create table room(
id bigint not null primary key,
player1 varchar(20) not null,
player2 varchar(20) not null,
player3 varchar(20) not null,
player4 varchar(20) not null
);
create table game(
id smallint not null primary key,
room_id bigint not null ,
colour enum('r','b','y','g') not null default 'r',
team1_req smallint not null default 0,
team2_req smallint not null default 0,
team1_got smallint not null default 0,
team2_got smallint not null default 0,
created datetime not null
);
create table game_state(
room_id bigint not null,
game_id smallint not null,
ser_num smallint not null auto increment primary key,
state varchar(500) not null,
primary key(room_id,game_id),
);
| c4ae72208e91654aa8541ddccb8c17077d97aac8 | [
"Markdown",
"SQL",
"JavaScript",
"PHP"
]
| 4 | PHP | hsnmtw/okia | d8b887589e6e7cbaa9ddc9fc256a883c9515eadb | 0d1aad87242c38d7df75424d468ca8f1b61361bd |
refs/heads/master | <file_sep>import vk
import json
import time
import getpass
id_app = getpass.getpass('Enter App id: ')
login = getpass.getpass('Enter login: ')
password = getpass.getpass('Enter password: ')
def vkAutorization():
session = vk.AuthSession(id_app, login, password, scope='wall, messages, groups')
vk_api = vk.API(session)
return vk_api
def id_groups_load():
filename = 'groups_id.json'
with open(filename, mode='r', encoding='utf-8') as myfile:
data = json.load(myfile)
return data
def add_python_news():
news = []
post = {}
python_news = []
for id in id_groups_load():
post = vkAutorization().wall.search(owner_id=-id['owner_id'], query='Python', extended='1', count='1')['wall'][1]
news.append(post)
post = {}
for posts in news:
if ((time.time() - posts['date']) <= 86400) and (posts['from_id'] == posts['to_id']) and (posts['post_type'] != 'copy'):
post = posts
python_news.append(post)
post = {}
del news[0]
return python_news
if __name__ == "__main__":
py_posts = add_python_news()
filename = 'python_posts'
with open(filename, mode='w', encoding='utf-8') as myfiles:
json.dump(py_posts, myfiles)
<file_sep>from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
import json
import random
import getpass
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
token = getpass.getpass('Enter your Bot token: ')
def start(bot, update):
update.message.reply_text('Hi!')
def help(bot, update):
update.message.reply_text('Help!')
def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))
def news_load():
filename = 'xpost.json'
with open(filename, mode="r", encoding='utf-8') as myfile:
data = json.load(myfile)
return data
def random_python_news(bot, update):
post = random.choice(news_load())
update.message.reply_text(post['attachments'][0]['link']['title'] + post['attachments'][0]['link']['preview_url'])
return 0
def main():
updater = Updater(token)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("python_news", random_python_news))
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()<file_sep>import vk
import json
import time
import getpass
filename = 'groups_id.json'
with open(filename, mode="w", encoding='utf-8') as myfile:
id_app = getpass.getpass('Enter App id: ')
login = getpass.getpass('Enter login: ')
password = getpass.getpass('Enter password: ')
def vkAutorization():
session = vk.AuthSession(id_app, login, password, scope='wall, messages, groups')
vk_api = vk.API(session)
return vk_api
def group_request():
search = ['Python']
groups = vkAutorization().groups.search(q='Python', count='10', extended='1')
del groups[0]
return groups
def python_groups_id():
id_group = []
owner_id = {}
for group in group_request():
if group['is_closed'] == 0:
newses = vkAutorization().wall.search(owner_id=-group['gid'], query='Python', extended='1')['wall']
time.sleep(1)
del newses[0]
for news in newses:
if ((time.time() - news['date']) <= 86400):
print(group['gid'], group['name'])
owner_id['owner_id'] = group['gid']
id_group.append(owner_id)
owner_id = {}
break
return id_group
if __name__ == "__main__":
json.dump(python_groups_id(), myfile)
<file_sep># Telegram Bot #
## In this project I created Telegram Bot, which gives the user latest news about Python programming language from publics and communities from vk.com ##
This Bot takes information from vk.com used API VK. You can familiarize with it [here](https://vk.com/dev). Before start the work, you should create your Application [here](https://vk.com/editapp?act=create), get your application's ID. This data will allow you be autorized and work with API VK Methods. Also it uses module VK to facilitate work with API requests. To start working with [Telegram](http://web.telegram.org.ru/#/login) API find @BotFather, send him /start, /newbot, write the name of the bot and you will get your access token.
### Example of Telegram token ###
<KEY>
# Groups about Python #
In this part we will log in in VK using **getpass.getpass()** to enter our data. You should run this file from console, enter you application ID, VK login and password. This script will create file in your project's directory. Using API methods this script will check VK publics by keyword "Python" and search news which contain this keyword. ID of suitable groups will dump in json-file
**Using methods**
[Group seacrh](https://vk.com/dev/groups.search)
[News check](https://vk.com/dev/wall.search)
# Python Posts #
Further, using file from first script, we will make some data base with news about Python from VK publics. We will also use, as before VK API Methods, and find tematic news about Python. ID of publics about Python will help us. At the end of this script we will have json-file with news. This script requires authorization in VK, just like in first script.
**Using methods**
[Search news by ID of public](https://vk.com/dev/wall.search)
# NewsBot #
And finally directly bot. As it was said, you need Telegram token for work with Telegram API. This script using json-file from previous script and take title of news and link. To start working with this bot, you should find it in Telegram's search by the name NewsBot. Press start and command **/python_news** gives you latest news about Python.
| ddc8121c0a6036faa367fb10fe5a6d983abd8eae | [
"Markdown",
"Python"
]
| 4 | Python | mcproger/TelegramBot | 4c3564c017407620630214ee26a87f1a11e122eb | 9a6e2907b074f6ae9afdf62f5139ed7a0612438c |
refs/heads/master | <file_sep># intervalModifierCalculator
<b>What is this?</b><br>
A simple calculator used to determine the suggested interval modifier % in Anki.
<b>What is interval modifier?</b><br>
Interval modifier allows you to apply a multiplication factor to the intervals Anki generates. At its default of 100% it does nothing; if you set it to 80% for example, intervals will be generated at 80% of their normal size (so a 10 day interval would become 8 days). You can thus use the multiplier to make Anki present cards more or less frequently than it would otherwise, trading study time for retention or vice versa. (anki manual, 2021)
<b>How is the calculation determined?</b><br>
log(desired retention%) / log(current retention%)
<b>What should my desired retention be?</b><br>
85% keeps it challenging enough to strengthen memory retention
<b>How do I get my current retention</b><br>
I recommend downloading the addon "True Retention" and then inputting the "true retention%" under the stats field from Anki.
<b>Why do I even need to change the interval modifier?</b><br>
Adjusting the interval modifier will allow you increase your "true retention" by increasing/decreasing the frequency you see cards.
Please let me know if there are any issues.
<file_sep>const myBtn = document.querySelector("#myBtn");
//final version
myBtn.addEventListener("click", function () {
let desiredPercent = document.querySelector("#retention").value;
let currentPercent = document.querySelector("#current").value;
let desired = desiredPercent / 100;
let current = currentPercent / 100;
let decimalForm = getInterval(desired, current);
let suggested = Math.floor(decimalForm);
if (currentPercent >= 100) {
document.querySelector("h2").classList.remove("message");
document.querySelector("h2").textContent = "You're a Genius";
} else if (isNaN(suggested)) {
document.querySelector("h2").classList.add("message");
document.querySelector("h2").textContent = "Please input numbers";
} else {
document.querySelector("h2").classList.remove("message");
document.querySelector("h2").textContent = `${suggested}%`;
}
});
function getInterval(x, y) {
return (Math.log(x) / Math.log(y)) * 100;
}
// don't forget to use .value to get the value 바보
//input as a decimal
// myBtn.addEventListener("click", function () {
// let desired = document.querySelector("#retention").value;
// let current = document.querySelector("#current").value;
// let decimalForm = getInterval(desired, current);
// let suggested = Math.floor(decimalForm);
// document.querySelector("h2").textContent = `${suggested}%`;
// });
// function getInterval(x, y) {
// return (Math.log(x) / Math.log(y)) * 100;
// }
//input as a %
// myBtn.addEventListener("click", function () {
// let desiredPercent = document.querySelector("#retention").value;
// let currentPercent = document.querySelector("#current").value;
// let desired = desiredPercent / 100;
// let current = currentPercent / 100;
// let decimalForm = getInterval(desired, current);
// let suggested = Math.floor(decimalForm);
// document.querySelector("h2").textContent = `${suggested}%`;
// });
| fe56e49a422ea35707c5ce3693e1042ea4baf375 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | coofzilla/intervalModifierCalculator | a3b5d117dbb38a0c0720a552da802e75133c0e78 | c4a91ffd7bda52fe87d18e1ce19952bc159e4f9f |
refs/heads/master | <file_sep><?php
namespace App\Model;
/**
* Created by PhpStorm.
* User: mkowal
* Date: 11.06.2019
* Time: 15:42
*/
class UserModel
{
/**
* @var int
*/
private $id;
/**
* @var string
*/
private $firstName;
/**
* @var string
*/
private $lastName;
/**
* @var string
*/
private $email;
/**
* @var string
*/
private $gender;
/**
* @var bool
*/
private $isActive;
/**
* @var string
*/
private $password;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @var \DateTime
*/
private $updatedAt;
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
* @return UserModel
*/
public function setId(int $id): UserModel
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getFirstName(): string
{
return $this->firstName;
}
/**
* @param string $firstName
* @return UserModel
*/
public function setFirstName(string $firstName): UserModel
{
$this->firstName = $firstName;
return $this;
}
/**
* @return string
*/
public function getLastName(): string
{
return $this->lastName;
}
/**
* @param string $lastName
* @return UserModel
*/
public function setLastName(string $lastName): UserModel
{
$this->lastName = $lastName;
return $this;
}
/**
* @return string
*/
public function getEmail(): string
{
return $this->email;
}
/**
* @param string $email
* @return UserModel
*/
public function setEmail(string $email): UserModel
{
$this->email = $email;
return $this;
}
/**
* @return string
*/
public function getGender(): string
{
return $this->gender;
}
/**
* @param string $gender
* @return UserModel
*/
public function setGender(string $gender): UserModel
{
$this->gender = $gender;
return $this;
}
/**
* @return bool
*/
public function isActive(): bool
{
return $this->isActive;
}
/**
* @param bool $isActive
* @return UserModel
*/
public function setIsActive(bool $isActive): UserModel
{
$this->isActive = $isActive;
return $this;
}
/**
* @return string
*/
public function getPassword(): string
{
return $this->password;
}
/**
* @param string $password
* @return UserModel
*/
public function setPassword(string $password): UserModel
{
$this->password = $password;
return $this;
}
/**
* @return \DateTime
*/
public function getCreatedAt(): \DateTime
{
return $this->createdAt;
}
/**
* @param \DateTime $createdAt
* @return UserModel
*/
public function setCreatedAt(\DateTime $createdAt): UserModel
{
$this->createdAt = $createdAt;
return $this;
}
/**
* @return \DateTime
*/
public function getUpdatedAt(): \DateTime
{
return $this->updatedAt;
}
/**
* @param \DateTime $updatedAt
* @return UserModel
*/
public function setUpdatedAt(\DateTime $updatedAt): UserModel
{
$this->updatedAt = $updatedAt;
return $this;
}
}<file_sep>## NEWS SYSTEM
This code in simple News system with register/login method written in plain PHP
without using any kind of framework.
Only users that have account and are logged in can add new, edit or delete newses.
Fields for registration are handled by MySQL engine to fill fields of
`created_at`, `updated_at`. Until News will be edited for the first time field will contain
*0000-00-00 00:00:00*
On creating a new News MySQL engine is filling fields `created_at`, `updated_at`.
And when News is edited field `updated_at` is changed from MySQL engine
To test it on please use login:
`<EMAIL>` and password `<PASSWORD>`<file_sep><?php
include_once('src/Controller/NewsesController.php');
if(isset($_SESSION["login"]) && $_SESSION["login"] === true){
$newsesController = new \App\Controller\NewsesController();
$newses = $newsesController->getAllNewses();
if (isset($_POST['edit'])) {
include('news_edit.php');
}
if (isset($_POST['add_news'])) {
$newsesController->addNews();
header('Location:/');
}
?>
<script type="text/javascript">
function showHideAddNews() {
var x = document.getElementById("createNews");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<div class="col-xs-10">
<div class="col-xs-8">
<button class="btn btn-success" onclick="showHideAddNews()">Create News</button>
</div>
<div class="container" id="createNews" style="display: none">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1>Create post</h1>
<form action="" method="POST">
<div class="form-group">
<label for="news">News name</label>
<input type="text" class="form-control" id="name" name="name" required minlength="3" maxlength="20"/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea rows="5" class="form-control" name="description" id="description" required minlength="3" maxlength="2000"></textarea>
</div>
<div class="form-group">
<label for="is_active">Is Active</label>
<select id="is_active" name="is_active" placeholder="" class="input-xlarge">
<option value="true">true</option>
<option value="false">false</option>
</select>
</div>
<div class="form-group">
<input type="submit" name="add_news" class="btn btn-default" value="Add News">
</div>
</form>
</div>
</div>
</div>
<div class="container">
<div class="row">
<table class="table table-hover table-responsive">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Is Active</th>
<th>Created</th>
<th>Updated</th>
<th>Author</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
foreach ($newses as $id => $news){
?>
<tr id="desc<?php echo $news['id']?>">
<td><?php echo $news['id']?></td>
<td id="desc_name" contenteditable="true" ><?php echo $news['name']; ?></td>
<td id="desc_desc" contenteditable="true" ><?php echo $news['description']; ?></td>
<td id="desc_is_active"><?php echo $news['is_active']; ?></td>
<td id="desc_created"><?php echo $news['created']; ?></td>
<td id="desc_updated"><?php echo $news['updated']; ?></td>
<td id="desc_author"><?php echo $news['author_id']; ?></td>
<td>
<form action="" method="POST">
<input type="text" class="form-control" id="editId" name="editId"
value="<?php echo $news['id']?>" style="display: none;"/>
<input type="text" class="form-control" id="editId" name="editName"
value="<?php echo $news['name']?>" style="display: none;"/>
<input type="text" class="form-control" id="editId" name="editDescription"
value="<?php echo $news['description']?>" style="display: none;"/>
<input type="text" class="form-control" id="editId" name="editIsActive"
value="<?php echo $news['is_active']?>" style="display: none;"/>
<input type="submit" name="edit" class="btn btn-warning btn-sm" value="Edit">
</form>
</td>
<td>
<form action="" method="POST">
<input type="text" class="form-control" id="descId" name="descId"
value="<?php echo $news['id']?>" style="display: none;"/>
<input type="submit" name="delete" class="btn btn-danger btn-sm" value="Delete">
</form>
</td>
</tr>
<?php $i++; } ?>
</tbody>
</table>
</div>
</div>
</div>
<?php
} else {
?>
<strong>You have no permission to be here, leave and never come back</strong>
<?php
}
?>
<file_sep><?php
include_once('src/Controller/UserController.php');
include_once('src/Model/UserModel.php');
include_once('src/Controller/NewsesController.php');
$newsesController = new \App\Controller\NewsesController();
$newses = $newsesController->getActiveNewses();
if (isset($_POST['register'])) {
$userController = new \App\Controller\UserController();
if ($userController->isUserExist($_POST['email'])){
$register_info = 'User with that email already exist';
}else {
if ($userController->registerUser()) {
$register_info = 'Your account has been created';
}
}
}
if (isset($_POST['login'])) {
session_start();
$userController = new \App\Controller\UserController();
if ($userController->loginUser()){
header('Location:/');
}else {
$register_info = 'Failed to login, wrong password';
}
}
?>
<script type="text/javascript">
function showHide(id) {
var x = document.getElementById("showHide");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<button class="btn btn-success" onclick="showHide()">Login/Register</button>
<div style="display: none" id="showHide">
<div class="col-xs-6" style="float: left">
<form class="form-horizontal" action='' method="POST">
<fieldset>
<div id="legend">
<legend class="">Register</legend>
</div>
<div class="control-group">
<label class="control-label" for="username">First Name</label>
<div class="controls">
<input type="text" id="first_name" name="first_name" placeholder="" class="input-xlarge" required minlength="3" maxlength="20">
<p class="help-block">First name can contain any letters, without spaces</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="username">Last Name</label>
<div class="controls">
<input type="text" id="last_name" name="last_name" placeholder="" class="input-xlarge" required minlength="3" maxlength="20">
<p class="help-block">Last name can contain any letters, without spaces</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="username">Gender</label>
<div class="controls">
<select id="gender" name="gender" placeholder="" class="input-xlarge">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<p class="help-block">Gender can be selected from male and female</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">E-mail</label>
<div class="controls">
<input type="email" id="email" name="email" placeholder="" class="input-xlarge">
<p class="help-block">Please provide your E-mail</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="password_1" name="password" placeholder="" class="input-xlarge" required minlength="3" maxlength="20">
<p class="help-block">Password should be at least 3 characters</p>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" name="register" class="btn btn-success" value="Register">
</div>
</div>
</fieldset>
</form>
</div>
<div class="col-xs-6">
<form class="form-horizontal" action='' method="POST">
<fieldset>
<div id="legend">
<legend class="">Login</legend>
</div>
<div class="control-group">
<!-- E-mail -->
<label class="control-label" for="email">E-mail</label>
<div class="controls">
<input type="text" id="email" name="email" placeholder="" class="input-xlarge">
<p class="help-block">Please provide your E-mail</p>
</div>
</div>
<div class="control-group">
<!-- Password 1-->
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="password_1" name="password" placeholder="" class="input-xlarge">
<p class="help-block">Password should be at least 3 characters</p>
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<input type="submit" name="login" class="btn btn-success" value="Login">
</div>
</div>
</fieldset>
</form>
</div>
</div>
<P><?php echo $register_info;?></P>
<div class="container">
<div class="row">
<table class="table table-hover table-responsive">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Is Active</th>
<th>Created</th>
<th>Updated</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
foreach ($newses as $id => $news){
?>
<tr id="desc<?php echo $news['id']?>">
<td><?php echo $news['id']?></td>
<td id="desc_name"><?php echo $news['name']; ?></td>
<td id="desc_desc"><?php echo $news['description']; ?></td>
<td id="desc_is_active"><?php echo $news['is_active']; ?></td>
<td id="desc_created"><?php echo $news['created_at']; ?></td>
<td id="desc_updated"><?php echo $news['updated_at']; ?></td>
</tr>
<?php $i++; } ?>
</tbody>
</table>
</div>
</div>
</div><file_sep><?php
namespace App\Controller;
/**
* Created by PhpStorm.
* User: mkowal
* Date: 12.06.2019
* Time: 00:08
*/
use App\Model\UserModel;
/**
* Class UserController
*
* @package App\Controller
*/
class UserController
{
private $user;
private $connection;
public function __construct()
{
$config = include($_SERVER['DOCUMENT_ROOT'].'/config.php');
try{
$this->connection = new \mysqli($config['host'], $config['user'], $config['password'], $config['name']);
}catch (\Exception $e){
echo $e->getMessage() . '<br>' . 'There have been a connection issue';
}
}
/**
* Method for allowing user to log in
* @return bool
*/
public function loginUser() : bool
{
$email = $_POST['email'];
$password = $_POST['<PASSWORD>'];
$sql = 'SELECT * FROM users
WHERE email = "'.$email.'"';
$query = $this->connection->query($sql);
$result = $query->fetch_array();
if ($query->num_rows == 1 && password_verify($password, $result['password']))
{
$_SESSION['login'] = true;
$_SESSION['user_id'] = $result['id'];
$_SESSION['first_name'] = $result['first_name'];
$_SESSION['last_name'] = $result['last_name'];
return true;
}
else
{
return false;
}
}
/**
* Method for creating new account for user.
* @return bool
*/
public function registerUser() : bool
{
$sql = 'INSERT
INTO users (first_name, last_name, gender, email, password)
VALUES (?, ?, ?, ?, ?);';
$statement = $this->connection->prepare($sql);
$hashedPassword = password_hash($this->user->getPassword(), PASSWORD_DEFAULT);
$statement->bind_param('sssss',
$this->user->getFirstName(),
$this->user->getLastName(),
$this->user->getGender(),
$this->user->getEmail(),
$hashedPassword
);
$query = $statement->execute();
return $query;
}
/**
* Validating if user already exit in DB, if not creating a model of user
* that will be used later for creating new user.
*
* @param string $email
* @return bool
*/
public function isUserExist(string $email) : bool
{
$user = $this->connection->query('SELECT * FROM users WHERE email = "'.$email.'"');
if ($user->num_rows > 0){
return true;
}
$this->setUser();
return false;
}
/**
* Setting UserModel for later use
*
* @return UserModel
*/
private function setUser() : UserModel
{
$user = new UserModel();
$user
->setFirstName($_POST['first_name'])
->setLastName($_POST['last_name'])
->setEmail($_POST['email'])
->setGender($_POST['gender'])
->setPassword($_POST['<PASSWORD>']);
$this->user = $user;
return $user;
}
/**
* @return UserModel
*/
public function getUser() : UserModel
{
return $this->user;
}
/**
* Method to perform logout and destroying session.
* @return bool
*/
public static function logout() : bool
{
session_destroy();
unset($_SESSION['login']);
unset($_SESSION['user_id']);
unset($_SESSION['first_name']);
unset($_SESSION['last_name']);
return true;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: mkowal
* Date: 11.06.2019
* Time: 15:48
*/
namespace App\Model;
class NewsModel
{
/**
* @var int
*/
private $id;
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $description;
/**
* @var bool
*/
private $isActive;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @var \DateTime
*/
private $updatedAt;
/**
* @var int
* UserID
*/
private $authorId;
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
* @return NewsModel
*/
public function setId(int $id): NewsModel
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
* @return NewsModel
*/
public function setName(string $name): NewsModel
{
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getDescription(): string
{
return $this->description;
}
/**
* @param string $description
* @return NewsModel
*/
public function setDescription(string $description): NewsModel
{
$this->description = $description;
return $this;
}
/**
* @return bool
*/
public function isActive(): bool
{
return $this->isActive;
}
/**
* @param bool $isActive
* @return NewsModel
*/
public function setIsActive(bool $isActive): NewsModel
{
$this->isActive = $isActive;
return $this;
}
/**
* @return \DateTime
*/
public function getCreatedAt(): \DateTime
{
return $this->createdAt;
}
/**
* @param \DateTime $createdAt
* @return NewsModel
*/
public function setCreatedAt(\DateTime $createdAt): NewsModel
{
$this->createdAt = $createdAt;
return $this;
}
/**
* @return \DateTime
*/
public function getUpdatedAt(): \DateTime
{
return $this->updatedAt;
}
/**
* @param \DateTime $updatedAt
* @return NewsModel
*/
public function setUpdatedAt(\DateTime $updatedAt): NewsModel
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* @return int
*/
public function getAuthorId(): int
{
return $this->authorId;
}
/**
* @param int $authorId
* @return NewsModel
*/
public function setAuthorId(int $authorId): NewsModel
{
$this->authorId = $authorId;
return $this;
}
}<file_sep>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>News Test</title>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<?php
session_start();
// Checks if user is logged in, so correct page could be displayed.
if(isset($_SESSION["login"]) && $_SESSION["login"] === true){
// Page for all manipulation of newses
include("news_admin.php");
}else{
// Main page for not logged in user, where all active newses are displayed, and register or login is possible
include('register.php');
}
include('footer.php');<file_sep><?php
include_once('src/Controller/NewsesController.php');
include_once('src/Controller/UserController.php');
if(isset($_SESSION["login"]) && $_SESSION["login"] === true){
$newsesController = new \App\Controller\NewsesController();
$newses = $newsesController->getAllNewses();
if (isset($_POST['delete'])) {
$newsesController->deleteNews($_POST['descId']);
header('Location:/');
}
if (isset($_POST['edit'])) {
$newsesController->editNews();
header('Location:/');
}
if (isset($_POST['add_news'])) {
$newsesController->addNews();
header('Location:/');
}
if (isset($_POST['logout']))
{
\App\Controller\UserController::logout();
header('Location:/');
}
?>
<script type="text/javascript">
function showHideAddNews() {
var x = document.getElementById("createNews");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function showHideEdit(id) {
var x = document.getElementsByClassName("editNews"+id);
for (var i = 0; i < x.length; i++) {
if (x[i].style.display === "none") {
x[i].style.display = "block";
} else {
x[i].style.display = "none";
}
}
}
</script>
<div class="col-xs-10">
<div class="col-xs-8">
<button class="btn btn-success" onclick="showHideAddNews()">Create News</button>
<div class="col-xs-8" style="float: right;">
<span>You are loged in as: <?php echo $_SESSION['first_name']?> <?php echo $_SESSION['last_name']?> </span>
<form action="" method="POST">
<input type="submit" name="logout" class="btn btn-default" value="Logout">
</form>
</div>
</div>
<div class="container" id="createNews" style="display: none">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1>Create post</h1>
<form action="" method="POST">
<div class="form-group">
<label for="news">News name</label>
<input type="text" class="form-control" id="name" name="name" required minlength="3" maxlength="20"/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea rows="5" class="form-control" name="description" id="description" required minlength="3" maxlength="2000"></textarea>
</div>
<div class="form-group">
<label for="is_active">Is Active</label>
<select id="is_active" name="is_active" placeholder="" class="input-xlarge">
<option value="1">true</option>
<option value="0">false</option>
</select>
</div>
<div class="form-group">
<input type="submit" name="add_news" class="btn btn-default" value="Add News">
</div>
</form>
</div>
</div>
</div>
<div class="container">
<div class="row">
<table class="table table-hover table-responsive">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Is Active</th>
<th>Created</th>
<th>Updated</th>
<th>Author</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
foreach ($newses as $id => $news){
?>
<tr id="desc<?php echo $news['id']?>">
<td><?php echo $news['id']?></td>
<td id="desc_name"><?php echo $news['name']; ?></td>
<td id="desc_desc"><?php echo $news['description']; ?></td>
<td id="desc_is_active"><?php echo $news['is_active']; ?></td>
<td id="desc_created"><?php echo $news['created_at']; ?></td>
<td id="desc_updated"><?php echo $news['updated_at']; ?></td>
<td id="desc_author"><?php echo $news['author_id']; ?></td>
<td>
<button type="button" class="btn btn-warning btn-sm" onclick="showHideEdit(<?php echo $news['id']?>)"> Edit </button>
</td>
<td>
<form action="" method="POST">
<input type="text" class="form-control" id="descId" name="descId"
value="<?php echo $news['id']?>" style="display: none;"/>
<input type="submit" name="delete" class="btn btn-danger btn-sm" value="Delete">
</form>
</td>
</tr>
<tr>
<td>
<input type="text" class="form-control" id="editId<?php echo $news['id']?>" name="editId<?php echo $news['id']?>"
value="<?php echo $news['id']?>" style="display: none;" form="editForm<?php echo $news['id']?>"/>
</td>
<td>
<input type="text" class="form-control editNews<?php echo $news['id']?>" id="editName<?php echo $news['id']?>" name="editName<?php echo $news['id']?>"
value="<?php echo $news['name']?>" form="editForm<?php echo $news['id']?>" style="display: none;"/>
</td>
<td>
<input type="text" class="form-control editNews<?php echo $news['id']?>" id="editDescription<?php echo $news['id']?>" name="editDescription<?php echo $news['id']?>"
value="<?php echo $news['description']?>" form="editForm<?php echo $news['id']?>" style="display: none;"/>
</td>
<td>
<select form="editForm<?php echo $news['id']?>" id="editIsActive<?php echo $news['id']?>" name="editIsActive<?php echo $news['id']?>" placeholder="" class="input-xlarge editNews<?php echo $news['id']?>" style="display: none;"/>
<option value="1">true</option>
<option value="0">false</option>
</select>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
<form action="" method="POST" id="editForm<?php echo $news['id']?>">
<input type="submit" name="edit" style="display: none;"
class="btn btn-default btn-sm editNews<?php echo $news['id']?>" value="Save">
</form>
</td>
<td>
</td>
</tr>
<?php $i++; } ?>
</tbody>
</table>
</div>
</div>
</div>
<?php
} else {
?>
<strong>You have no permission to be here, leave and never come back</strong>
<?php
}
?>
<file_sep><?php
return [
'host' => 'localhost',
'user' => 'redrum_root',
'password' => '<PASSWORD>',
'name' => 'redrum_test'
];
?>
<file_sep><?php
/**
* Created by PhpStorm.
* User: mkowal
* Date: 12.06.2019
* Time: 21:02
*/
namespace App\Controller;
/**
* Class NewsesController
*
* @package App\Controller
*/
class NewsesController
{
/**
* @var \mysqli
*/
private $connection;
/**
* NewsesController constructor.
*/
public function __construct()
{
$config = include($_SERVER['DOCUMENT_ROOT'].'/config.php');
try{
$this->connection = new \mysqli($config['host'], $config['user'], $config['password'], $config['name']);
}catch (\Exception $e){
echo $e->getMessage() . '<br>' . 'There have been a connection issue';
}
}
/**
* Selecting only active newses that will be showed for not logged in users
* @return array
*/
public function getActiveNewses() : array
{
$sql = 'SELECT * FROM newses
WHERE is_active = 1';
$query = $this->connection->query($sql);
$data = [];
while ($row = $query->fetch_array(MYSQLI_ASSOC)) {
$data[] = $row;
}
return $data;
}
/**
* Fetch all Newses that will be showed for logged in user, so it could be
* edit or delete.
* @return array
*/
public function getAllNewses() : array
{
$sql = 'SELECT * FROM newses';
$query = $this->connection->query($sql);
$data = [];
while ($row = $query->fetch_array(MYSQLI_ASSOC)) {
$data[] = $row;
}
return $data;
}
/**
* Deleting News
* @param $id
*/
public function deleteNews(string $id) : bool
{
$deleteSQL = 'DELETE FROM newses
WHERE id = "'.$id.'"';
$query = $this->connection->query($deleteSQL);
return $query;
}
/**
* Editing News
* @return bool
*/
public function editNews() : bool
{
foreach ($_POST as $item) {
//ID is always first
$id = $item;
break;
}
$updateSQL = 'UPDATE
newses SET name = "'.$_POST['editName'.$id].'",
description= "'.$_POST['editDescription'.$id].'",
is_active = "'.$_POST['editIsActive'.$id].'"
WHERE id = "'.$id.'"';
$statement = $this->connection->prepare($updateSQL);
$query = $statement->execute();
return $query;
}
/**
* Adding new News
* @return bool
*/
public function addNews()
{
$sql = 'INSERT
INTO newses (name, description, author_id, is_active)
VALUES (?, ?, ?, ?);';
$statement = $this->connection->prepare($sql);
$statement->bind_param('ssss',
$_POST['name'],
$_POST['description'],
$_SESSION['user_id'],
$_POST['is_active']
);
$query = $statement->execute();
return $query;
}
} | 88c160224da432d7f96657534900721b66f15330 | [
"Markdown",
"PHP"
]
| 10 | PHP | mkowal87/news | ed4da11753e655807e1adde057b7670e34552964 | 2b1b47e27422bcf7e7747dc8082976fecc486540 |
refs/heads/master | <repo_name>bendyna/ProgrammingAssignment2<file_sep>/cachematrix.R
makeCacheMatrix <- function(m = matrix()) {
## creates a special "matrix", which is really a list containing
## a function to
## 1. set the value of the matrix
## 2. get the value of the matrix
## 3. set the value of the inverse
## 4. get the value of the inverse
cacheInverse <- NULL
set <- function(newMatrix) {
m <<- newMatrix
## value changed, so cacheInverse is no longer valid
cacheInverse <<- NULL
}
get <- function() m
setInverse <- function(inverse) cacheInverse <<- inverse
getInverse <- function() cacheInverse
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
cacheSolve <- function(m, ...) {
## calculates the inverse of the special "matrix" created with the
## above function. However, it first checks to see if the inverse has
## already been calculated. If so, it gets the inverse from the cache
## and skips the computation. Otherwise, it calculates the inverse of
## the data and sets the value of the inverse in the cache via the
## setInverse function.
inverse <- m$getInverse()
if(!is.null(inverse)) {
message("getting cached data")
## we have cache of inverse, so just return it
return(inverse)
}
data <- m$get()
## calculate inverse of matrix
inverse <- solve(data, ...)
## save inverse in cache of special "matrix"
m$setInverse(inverse)
inverse
}
| 09be09589d7c2c73679195a7e8eda635ef503114 | [
"R"
]
| 1 | R | bendyna/ProgrammingAssignment2 | 9ed2b68046c46b08040e980a9c2bd8cde3fb54ac | b3c2bc19a4ee9ff3bd06a75135a80e2b314bbcb7 |
refs/heads/master | <file_sep># 1.5.1
d <- slice(diamonds, c(seq(1, nrow(diamonds), by = 2)))
# 1.5.2
my_df <- mtcars %>%
select(mpg, am, vs, hp) %>%
filter(mpg > 14, hp > 100) %>%
arrange(desc(mpg)) %>%
slice(1:10) %>%
rename(`Miles per gallon` = mpg, `Gross horsepower` = hp)<file_sep># 1.6.1
all_to_factor <- function(x) {
as.data.frame(sapply(x, function(x) as.factor(x), simplify = F))
}
# 1.6.2
rescale <- function(x) {
1 + ((x - min(x)) / (max(x) - min(x)))
}
log_transform <- function(x) {
y <- mutate_if(x, is.numeric, rescale)
z <- mutate_if(y, is.numeric, log)
return(z)
}
# 1.6.3
descriptive_stats <- function(test_data) {
test_data %>%
group_by(gender, country) %>%
summarize_all(funs(n = n(), mean = mean(., na.rm = T), sd = sd(., na.rm = T), median = median(., na.rm = T), first_quartile = unname(quantile(., na.rm = T)[2]), third_quartile = unname(quantile(., na.rm = T)[4]), na_values = sum(is.na(.))))
}
# 1.6.4
to_factors <- function (data, factors){
data[factors] <- data[factors] %>%
mutate_if(is.numeric, funs(as.factor(ifelse(. > mean(., na.rm = T), 1, 0))))
return(data)
}
# 1.6.5
data <- dplyr::group_by(diamonds, color)
high_price <- data_frame()
for (i in levels(diamonds$color)) {
res <- data %>%
filter(color == i) %>%
arrange(desc(price)) %>%
select(color, price) %>%
head(10)
high_price <- bind_rows(high_price, res)
}<file_sep># 1.7.1
filter.expensive.available <- function(data, vect) {
dat <- data[(price>500000) & (brand %in% vect) & (available == T),
.(price, available, brand)]
return(dat)
}
# 1.7.2
ordered.short.purchase.data <- function(data){
data <- data[quantity > 0]
data <- data[order(price, decreasing = T)]
data <- data[, list(ordernumber, product_id)]
return(data)
}
# 1.7.3
purchases.median.order.price <- function(purchases) {
median(purchases[quantity > 0, list(summa = sum(price*quantity)), by = ordernumber]$summa)
}
<file_sep># 2.3.1
mpg_facet <- ggplot(mtcars, aes(x = mpg)) +
facet_grid(am ~ vs) +
geom_dotplot()
# 2.3.2
sl_wrap <- ggplot(iris, aes(x = Sepal.Length)) +
facet_wrap( ~ Species) +
geom_density()
# 2.3.3
my_plot <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point() +
geom_smooth() +
facet_wrap( ~ Species)
# 2.3.4
my_plot <- ggplot(myMovieData, aes(x = Type, y = Budget)) +
facet_grid(. ~ Year) +
geom_boxplot() +
theme(axis.text.x = element_text(angle = 90, hjust = 1))<file_sep># 1.3.1
get_negative_values <- function(test_data){
res<-apply(test_data,2, function(x) x[!is.na(x) & x<0])
return(res[sapply(res,function(x) length(x)>0 )])}
# 1.3.2
na_rm <- function(x) {
res1 <- function(y) {y[is.na(y)] <- mean(y, na.rm=T); y}
return(as.data.frame(apply(x,2,res1)))
}<file_sep># 1.4.1
my_names <- function (dataset, names){
dataset[grepl(paste(names, collapse = "|"), dataset$name),]
}
# 1.4.2
find_outliers <- function(test_data) {
funny <- function(z) ifelse(abs(z) > mean(z) + 2*sd(z), 1, 0)
var_fact <- names(which(sapply(test_data, is.factor)))
var_num <- names(which(sapply(test_data, is.numeric)))
res <- test_data %>%
group_by_(.dots = var_fact) %>%
mutate_at(var_num, funs(is_outlier = funny))
return(res)
}
# 1.4.3
smart_lm <- function(data) {
satis_cols <-
names(which(sapply(data[-1],
function(x) shapiro.test(x)$p.value > 0.05)))
if (length(satis_cols) > 0) {
pred_col <- colnames(data[1])
foo <- as.formula(
paste(pred_col,
paste(satis_cols, collapse = " + "),
sep = " ~ "))
lm(foo, data = data)$coefficients
} else {
print("There are no normal variables in the data")
}
}
# 1.4.4
one_sample_t <- function(data, param) {
mu = param
data <- data[sapply(data, is.numeric)]
lapply(data,
function(x) c(t.test(x, mu = param)$statistic,
t.test(x, mu = param)$parameter,
t.test(x, mu = param)$p.value))
}
# 1.4.5
get_p_value <- function(test_list) {
lapply(test_list, function(x) x$p.value)
}
<file_sep># 1.2.1
row_max <- apply(my_df, MARGIN = 1, FUN = max)
# 1.2.2
col_median <- apply(my_df, MARGIN = 2, FUN = median)
<file_sep>Решения задач из курса **Анализ данных в R. Часть 2**
Ссылка - [https://stepik.org/course/724]()<file_sep># 2.1.1
depth_hist <- qplot(x = depth, data = diamonds)
# 2.1.2
price_carat_clarity_points <- qplot(data = diamonds, x = carat, y = price, color = clarity)
# 2.1.3
x_density <- qplot(data = diamonds, x = x, geom = "density")
# 2.1.4
x_cut_density <- qplot(data = diamonds, x = x, geom = "density", color = cut)
# 2.1.5
price_violin <- qplot(data = diamonds, x = color, y = price, geom = 'violin')<file_sep># 1.8.1
get.category.ratings <- function(purchases, product.category) {
setkey(product.category, product_id)
setkey(purchases, product_id)
merge(product.category, purchases, by = 'product_id')[,list(totalcents = sum(totalcents), quantity=sum(quantity)), by = category_id]
}
# 1.8.2
mark.position.portion <- function(sample.purchases) {
sample.purchases <- sample.purchases[quantity>0]
sample.purchases[, "price.portion" := as.character(sprintf("%.2f",
round(((quantity*price)/ sum(price*quantity))*100, 2))),
by = ordernumber]}<file_sep># 2.2.1
my_plot <- ggplot(mtcars,aes(x = factor(am), y = mpg)) +
geom_violin() +
geom_boxplot(width = 0.2)
# 2.2.2
my_plot <- ggplot(sales, aes(x = income, y = sale)) +
geom_point(aes(color = shop)) +
geom_smooth()
# 2.2.3
my_plot <- ggplot(sales, aes(x = shop, y = income, col = season))+
stat_summary(fun.data = mean_cl_boot, position = position_dodge(0.2))
# 2.2.4
my_plot <- ggplot(sales, aes(x = date, y = sale, group = shop, col = shop))+
stat_summary(fun.data = mean_cl_boot, geom = "errorbar", position = position_dodge(0.2)) + # добавим стандартную ошибку
stat_summary(fun.data = mean_cl_boot, geom = "point", position = position_dodge(0.2)) + # добавим точки
stat_summary(fun.data = mean_cl_boot, geom = "line", position = position_dodge(0.2))<file_sep>iris_plot <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, col = Species)) +
geom_point() +
geom_smooth() +
scale_color_discrete(name = "Вид цветка", label = c("Ирис щетинистый",
"Ирис разноцветный",
"Ирис виргинский")) +
scale_x_continuous(name = "Длина чашелистика", limits = c(4,8)) +
scale_y_continuous(name = "Длина лепестка", breaks = c(1,seq(1,7,1)),limits = c(1,7)) | 6adccda75fa363eb5b70efd0a451b796d46c6c98 | [
"Markdown",
"R"
]
| 12 | R | Legosta/Data_analysis_in_R._Part_2_stepik.org | ab0ad28368ae667c16af412f12b0ed9d0b704013 | 74c59b1ec332bddbaa48ca4243f1e4ba3f644d77 |
refs/heads/master | <repo_name>marciopocebon/checktranslations<file_sep>/Makefile
xmldocdiff: main.cpp
g++ -o xmldocdiff main.cpp
<file_sep>/main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <cctype>
#include <cstring>
static std::string readfile(const char filename[], const bool dots)
{
std::ifstream f(filename);
if (!f.is_open()) {
std::cerr << "error: failed to open '" << filename << "'\n";
return "";
}
std::ostringstream ret;
enum {tagname, tagdata, content} state = content;
for (char c = f.get(); f.good(); c = f.get()) {
// update state..
if (c == '<') {
state = tagname;
} else if (c == ' ' && state == tagname) {
state = tagdata;
} else if (c == '>' && (state == tagname || state == tagdata)) {
state = content;
}
// filtering input data..
if (state == tagname) {
ret << c;
} else if (state == content) {
if (c == '\n')
ret << c;
else if (dots && (c == '.' ||
c == '!' ||
c == '?' ||
c == '\"' ||
c == '>' ||
std::isdigit(c&0xff))) {
ret << c;
}
}
}
return ret.str();
}
int main(int argc, char** argv)
{
std::cout << "xmldocdiff\n";
std::string file1, file2;
bool dots = false;
if (argc == 3) {
file1 = argv[1];
file2 = argv[2];
} else if (argc == 4 && strcmp(argv[1],"--dots")==0) {
file1 = argv[2];
file2 = argv[3];
} else {
std::cout << "syntax: xmldocdiff [--dots] file1.xml file2.xml\n";
return 1;
}
const std::string data1(readfile(argv[1], dots));
const std::string data2(readfile(argv[2], dots));
/*
std::ofstream f1("dbg1.txt");
f1 << data1;
std::ofstream f2("dbg2.txt");
f2 << data2;
*/
// match data1 and data2, ignoring newlines
unsigned int line1 = 1, line2 = 1;
std::string::size_type pos1 = 0, pos2 = 0;
while (pos1 < data1.size() || pos2 < data2.size()) {
unsigned char c1 = 0;
while (pos1 < data1.size() && c1 == 0) {
c1 = data1[pos1++];
if (c1 == '\n') {
line1++;
c1 = 0;
}
}
unsigned char c2 = 0;
while (pos2 < data2.size() && c2 == 0) {
c2 = data2[pos2++];
if (c2 == '\n') {
line2++;
c2 = 0;
}
}
if (c1 != c2) {
std::cerr << "mismatch.\n"
<< " line1=" << line1 << " line2=" << line2 << "\n"
<< " data1=" << (char)c1 << " data2=" << (char)c2 << "\n";
return 1;
}
}
return 0;
}
| 393afd53d1859391b2e84e69071dd8589bc8df33 | [
"Makefile",
"C++"
]
| 2 | Makefile | marciopocebon/checktranslations | 33b0c3220ab1ad76cf323a09a0836af466ea4ab8 | 011ff7178421e29b6cdfaa24e12f65d6890b6c24 |
refs/heads/main | <file_sep>
<!-- PROJECT LOGO -->
<br />
<p align="center">
<a href="https://www.fablabpalermo.org">
<img src="logo.png" alt="Logo" >
</a>
<h2 align="center">Fabphone</h>
<h3 align="center">
Giochiamo tra Fablab con il VoIP e la Digital Fabrication
</h3>
</p>
<br />
<!-- TABLE OF CONTENTS -->
## Sommario :phone:
* [Descrizione del progetto](#Descrizione-del-progetto)
* [Hardware, software e competenze necessarie](#Hardware,-software-e-competenze-necessarie)
* [Getting Started](#getting-started)
* [Installazione software](#Installazione-software)
* [Assemblaggio hardware](#Assemblaggio-hardware)
<!-- ABOUT THE PROJECT -->
## Descrizione del progetto
Fabphone è un progetto ludico che si ispira ai "telefoni rossi" della guerra fredda.
Lo scopo del progetto è quello di coinvolgere i Fablab (quelli riportati su fablabs.io) in una iniziativa di co-progettazione attraverso la "gamification": ogni laboratorio costruisce la propria versione di questo telefono VoIP, personalizzando e migliorando hardware e software senza limiti.
Unica regola: tutti i fabphone devono essere in grado di telefonarsi, costituendo un client di una linea VoIP privata che connette i Fablab per comunicare, sperimentare e giocare.
Il progetto nasce da Falab Palermo, che ha creato i primi due telefoni e gestisce attualmente la rete VoIP Fabphone.
<!-- Hardware software -->
### Hardware, software e competenze necessarie
Il progetto è stato finora realizzato utilizzando Raspberry Pi 3 e 4, cuffie e microfoni USB, tastierino a membrana a matrice a 16 tasti (4x4), diffusore acustico amplificato.
Sulle Raspberry viene installato Raspbian, un client VoIP (twinkle), un client VPN (openvpn) per la connessione sicura verso il server VoIP, uno script Phyton per l'utilizzo del tastierino a matrice come tastiera, tre script per l'auto-avvio del sistema.
Esiste anche un lato server che verrà descritto ma che non è necessario conoscere nel dettaglio a meno che non si voglia contribuire nel miglioramento e nella gestione della rete VoIP, attualmente gestita da Fablab Palermo su server di un membro del direttivo.
Le competenze necessarie per riuscire a costruire un Fabphone sono di livello medio basso per quanto riguarda le connessioni tra gli hardware e le installazioni software. Dal punto di vista della costruzione di eventuali "case", Fablab Palermo ha deciso di non condividere nessun file per spingere il più possibile la personalizzazione e quindi le relative competenze di artigianato digitale sono variabili.
Per quanto riguarda il lato server, qualora si voglia contribuire in quel senso, le competenze necessarie spaziano dalla gestione di VPS, al protocollo VPN, all'utilizzo di sistemi Asterisk. Se volete contribuire sul lato server... chiamate Fablab Palermo col vostro Fabphone! (anche una mail andrà benissimo :smile: ).
<!-- GETTING STARTED -->
## Getting Started
Il primo passo è quello di installare il sistema operativo sulla Raspberry, seguendo la guida:
https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up
Non appena la Raspberry è funzionante con Raspbian, seguite l'installazione guidata al primo avvio, dove vi verrà chiesto di configurare sia la vostra rete sia la vostra password root
Segnatevi la password perché più in là vi servirà
<img src="doc/img/wizard.JPG">
<img src="doc/img/wizard2.JPG">
<img src="doc/img/wizard3.JPG">
<img src="doc/img/wizard3-1.JPG">
<img src="doc/img/wizard4.JPG">
<img src="doc/img/wizard4-1.JPG">
<img src="doc/img/wizard6.JPG">
Una volta conclusi l'installazione guidata e l'aggiornamento del sistema, vi verrà richiesto di riavviare.
Una volta riavviato, per evitare che dopo l'assemblaggio di tutto il vostro Fabphone sia sempre necessario collegare la Raspberry a monitor e tastiera per controllarla, vi consigliamo di abilitare sia VNC che SSH, come illustrato nei seguenti screenshot
<img src="doc/img/confrasp.PNG">
<img src="doc/img/confrasp2.PNG">
<br />
<br />
<h2>
<span style="color: red"> Prima di continuare con l'installazione software si consiglia di contattarci via email per avere sia i setaggi che i file di configurazione per la VPN </span>
<h1>
<!-- installation -->
## Installazione software
Per gestire la Raspberry da remoto, scaricare e installare REALVNC Viwer per il vostro sistema operativo dal link https://www.realvnc.com/en/connect/download/viewer/
recuperiamo l'IP della nostra rasp usando il comando aprendo il terminale
<img src="doc/img/termianle.PNG">
```sh
ifconfig wlan0
```
<img src="doc/img/ifcofig.JPG">
esempio 192.168.137.177
inseriamolo sul software appena scaricato e usiamo i dati di acesso
ip.jpg
<img src="doc/img/ip.jpg">
user : pi
Password : <PASSWORD> durante il primo avvio
Per prima cosa aprire il terminale
<img src="doc/img/termianle.PNG">
Controllare di essere nella cartella home con il comando pwd
```sh
pwd
```
<img src="doc/img/cartellahome.JPG">
Se la cartella è "/home/pi" potete continuare; in caso contrario digitare "cd /home/pi"
```sh
cd /home/pi
```
A questo punto, per avere tutti i file necessari, occorrerà scaricare il contentuto del Git nella cartella Home della propria Raspberry, avviando il terminale e utilizzando il comando "git clone"
```sh
git clone https://github.com/FablabPalermo/fabphone.git
```
Una volta scaricato il Git, usate il comando "cd fabphone" per entrare nella cartella corrispondente
```sh
cd fabphone
```
---
La cartella fabphone contiene 3 script per l'auto-avvio e la cartella VoIP dove al suo interno troverete sia l'audio che viene riprodotto dal fabphone sia lo script python "voip.py", che non fa altro che mandare dei comandi alla pressione dei vari tasti
Scrivendo sul terminale "ls" e premendo invio, vedrete questi file e cartelle
--openvpn.sh #script avvio vpn <br />
--voip.sh #script avvio tastiera fabphone <br />
--twinkle.sh #script avvio client voip <br />
---voip #cartella che contine script tastiera e audio <br />
---doc #cartella che contine le immaggini su gitub
---
Dentro questa cartella deve essere copiato il file che verrà allegato all'email
esempio:
voip_raspvoip_voip.ovpn
Consigliamo per i meno esperti di copiare il file su una pendrive e copiarlo dentro la cartella fabphone che si trova all'interno della cartella home
<img src="doc/img/cd.JPG">
<img src="doc/img/cd2.JPG">
<img src="doc/img/cd3.JPG">
<img src="doc/img/cd4.JPG">
<img src="doc/img/cd5.JPG">
<img src="doc/img/cd6.JPG">
Ogni Fablab avrà un file con nome diverso
Modificare il file -openvpn.sh usando il terminale
```sh
echo "sudo openvpn ~/fabphone/nome-del-vostro-file.ovpn" > openvpn.sh
```
Dove c'è scritto "nome-del-vostro-file.ovpn", cambiarlo con il nome del file allegato all'email
Esempio:
```sh
echo "sudo openvpn ~/fabphone/voip_raspvoip_voip.ovpn" > openvpn.sh
```
Per rendere eseguibili questi script all'avvio, dobbiamo lanciare il comando "chmod +x" sui singoli file per dare il permesso di esecuzione
```sh
chmod +x openvpn.sh
chmod +x voip.sh
chmod +x twinkle.sh
```
Ora si dovranno avviare gli script di auto-avvio:
```sh
sudo nano /etc/xdg/lxsession/LXDE-pi/autostart
```
<img src="doc/img/startup.PNG">
Aggiungere
```sh
@/home/pi/fabphone/openvpn.sh
@/home/pi/fabphone/voip.sh
@lxterminal -e /home/pi/fabphone/twinkle.sh
```
<img src="doc/img/startup3.PNG">
Premere la combinazione di tasti "ctrl+x" per salvare
Premere il tasto "S" e dopo premere "invio" per confermare il salvataggio
<img src="doc/img/autoavio.JPG">
Per installare tutto il materiale affinché il sistema Fabphone funzioni correttamente, digitare sul terminale
```sh
sudo apt-get install mpg123 twinkle openvpn -y
sudo pip3 install adafruit-circuitpython-matrixkeypad
sudo pip3 install pynput
```
Al completamanto di questo passaggio si consiglia un reboot della Raspberry
Ora occorrerà configurare il client VoIP
<img src="doc/img/voip.PNG">
<img src="doc/img/voip2.PNG">
<img src="doc/img/voip3.PNG">
<img src="doc/img/voip4.PNG">
<img src="doc/img/voip5.PNG">
<img src="doc/img/voip6.PNG">
Per la corretta configurazione è necessario collegare le cuffie USB alla Rasp in modo da poterle selezionare come dispositivi di comunicazione sul client VoIP.
<img src="doc/img/voip7.PNG">
<img src="doc/img/voip8.PNG">
---
<!-- hardware -->
## Assemblaggio hardware
<img src="doc/img/schema.png">
ATTENZIONE! Il suddetto file openvpn va copiato su una sola Rasp, poiché ogni Fabphone, e quindi ogni Rasp, avrà un suo file.
Copiare lo stesso file su più Rasp provocherà un ban automatico dalla rete VoIP.
Finiti questi passaggi, potete passare all'assemblaggio dell'hardware.
Il collegamento di cuffia con microfono avverrà via USB
Il diffusore acustico amplificato deve invece essere collegato al jack audio della Rasp.
Per il collegamento del tastierino a membrana seguire le seguenti immagini
A questo punto sarà opportuno eseguire un riavvio della Rasp
Se tutto funziona correttamente, al riavvio sentirete tramite il diffusore acustico il messaggio "Fabphone attivo"
Ora potete fare una prima chiamata di test (per la lista nei numeri attivi consultare questo link:...)
IMG Legenda tasti
Per effettuare una chiamata:
ATTENZIONE! Attualmente non è stato implementato nessun sistema di gestione di avvio/chiusura chiamata attraverso il sollevamento della cornetta
- Premere il tasto "*"
- Verrà riprodotto il messaggio "Comporre il numero"
- Comporre il numero (in caso di errore di digitazione usare il tasto "D")
- Premere il tasto "B" per fare partire la chiamata
- Per chiudere la chiamata premere il tasto "C"
<file_sep>python3 ~/fabphone/voip/voip.py
<file_sep>import time
import digitalio
import board
import adafruit_matrixkeypad
from pynput.keyboard import Key, Controller
import os
keyboard = Controller()
#FabLab raspi
rows = [digitalio.DigitalInOut(x) for x in (board.D26, board.D19, board.D13, board.D6)]
cols = [digitalio.DigitalInOut(x) for x in (board.D5, board.D21, board.D20, board.D16)]
keys = ((1, 2, 3,'A'),
(4, 5, 6,'B'),
(7, 8, 9,'C'),
('*', 0, '#','D'))
keypad = adafruit_matrixkeypad.Matrix_Keypad(rows, cols, keys)
os.system('mpg123 ~/fabphone/voip/audio/start.mp3 &')
time.sleep(1)
while True:
keys = keypad.pressed_keys
#if keys:
# print(keys)
if keys == [1]:
keyboard.press('1')
keyboard.release('1')
os.system('mpg123 ~/fabphone/voip/audio/1.mp3 &')
time.sleep(0.5)
if keys == [2]:
keyboard.press('2')
keyboard.release('2')
os.system('mpg123 ~/fabphone/voip/audio/2.mp3 &')
time.sleep(0.5)
if keys == [3]:
keyboard.press('3')
keyboard.release('3')
os.system('mpg123 ~/fabphone/voip/audio/3.mp3 &')
time.sleep(0.5)
if keys == [4]:
keyboard.press('4')
keyboard.release('4')
os.system('mpg123 ~/fabphone/voip/audio/4.mp3 &')
time.sleep(0.5)
if keys == [5]:
keyboard.press('5')
keyboard.release('5')
os.system('mpg123 ~/fabphone/voip/audio/5.mp3 &')
time.sleep(0.5)
if keys == [6]:
keyboard.press('6')
keyboard.release('6')
os.system('mpg123 ~/fabphone/voip/audio/6.mp3 &')
time.sleep(0.5)
if keys == [7]:
keyboard.press('7')
keyboard.release('7')
os.system('mpg123 ~/fabphone/voip/audio/7.mp3 &')
time.sleep(0.5)
if keys == [8]:
keyboard.press('8')
keyboard.release('8')
os.system('mpg123 ~/fabphone/voip/audio/8.mp3 &')
time.sleep(0.5)
if keys == [9]:
keyboard.press('9')
keyboard.release('9')
os.system('mpg123 ~/fabphone/voip/audio/9.mp3 &')
time.sleep(0.5)
if keys == [0]:
keyboard.press('0')
keyboard.release('0')
os.system('mpg123 ~/fabphone/voip/audio/0.mp3 &')
time.sleep(0.5)
if keys == ['A']:
keyboard.type('answer')
keyboard.press(Key.enter)
keyboard.release(Key.enter)
time.sleep(0.5)
if keys == ['B']:
keyboard.type('@192.168.241.2')
keyboard.press(Key.enter)
keyboard.release(Key.enter)
time.sleep(0.5)
if keys == ['*']:
keyboard.type('call sip:')
os.system('mpg123 ~/fabphone/voip/audio/componi.mp3 &')
time.sleep(0.5)
if keys == ['C']:
keyboard.type('bye')
keyboard.press(Key.enter)
keyboard.release(Key.enter)
time.sleep(0.5)
if keys == ['D']:
keyboard.press(Key.backspace)
keyboard.release(Key.backspace)
time.sleep(0.5)
<file_sep>sudo openvpn ~/fabphone/voip_rasp2_voip.ovpn | 4314b9f2a625a56b9c5f9432c496472983c0794f | [
"Markdown",
"Python",
"Shell"
]
| 4 | Markdown | FablabPalermo/fabphone | 764f99252fe0fdd4735cf33ce8980a7a5730b01e | 01ba2c0aeb2b8eebcdeec0157a68e22e24da34f2 |
refs/heads/main | <file_sep>print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, or L ")
add_pepperoni = input("Do you want pepperoni? Y or N ")
extra_cheese = input("Do you want extra cheese? Y or N ")
s = 15
m = 20
l = 25
if size == "s":
if add_pepperoni == "y":
s += 2
else:
s += 0
if extra_cheese == "y":
s += 1
print(str(s))
else:
s += 0
print(str(s))
if size == "m":
if add_pepperoni == "y":
m += 3
else:
m += 0
if extra_cheese == "y":
m += 1
print(str(m))
else:
m += 0
print(str(m))
if size == "l":
if add_pepperoni == "y":
l += 3
else:
l += 0
if extra_cheese == "y":
l += 1
print(str(l))
else:
l += 0
print(str(l))
<file_sep>print("Welcome to the tip calculator.")
total_bill = input("What was the total bill? $")
percentage_tips = input("What percentage tip would you lie to give? 10, 12, or 15? 12: ")
split = input("How many people you want to split the bill?")
tips_percentage = 1 + (float(percentage_tips) / 100)
total_pay = tips_percentage * float(total_bill)
each_person_pay = round(total_pay / float(split), 2)
final_amount = "{:.2f}".format(each_person_pay)
print(f"Each Person should pay: ${final_amount}")
<file_sep>print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
lowercase_name = name1 + name2
lower_name = lowercase_name.lower()
add_t = lower_name.count("t")
add_r = lower_name.count("r")
add_u = lower_name.count("u")
add_e = lower_name.count("e")
add_l = lower_name.count("l")
add_o = lower_name.count("o")
add_v = lower_name.count("v")
add_e = lower_name.count("e")
add_true = add_t + add_r + add_u + add_e
add_love = add_l + add_o + add_v + add_e
print("t "+str(add_t))
print("r "+str(add_r))
print("u "+str(add_u))
print("e "+str(add_e))
print("\n")
print("l "+str(add_l))
print("o "+str(add_o))
print("v "+str(add_v))
print("e "+str(add_e))
total = int(str(add_true) + str(add_love))
# print(str(total))
if total < 10 or total > 90:
print(f"your score is {total}, you go together like coke and mentos.")
elif 40 <= total <= 50:
print(f"your score is{total}, you are alright together.")
else:
print(f"you score is {total}")
| 714033bd53d1d43fb718462d17b49bf1bb0b50c3 | [
"Python"
]
| 3 | Python | 846754008/Solving-question-from-instructor-Angela | 2fc8b4b23147a09f8b5ee438ac8aa260af4718d6 | b49e9ca51c7c3216af75d64f880eeee879444294 |
refs/heads/main | <file_sep>#pragma once
#include <map>
#include <set>
#include "City.hpp"
#include "Color.hpp"
namespace pandemic
{
class Board
{
private:
std::map<City, int> pandemic;
std::set<Color> discoveredCure;
std::set<City> researchStation;
public:
static std::map<City, std::set<City>> connection;
static std::map<City, Color> colorCity;
int &operator[](City city);
bool is_clean();
void remove_cures();
void remove_stations();
friend std::ostream &operator<<(std::ostream &os, const Board &board);
bool hasDisCure(Color color);
bool hasResStation(City city);
void addDisCure(Color color);
void addResStation(City city);
};
} | bf47d0666608960220c08b6da6524fbc2d8a6914 | [
"C++"
]
| 1 | C++ | Roniharel100/CPP_EX4-pandemic_b | 137c941adb2f8fb471764ad08759d4aa8f08297a | 85284b889ac06960953eec4343924fef2d7b486d |
refs/heads/master | <file_sep>const fs = require("fs");
const chalk = require("chalk");
const getNotes = () => {
return "get Notes ....";
};
//Adding Notes
const addNotes = (title, body) => {
const notes = loadNotes();
const duplicateNotes = notes.filter((note) => {
if (note.title === title) {
return true;
}
});
if (duplicateNotes.length === 0) {
notes.push({
title: title,
body: body,
});
saveNotes(notes);
console.log(chalk.green.inverse("Added Note"));
} else {
console.log(chalk.red.inverse("Title already taken"));
}
};
//Removing Notes
const removeNotes = (title) => {
// console.log("Hey i complete the callenge");
const notes = loadNotes();
const removedArray = notes.filter((note) => {
if (note.title !== title) {
return true;
}
});
if (notes.length === removedArray.length) {
console.log(chalk.bgRed.inverse("No! Notes Found"));
} else {
console.log(chalk.bgGreen.inverse("Notes Removed"));
}
saveNotes(removedArray);
};
//Listing Notes
const listNotes = () => {
console.log(chalk.blue.bold.inverse("Your Notes"));
const notes = loadNotes();
notes.forEach((ele, ind) => {
console.log(ele.title);
});
};
//Reading Notes
const readNotes = (title) => {
const notes = loadNotes();
let note;
for (let i = 0; i < notes.length; i++) {
if (title === notes[i].title) {
note = notes[i];
break;
}
}
if (note === undefined) {
console.log(chalk.red.inverse("ERROR"));
} else {
console.log(chalk.yellow.inverse("Title : " + note.title));
console.log(chalk.yellow.inverse("Body : " + note.body));
}
};
const saveNotes = (notes) => {
const JSONdata = JSON.stringify(notes);
fs.writeFileSync("notes.json", JSONdata);
};
const loadNotes = () => {
try {
const buffer = fs.readFileSync("notes.json");
const bufferS = buffer.toString();
const bufferJ = JSON.parse(bufferS);
return bufferJ;
} catch (err) {
return [];
}
};
module.exports = {
getNotes: getNotes,
addNotes: addNotes,
removeNotes: removeNotes,
listNotes: listNotes,
readNotes: readNotes,
};
<file_sep># Notes APP
### Adding Notes : node app.js add --title="Notes Title" --body="Notes Body"
### Remove Notes : node app.js remove --title="Notes Title"
### Listing Notes : node app.js list
### Reading Notes : node app.js read --title="Notes Title"
| cb9db28562a5ec7fca3e96f3bcb04f65835981ea | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | mkp0/Notes-app-with-NodeJS | c52451590b9a96d9811d024271c7bb2b1fe745ff | 8835047c996c6a537023e0c9a79bebfc305ebcbb |
refs/heads/master | <repo_name>nmittler/istio-spring<file_sep>/ratings/src/main/java/io/istio/spring/ratings/GlobalExceptionHandler.java
package io.istio.spring.ratings;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(NotFoundException.class)
protected ResponseEntity<Object> handleNotFound(NotFoundException e, WebRequest request) {
return handleExceptionInternal(e, e.getMessage(), new HttpHeaders(),
HttpStatus.NOT_FOUND,
request);
}
}
<file_sep>/reviews/src/main/java/io/istio/spring/reviews/RatingProperties.java
/*******************************************************************************
* Copyright (c) 2017 Istio Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package io.istio.spring.reviews;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
@ConfigurationProperties(prefix = "rating.service")
public class RatingProperties {
private boolean enabled;
private String url;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Bean
public RestTemplate rest(RestTemplateBuilder builder) {
return builder.build();
}
}
<file_sep>/api/build.gradle
description = 'Service API messages'
dependencies {
compile 'com.google.guava:guava',
// Included for proper handling of Java 8 Optional fields
'com.fasterxml.jackson.datatype:jackson-datatype-jdk8'
}
<file_sep>/settings.gradle
rootProject.name = 'istio-spring'
include ':istio-spring-api'
include ':istio-spring-ratings'
include ':istio-spring-reviews'
include ':istio-spring-boot-starter'
project(':istio-spring-api').projectDir = "$rootDir/api" as File
project(':istio-spring-ratings').projectDir = "$rootDir/ratings" as File
project(':istio-spring-reviews').projectDir = "$rootDir/reviews" as File
project(':istio-spring-boot-starter').projectDir = "$rootDir/boot-starter" as File
<file_sep>/boot-starter/build.gradle
description = 'Istio circuit breaker adapter library for String/Hystrix applications'
dependencies {
compile 'org.springframework.boot:spring-boot',
'org.springframework:spring-aspects',
'org.springframework:spring-webmvc',
'com.netflix.hystrix:hystrix-javanica'
}
<file_sep>/ratings/build.gradle
apply plugin: 'org.springframework.boot'
description = 'Spring-based version of the reviews application.'
dependencies {
compile project(':istio-spring-api'),
'org.springframework.boot:spring-boot-starter-web',
'org.springframework.cloud:spring-cloud-commons',
'com.google.guava:guava',
'org.apache.httpcomponents:httpclient',
'com.netflix.hystrix:hystrix-javanica',
'com.fasterxml.jackson.datatype:jackson-datatype-jdk8'
}
bootRepackage {
mainClass = 'io.istio.spring.ratings.RatingsApplication'
}
<file_sep>/build.gradle
buildscript {
ext {
springBootVersion = '1.5.7.RELEASE'
springCloudCommonsVersion = '1.0.0.RELEASE'
springVersion = '4.3.11.RELEASE'
guavaVersion = '15.0'
httpClientVersion = '4.5.1'
hystrixJavanicaVersion = '1.5.6'
jacksonVersion = '2.8.10'
}
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
subprojects {
apply plugin: 'java'
apply plugin: 'io.spring.dependency-management'
group = "org.istio"
description = 'Spring-based version of the reviews application.'
version = "1.0.0-SNAPSHOT"
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
repositories {
mavenCentral()
mavenLocal()
}
// Configure Spring's dependency management plugin.
dependencyManagement {
dependencies {
dependency "org.springframework.boot:spring-boot:${springBootVersion}"
dependency "org.springframework.boot:spring-boot-starter-web:${springBootVersion}"
dependency "org.springframework:spring-core:${springVersion}"
dependency "org.springframework:spring-aop:${springVersion}"
dependency "org.springframework:spring-aspects:${springVersion}"
dependency "org.springframework:spring-webmvc:${springVersion}"
dependency "org.springframework.cloud:spring-cloud-commons:${springCloudCommonsVersion}"
dependency "com.google.guava:guava:${guavaVersion}"
dependency "org.apache.httpcomponents:httpclient:${httpClientVersion}"
dependency "com.netflix.hystrix:hystrix-javanica:${hystrixJavanicaVersion}"
dependency "com.fasterxml.jackson.datatype:jackson-datatype-jdk8:${jacksonVersion}"
}
}
}
<file_sep>/boot-starter/src/main/java/io/istio/spring/IstioRestTemplateCustomizer.java
/*******************************************************************************
* Copyright (c) 2017 Istio Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package io.istio.spring;
import java.io.IOException;
import org.springframework.boot.web.client.RestTemplateCustomizer;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.RestTemplate;
public class IstioRestTemplateCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
// Add an interceptor to identify all URIs that are being requested during a service method.
restTemplate.getInterceptors().add(new Interceptor());
}
private static final class Interceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
System.err.println("NM: RestTemplate thread ID=" + Thread.currentThread().getId());
CircuitBreakerProperties props = IstioContext.getInstance().getCircuitBreakerProperties();
if (props != null) {
// TODO(nmittler): Add Envoy headers (See https://envoyproxy.github.io/envoy/configuration/http_filters/router_filter.html#http-headers)
System.err.println(
"NM: Making request with config: " + props + " to endpoint: " + request.getURI());
}
return execution.execute(request, body);
}
}
}
<file_sep>/boot-starter/src/main/java/io/istio/spring/CircuitBreakerProperties.java
/*******************************************************************************
* Copyright (c) 2017 Istio Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package io.istio.spring;
import static com.google.common.base.Preconditions.checkNotNull;
import java.time.Duration;
import javax.annotation.Nullable;
/**
* The Istio circuit breaker configuration.
*/
public final class CircuitBreakerProperties {
private static final Duration ONE_MS = Duration.ofMillis(1);
private static final CircuitBreakerProperties DEFAULTS =
newBuilder()
.maxConnections(Integer.MAX_VALUE)
.httpMaxPendingRequests(1024)
.httpMaxRequests(1024)
.sleepWindow(Duration.ofSeconds(30))
.httpConsecutiveErrors(5)
.httpDetectionInterval(Duration.ofSeconds(10))
.httpMaxRequestsPerConnection(Integer.MAX_VALUE)
.httpMaxEjectionPercent(10)
.build();
private final Integer maxConnections;
private final Integer httpMaxPendingRequests;
private final Integer httpMaxRequests;
private final Duration sleepWindow;
private final Integer httpConsecutiveErrors;
private final Duration httpDetectionInterval;
private final Integer httpMaxRequestsPerConnection;
private final Integer httpMaxEjectionPercent;
private CircuitBreakerProperties(Builder builder) {
this.maxConnections = builder.maxConnections;
this.httpMaxPendingRequests = builder.httpMaxPendingRequests;
this.httpMaxRequests = builder.httpMaxRequests;
this.sleepWindow = builder.sleepWindow;
this.httpConsecutiveErrors = builder.httpConsecutiveErrors;
this.httpDetectionInterval = builder.httpDetectionInterval;
this.httpMaxRequestsPerConnection = builder.httpMaxRequestsPerConnection;
this.httpMaxEjectionPercent = builder.httpMaxEjectionPercent;
}
@Nullable
public Integer getMaxConnections() {
return maxConnections;
}
@Nullable
public Integer getHttpMaxPendingRequests() {
return httpMaxPendingRequests;
}
@Nullable
public Integer getHttpMaxRequests() {
return httpMaxRequests;
}
@Nullable
public Duration getSleepWindow() {
return sleepWindow;
}
@Nullable
public Integer getHttpConsecutiveErrors() {
return httpConsecutiveErrors;
}
@Nullable
public Duration getHttpDetectionInterval() {
return httpDetectionInterval;
}
@Nullable
public Integer getHttpMaxRequestsPerConnection() {
return httpMaxRequestsPerConnection;
}
@Nullable
public Integer getHttpMaxEjectionPercent() {
return httpMaxEjectionPercent;
}
@Override
public String toString() {
return "CircuitBreakerProperties{"
+ "maxConnections=" + maxConnections + ", httpMaxPendingRequests=" + httpMaxPendingRequests
+ ", httpMaxRequests=" + httpMaxRequests + ", sleepWindow=" + sleepWindow
+ ", httpConsecutiveErrors=" + httpConsecutiveErrors + ", httpDetectionInterval="
+ httpDetectionInterval + ", httpMaxRequestsPerConnection=" + httpMaxRequestsPerConnection
+ ", httpMaxEjectionPercent=" + httpMaxEjectionPercent + '}';
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
private Integer maxConnections;
private Integer httpMaxPendingRequests;
private Integer httpMaxRequests;
private Duration sleepWindow;
private Integer httpConsecutiveErrors;
private Duration httpDetectionInterval;
private Integer httpMaxRequestsPerConnection;
private Integer httpMaxEjectionPercent;
public Builder maxConnections(int maxConnections) {
this.maxConnections = maxConnections;
return this;
}
public Builder httpMaxPendingRequests(int httpMaxPendingRequests) {
this.httpMaxPendingRequests = httpMaxPendingRequests;
return this;
}
public Builder httpMaxRequests(int httpMaxRequests) {
this.httpMaxRequests = httpMaxRequests;
return this;
}
public Builder sleepWindow(Duration sleepWindow) {
if (sleepWindow.compareTo(ONE_MS) < 0) {
throw new IllegalArgumentException("sleepWindow must be >= 1ms");
}
this.sleepWindow = checkNotNull(sleepWindow);
return this;
}
public Builder httpConsecutiveErrors(int httpConsecutiveErrors) {
this.httpConsecutiveErrors = httpConsecutiveErrors;
return this;
}
public Builder httpDetectionInterval(Duration httpDetectionInterval) {
if (httpDetectionInterval.compareTo(ONE_MS) < 0) {
throw new IllegalArgumentException("httpDetectionInterval must be >= 1ms");
}
this.httpDetectionInterval = httpDetectionInterval;
return this;
}
public Builder httpMaxRequestsPerConnection(int httpMaxRequestsPerConnection) {
this.httpMaxRequestsPerConnection = httpMaxRequestsPerConnection;
return this;
}
public Builder httpMaxEjectionPercent(int httpMaxEjectionPercent) {
this.httpMaxEjectionPercent = httpMaxEjectionPercent;
return this;
}
public CircuitBreakerProperties build() {
return new CircuitBreakerProperties(this);
}
}
}
<file_sep>/boot-starter/src/main/java/io/istio/spring/IstioContext.java
/*******************************************************************************
* Copyright (c) 2017 Istio Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package io.istio.spring;
final class IstioContext {
private static final ThreadLocal<IstioContext> currentCommand =
new ThreadLocal<IstioContext>() {
@Override protected IstioContext initialValue() {
return new IstioContext();
}
};
static IstioContext getInstance() {
return currentCommand.get();
}
private CircuitBreakerProperties circuitBreakerProperties;
void init(CircuitBreakerProperties circuitBreakerProperties) {
this.circuitBreakerProperties = circuitBreakerProperties;
}
CircuitBreakerProperties getCircuitBreakerProperties() {
return circuitBreakerProperties;
}
void clear() {
this.circuitBreakerProperties = null;
}
}
<file_sep>/README.md
A playground for using Spring MVC with Istio.<file_sep>/boot-starter/src/main/java/io/istio/spring/EnvoyHeaders.java
/*******************************************************************************
* Copyright (c) 2017 Istio Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package io.istio.spring;
/**
* Headers supported by Envoy to control request behavior.
*/
public final class EnvoyHeaders {
private EnvoyHeaders() {
}
public final String X_ENVOY_EXPECTED_RQ_TIMEOUT_MS = "x-envoy-expected-rq-timeout-ms";
public final String X_ENVOY_MAX_RETRIES = "x-envoy-max-retries";
public final String X_ENVOY_RETRY_ON = "x-envoy-retry-on";
public final String X_ENVOY_RETRY_GRPC_ON = "x-envoy-retry-grpc-on";
public final String X_ENVOY_UPSTREAM_ALT_STAT_NAME = "x-envoy-upstream-alt-stat-name";
public final String X_ENVOY_UPSTREAM_CANARY = "x-envoy-upstream-canary";
public final String X_ENVOY_UPSTREAM_RQ_TIMEOUT_ALT_RESPONSE =
"x-envoy-upstream-rq-timeout-alt-response";
public final String X_ENVOY_UPSTREAM_RQ_TIMEOUT_MS = "x-envoy-upstream-rq-timeout-ms";
public final String X_ENVOY_UPSTREAM_RQ_PER_TRY_TIMEOUT_MS =
"x-envoy-upstream-rq-per-try-timeout-ms";
public final String X_ENVOY_UPSTREAM_SERVICE_TIME = "x-envoy-upstream-service-time";
public final String X_ENVOY_ORIGINAL_PATH = "x-envoy-original-path";
public final String X_ENVOY_IMMEDIATE_HEALTH_CHECK_FAIL = "x-envoy-immediate-health-check-fail";
public final String X_ENVOY_OVERLOADED = "x-envoy-overloaded";
}
| d1b19a939437302a1ca02fb3d97b418c6a884275 | [
"Markdown",
"Java",
"Gradle"
]
| 12 | Java | nmittler/istio-spring | bddb5dde2aac8d6f849c9b700f347890f1c57fe8 | 596d027a8f60eb77fe8788c33a1f3ab85357fa90 |
refs/heads/master | <repo_name>Frank-1000/practice<file_sep>/babai2/babai2/js/friand.js
$(function(){
// new Promise(function(){
$.ajax({
type: "get",
url: "./server/firand.json",
dataType: "json",
success: function (response) {
let data = response;
// console.log(data);
let html = data.map((ele)=>{
let ulHTML=ele.list.map((ele,index)=>{
return`
<li><a href="http://www.800pharm.com/shop/groupId_1995.html" target="_blank" rel="noopener">${ele}</a></li>
`;
}).join("");
return`
<ul class="ft" style="display: none;">
${ulHTML}
</ul>
`;
}).join("");
$(".ttt").html(html);
// 默认第二个 .ft 显示
$(".ft").eq(1).css("display","block");
// 将内容插入到.hd 后
// $(".hd").appendTo(html);
// console.log(html)
},
error: function() {
console.log("++");
}
});
// }).then(function(){
$(".hd").children().mouseover(function(){
$(this).addClass("cur").siblings().removeClass("cur");
index= $(this).index();
$(".ft").eq(index).css("display","block").siblings().css("display","none");
$(".hd").css("display","block");
})
// $(".hd").css("display","block");
// })
})
<file_sep>/babai2/babai2/js/Cookie.js
let Cookie = {
get(key) {
let result = null;
let arr = document.cookie.split("; ")
arr.forEach((ele) => {
let item = ele.split("=");
if (key == item[0]) {
result = item[1];
}
})
return result;
},
set(key, val, day) {
if (day) {
let date = new Date();
date.setDate(date.getDate() + day);
document.cookie = `${key}=${val};expires=${date}`;
} else {
document.cookie = `${key}=${val}`;
}
},
remove(key) {
this.set(key, null, -1);
},
clear() {
this.keys().forEach(ele => this.remove(ele));
},
keys() {
let result = [];
let arr = document.cookie.split("; ")
arr.forEach((ele) => {
let item = ele.split("=");
result.push(item[0]);
})
return result;
}
};<file_sep>/babai2/js/list.js
$(function(){
/* 001-当页面加载完的时候,要发请求获取数据 */
console.log("___");
let currentType = 0;
new Promise(function(resolve, reject) {
$.ajax({
type: "get",
url: "../server/getPageCount.php",
dataType: "json",
success: function(response) {
let pageCount = response.data;
for (let i = 0; i < pageCount; i++) {
let oPage = $(`<a href="javascript:;">${i+1}</a>`);
$(".pages").append(oPage);
}
$(".pages").children("a").first().addClass("active");
resolve();
}
});
}).then(function() {
getDatWithPage(currentType, 0);
})
/* 002-当拿到数据后根据数据来渲染页面 */
$(".pages").on("click", "a", function(e) {
e.preventDefault();
$(this).addClass("active").siblings().removeClass("active");
/* 先获取当前是第几页 */
let index = $(this).index();
// console.log(index);
getDatWithPage(currentType, index);
})
let getDatWithPage = (type, page) => {
$.ajax({
type: "get",
url: "../server/getProductData.php",
data: `type=${type}&page=${page}`,
dataType: "json",
success: function(response) {
let data = response.data;
// console.log(data);
let html = data.map((ele) => {
// console.log(item);
return `
<div class="mod" id=${ele.id}>
<dl class="b_prod">
<dt class="pic">
<a href="../html/goods.html?${ele.id}" title="伊泰青"
target="_blank"><img
src=${ele.img} alt="伊泰青"
style="width: 100px; height: 100px; padding-top: 0px;"></a>
<span class="tag"></span>
</dt>
<dd class="b_info">
<p class="tit">
<a href="../html/goods.html?${ele.id}" title="伊泰青"
target="_blank">
<i class="rx"></i>
${ele.name}
</a>
</p>
<p class="gnzz" vlimit="88" title="高血压病。">${ele.title}</p>
<p class="c_name">${ele.title2}</p>
</dd>
</dl>
<span class="pdPrice">
<b>¥</b>${ele.price}</span>
<a target="_blank" class="goNextBtn"
href="../html/goods.html?${ele.id}">${ele.a};</a>
</div>
`
}).join("");
$(".b_result").html(html);
},
error: function() {
console.log("++");
}
});
}
$(".listShow1").click(function() {
let index = $(this).index();
currentType = index;
getDatWithPage(currentType, 0);
$(this).addClass("red").siblings().removeClass("red");
})
})
// $(function () {
// $.ajax({
// type: "get",
// url: "../server/data.json",
// // data: `type=${type}&page=${page}`,
// dataType: "json",
// success: function(response) {
// let data = response;
// console.log(data);
// let html = data.map((ele) => {
// // console.log(item);
// return `
// <div class="mod">
// <dl class="b_prod">
// <dt class="pic">
// <a href="http://www.800pharm.com/shop/product-100910-1505763.html" title="伊泰青"
// target="_blank"><img
// src="${ele.img}" alt="伊泰青"
// style="width: 100px; height: 100px; padding-top: 0px;"></a>
// <span class="tag"></span>
// </dt>
// <dd class="b_info">
// <p class="tit">
// <a href="http://www.800pharm.com/shop/product-100910-1505763.html" title="伊泰青"
// target="_blank">
// <i class="rx"></i>
// ${ele.name}
// </a>
// </p>
// <p class="gnzz" vlimit="88" title="高血压病。"> ${ele.title}</p>
// <p class="c_name">${ele.title2}</p>
// </dd>
// </dl>
// <span class="pdPrice">
// <b>¥</b>${ele.pri}</span>
// <a target="_blank" class="goNextBtn"
// href="http://www.800pharm.com/shop/product-100910-1505763.html">${ele.a};</a>
// </div>
// `
// }).join("");
// console.log(html)
// $(".b_result").html(html);
// },
// error: function() {
// console.log("++");
// }
// });
// })<file_sep>/babai2/babai2/js/goos.js
$(function(){
var a=1;
$(".icon_add").click(function(){
a++;
$("#quantity").val(a);
})
$(".icon_rec").click(function(){
a--;
if(a<=0){
a=0;
}
$("#quantity").val(a);
})
// 弹出登陆框
$(".buy").click(function(){
$(".pop").css("display","flex");
})
// 关闭登陆框
$(".close").click(function(){
$(".pop").css("display","none");
})
})
<file_sep>/README.md
# practice
这是八百方网上药店的部分代码,包含登录、注册、商品列表、商品详情等功能,主要技术为jq+ajax;
<file_sep>/babai2/js/goodsList.js
$(function () {
let urlA = location.href;
console.log(urlA)
function urls() {
let urlB = urlA.split("?");
return urlB[1];
}
let url = urls();
$.ajax({
type: "get",
url: "../server/goodsList.php",
data: `id=${url}`,
dataType: "json",
success: function (response) {
let o = response.res[0];
// console.log(o);
console.log("+++");
if(response.res[0]){
$(".font18").get(0).innerText = o.name;
$(".name1").get(0).innerText = o.name;
$(".name2").get(0).innerText = o.title;
$(".price_shang").get(0).innerText = o.price;
}
},
});
})<file_sep>/babai2/js/tob.js
$(function () {
/* 异步请求网络请求 */
/* 发送网络请求 */
// console.log($('.sort-item'))
$.ajax({
type: "get",
url: "./server/data1.json",
dataType: "json",
success: function (response) {
data=response;
console.log(response);
console.log("----");
console.log(data[0].details);
let detailss= data[0].details;
detailss.map(function(ele){
htmls=""
items=ele.items;
for(let i=0;i<items.length;i++){
htmls+=`<li>${items[i]}</li>`
}
// console.log(htmls);
})
// for(var i=0;i<$(".sort-item-box").length;i++){
// }
}
});
})
<file_sep>/babai2/babai2/js/login.js
$(function() {
let phoneInput=$(".phone");
let phoneReg = /^1[3-9]\d{9}$/;
let passwordReg = /^[a-zA-Z0-9]{6,16}$/;
let passwordInput=$(".pws")
let aaa=$(".erroy");
let bbb=$(".ppp");
var a=0,b=0;
$(".btn-hd-email").click(function() {
$(this).addClass("current").siblings().removeClass("current");
$(".phone-box").css("display","none");
$(".form-inline-email").css("display","block");
})
$(".btn-hd-tel").click(function() {
$(this).addClass("current").siblings().removeClass("current");
$(".phone-box").css("display","block");
$(".form-inline-email").css("display","none");
})
// 手机验证
phoneInput.blur(function() {
/* 先获取输入框的值,检查和清理(空格|空) */
var val = $(this).val().trim();
if (val.length == 0) {
bbb.text("手机号码不能为空!");
aaa.slideDown(1);
a=0;
d=a+b;
console.log("a="+a+",b="+b+"d="+d);
} else {
if (!phoneReg.test(val)) {
bbb.text("手机号码不符合规范!");
aaa.slideDown(1);
a=0;
d=a+b;
console.log("a="+a+",b="+b+"d="+d);
} else {
$(this).parents(".form-item").removeClass("form-group-error");
a=1;
d=a+b;
// console.log("a="+a+",b="+b+"d="+d);
}
}
})
// 密码验证
passwordInput.blur(function() {
/* 先获取输入框的值,检查和清理(空格|空) */
var val = $(this).val().trim();
if (val.length == 0) {
bbb.text("密码不能为空!");
aaa.slideDown(1);
b=0;
d=a+b;
console.log("a="+a+",b="+b+"d="+d);
} else {
if (!passwordReg.test(val)) {
bbb.text("密码不符合规范!");
aaa.slideDown(1);
b=0;
d=a+b;
console.log("a="+a+",b="+b+"d="+d);
} else {
b=1;
d=a+b;
console.log("a="+a+",b="+b+"d="+d);
}
}
})
phoneInput.click(function(){
aaa.slideUp(1);
phoneInput.css("border","1px solid blue");
})
phoneInput.blur(function(){
phoneInput.css("border","none");
})
passwordInput.click(function(){
aaa.slideUp(1);
passwordInput.css("border","1px solid blue");
})
passwordInput.blur(function(){
passwordInput.css("border","none");
})
// 发送网络请求
$(".login-btn-submit").click(function() {
if(d!=2){
alert("请完善信息");
return;
}else{
$.ajax({
type: "post",
url: "../server/api/login.php",
data: `phone=${phoneInput.val()}&password=${<PASSWORD>Input.val()}`,
dataType: "json",
success: function(response) {
if (response.status == "success") {
alert(response.data.msg);
window.location.href = "http://127.0.0.1/BBB/babai2/bbf.html";
} else {
alert(response.data.msg);
}
}
});
}
})
})<file_sep>/babai2/js/goods.js
$(function(){
let urlA = location.href;
// let cookieImg=null;
function urls() {
let urlB = urlA.split("?");
return urlB[1];
}
let url = urls();
$.ajax({
type: "get",
url: "../server/goods.php",
data: `id=${url}`,
dataType: "json",
success: function (response) {
let o = response.res[0];
// console.log(o);
// console.log("+++");
if(response.res[0]){
$(".font18").get(0).innerText = o.name;
$(".name1").get(0).innerText = o.name;
$(".name2").get(0).innerText = o.title;
$(".price_shang").get(0).innerText = o.pri;
$(".price_shi").get(0).innerText = o.del;
// cookieImg.get(0)=o.img;
}
},
});
// 增加商品数量
var a=1;
$(".icon_add").click(function(){
a++;
$("#quantity").val(a);
})
$(".icon_rec").click(function(){
a--;
if(a<=0){
a=0;
}
$("#quantity").val(a);
})
// 弹出登陆框
$(".add_cart").click(function(){
var cookieName=$(".font18").get(0).innerText;
var cookiePir= $(".price_shang").get(0).innerText;
Cookie.set("cookieName",cookieName,'/',14);
Cookie.set("cookiePir",cookiePir,'/',14);
alert("添加购物车成功")
})
$(".add_cart2").click(function(){
// alert("添加购物车成功");
window.location.href = "http://127.0.0.1/BBB/babai2/html/car.html";
})
})
<file_sep>/babai2/server/inserData.php
<?php
header("Content-Type:text/html;charset=UTF-8");
# INSERT INTO `products` (`id`, `src`, `title`, `price`, `disCount`, `shopName`)
# VALUES (NULL, '0h_4e', '怡鲜来 丹麦进口冰鲜三文鱼刺身拼盘300g 日式刺身2款 新鲜生鱼片 北极贝刺身套餐 海鲜水产', '68.00', '400+评价', '怡鲜来旗舰店');
# 001-先加载JSON数据
$json = file_get_contents("./data.json");
# 002-把JSON数据转换为PHP数组
$arrData = json_decode($json,true);
// var_dump($arrData);
# Array ( [src] => https://image2.suning.cn/uimg/b2c/newcatentries/0070090031-000000000803018569_1.jpg_400w_400h_4e [title] => 怡鲜来 丹麦进口冰鲜三文鱼刺身拼盘300g 日式刺身2款 新鲜生鱼片 北极贝刺身套餐 海鲜水产 [price] => 78.80 [disCount] => 400+评价 [shopName] => 怡鲜来旗舰店 )
// print_r($arrData);
# 003-先连接数据库
$db = mysqli_connect("127.0.0.1","root","","BBF");
# 004-遍历数组获取数组中每个元素
for($i = 0;$i<count($arrData);$i++)
{
$img = $arrData[$i]["img"];
$name = $arrData[$i]["name"];
$title = $arrData[$i]["title"];
$title2 = $arrData[$i]["title2"];
$price = $arrData[$i]["pri"];
$a = $arrData[$i]["a"];
$sql = "INSERT INTO `products` (`id`, `img`, `name`, `title`, `title2`, `price`, `a`)
VALUES (NULL, '$img', '$name', '$title', '$title2','$price', '$a')";
// echo $sql;
// echo "<br>";
mysqli_query($db, $sql);
}
// print_r($json);
// print_r(floatval(substr($arrData[2]["price"],2)));
// print_r(substr("1234", 1));
?>
<file_sep>/babai2/server/goods.php
<?php
$goods = $_GET['id'];
$db = mysqli_connect("127.0.0.1", "root", "", "bbf");
$sql="SELECT * FROM hotlist where id=$goods";
$result = mysqli_query($db,$sql);
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
$response = array("status"=>"success","res" => $data);
echo json_encode($response,true);
?>
<file_sep>/babai2/babai2/js/floor.js
$(function(){
$.ajax({
type: "get",
url: "./server/floor.json",
dataType: "json",
success: function (response) {
let data = response;
// console.log(data);
let html = data.map((ele,index)=>{
let topHTML=ele.top.map((ele,index)=>{
return`
<a target="_blank" href="http://www.800pharm.com/shop/product-100795-1400519.html">${ele.a}</a>
`;
}).join("");
let dlHTML=ele.dl.map((ele,index)=>{
return`
<a target="_blank" href="http://www.800pharm.com/shop/product-100068-602468.html">${ele.a}</a>
`;
}).join("");
let listHTML=ele.list.map((ele)=>{
return`
<li class="floor-extra-item">
<a href="http://www.800pharm.com/shop/product-100091-403325.html" title="【蔓迪】 米诺地尔酊"
target="_blank">
<img src=${ele.img}
alt="【蔓迪】 米诺地尔酊" class="pd-img">
<div class="pd-wrapper">
<p class="pd-name">${ele.name}</p>
<p class="pd-desp">${ele.title}</p>
<p class="pd-price">
<em>¥${ele.pri}</em>
<del>¥${ele.del}</del>
</p>
</div>
</a>
</li>
`;
}).join("");
return`
<div class="main-floor-box nav-item-box">
<div class="floor-header">
<h2><i class="i-icon floor-${index+1}"></i>${ele.h2}</h2>
<div class="floor-rec-list">
${topHTML}
</div>
</div>
<div class="floor-body">
<div class="floor-main">
<div class="floor-main-content">
<a href="http://www.800pharm.com/shop/product-100815-1392709.html?gg_code=index_yao_main"
title="" target="_blank" style="background-color:#null"><img
src=${ele.src} alt="" border="0"
width="310" height="520"></a>
</div>
</div>
<div class="floor-side">
<div class="floor-side-img">
<a href="http://www.800pharm.com/shop/product-100986-1704772.html?gg_code=index_yao_1" title=""
target="_blank" style="background-color:#null"><img
src=${ele.src2} alt="" border="0"
width="190" height="360"></a>
</div>
<div class="floor-side-rec">
${dlHTML}
</div>
</div>
<div class="floor-extra">
<ul class="floor-extra-list">
${listHTML}
</ul>
</div>
</div>
</div>
`;
}).join("");
$(".kkk").html(html);
},
error: function() {
console.log("++");
}
});
})
| eeda3e6e37c769cd1de4c182dcf804b3e20834f1 | [
"JavaScript",
"PHP",
"Markdown"
]
| 12 | JavaScript | Frank-1000/practice | 7f28b76d5047950dfe22a82c27e763089d8c81f0 | 520bf5988ce83120e01ed58e93d30805c055a124 |
refs/heads/master | <repo_name>theoboraud/Perceptron<file_sep>/PPT.py
import numpy as np
import matplotlib.pyplot as plt
# ------------------------------------------- #
# ---------------- VARIABLES ---------------- #
# ------------------------------------------- #
# Numpy seed
np.random.seed(0)
# Training loop
learning_rate = 0.1
costs = []
# Number of trainings
train_time = 100000
# Number of tests
test_time = 100000
# ------------------------------------------- #
# ---------------- FUNCTIONS ---------------- #
# ------------------------------------------- #
# Sigmoid functions
def sigmoid(x):
return 1/(1 + np.exp(-x))
def sigmoid_p(x):
return sigmoid(x) * (1 - sigmoid(x))
# Create random dataset for training and testing the Perceptron
def random_data(loc, scale, size, group):
dataset = np.empty((size, 3))
dataset[:,:2] = np.random.normal(loc, scale, (size, 2))
dataset[:,2] = group
return dataset
# Estimate Perceptron with stochastic gradient descent
def train(data):
# Random weight generation
weight_1, weight_2, bias = np.random.randn(), np.random.randn(), np.random.randn()
for i in range(train_time):
random_i = np.random.randint(len(data))
point = data[random_i]
activation = point[0] * weight_1 + point[1] * weight_2 + bias
prediction = sigmoid(activation)
target = point[2]
# Cost function
cost = np.square(prediction - target)
# Derivatives
dcost_prediction = 2 * (prediction - target)
dprediction_activation = sigmoid_p(activation)
dactivation_w1 = point[0]
dactivation_w2 = point[1]
dactivation_b = 1
# Slope of cost function
dcost_activation = dcost_prediction * dprediction_activation
# Change weight and bias
weight_1 = weight_1 - (learning_rate * dcost_activation * dactivation_w1)
weight_2 = weight_2 - (learning_rate * dcost_activation * dactivation_w2)
bias = bias - (learning_rate * dcost_activation * dactivation_b)
return [weight_1, weight_2, bias]
# Prediction with weights
def predict(data, weights):
score = 0 # Store the number of time the Perceptron predicted the correct output
for i in range(test_time):
# Select a random point into the dataset
random_i = np.random.randint(len(data))
point = data[random_i]
# Compute the activation of the selected point using the weights obtained and define the prediction made
activation = point[0] * weights[0] + point[1] * weights[1] + weights[2]
prediction = sigmoid(activation)
# Compare the prediction with the target output
target = point[2]
if (target == 1 and prediction >= 0.5) or (target == 0 and prediction < 0.5):
score += 1
# Print out the mean accuracy from score
score = 1.0*score/test_time
print("Mean accuracy: " + '{percent:.2%}'.format(percent=score))
# ------------------------------------------- #
# ----------------- TESTING ----------------- #
# ------------------------------------------- #
# Generate training data
loc1 = 1
loc2 = 3
scale = 0.5
size = 5000
training_data_1 = random_data(loc1, scale, size, 0)
training_data_2 = random_data(loc2, scale, size, 1)
training_data = np.concatenate([training_data_1, training_data_2], axis = 0)
# Print training_data
#plt.scatter(training_data_1[:, 0],training_data_1[:, 1], color = 'red', alpha = 0.1, label = "Group 1")
#plt.scatter(training_data_2[:, 0], training_data_2[:, 1], color = 'blue', alpha = 0.1, label = "Group 2")
#plt.show()
# Generate test data
test_data_1 = random_data(loc1, scale, size, 0)
test_data_2 = random_data(loc2, scale, size, 1)
test_data = np.concatenate([test_data_1, test_data_2], axis = 0)
weights = train(training_data)
predict(test_data, weights)
# Compute weight function
x1 = -1
y1 = (1 - weights[2] - weights[0] * x1) / weights[1]
x2 = 5
y2 = (1 - weights[2] - weights[0] * x2) / weights[1]
# Print test_data
plt.scatter(test_data_1[:, 0],training_data_1[:, 1], color = 'red', alpha = 0.1, label = "Group 0")
plt.scatter(test_data_2[:, 0], training_data_2[:, 1], color = 'blue', alpha = 0.1, label = "Group 1")
plt.plot([x1, x2], [y1, y2], color = 'green')
plt.show()
| 25f1e884b36f0d64fb620116ca61e9449610ffe1 | [
"Python"
]
| 1 | Python | theoboraud/Perceptron | d93c1401c8650ee6006fdc8206fe8e85f669f28d | 2d1a2de1775375c44fc7ca8d3c1bf442ca2f5255 |
refs/heads/master | <repo_name>giftuals/tokenizer<file_sep>/src/Exception/ConfigurationException.php
<?php
namespace Tokenizer\Exception;
use Exception;
/**
* ConfigurationException
*
* PHP version 7.2
*
* @category PHP
* @package Tokenizer
* @author <NAME> <<EMAIL>>
* @copyright 2020 Giftuals
* @license https://giftuals.com No License
* @version 1.0
* @link https://giftuals.com
* @since 31-01-2020
*/
class ConfigurationException extends Exception
{
}
<file_sep>/tests/Config/ConfigTest.php
<?php
declare(strict_types=1);
use Tokenizer\Config\Config;
use PHPUnit\Framework\TestCase;
final class ConfigTest extends TestCase
{
public function testCanAddSettings()
{
$custom_settings = ['foo' => 'bar'];
$config = new Config($custom_settings);
$expected = 'bar';
$result = $config->offsetGet('foo');
$this->assertEquals($expected, $result);
}
}
<file_sep>/tests/TokenizerTest.php
<?php
declare(strict_types=1);
use Tokenizer\Tokenizer;
use Tokenizer\Config\Config;
use PHPUnit\Framework\TestCase;
use Tokenizer\Exception\ConfigurationException;
final class TokenizerTest extends TestCase
{
/**
*
* @dataProvider requiredSettingsProvider
*/
public function testInvalidatesMissingConfigSettings($config_settings)
{
$config = new Config($config_settings);
$this->expectException(ConfigurationException::class);
$tokenizer = new Tokenizer($config);
}
public function requiredSettingsProvider() : array
{
return [
'Hash HMAC key' => [
[],
ConfigurationException::class,
],
'Issuer claim' => [
[Tokenizer::CLAIM_ISSUER => 'foo'],
ConfigurationException::class,
],
'Subject claim' => [
[Tokenizer::CLAIM_SUBJECT => 'foo'],
ConfigurationException::class,
],
'Audience claim' => [
[Tokenizer::CLAIM_AUDIENCE => 'foo'],
ConfigurationException::class,
],
'Combination' => [
[
Tokenizer::CLAIM_ISSUER => 'foo',
Tokenizer::CLAIM_AUDIENCE => 'foo',
],
ConfigurationException::class,
],
];
}
public function testValidatesMinimumConfigSettings()
{
$config = new Config([
Tokenizer::HASH_HMAC_KEY => 'foo',
Tokenizer::CLAIM_ISSUER => 'foo',
Tokenizer::CLAIM_SUBJECT => 'foo',
Tokenizer::CLAIM_AUDIENCE => 'foo',
]);
$tokenizer = new Tokenizer($config);
$this->assertInstanceOf(Tokenizer::class, $tokenizer);
}
public function testCanCreateToken()
{
$config = new Config([
Tokenizer::HASH_HMAC_KEY => 'foo',
Tokenizer::CLAIM_ISSUER => 'foo',
Tokenizer::CLAIM_SUBJECT => 'foo',
Tokenizer::CLAIM_AUDIENCE => 'foo',
]);
$tokenizer = new Tokenizer($config);
$result = $tokenizer->createToken([
'foo' => 'bar',
]);
$this->assertIsString($result);
}
/**
*
* @dataProvider exampleTokensProvider
*/
public function testCanValidateToken($settings, $token, $must_match)
{
$config = new Config($settings);
$tokenizer = new Tokenizer($config);
$result = $tokenizer->createToken();
if (true === $must_match) {
$this->assertEquals($token, $result);
} else {
$this->assertNotEquals($token, $result);
}
}
public function exampleTokensProvider()
{
return [
'Fixed issued at' => [
[
Tokenizer::HASH_HMAC_KEY => 'foo',
Tokenizer::CLAIM_ISSUER => 'foo',
Tokenizer::CLAIM_SUBJECT => 'foo',
Tokenizer::CLAIM_AUDIENCE => 'foo',
Tokenizer::CLAIM_TIMEZONE => 'Europe/Amsterdam',
Tokenizer::CLAIM_ISSUED_AT => '03-02-2020 21:35:30',
],
'<KEY>',
true
],
'Dynamic issued at' => [
[
Tokenizer::HASH_HMAC_KEY => 'foo',
Tokenizer::CLAIM_ISSUER => 'foo',
Tokenizer::CLAIM_SUBJECT => 'foo',
Tokenizer::CLAIM_AUDIENCE => 'foo',
],
'<KEY>',
false
],
'Changed key' => [
[
Tokenizer::HASH_HMAC_KEY => 'bar',
Tokenizer::CLAIM_ISSUER => 'foo',
Tokenizer::CLAIM_SUBJECT => 'foo',
Tokenizer::CLAIM_AUDIENCE => 'foo',
Tokenizer::CLAIM_TIMEZONE => 'Europe/Amsterdam',
Tokenizer::CLAIM_ISSUED_AT => '03-02-2020 21:35:30',
],
'<KEY>',
false
],
];
}
public function testCanReadPayloadWithoutRequiredClaims()
{
$config = new Config([
Tokenizer::HASH_HMAC_KEY => 'foo',
Tokenizer::CLAIM_ISSUER => 'foo',
Tokenizer::CLAIM_SUBJECT => 'foo',
Tokenizer::CLAIM_AUDIENCE => 'foo',
Tokenizer::CLAIM_TIMEZONE => 'Europe/Amsterdam',
Tokenizer::CLAIM_ISSUED_AT => '03-02-2020 21:35:30',
]);
$tokenizer = new Tokenizer($config);
$token = $tokenizer->createToken([
'foo' => 'bar',
'baz' => 'qux',
]);
$result = $tokenizer->getTokenPayload($token);
$expected = ['foo' => 'bar', 'baz' => 'qux'];
$this->assertEquals($expected, $result);
}
public function testCanReadPayloadWithRequiredClaims()
{
$config = new Config([
Tokenizer::HASH_HMAC_KEY => 'foo',
Tokenizer::CLAIM_ISSUER => 'foo',
Tokenizer::CLAIM_SUBJECT => 'foo',
Tokenizer::CLAIM_AUDIENCE => 'foo',
Tokenizer::CLAIM_TIMEZONE => 'Europe/Amsterdam',
Tokenizer::CLAIM_ISSUED_AT => '03-02-2020 21:35:30',
]);
$tokenizer = new Tokenizer($config);
$token = $tokenizer->createToken([
Tokenizer::CLAIM_TIMEZONE => 'Europe/Amsterdam',
Tokenizer::CLAIM_ISSUED_AT => '03-02-2020 21:35:30',
'foo' => 'bar',
'baz' => 'qux',
]);
$result = $tokenizer->getTokenPayload($token, true);
ksort($result);
$expected = [
'foo' => 'bar',
'baz' => 'qux',
Tokenizer::CLAIM_ISSUED_AT => '03-02-2020 21:35:30',
Tokenizer::CLAIM_TIMEZONE => 'Europe/Amsterdam',
];
ksort($expected);
$this->assertEquals($expected, $result);
}
}
<file_sep>/README.md
# Tokenizer
PHP JWT library that allows you to create trustworthy links from and to your website or webapp
[](https://travis-ci.org/giftuals/tokenizer)
## Requirements
* PHP >= 7.2.0
## Installation
```bash
composer require giftuals/tokenizer --dev
```
## Usage
```php
$config = new Tokenizer\Config\Config([
Tokenizer\Tokenizer::HASH_HMAC_KEY => 'some-uber-secret-key',
Tokenizer\Tokenizer::CLAIM_ISSUER => 'Giftuals',
Tokenizer\Tokenizer::CLAIM_SUBJECT => 'Example token',
Tokenizer\Tokenizer::CLAIM_AUDIENCE => 'https://backend.giftuals.com',
]);
$tokenizer = new Tokenizer\Tokenizer($config);
$jwt = $tokenizer->createToken([
'my_own_claim' => 'some random value',
]);
try {
$tokenizer->isValidToken($jwt);
$payload = $tokenizer->getTokenPayload($jwt);
} catch (Tokenizer\Exception\InvalidTokenException $e) {
// Something went wrong
}
```
## Authors
<NAME> ([giftuals](https://github.com/giftuals))
## License
Licensed under the MIT License
<file_sep>/src/Tokenizer.php
<?php
namespace Tokenizer;
use DateTime;
use Tokenizer\Config\Config;
use InvalidArgumentException;
use Tokenizer\Exception\InvalidTokenException;
use Tokenizer\Exception\ConfigurationException;
/**
* Tokenizer
*
* PHP version 7.2
*
* @category PHP
* @package Tokenizer
* @author <NAME> <<EMAIL>>
* @copyright 2020 Giftuals
* @license https://giftuals.com No License
* @version 1.0
* @link https://giftuals.com
* @since 31-01-2020
*/
class Tokenizer
{
const CLAIM_ALGORITHM = 'alg';
const CLAIM_TYPE = 'typ';
const CLAIM_ISSUER = 'iss';
const CLAIM_SUBJECT = 'sub';
const CLAIM_AUDIENCE = 'aud';
const CLAIM_ISSUED_AT = 'iat';
const CLAIM_TIMEZONE = 'zoneinfo';
const CLAIM_WEBSITE = 'website';
const CLAIM_SUB_ID = 'sub_id';
const HASH_HMAC_KEY = 'hash_hmac_key';
/**
*
* @var Config
*/
private $config;
/**
*
* @throws ConfigurationException
*/
public function __construct(Config $config)
{
if ($this->isValidConfig($config)) {
$this->config = $config;
}
}
/**
*
* @throws ConfigurationException
*/
private function isValidConfig(Config $config) : bool
{
if (false === $config->offsetExists(self::HASH_HMAC_KEY)) {
throw new ConfigurationException('Setting "' . self::HASH_HMAC_KEY . '" is not specified');
}
$configurable_claims = [
self::CLAIM_ISSUER,
self::CLAIM_SUBJECT,
self::CLAIM_AUDIENCE,
];
foreach ($configurable_claims as $claim) {
if (false === $config->offsetExists($claim)) {
throw new ConfigurationException('Setting "' . $claim . '" is not specified');
}
$required_payload[$claim] = $config->offsetGet($claim);
}
return true;
}
public function createToken(array $payload = []) : string
{
$header = array(
self::CLAIM_ALGORITHM => 'HS256',
self::CLAIM_TYPE => 'jwt',
);
$jwt_header = $this->base64EncodeUrl(json_encode($header));
$required_payload = $this->getRequiredPayload($this->config);
$full_payload = array_merge($required_payload, $payload);
$jwt_payload = $this->base64EncodeUrl(json_encode($full_payload));
$jwt_signature = $this->createSignature($jwt_header, $jwt_payload, $this->config);
return sprintf('%s.%s.%s', $jwt_header, $jwt_payload, $jwt_signature);
}
public function getTokenPayload($jwt, $include_required_payload = false) : array
{
if ($this->isValidToken($jwt)) {
$shrapnel = explode('.', $jwt);
$payload = json_decode($this->base64DecodeUrl($shrapnel[1]), true);
if ($include_required_payload) {
return $payload;
}
$required_payload_claims = $this->getRequiredPayloadClaims();
return array_diff_key($payload, array_flip($required_payload_claims));
}
}
/**
*
* @throws InvalidTokenException
*/
public function isValidToken($jwt) : bool
{
$shrapnel = explode('.', $jwt);
if (3 !== count($shrapnel)) {
throw new InvalidTokenException('Invalid token provided');
}
$header = $shrapnel[0];
$payload = $shrapnel[1];
$actual = $shrapnel[2];
$expected = $this->createSignature($header, $payload, $this->config);
if ($actual !== $expected) {
throw new InvalidTokenException('Invalid signature provided');
}
return true;
}
private function getRequiredPayloadClaims() : array
{
return [
self::CLAIM_ISSUER,
self::CLAIM_SUBJECT,
self::CLAIM_AUDIENCE,
self::CLAIM_ISSUED_AT,
self::CLAIM_TIMEZONE,
];
}
private function getRequiredPayload(Config $config) : array
{
if ($config->offsetExists(self::CLAIM_ISSUED_AT)) {
$issued_at = $config->offsetGet(self::CLAIM_ISSUED_AT);
} else {
$issued_at = date('d-m-Y H:i:s');
}
if ($config->offsetExists(self::CLAIM_TIMEZONE)) {
$timezone_name = $config->offsetGet(self::CLAIM_TIMEZONE);
} else {
$date = new DateTime();
$timezone = $date->getTimezone();
$timezone_name = $timezone->getName();
}
$required_payload = [
self::CLAIM_ISSUED_AT => $issued_at,
self::CLAIM_TIMEZONE => $timezone_name,
];
return $required_payload;
}
private function createSignature($header, $payload, Config $config) : string
{
$signature = hash_hmac(
'sha256',
$header . $payload,
$config->offsetGet(self::HASH_HMAC_KEY)
);
$jwt_signature = $this->base64EncodeUrl($signature);
return $jwt_signature;
}
/**
*
* @link https://www.php.net/manual/en/function.base64-encode.php
*/
private function base64EncodeUrl($string)
{
return str_replace(array('+','/','='), array('-','_',''), base64_encode($string));
}
/**
*
* @link https://www.php.net/manual/en/function.base64-decode.php
*/
private function base64DecodeUrl($string)
{
return base64_decode(str_replace(array('-','_'), array('+','/'), $string));
}
}
<file_sep>/src/Config/Config.php
<?php
namespace Tokenizer\Config;
use ArrayObject;
use Tokenizer\Exception\ConfigurationException;
class Config extends ArrayObject
{
public function __construct(array $settings = [])
{
if (0 < count($settings)) {
foreach ($settings as $setting => $value) {
$this->offsetSet($setting, $value);
}
}
}
}
<file_sep>/public/example.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include 'vendor/autoload.php';
$config = new Tokenizer\Config\Config([
Tokenizer\Tokenizer::HASH_HMAC_KEY => 'some-uber-secret-key',
Tokenizer\Tokenizer::CLAIM_ISSUER => 'Giftuals',
Tokenizer\Tokenizer::CLAIM_SUBJECT => 'Example token',
Tokenizer\Tokenizer::CLAIM_AUDIENCE => 'https://backend.giftuals.com',
]);
try {
$tokenizer = new Tokenizer\Tokenizer($config);
} catch (Tokenizer\Exception\ConfigurationException $e) {
d($e->getMessage());
}
$jwt = $tokenizer->createToken([
'my_own_claim' => 'some random value',
]);
try {
$tokenizer->isValidToken($jwt);
$payload = $tokenizer->getTokenPayload($jwt);
} catch (Tokenizer\Exception\InvalidTokenException $e) {
d($e->getMessage());
}
d($payload); | cdf54ce1baeaaab49c5c01df926453a020b9552e | [
"Markdown",
"PHP"
]
| 7 | PHP | giftuals/tokenizer | 6caabad0cfac1e9f048ff4f328b9bf4218da9911 | 3340b313bedb9c4d486ad17e9d23a9c29ec41a9b |
refs/heads/master | <repo_name>huxuanchenxy/hiworld<file_sep>/test233.php
<?php
echo 'hello world !!!';
echo 'huyanxiang333333333';
?> | 4078b17438ae685b92606e0b50aca2694a7eae9b | [
"PHP"
]
| 1 | PHP | huxuanchenxy/hiworld | 7ff55a6ebc93b7b83d0a9b3c341e4d0197250aa6 | 3ae56667c98a0e3c0eb202e8a6a78dff2c1ffe8b |
refs/heads/master | <repo_name>adamwberck/Project4<file_sep>/test.c
//
// Created by Adam on 2019-04-20.
//
#include <stdio.h>
#include <malloc.h>
#include "test.h"
//just test functions
void first_test(struct boot my_boot){
//Load Test File.txt to write to disk
FILE *test_file = fopen("Test File2.txt","r");
int test_file_size = (int) fsize("Test File2.txt");
printf("size %d\n", test_file_size);
char *my_test_file_data = malloc(sizeof(char)*test_file_size);
//fprintf(test_file,"%s",my_test_file_data);
fread(my_test_file_data, sizeof(char), (size_t) test_file_size, test_file);
fclose(test_file);
//create test file write to logic dir, write to fat, and write to disk
MY_FILE root_folder;
root_folder.FAT_LOC=my_boot.root.FAT_location;
root_folder.isEOF=false;
root_folder.data_loc=0;
root_folder.DATA_SIZE=my_boot.root.size;
srandom((unsigned int) time(NULL));
MY_FILE *folders[6];
folders[0] = make_dir(&root_folder, "folder0\0\0");
folders[1] = make_dir(&root_folder, "folder1\0\0");
folders[2] = make_dir(&root_folder, "folder2\0\0");
folders[3] = make_dir(&root_folder, "folder3\0\0");
folders[4] = make_dir(&root_folder, "folder4\0\0");
folders[5] = make_dir(&root_folder, "folder5\0\0");
MY_FILE *file[35];
for(int i=0;i<30;i++) {
uint16_t start = (uint16_t) (random() % (strlen(my_test_file_data)-100));
uint16_t bytes = (uint16_t) (random() % (strlen(my_test_file_data)-start));
uint16_t folder = (uint16_t) (random() % 7);
char name[9]="\0\0\0\0\0\0\0\0\0";
memcpy(name,"test",4);
char str[3];
sprintf(str,"%.2d",i);
strcat(name,str);
//printf("%s %d \n",name,bytes);
if(folder!=6) {
file[i] = user_create_file(folders[folder], name, "txt", my_test_file_data + start, bytes);
}
else {
file[i] = user_create_file(&root_folder, name, "c", my_test_file_data + start, bytes);
}
}
}
void second_test(){
make_dir(current_dir,"folder123");
user_create_file(current_dir,"testA","txt","This is a test of file creation",31);
change_dir("folder123");
user_create_file(current_dir,"test0","txt","This is 0 test of file creation",31);
user_create_file(current_dir,"test1","txt","This is 1 test of file creation",31);
make_dir(current_dir,"sub1");
change_dir("sub1");
user_create_file(current_dir,"abcdefghi","txt","This is 2 test of file creation",31);
user_create_file(current_dir,"test3","txt","This is 3 test of file creation",31);
display_everything();
change_dir("..");
change_dir("..");
user_delete_file(current_dir,"testA","txt");
display_everything();
}
<file_sep>/my_dir_stack.h
//
// Created by Adam on 2019-04-17.
//
#ifndef PROJECT4_MY_DIR_STACK_H
#define PROJECT4_MY_DIR_STACK_H
#include <stdint.h>
#include <stdbool.h>
struct MY_FILE {
uint16_t data_loc;
uint16_t DATA_SIZE;
uint16_t FAT_LOC;
uint16_t pFAT_LOC;
bool isEOF;
}typedef MY_FILE;
struct my_dir_stack{
MY_FILE *array[1000];
int size;
};
struct my_dir_stack create_my_dir_stack();
void put_my_dir_stack(struct my_dir_stack *stack, MY_FILE *element);
MY_FILE *pop_my_dir_stack(struct my_dir_stack *stack);
#endif //PROJECT4_MY_STACK_H
<file_sep>/user_commands.h
//
// Created by mandr on 2019-04-21.
//
#ifndef PROJECT4_USER_COMMANDS_H
#define PROJECT4_USER_COMMANDS_H
#include "disk.h"
MY_FILE *move_dir(MY_FILE *new_folder, MY_FILE *parent, MY_FILE *file, char *name);
MY_FILE *user_move_file(MY_FILE *new_folder, MY_FILE *parent,MY_FILE *file,char name[NAME_LENGTH],char ext[EXT_LENGTH]);
MY_FILE *copy_dir(MY_FILE *new_folder,MY_FILE *duplicating_file,char name[NAME_LENGTH]);
MY_FILE *user_copy_file(MY_FILE *new_folder,MY_FILE *file,char name[NAME_LENGTH],char ext[EXT_LENGTH]);
MY_FILE *make_dir(MY_FILE *parent, char *name);
MY_FILE *user_create_file(MY_FILE *parent,char *name,char *ext,char *data,uint16_t size);
void display_file_data(MY_FILE *file);
char *uniform_the_ext(char *ext);
char *uniform_the_name(char *name);
void user_delete_file(MY_FILE *parent, char *name, char *ext );
void delete_dir(MY_FILE *parent, char *name );
MY_FILE *user_open_file(MY_FILE *parent,char name[NAME_LENGTH],char ext[EXT_LENGTH]);
#endif //PROJECT4_USER_COMMANDS_H
<file_sep>/my_stack.c
//
// Created by mandr on 2019-04-17.
//
#include "my_stack.h"
void put_my_stack(struct my_stack *stack,uint16_t element){
stack->array[stack->size++] = element;
}
uint16_t pop_my_stack(struct my_stack *stack){
return stack->array[--stack->size];
}
struct my_stack create_my_stack(){
struct my_stack stack;
stack.size =0;
return stack;
}<file_sep>/test.h
//
// Created by mandr on 2019-04-20.
//
#ifndef PROJECT4_FIRST_TEST_H
#define PROJECT4_FIRST_TEST_H
#include "disk.h"
#include "user_commands.h"
#include "my_dir_stack.h"
#include <math.h>
void first_test();
void second_test();
#endif //PROJECT4_FIRST_TEST_H
<file_sep>/disk.c
//
// Created by <NAME> on 2019-04-17.
//
#include "disk.h"
#include "my_stack.h"
#include "my_dir_stack.h"
#include "test.h"
char *FOLDER_EXT = "\\\\\\";
//make a new disk
void new_disk(char *disk_name){
struct boot my_boot = create_new_boot();
create_disk(my_boot,disk_name);
//using mmap to open my_disk
int int_disk = open(disk_name,O_RDWR,0);
void *new_disk = mmap(NULL,TOTAL_SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,int_disk,0);
write_dir_entry(my_boot.root,ROOT_LOCATION);//write the root to boot;
write_file_to_fat(my_boot.root,new_disk);//write the fat of the root
}
//mount the disk set the disk pointer to the mmap
void mount(){
//set current dir to root folder
struct boot my_boot = create_boot();
MY_FILE *root_folder = malloc(sizeof(MY_FILE));
root_to_myfile(my_boot, root_folder);
current_dir = root_folder;
current_dir_name="root";
put_my_dir_stack(&dir_stack,root_folder);
}
//create the boot and read the file size
struct boot create_boot() {
struct boot result;
result=create_new_boot();
memcpy(&result.root.size,disk+ROOT_LOCATION+NAME_LENGTH+EXT_LENGTH, sizeof(uint16_t));
return result;
}
//display the file system
void display_everything(){
MY_FILE root_folder;
root_folder.FAT_LOC=0;
root_folder.isEOF=false;
root_folder.data_loc=0;
char raw_root[ENTRY_SIZE];
struct dir_entry root_entry;
memcpy(raw_root,disk+ROOT_LOCATION,ENTRY_SIZE);
data_to_entry(raw_root,&root_entry);
root_folder.DATA_SIZE=root_entry.size;
display_file(root_entry,&root_folder,1);
}
//display an entry with the size
void display_entry(struct dir_entry entry){
//Have to make sure there is a null terminator at the end of the entry strings
char *new_name = malloc(sizeof(char)*(NAME_LENGTH+1));
size_t len = (size_t) fmin(strlen(entry.name), NAME_LENGTH);
memcpy(new_name,entry.name,len);
new_name[len]=0;
char *new_ext = malloc(sizeof(char)*(EXT_LENGTH+1));
len = (size_t) fmin(strlen(entry.extension), EXT_LENGTH);
memcpy(new_ext,entry.extension,len);
new_ext[len]=0;
if(memcmp(entry.extension,FOLDER_EXT,EXT_LENGTH)==0){
printf("%.9s\n",new_name);
return;
}
printf("%s.%s %.5d\n",new_name,new_ext,entry.size);
}
//display a file and its sub directories
void display_file(struct dir_entry entry,MY_FILE *file,int depth){
//if its folder display its contents
bool isFOLDER = memcmp(entry.extension,FOLDER_EXT,EXT_LENGTH)==0;
for(int i=0;i<depth;i++) {
if(isFOLDER || i+1<depth) {
printf("|");
} else{
printf("-");
}
}
display_entry(entry);
if(isFOLDER){
depth++;
while(!file->isEOF && file->DATA_SIZE>0) {
char data[ENTRY_SIZE];
read_data(file, data, ENTRY_SIZE);
struct dir_entry new_entry;
data_to_entry(data, &new_entry);
MY_FILE new_file;
entry_to_myfile(file, &new_entry, &new_file);
display_file(new_entry, &new_file, depth);
}
file->isEOF=false;
file->data_loc=0;
}
}
//change the current dir pointer to the new directory use the stack if going to the parent
void change_dir(char name[NAME_LENGTH]){
if(strcmp(name,"..")==0 && dir_stack.size>1){
free(current_dir);
current_dir=pop_my_dir_stack(&dir_stack);
if(dir_stack.size==1){
current_dir_name="root";
return;
}
//read
MY_FILE temp_file;
temp_file.data_loc = 0;
temp_file.DATA_SIZE = MAX_SIZE;
temp_file.isEOF = false;
temp_file.FAT_LOC = current_dir->pFAT_LOC;
if (current_dir->FAT_LOC != 0) {
uint16_t check_fat = 0;
while (!temp_file.isEOF && check_fat != current_dir->FAT_LOC) {
temp_file.data_loc += ENTRY_SIZE - sizeof(uint16_t);
read_data(&temp_file, &check_fat, sizeof(uint16_t));
}
}
temp_file.data_loc -= ENTRY_SIZE;
read_data(&temp_file,current_dir_name,NAME_LENGTH);
return;
}
struct dir_entry entry;
if(seek_to_dir_entry(&entry,current_dir,name,FOLDER_EXT)){
MY_FILE *new_dir = malloc(sizeof(MY_FILE));
entry_to_myfile(current_dir,&entry,new_dir);
put_my_dir_stack(&dir_stack, current_dir);
current_dir = new_dir;
current_dir_name = name;
return;
}
printf("Couldn't find directory %s\n",name);
}
//get the myfile version fo the the root folder
void root_to_myfile(struct boot my_boot, MY_FILE *root_folder) {
root_folder->FAT_LOC=my_boot.root.FAT_location;
root_folder->isEOF=false;
root_folder->data_loc=0;
root_folder->DATA_SIZE=my_boot.root.size;
}
//write a new disk mostly by writing null characters then writing the boot sector
void create_disk(struct boot my_boot,char *name){
FILE *new_disk = fopen(name,"w+");
uint16_t empty = FREE_BLOCK;
for(int i=0;i<TOTAL_SIZE;i++) {
fwrite(&empty, sizeof(uint16_t), 1, new_disk);
}
fseek(new_disk,0,SEEK_SET);
fwrite(my_boot.valid_check,1, sizeof(my_boot.valid_check),new_disk);
fwrite(&my_boot.boot_sector_size,2, 1,new_disk);
fwrite(&my_boot.total_size,4, 1,new_disk);
fwrite(&my_boot.block_size,2, 1,new_disk);
fwrite(&my_boot.total_blocks,2, 1,new_disk);
fwrite(&my_boot.FAT_size,2, 1,new_disk);
fwrite(&my_boot.max_size,2, 1,new_disk);
fclose(new_disk);
}
//move a file by copying the file then deleting a file
MY_FILE *move_file(MY_FILE *new_folder, MY_FILE *parent,MY_FILE *file,char name[NAME_LENGTH],char ext[EXT_LENGTH]){
MY_FILE *new_file = copy_file(new_folder,file,name,ext);
if(new_file!=NULL) {
delete_file(parent, name, ext);
}
return new_file;
}
//open file a return a pointer
MY_FILE *open_file(MY_FILE *parent,char name[NAME_LENGTH],char ext[EXT_LENGTH]){
struct dir_entry entry;
parent->isEOF=false;
parent->data_loc=0;
if(!seek_to_dir_entry(&entry,parent,name,ext)){
printf("Couldn't find %s.%s\n",name,ext);
return NULL;
}
parent->isEOF=false;
parent->data_loc=0;
MY_FILE *file = malloc(sizeof(MY_FILE));
entry_to_myfile(parent,&entry,file);
return file;
}
//close file by freeing the pointer
void close_file(MY_FILE *file) {
free(file);
}
//copy a file by creating a new file by reading the data of the file
MY_FILE *copy_file(MY_FILE *new_folder,MY_FILE *file,char name[NAME_LENGTH],char ext[EXT_LENGTH]){
char data[file->DATA_SIZE];
read_data(file,data,file->DATA_SIZE);
MY_FILE *copied_file = create_file(new_folder,name,ext,data,file->DATA_SIZE);
if(copied_file!=NULL) {
//if you are copying a folder
if (strcmp(ext, FOLDER_EXT) == 0) {
//read the data from the copied file
char copy_data[ENTRY_SIZE];
read_data(file, copy_data, ENTRY_SIZE);
struct dir_entry copy_entry;
data_to_entry(copy_data, ©_entry);
MY_FILE sub_file_copy;
entry_to_myfile(copied_file, ©_entry, &sub_file_copy);
//recursive copy the files that are in the folder
copy_file(copied_file, &sub_file_copy, copy_entry.name, copy_entry.extension);
}
}
return copied_file;
}
//delete the file with the given name and ext
void delete_file(MY_FILE *parent, char *filename, char *ext ){
//add file info to the directory
parent->data_loc=0;
//get dir entry
struct dir_entry entry;
if(!seek_to_dir_entry(&entry,parent,filename,ext)){
printf("Couldn't find %s.%s\n",filename,ext);
return;
}
//Since we are deleting a file we have to change the size of folder it is in.
//edit the size in parent
uint16_t d_size = edit_size_in_directory(parent, -1);
//check if the file is a folder
if(memcmp(entry.extension,FOLDER_EXT,3)==0){
//if its a folder clear all the fat of the sub files
MY_FILE dir_file;
entry_to_myfile(parent, &entry, &dir_file);
while(!dir_file.isEOF) {
char interior_entry_data[ENTRY_SIZE];
read_data(&dir_file, interior_entry_data, ENTRY_SIZE);
struct dir_entry interior_entry;
data_to_entry(interior_entry_data,&interior_entry);
//recursive delete the interior files
uint16_t old_pos = dir_file.data_loc;
bool old_isEOF = dir_file.isEOF;
dir_file.data_loc=0;
dir_file.isEOF=false;
delete_file(&dir_file,interior_entry.name,interior_entry.extension);
dir_file.isEOF=old_isEOF;
dir_file.data_loc=old_pos;
}
}
//erase fat
erase_fat( entry.FAT_location);
//erase dir info
parent->DATA_SIZE = d_size;
parent->data_loc+=ENTRY_SIZE;
uint16_t old_data_loc = parent->data_loc;
uint16_t amount_of_data = parent->DATA_SIZE-old_data_loc;
char rest_of_data[amount_of_data];
read_data(parent,rest_of_data,amount_of_data);
parent->data_loc = (uint16_t) (old_data_loc - ENTRY_SIZE);
write_data(parent,rest_of_data,amount_of_data);
parent->DATA_SIZE-=ENTRY_SIZE;
}
//helper function used when adding or deleting a file writing the new size of the directory
uint16_t edit_size_in_directory(const MY_FILE *parent, int direction) {
uint16_t d_size;
MY_FILE temp_file;
temp_file.data_loc=0;
temp_file.DATA_SIZE=MAX_SIZE;
temp_file.isEOF=false;
temp_file.FAT_LOC=parent->pFAT_LOC;
if(parent->FAT_LOC!=0) {
uint16_t check_fat = 0;
while (!temp_file.isEOF && check_fat != parent->FAT_LOC) {
temp_file.data_loc += ENTRY_SIZE - sizeof(uint16_t);
read_data(&temp_file, &check_fat, sizeof(uint16_t));
}
temp_file.data_loc -= ENTRY_SIZE;
temp_file.data_loc += NAME_LENGTH + EXT_LENGTH;
read_data(&temp_file, &d_size, sizeof(uint16_t));
d_size += ENTRY_SIZE*direction;
temp_file.data_loc -= sizeof(uint16_t);
write_data(&temp_file, &d_size, sizeof(uint16_t));
}
//special case if file is in root then the dir information is in the BOOT SECTOR
else{
memcpy(&d_size,disk+ROOT_LOCATION+NAME_LENGTH+EXT_LENGTH, sizeof(uint16_t));
d_size += ENTRY_SIZE*direction;
memcpy(disk+ROOT_LOCATION+NAME_LENGTH+EXT_LENGTH,&d_size,sizeof(uint16_t));
}
return d_size;
}
//convert an entry to a myfile pointer
void entry_to_myfile(const MY_FILE *parent, struct dir_entry *entry, MY_FILE *dir_file) {
dir_file->data_loc=0;
dir_file->DATA_SIZE= (*entry).size;
dir_file->isEOF=false;
dir_file->FAT_LOC= (*entry).FAT_location;
dir_file->pFAT_LOC=parent->FAT_LOC;
}
//returns true if found false if it doesn't exist in parent
bool seek_to_dir_entry(struct dir_entry *entry,MY_FILE *parent, const char *filename, const char *ext){
bool n = false;
bool e = false;
char raw_entry_data[ENTRY_SIZE];
while(!parent->isEOF && !(n && e)) {
read_data(parent,raw_entry_data,ENTRY_SIZE);
data_to_entry(raw_entry_data, entry);
int name_len = (int) fmin(strlen(filename), NAME_LENGTH);
n = memcmp(filename, entry->name, name_len) == 0;
int ext_len = (int) fmin(strlen(ext), EXT_LENGTH);
e = memcmp(ext, entry->extension, ext_len) == 0;
}
parent->data_loc-=ENTRY_SIZE;
return n&&e;
}
//taking raw read data an reading as a dir entry
void data_to_entry(char data[ENTRY_SIZE], struct dir_entry *new_entry) {
memcpy(new_entry->name,data,NAME_LENGTH);
data+=NAME_LENGTH;
memcpy(new_entry->extension,data,EXT_LENGTH);
data+=EXT_LENGTH;
memcpy(&new_entry->size,data,sizeof(int16_t));
data+=sizeof(int16_t);
memcpy(&new_entry->create_time,data,sizeof(time_t));
data+=sizeof(time_t);
memcpy(&new_entry->mod_time,data,sizeof(time_t));
data+=sizeof(time_t);
memcpy(&new_entry->FAT_location,data, sizeof(int16_t));
}
//erase the fat using a stack
void erase_fat(uint16_t fat_loc) {
struct my_stack stack = create_my_stack();
put_my_stack(&stack,fat_loc);
while(fat_loc!=NO_LINK){
fat_loc = fat_value(fat_loc);
put_my_stack(&stack,fat_loc);
}
uint16_t free_block = FREE_BLOCK;
while(stack.size>0){
//erase the first fat
uint16_t fat_to_erase = pop_my_stack(&stack);
uint32_t f_pos = fat_location(true,fat_to_erase);
memcpy(disk+f_pos,&free_block, sizeof(uint16_t));
//erase the second fat
f_pos = fat_location(false,fat_to_erase);
memcpy(disk+f_pos,&free_block, sizeof(uint16_t));
}
}
//get the size of a file (in real file system not it virtual file system)
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
return -1;
}
//read data using pointer
uint16_t read_data(struct MY_FILE *p_file,void *data, uint16_t bytes){
uint16_t bytes_read = 0;
uint16_t remaining_bytes = p_file->DATA_SIZE-p_file->data_loc; //amount of bytes left in file
p_file->isEOF = bytes>=remaining_bytes; //if remaining bytes is less than bytes available set EOF true
uint16_t bytes_to_read = bytes<=remaining_bytes ? bytes : remaining_bytes; //only get bytes <= to bytes available
while(bytes_read<bytes_to_read) {
//get location of data in block
uint16_t block_loc = (uint16_t) (p_file->data_loc % BLOCK_SIZE);//block_pos(disk,p_file->FAT_LOC,p_file->data_loc);
//set bytes to read to rest of block
uint16_t bytes_to_copy = (uint16_t) (BLOCK_SIZE - block_loc);
//set bytes to read to = rest of block or bytes
bytes_to_copy = bytes_to_copy <= (bytes_to_read-bytes_read) ? bytes_to_copy : (bytes_to_read-bytes_read);
//copy disk to data
memcpy(data+bytes_read, disk + get_disk_pos( p_file->FAT_LOC, p_file->data_loc), bytes_to_copy);
bytes_read += bytes_to_copy;
p_file->data_loc += bytes_to_copy;
}
return bytes_read;
}
//get the part of the disk the the file is pointing to
uint32_t get_disk_pos( uint16_t fat_loc, uint16_t data_loc){
uint16_t no_link = NO_LINK;
uint16_t old_fat_loc = fat_loc;
while(data_loc>=BLOCK_SIZE){//if your location is smaller than a block you are good
fat_loc = fat_value(fat_loc);//get the next fat
if(fat_loc==NO_LINK){//if you are trying to get a fat and its not there allocate more space
fat_loc = get_free_block(0x0000); //searching for free block starting at the first spot
//write to fat
uint32_t fat_on_disk_loc = fat_location(true, old_fat_loc);//get disk location of the old fat
memcpy(disk+fat_on_disk_loc, &fat_loc, 2);//put the value of the new fat in its spot
fat_on_disk_loc = fat_location(true, fat_loc);//get the disk location of the new fat
memcpy(disk+fat_on_disk_loc, &no_link, 2);//put the no link in memory
//do the same for fat2
fat_on_disk_loc = fat_location(false, old_fat_loc);
memcpy(disk+fat_on_disk_loc, &fat_loc, 2);
fat_on_disk_loc = fat_location(false, fat_loc);
memcpy(disk+fat_on_disk_loc, &no_link, 2);
}
old_fat_loc = fat_loc;
data_loc-=BLOCK_SIZE; //subtract the data location by the block size
}
return (uint32_t) (USER_SPACE_LOCATION + fat_loc * BLOCK_SIZE + data_loc);
}
//create a file
MY_FILE *create_file(MY_FILE *parent, char name[NAME_LENGTH],char ext[EXT_LENGTH],char *data,uint16_t size){
if(strlen(name)<=0){
return NULL;
}
struct dir_entry dup_file;
//forbid the creation of a duplicate file
if(seek_to_dir_entry(&dup_file,parent,name,ext)){
return NULL;
}
//reset the pointer
parent->data_loc=0;
parent->isEOF=false;
time_t the_time = time(NULL);
uint16_t fat_loc = get_free_block(0x0000);
struct dir_entry entry = create_entry(name,ext,size,the_time,the_time,fat_loc);
write_file_to_fat(entry,disk);
//edit size in parent
//special case if file is in root then the dir information is in the BOOT SECTOR
uint16_t d_size = edit_size_in_directory(parent,1);
//add file info to the directory
parent->DATA_SIZE= (uint16_t) (d_size - ENTRY_SIZE);
parent->data_loc=parent->DATA_SIZE;
char dir_entry_data[ENTRY_SIZE];
entry_to_data(entry,dir_entry_data);
write_data(parent,dir_entry_data,ENTRY_SIZE);
parent->DATA_SIZE+=ENTRY_SIZE;
//init the file pointer*/
MY_FILE *my_file=malloc(sizeof(MY_FILE));
my_file->data_loc = 0;
my_file->FAT_LOC = fat_loc;
my_file->DATA_SIZE=size;
my_file->isEOF =false;
my_file->pFAT_LOC=parent->FAT_LOC;
//write_data
write_data(my_file, data, size);
my_file->data_loc = 0;
parent->isEOF=false;
parent->data_loc=0;
return my_file;
}
//convert an entry to data
void entry_to_data(struct dir_entry entry,char array[ENTRY_SIZE]){
char *null_str = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
memcpy(array,null_str,ENTRY_SIZE);
memcpy(array,entry.name,strlen(entry.name));
array+=NAME_LENGTH;
memcpy(array,entry.extension,strlen(entry.extension));
array+=EXT_LENGTH;
memcpy(array,&entry.size, sizeof(entry.size));
array+=sizeof(entry.size);
memcpy(array,&entry.create_time, sizeof(entry.create_time));
array+=sizeof(entry.create_time);
memcpy(array,&entry.mod_time, sizeof(entry.mod_time));
array+=sizeof(entry.mod_time);
memcpy(array,&entry.FAT_location, sizeof(entry.FAT_location));
}
//write data to the disk using fat system
uint16_t write_data(struct MY_FILE *p_file, void *data, uint16_t bytes){
uint16_t bytes_wrote = 0;
while(bytes_wrote<bytes) {
//get location of data in block
uint16_t block_loc = (uint16_t) (p_file->data_loc % BLOCK_SIZE);
//set bytes to write to rest of block
uint16_t bytes_to_copy = (uint16_t) (BLOCK_SIZE - block_loc);
//set bytes what ever is smaller the remaining bytes or the rest of the block
bytes_to_copy = bytes_to_copy <= (bytes-bytes_wrote) ? bytes_to_copy : (bytes-bytes_wrote);
//copy disk to data
memcpy(disk + get_disk_pos(p_file->FAT_LOC, p_file->data_loc),data+bytes_wrote,bytes_to_copy);
bytes_wrote += bytes_to_copy;
p_file->data_loc += bytes_to_copy;
p_file->DATA_SIZE = p_file->DATA_SIZE >= p_file->data_loc ? p_file->DATA_SIZE : p_file->data_loc;
}
return bytes_wrote;
}
//write the first fat location of a new file
void write_file_to_fat(struct dir_entry entry,void *disk){
uint16_t no_link = NO_LINK;
uint32_t p_loc = fat_location(true, entry.FAT_location);//get address from loc
memcpy(disk+p_loc, &no_link, 2);//copy no link to this address
//do the same for fat2
p_loc = fat_location(false, entry.FAT_location);
memcpy(disk+p_loc, &no_link, 2);
}
//get the free block
uint16_t get_free_block(uint16_t start) {
int blocks = 1;
while(blocks<TOTAL_BLOCKS) {
blocks++;
start = (uint16_t) ((start + 1) % TOTAL_BLOCKS);
uint16_t test = fat_value(start);
if(test==FREE_BLOCK){
return start;
}
}
printf("Disk is full\n");
exit(1);
}
//write dir entry only used for the root
void write_dir_entry(struct dir_entry entry,uint32_t location){
char *null_str = "\0\0\0\0\0\0\0\0\0";
void *p_loc = disk+location;
memcpy(p_loc,null_str,NAME_LENGTH);
memcpy(p_loc,entry.name,strlen(entry.name));
p_loc+=NAME_LENGTH;
memcpy(p_loc,null_str,EXT_LENGTH);
memcpy(p_loc,entry.extension,strlen(entry.extension));
p_loc+=EXT_LENGTH;
memcpy(p_loc,&entry.size, sizeof(entry.size));
p_loc+=sizeof(entry.size);
memcpy(p_loc,&entry.create_time, sizeof(entry.create_time));
p_loc+=sizeof(entry.create_time);
memcpy(p_loc,&entry.mod_time, sizeof(entry.mod_time));
p_loc+=sizeof(entry.mod_time);
memcpy(p_loc,&entry.FAT_location, sizeof(entry.FAT_location));
}
//get the fat location of fat1 or fat2
uint32_t fat_location(bool isFAT1,uint16_t block){
uint32_t FAT_loc = isFAT1 ? FAT1_LOCATION : FAT2_LOCATION ;
return FAT_loc + block* sizeof(uint16_t);
}
//get the value in the fat at specified fat
uint16_t fat_value(uint16_t block){
uint p_loc = fat_location(true,block);
uint16_t return_value;
memcpy(&return_value,disk+p_loc,2);
return return_value;
}
//create the root entry
struct dir_entry create_root(){
return create_entry("root\0",FOLDER_EXT,0,time(NULL),time(NULL),0);
}
//entry creator
struct dir_entry create_entry(char name[NAME_LENGTH],char extension[EXT_LENGTH],uint16_t size,
time_t create_time, time_t mod_time,uint16_t FAT_location){
struct dir_entry entry;
memcpy(entry.name,name,NAME_LENGTH);
memcpy(entry.extension,extension,EXT_LENGTH);
entry.size = size;
entry.create_time = create_time;
entry.mod_time = mod_time;
entry.FAT_location = FAT_location;
return entry;
}
//boot creator
struct boot create_new_boot() {
struct boot b;
strcpy(b.valid_check,"This is Adam's FAT Drive");
b.boot_sector_size = BOOT_SECTOR_SIZE;
b.total_size = TOTAL_SIZE;
b.block_size = BLOCK_SIZE;
b.total_blocks = TOTAL_BLOCKS;
b.FAT_size = FAT_SIZE;
b.max_size = MAX_SIZE;
b.root = create_root();
return b;
}<file_sep>/user_commands.c
//
// Created by <NAME> on 2019-04-21.
//
#include "user_commands.h"
#include "disk.h"
//user commands just do what disk commands do but checks the input first to ensure its okay
MY_FILE *move_dir(MY_FILE *new_folder, MY_FILE *parent, MY_FILE *file, char *name){
name = uniform_the_name(name);
MY_FILE *m_file = move_file(new_folder,parent,file,name,"\\\\\\");
free(name);
return m_file;
}
MY_FILE *user_open_file(MY_FILE *parent,char name[NAME_LENGTH],char ext[EXT_LENGTH]){
name = uniform_the_name(name);
ext = uniform_the_ext(ext);
MY_FILE *file = open_file(parent,name,ext);
free(name);free(ext);
return file;
}
MY_FILE *user_move_file(MY_FILE *new_folder, MY_FILE *parent,MY_FILE *file,char name[NAME_LENGTH],char ext[EXT_LENGTH]){
name = uniform_the_name(name);
ext = uniform_the_ext(ext);
if(strstr(name,"\\")==NULL && strstr(ext,"\\")==NULL) {
MY_FILE *new_file = copy_file(new_folder,file,name,ext);
delete_file(parent,name,ext);
free(name);free(ext);
return new_file;
}
return NULL;
}
MY_FILE *copy_dir(MY_FILE *new_folder,MY_FILE *duplicating_file,char name[NAME_LENGTH]){
name = uniform_the_name(name);
MY_FILE *c_file = copy_file( new_folder, duplicating_file, name, "\\\\\\");
free(name);
return c_file;
}
char *uniform_the_name(char name[NAME_LENGTH]){
char *u_name =malloc(NAME_LENGTH* sizeof(char));
int len = name==NULL ? 0 :(int) strlen(name);
if(name!=NULL) {
strcpy(u_name, name);
}
while(len<NAME_LENGTH){
u_name[len++]=0;
}
return u_name;
}
char *uniform_the_ext(char ext[EXT_LENGTH]){
char *u_ext =malloc(EXT_LENGTH* sizeof(char));
int len = ext==NULL ? 0 : (int) strlen(ext);
if(ext!=NULL) {
strcpy(u_ext, ext);
}
while(len<EXT_LENGTH){
u_ext[len++]=0;
}
return u_ext;
}
//copy file that doesn't allow real files to be copied as folders
MY_FILE *user_copy_file(MY_FILE *new_folder,MY_FILE *file,char name[NAME_LENGTH],char ext[EXT_LENGTH]){
name = uniform_the_name(name);
ext = uniform_the_ext(ext);
if(strstr(name,"\\")==NULL && strstr(ext,"\\")==NULL) {
MY_FILE *c_file = copy_file( new_folder, file, name, ext);
free(name);free(ext);
return c_file;
}
free(name);free(ext);
return NULL;
}
MY_FILE *make_dir(MY_FILE *parent, char *name){
name = uniform_the_name(name);
char *data={NULL};
MY_FILE *new_dir = create_file( parent, name, "\\\\\\", data, 0);
free(name);
return new_dir;
}
MY_FILE *user_create_file(MY_FILE *parent,char *name,char *ext,char *data,uint16_t size){
name = uniform_the_name(name);
ext = uniform_the_ext(ext);
if(strstr(name,"\\")==NULL && strstr(ext,"\\")==NULL) {
MY_FILE *new_file = create_file(parent, name, ext, data, size);
free(name);free(ext);
return new_file;
}
free(name);free(ext);
return NULL;
}
void display_file_data(MY_FILE *file){
file->data_loc=0;
file->isEOF=false;
while(!file->isEOF){
char data[file->DATA_SIZE+1];
read_data(file,data,file->DATA_SIZE);
data[file->DATA_SIZE]=0;
printf("%s",data);
fflush(STDIN_FILENO);
}
}
void delete_dir(MY_FILE *parent, char *name ){
name = uniform_the_name(name);
delete_file(parent,name,"\\\\\\");
free(name);
}
void user_delete_file(MY_FILE *parent, char *name, char *ext ){
name = uniform_the_name(name);
ext = uniform_the_ext(ext);
if(strstr(name,"\\")==NULL && strstr(ext,"\\")==NULL) {
delete_file(parent,name,ext);
free(name);free(ext);
return;
}
free(name);free(ext);
}<file_sep>/my_stack.h
//
// Created by mandr on 2019-04-17.
//
#ifndef PROJECT4_MY_STACK_H
#define PROJECT4_MY_STACK_H
#include <stdint.h>
#include "disk.h"
struct my_stack{
uint16_t array[TOTAL_BLOCKS];
int size;
};
struct my_stack create_my_stack();
void put_my_stack(struct my_stack *stack, uint16_t element);
uint16_t pop_my_stack(struct my_stack *stack);
#endif //PROJECT4_MY_STACK_H
<file_sep>/helper.c
//
// Created by <NAME> on 2019-03-28.
//
#include "helper.h"
//finds newline char and replaces it with null terminator
void remove_newline_char(char **str){
char *s = *str;//get pointer to char
int i=0;
//loop through string
while(s[i]!='\0'){//stop looping when you get to null terminator
//replace newline with null terminator
if(s[i]=='\n'||s[i]=='\r'){
s[i]='\0';
}
i++;
}
}
//find in array using binary search, recursive method
bool find_array_b(char **array,char *element,int i,int j){
if (j >= i) {
//mid index is left bound plus half the difference
int mid = i + (j - i) / 2;
// check if element is in middle
if (strcmp(array[mid],element)==0)
return true;
// is it in the left
if (strcmp(array[mid],element)>0) {
return find_array_b(array, element, i, mid - 1);
// then its in the right
}else {
return find_array_b(array, element, mid + 1, j);
}
}
//not in array
return false;
}
//replace tabs white space with a space
void replace_other_whitespace(char **str) {
char *s = *str;//get pointer to char
int i=0;
//loop through string
while(s[i]!='\0'){//stop looping when you get to null terminator
//replace h-tab v-tab and form feed with space
if(s[i]=='\t'||s[i]=='\v'||s[i]=='\f'){
s[i]=' ';
}
i++;
}
}<file_sep>/myshell.h
//
// Created by mandr on 2019-03-09.
//
#ifndef PROJECT4_MYSHELL_H
#define PROJECT4_MYSHELL_H
#include <stdbool.h>
char** parse_file_and_extension(char *input);
void remove_newline_char(char **str);
void get_input(char* prompt,char **input);
char** parse_input(char* input,int count);
int get_count(char *input);
void my_built_in(char** args);
char *get_prompt() ;
void replace_other_whitespace(char **str);
#endif //PROJECT4_MYSHELL_H
<file_sep>/helper.h
//
// Created by <NAME> on 2019-03-28.
//
#ifndef PROJECT3C_HELPER_H
#define PROJECT3C_HELPER_H
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
void remove_newline_char(char **str);
void replace_other_whitespace(char **str);
bool find_array_b(char **array,char *element,int i,int j);
bool find_array_l(char **array,char *element);
#endif //PROJECT3C_HELPER_H
<file_sep>/disk.h
//
// Created by <NAME> on 2019-04-17.
//
#ifndef PROJECT4_MAIN_H
#define PROJECT4_MAIN_H
#include <stdio.h>
#include <memory.h>
#include <time.h>
#include <sys/mman.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include "my_dir_stack.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define FREE_BLOCK 0x0000
#define NO_LINK 0xFFFF
#define VALID_CHECK_SIZE 24
#define BOOT_SECTOR_SIZE 512
#define TOTAL_SIZE 2114048
#define BLOCK_SIZE 512
#define FAT_SIZE 8192
#define MAX_SIZE 65535
//entry is 32 bytes
#define ENTRY_SIZE 32
//root location is 0x26
#define ROOT_LOCATION 0x26
#define FAT1_LOCATION 0x200
#define FAT2_LOCATION 0x2200
#define USER_SPACE_LOCATION 0x4200
#define NAME_LENGTH 9
#define EXT_LENGTH 3
#define TOTAL_BLOCKS 4096
struct dir_entry{
char name[NAME_LENGTH];
char extension[EXT_LENGTH];
uint16_t size;
time_t create_time;
time_t mod_time;
uint16_t FAT_location;
};
struct boot{
char valid_check[24];
uint16_t boot_sector_size; //512
uint32_t total_size; //2096128
uint16_t block_size; //512
uint16_t total_blocks; //4094
uint16_t FAT_size; //8188
uint16_t max_size; //65535
struct dir_entry root;
};
struct boot create_boot();
uint16_t edit_size_in_directory(const MY_FILE *parent, int direction);
void new_disk(char *disk_name);
void change_dir(char name[NAME_LENGTH]);
void display_everything();
void display_file(struct dir_entry entry,MY_FILE *file,int depth);
void root_to_myfile(struct boot my_boot, MY_FILE *root_folder);
void close_file(MY_FILE *file);
void create_disk(struct boot my_boot,char* disk_name);
MY_FILE *open_file(MY_FILE *parent,char name[NAME_LENGTH],char ext[EXT_LENGTH]);
MY_FILE *move_file(MY_FILE *new_folder, MY_FILE *parent,MY_FILE *file,char name[NAME_LENGTH],
char ext[EXT_LENGTH]);
MY_FILE *copy_file(MY_FILE *new_folder,MY_FILE *file,char name[NAME_LENGTH],char ext[EXT_LENGTH]);
bool seek_to_dir_entry(struct dir_entry *entry,MY_FILE *parent, const char *filename, const char *ext);
void entry_to_myfile(const MY_FILE *parent, struct dir_entry *entry, MY_FILE *dir_file);
void entry_to_data(struct dir_entry entry,char array[ENTRY_SIZE]);
void delete_file(MY_FILE *parent, char filename[NAME_LENGTH],char ext[EXT_LENGTH] );
uint16_t write_data( struct MY_FILE *p_file, void *data, uint16_t bytes);
uint32_t get_disk_pos( uint16_t fat_loc, uint16_t data_loc);
MY_FILE *create_file(MY_FILE *parent, char name[NAME_LENGTH],char ext[EXT_LENGTH], char *data,uint16_t size);
void write_file_to_fat(struct dir_entry entry,void *disk);
void write_dir_entry(struct dir_entry entry,uint32_t location);
uint16_t fat_value( uint16_t block);
uint32_t fat_location(bool isFAT1, uint16_t block);
struct dir_entry create_root();
struct boot create_new_boot();
struct dir_entry create_entry(char name[9],char extension[3],uint16_t size, time_t create_time,
time_t mod_time,uint16_t FAT_location);
uint16_t get_free_block(uint16_t start);
uint16_t read_data(struct MY_FILE *p_file,void *data, uint16_t bytes);
off_t fsize(const char *filename);
void erase_fat( uint16_t fat_loc);
void data_to_entry(char data[32], struct dir_entry *new_entry);
void mount();
void *disk;
MY_FILE *current_dir;
struct my_dir_stack dir_stack;
char *current_dir_name;
#endif //PROJECT4_MAIN_H
<file_sep>/my_dir_stack.c
//
// Created by mandr on 2019-04-17.
//
#include "my_dir_stack.h"
void put_my_dir_stack(struct my_dir_stack *stack,MY_FILE *element){
stack->array[stack->size++] = element;
}
MY_FILE *pop_my_dir_stack(struct my_dir_stack *stack){
return stack->array[--stack->size];
}
struct my_dir_stack create_my_dir_stack(){
struct my_dir_stack stack;
stack.size =0;
return stack;
}<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.12)
project(Project4 C)
set(CMAKE_C_STANDARD 99)
add_executable(Project4 myshell.c myshell.h disk.c disk.h my_stack.c my_stack.h
test.c test.h my_dir_stack.c my_dir_stack.h user_commands.c user_commands.h helper.c helper.h)<file_sep>/myshell.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <memory.h>
#include <ctype.h>
#include <stdbool.h>
#include <wait.h>
#include <dirent.h>
#include <sys/fcntl.h>
#include <errno.h>
#include <sys/mman.h>
#include "myshell.h"
#include "disk.h"
#include "user_commands.h"
MY_FILE *opened_file;
char *current_disk;
int main() {
int repeat =0;
current_disk = "NO DISK";
current_dir_name="";
do{
char *prompt = get_prompt();
char *input;
get_input(prompt, &input);
int count = get_count(input);
//parsed_input list of char* pointers
char **parsed_input = parse_input(input, count);
my_built_in(parsed_input);
free(parsed_input);
repeat++;
}while(repeat<100000000);//keep going unless end of file, always go if interactive mode
return(0);
}
char *get_prompt() {
char *prompt = malloc(sizeof(char)*(10+1+strlen(current_dir_name)+strlen(current_disk)));
strcpy(prompt,current_disk);
strcat(prompt,"|");
strcat(prompt,current_dir_name);
strcat(prompt,"~FAT shell>");
return prompt;
}
//function does built in commands
void my_built_in(char** args) {
char *cmd = args[0];
//exit or quit
if (strcmp(cmd, "exit") == 0 || strcmp(cmd, "quit") == 0) {
exit(0);
//cd
} else if (strcmp(cmd, "cd") == 0) {
change_dir(args[1]);
//clear screen
} else if (strcmp(cmd, "clr") == 0) {
//goto position(1,1) then clear the screen
printf("\e[1;1H\e[2J");
//
} else if (strcmp(cmd, "mount") == 0) {
struct boot *my_boot = malloc(sizeof(struct boot));
strcpy(my_boot->valid_check, "This is Adam's FAT Drive");
//using mmap to open my_disk
int int_disk = open(args[1], O_RDWR, 0);
disk = mmap(NULL, TOTAL_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, int_disk, 0);
if (memcmp(my_boot->valid_check, disk, VALID_CHECK_SIZE) != 0) {
printf("Not correctly formatted disk\n");
}
current_disk=args[1];
//set current dir to root folder
mount();
} else if (strcmp(cmd, "open") == 0) {
char **file_name_ext = parse_file_and_extension(args[1]);
opened_file = user_open_file(current_dir, file_name_ext[0], file_name_ext[1]);
if (opened_file != NULL) {
printf("File %s.%s opened\n",file_name_ext[0],file_name_ext[1]);
}else{
printf("open failed\n");
}
} else if (strcmp(cmd, "close") == 0) {
close_file(opened_file);
opened_file=NULL;
printf("File closed\n");
} else if (strcmp(cmd,"display")==0){
display_everything();
} else if (strcmp(cmd,"create")==0){
//open file and write it two interior disk
FILE *test_file = fopen(args[1],"r");
int test_file_size = (int) fsize(args[1]);
printf("size %d\n", test_file_size);
char *my_test_file_data = malloc(sizeof(char)*test_file_size);
fread(my_test_file_data, sizeof(char), (size_t) test_file_size, test_file);
fclose(test_file);
char **file_name_ext = parse_file_and_extension(args[1]);
opened_file = user_create_file(current_dir, file_name_ext[0], file_name_ext[1], my_test_file_data,
(uint16_t) test_file_size);
if (opened_file != NULL) {
printf("File %s.%s created\n",file_name_ext[0],file_name_ext[1]);
}else{
printf("create failed\n");
}
free(my_test_file_data);
} else if(strcmp(cmd,"read")==0){
if(opened_file!=NULL) {
display_file_data(opened_file);
}else{
printf("No file opened\n");
}
} else if(strcmp(cmd,"delete")==0){
char **file_name_ext = parse_file_and_extension(args[1]);
user_delete_file(current_dir, file_name_ext[0], file_name_ext[1]);
} else if(strcmp(cmd,"copy")==0){
char **file_name_ext = parse_file_and_extension(args[1]);
user_copy_file(current_dir,opened_file,file_name_ext[0],file_name_ext[1]);
} else if(strcmp(cmd,"mkdir")==0){
make_dir(current_dir,args[1]);
} else if(strcmp(cmd,"rmdir")==0){
delete_dir(current_dir,args[1]);
} else if(strcmp(cmd,"disk")==0){
new_disk(args[1]);
}
}
//counts the different arguments in input including command
int get_count(char *input) {
bool part_of_word = false;
int count=0;
for(int i=0;i<strlen(input);i++){
if(!isspace(input[i])&&!part_of_word){
part_of_word=true;
count++;
}
else if(isspace(input[i])){
part_of_word=false;
}
}
return count;
}
//parses input into char** (a char array);
char** parse_input(char* input,int count){
char** output = 0;
char del[2]=" ";
output = malloc(sizeof(char*) * (count+2));
int j = 0;
char* token = strtok(input, del);
while (token)
{
*(output + j++) = strdup(token);
token = strtok(0, del);
}
*(output+ j) = 0;
return output;
}
char** parse_file_and_extension(char *input){
char** output = 0;
char del[2]=".";
output = malloc(sizeof(char*) * (4));
int j = 0;
char* token = strtok(input, del);
while (token)
{
*(output + j++) = strdup(token);
token = strtok(0, del);
}
*(output+ j) = 0;
return output;
}
//gets input from user
void get_input(char* prompt,char **input){
size_t buffer_size = 32;//aprox size of a command; can be changed by getline if not large enough
*input = (char *) malloc(buffer_size * sizeof(char)); //allocate space for input
printf("%s",prompt);
getline(input, &buffer_size, stdin);//getline
remove_newline_char(input);
replace_other_whitespace(input);
}
| cd235f100b3f40ceeb8e01d4f5d2e56413115ebd | [
"C",
"CMake"
]
| 15 | C | adamwberck/Project4 | 280a8bb02af3b303bdf173f3f3c7f55b3a274e3e | 6628b4c67bd1539a855282e720f9e11cb10cde2d |
refs/heads/master | <file_sep>import React from 'react'
import { VideoItem } from './VideoItem'
const VideoList = ({ videos, onVideoSubmit }) => {
const renderedList = videos.map((v) => { return <VideoItem video={v} key={v.id.VideoId} onVideoSubmit={onVideoSubmit} /> })
return (
<div className="ui relaxed divided list">
{renderedList}
</div>
)
}
export default VideoList<file_sep>import React, { Component } from 'react';
class SearchBar extends React.Component {
state = { term : ""}
onInputChange = event => {
this.setState({ term : event.target.value});
}
onFormSubmit = event => {
event.preventDefault();
this.props.onFormSubmit(this.state.term)
}
render() {
return (
<div className="ui segment">
<svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-align-center" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M8 1a.5.5 0 0 1 .5.5V6h-1V1.5A.5.5 0 0 1 8 1zm0 14a.5.5 0 0 1-.5-.5V10h1v4.5a.5.5 0 0 1-.5.5zM2 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V7z"/>
</svg>
<form onSubmit={this.onFormSubmit} className="ui form">
<div className="field">
<label>Video Search</label>
<input type="text" placeholder="Type your search here.." value= {this.state.term} onChange={this.onInputChange} />
</div>
</form>
</div>
);
}
}
export default SearchBar;
| b73fe35a84d16025374b5c62ffd1e80b129b167d | [
"JavaScript"
]
| 2 | JavaScript | zuckpa1999/video | 6b8e37cdadb253523f4bacf83ebfd0f2710ab3e1 | d4a56b830bdd2dac1793c66058ae3f9ebadf34ec |
refs/heads/master | <file_sep># fruit-phenology
This repository includes datasets and R codes used for the review entitled "Continental-scale patterns and climatic drivers of fruiting phenology: a quantitative Neotropical review",
accepted for publication in Global and Planetary Change (http://dx.doi.org/10.1016/j.gloplacha.2016.12.001), and authored by <NAME>, <NAME> and <NAME>.
The file "fruit phenology Neotrop-Mendoza-analyses and figures.R" contains the codes for analyzing data and plotting the figures of the manuscript.
URL: https://zenodo.org/badge/latestdoi/62281350
<file_sep>
library(sp)
library(raster)
library(rgdal)
library(maps)
library(mapdata)
library(spatialEco)
library (ggplot2)
####A SIMPLE FUNCTION (for internal operations)####
lengthunique = function(x) return(length(unique(x)))
#### DATASETS #####
neolong <- read.delim("Mendoza_dat_GPC.txt") #database including the 218 datasets reviewed: "DO" means Direct Observations
lengthunique(neolong$ID)
drivers <- read.delim("drivers.txt") #environmental drivers of each dataset
lengthunique(drivers$ID)
ests <- read.delim("nb spp kier.txt") ## appendix of Kier et al. 2005 JBiogeograph with the estimated number of spp
####SPATIAL ANALYSES####
##Adding vegetation types from WWF##
# Create a directory for the data
localDir <- 'R_GIS_data'
if (!file.exists(localDir)) {
dir.create(localDir)
}
#Load the Olson's vegetation data from the WWF site (65 Mb)
url <- "http://assets.worldwildlife.org/publications/15/files/original/official_teow.zip"
file <- paste(localDir, basename(url), sep='/')
if (!file.exists(file)) {
download.file(url, file)
unzip(file, exdir=localDir)
}
# Show the unzipped files
list.files(localDir)
# layerName is the name of the unzipped shapefile without file type extensions
layerName <- "wwf_terr_ecos"
data_name <- "WWF"
# Read in the data
file <- paste(getwd(),localDir,"WWF.RData",sep="/")
if (!file.exists(file)) {
data_projected <- readOGR(dsn = paste(getwd(), localDir,"official",sep="/"), layer=layerName)
# What is this thing and what's in it?
class(data_projected)
slotNames(data_projected)
# It's an S4 "SpatialPolygonsDataFrame" object with the following slots:
# [1] "data" "polygons" "plotOrder" "bbox" "proj4string"
# What does the data look like with the default plotting command?
#plot(data_projected)
# Could use names(data_projected@data) or just:
names(data_projected)
# Reproject the data onto a "longlat" projection and assign it to the new name
assign(data_name,spTransform(data_projected, CRS("+proj=longlat")))
# The WWF dataset is now projected in latitude longitude coordinates as a
# SpatialPolygonsDataFrame. We save the converted data as .RData for faster
# loading in the future.
save(list=c(data_name),file=paste(getwd(),localDir,"WWF.RData",sep="/"))
}
loc = data.frame(x = neolong$long, y = neolong$lat, ID = neolong$ID, ref = neolong$ref_short, locality = neolong$locality, vegetation = neolong$vegetation, biome = neolong$biome, species = neolong$species, Nindiv = neolong$Nindiv, studylength = neolong$studylength)
coordinates(loc) <- c("x","y")
crs.geo <- CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 ") # geographical, datum WGS84
proj4string(loc) <- crs.geo # define projection system of our study locations
#summary(loc)
#class(loc)
#Spatial join between our study locations (loc) and the polygons with the vegetation types
if(!file.exists(paste(getwd(), localDir, "spjoin.RData", sep = "/"))) {
load(file)
#spatial join between polygons (data_projected) and points (loc)
pts.poly <- over(loc, data_projected)
spjoin <- data.frame(loc, pts.poly)
spjoin$ECO_ID[spjoin$ID == 29] <- 60170
spjoin$ECO_ID[spjoin$ID == 75] <- 61301
save(spjoin, file = paste(getwd(), localDir, "spjoin.RData", sep = "/"))
}
load(paste(getwd(),localDir,"spjoin.RData",sep="/"))
#kml file for neolong (used for interactive map)
file <- paste(getwd(),localDir,"dat.kml",sep="/")
if(!file.exists(file)) writeOGR(loc, dsn =paste(getwd(),localDir,"dat.kml" ,sep="/"), layer="neolong", driver = "KML") #kml file created (for interactive map)
##LACKING:include reference, GPC classification type and biome name in dat.kml
#### SOME STATS ABOUT THE DATABASE####
####How many datasets does our dataset have?####
uniquestudy = lengthunique(neolong$ID) #218
####How many unique references does our dataset have?####
uniqueref = lengthunique(neolong$ref) #177
tt <-table(sort(neolong$ref))
length(which(tt>1)) ## not unique references
### surface of the studied polygon: 17700000 km2
(studyperarea = 17000000/218)
####what are the censuring frequency times?####
censtime = function(data = neolong){
freqcens = numeric()## we transform the qualitative variable in a quantitative one
weekly = length(which(data$frequency=="weekly"|data$frequency=="dayly" ))
biweekly = length(grep("biweekly",data$frequency))
monthly = length(grep("monthly",data$frequency))-length(which(data$frequency == "bimonthly"))
day20 = length(which(data$frequency == "20-day"|data$frequency == "every six weeks"))
bimonthly = length(which(data$frequency == "bimonthly"))
sporadic = length(grep("sporadic", data$frequency)) + length(grep("irregular", data$frequency))
unespecified = length(grep("unespecified",data$frequency))+length(grep("herbarium",data$frequency))
summaryvar = data.frame(var = c("weekly", "biweekly","monthly", "day20","bimonthly","sporadic","unespecified"),freq = c(weekly, biweekly, monthly, day20, bimonthly, sporadic, unespecified))
summaryvar$per = (summaryvar$freq/sum(summaryvar$freq))*100
return(summaryvar)
}
####vegetation types####
vegtyp = aggregate(data.frame(nbstu = neolong$ID), by = list(vegetation = neolong$vegetation), lengthunique)
vegtyp[order(vegtyp $ nbstu, decreasing = T),]
#### which are the long-term datasets?####
longterm = neolong[which(neolong$studylength >= 120),]
(longtermtable = data.frame(ID = longterm$ID, author = longterm$ref_short, locality = longterm$locality, length = longterm$studylength, DOI = longterm$DOI))
####CLIMATIC DRIVERS####
#frequency of studies without statistical test
(perctest = aggregate(data.frame(nstu = drivers$ID), by = list(presencetest = drivers$presencetest),length))
(perctest2 = (perctest$nstu[perctest$presencetest=="no"]/sum(perctest$nstu))*100)
#First, I calculate the number of datasets related to each environmental variable
freqdriv1 = aggregate(data.frame(nstu=drivers$ID),by =list(climvar=drivers$climvar),length)
(freqdriv1[order(freqdriv1$nstu,decreasing=T),]) #ordering drivers according to their importance
####Table 2####
#total frequencies for table 2
(rainfreq = (160/218) *100)
(tempfreq = (42/218) *100)
(daylengthfreq = (20/218) *100)
(floodingfreq = (13/218) *100)
(irradiancefreq = (7/218) *100)
(ensofreq = (3/218) *100)
(airfreq = (3/218) *100)
(evapofreq = (1/218) *100)
(nonefreq = (48/218) *100)
sum(freqdriv1$nstu[freqdriv1$climvar == "biotic"])/lengthunique(drivers$ID) ## percentage of studies addressing a biotic variable
(lengthunique(drivers$ID) -(freqdriv1$nstu[freqdriv1$climvar == "biotic"] + freqdriv1$nstu[freqdriv1$climvar == "none"]))/lengthunique(drivers$ID) ## percentage of studies addressing a biotic variable
## percentage of studies addressing an environmental variable
#Second, I explore datasets without statistical analyses (Table 2)
driversnotest <- drivers[drivers$presencetest=="no",]
freqdriv2 = aggregate(data.frame(nstu = driversnotest$ID),by = list(climvar = driversnotest$climvar),length)
(freqdriv2[order(freqdriv2$nstu,decreasing=T),]) #ordering drivers according to their importance ##Table 2 (statistically non-tested)
#Third, I explore datasets with statistical analyses (Table 2)
driverstest <- drivers[drivers$presencetest == "yes",]
(lengthunique(driverstest$ID)/lengthunique(drivers$ID))*100
freqdriv3 = aggregate(data.frame(nstu = driverstest$ID),by=list(climvar=driverstest$climvar),length)
freqdriv3[order(freqdriv3$nstu,decreasing = T),] #ordering drivers according to their importance
#frequency of each type of statistical test
(freqtest = aggregate(data.frame(nstu=driverstest$ID),by=list(test=driverstest$typetest),lengthunique))
(3+1)/lengthunique(driverstest$ID) #datasets including cross-correlations or moving correlation
#sign of correlations for Table 2
(signrain = aggregate(data.frame(nstu = driverstest[driverstest$climvar=="rainfall",]$ID),by = list(signcorr = driverstest[driverstest$climvar=="rainfall",]$signcorr),length))
(signtemp = aggregate(data.frame(nstu = driverstest[driverstest$climvar=="temperature",]$ID),by=list(sign_temp = driverstest[driverstest$climvar=="temperature",]$signcorr),length))
(signdl = aggregate(data.frame(nstu=driverstest[driverstest$climvar=="daylength",]$ID),by=list(sign_daylength = driverstest[driverstest$climvar=="daylength",]$signcorr),length))
(signflooding = aggregate(data.frame(nstu = driverstest[driverstest$climvar == "flooding"|driverstest$climvar == "tide levels",]$ID),by=list(sign_flooding = driverstest[driverstest$climvar == "flooding"|driverstest$climvar == "tide levels", ]$signcorr), length))
(signirradiance = aggregate(data.frame(nstu = driverstest[driverstest$climvar=="irradiance"|driverstest$climvar == "solar radiation", ]$ID), by = list(sign_irrad = driverstest[driverstest$climvar == "irradiance"|driverstest$climvar == "solar radiation",]$signcorr), length))
(signENSO = aggregate(data.frame(nstu = driverstest[driverstest$climvar == "ENSO",]$ID), by = list(sign_ENSO = driverstest[driverstest$climvar=="ENSO",]$signcorr),length))
(signhumid=aggregate(data.frame(nstu = driverstest[driverstest$climvar == "air humidity", ]$ID), by = list(sign_humid = driverstest[driverstest$climvar == "air humidity",]$signcorr), length))
(signevapo = driverstest[driverstest$climvar == "evaporation",])
#how many drivers were included in each study?
nbstudies = aggregate(data.frame(nbvar=drivers$climvar), by=list(ID=drivers$ID),lengthunique)
nbstudies[order(nbstudies$nbvar,decreasing=T),]
table(nbstudies$nbvar)
####Table 3####
#link each study to its vegetation type and explore its seasonality regarding precipitation
driv <- merge(drivers, neolong, by="ID", all.x=TRUE) #we include vegetation type in the drivers' dataset
raindriv = driv[driv$climvar=="rainfall",]
(t3 <- aggregate(data.frame(nstu = neolong$ID), by = list(peak = neolong$peak, veg = neolong$vegetation), length))
vegtyp2 = aggregate(data.frame(nbstu = driv$ID), by = list(vegetation = driv$vegetation), lengthunique)
vegtyp2[order(vegtyp $ nbstu, decreasing = T),]
signrain = factor(levels=c("positive","negative","none","ambiguous"))
for (i in 1:length(raindriv$signcorr))
{
if (raindriv$signcor[i]=="positive"|raindriv$signcorr[i]=="negative"|raindriv$signcorr[i] == "none") signrain[i] = raindriv$signcorr[i]
else signrain[i]= "ambiguous"
}
raindriv = data.frame(raindriv,signrain)
signrainveg = aggregate(data.frame(nstu=raindriv$ID),by=list(signcorr=raindriv$signcorr,vegtype=raindriv$vegetation),length)
(tt = table(raindriv$vegetation, raindriv$signrain))
##include table 3 here
(rainforest = chisq.test(c(rainy = 42, dry =17, aseasonal = 16, transition = 11))) ##significant
#desert = chisq.test(c(positive=6, negative= 4,none=1)) #not valid
dry = chisq.test(c(positive=9, negative=5,none=1))
(cerrado = chisq.test(c(rainy = 11, transition = 6, dry = 0))) ##significant
flooded = chisq.test(c(rainy = 10, transition = 5, dry = 5)) ##non-significant
#grassland=chisq.test(c(positive=4, negative=4,none=3))
#montane=chisq.test(c(positive=5, negative=3,none=1))
####Supplementary Table 1####
(ST1 <- aggregate (driv$ID, by = list(climvar = driv$climvar, vegetation = driv$vegetation), lengthunique))
##Carlos' graph:
temp <- driv[driv$climvar=="temperature",]
prec <- driv[driv$climvar=="rainfall",]
hist(abs(temp$lat))
hist(abs(prec$lat), breaks = c(0,5,10,15,20,25,30))
#### FIGURES OF THE PAPER #####
#### Figure1: bibliographic analysis of the number of papers including the term "phenology", "phenology + tropic" and "phenology +tropic +fruit" in Scopus####
figure1 = function(filename = "figure1.tif"){
pheno = read.delim("Scopus-phenolog.txt") #this query was done on the 24/04/2016 using the term "phenolog*" for ALL document types and fields "TITLE-ABS-KEY" in Scopus
phenotrop = read.delim("Scopus-phenolog AND trop.txt") #this query was done on the 24/04/2016 using the term "phenolog* AND trop*" for ALL document types and fields "TITLE-ABS-KEY" in Scopus
phenotropfr = read.delim("Scopus-phenolog AND trop AND fruit.txt") #this query was done on the 24/04/2016 using the term "phenolog* AND trop* AND fruit*" for ALL document types and fields "TITLE-ABS-KEY" in Scopus
totalpub = read.delim("Scopus-totalpub.txt") #this query was done on the 24/04/2016 using the terms Ecology OR Biometeorology OR Evolution for ALL document types and fields "TITLE-ABS-KEY" in Scopus
scyear1 = merge(pheno,phenotrop,by="YEAR", all.x=T)
scyear2 = merge(scyear1,phenotropfr,by="YEAR", all.x=T)
scyear3 = merge(scyear2,totalpub,by="YEAR", all.x=T)[-c(1:91),] #we exclude datasets before 1970
scyear96 = rbind(data.frame(YEAR=1995, pheno = sum(scyear3$pheno[scyear3$YEAR<1996]), phenotrop = sum(scyear3$phenotrop[scyear3$YEAR < 1996],na.rm = T),phenotropfr = sum(scyear3$phenotropfr[scyear3$YEAR < 1996],na.rm = T),totalpub = sum(scyear3$totalpub[scyear3$YEAR<1996],na.rm = T)),scyear3[scyear3$YEAR >= 1996,])
tiff(filename = filename, height = 1000, width = 2100, pointsize = 24)
par(mar = c(8,6,2,6))
counts = t(as.matrix(scyear3[,2:4],beside = TRUE))
counts2 = t(as.matrix(scyear3[,2:4]/scyear3$totalpub, beside = TRUE)) #we standarized by the total amount of publications in ecological fields
barplot(counts,las = 2, ylim = c(0,2500), names.arg = as.character(scyear3$YEAR), border = TRUE, col = c("grey80","white", "black"), cex.axis = 1.25, cex = 1.25)
#barplot(counts2,las=2,ylim=c(0,0.5),names.arg=as.character(scyear3$YEAR),col=c("grey80","darkblue","red"),cex.axis=1.15,cex=1.15)
mtext(side=2, text = "number of publications in topics of this review", line = 4.5, cex = 1.5, las = 0)
mtext(side = 1, text = "year of addition to Scopus® database", line = 5, cex = 1.5)
legend(1,2500, legend = c("phenolog*", "phenolog* + trop*","phenolog* + trop* + fruit*"),bty="n",border=rep("black",3),cex=1.5,fill=c("grey80","white","black"))
legend(1,2000, legend = c("Ecology, Biometeorology or Evolution publications"), bty = "n", lty = 2, cex = 1.5, col = c("grey20"), lwd = 3)
lm1 = lm(log(scyear3$pheno) ~ scyear3$YEAR)# exponential least square fit for the number of publications as function of the publication year
summary(lm1) #very good adjustement to an exponential fit
lm2 = lm(log(scyear3$pheno[scyear3$YEAR >= 1996]) ~ scyear3$YEAR[scyear3$YEAR >= 1996])# exponential least square fit for the number of publications as function of the publication year (since 1996)
summary(lm2)
#test of the exponential fit
#plot(scyear3$YEAR,scyear3$pheno)
#lines(scyear3$YEAR, exp(predict(lm1,list(scyear3$YEAR))),col="blue")
#lines(scyear3$YEAR[scyear3$YEAR>=1996], exp(predict(lm2,list(scyear3$YEAR[scyear3$YEAR>=1996]))),col="red")
par(new = T)
plot(scyear3$YEAR, scyear3$totalpub/40, col = "grey20", ylim = c(0,2100), lty = 2, lwd = 3, type = "l", axes = F, xlab = "", ylab = "")
axis(side = 4, at = seq(0,2000,500), labels = seq(0,2000,500)*40, col = "grey20", las = 1, cex.axis = 1.25, cex = 1.25, col.axis = "grey20")
mtext(side = 4, text = "number of publications in ecological fields", line = 4.5, cex = 1.5, las = 0)
#plot(scyear$YEAR[scyear>=1996], scyear$pheno[scyear>=1996],type="l",xlab="",ylab="",las=1,bty="l",lwd=2)
#lines(scyear$YEAR, scyear$tropicpheno,col="blue",lwd=2)
#
dev.off()
}
####Figure 2: statistics
#what is the sampling effort in terms of number of species?
hsp = hist(neolong$species)
hsp$counts [1]/ sum(hsp$counts)
summary(neolong$species)
#what is the sampling effort in terms of monitoring length?
hlength = hist(neolong$studylength, breaks = c(12, 24, 36, 48, 60, 120, 480), main = "studylength")
str(hlength)
hlength$counts[1]/ sum(hlength$counts)
summary(neolong$studylength)
####Figure 3: How many countries do we have in our dataset?####
figure3 = function(data = neolong, cex=2, filename = "figure3.tif",...){
data$country = as.character(data$country)
lengthunique(data$country) #number of study sites
countryfreq = aggregate(data.frame(numb = data$ID), by = list(country = data$country), lengthunique)
countryfreq[order(countryfreq$numb, decreasing = T),]
(statefreq = aggregate(data.frame(numb = data$ID), by = list(state = data$BrazilState), lengthunique))
max(statefreq$numb)/lengthunique(data$ID) #frequency of studies from São Paulo state in Brazil
sort(statefreq$numb, decreasing = T) [2]/lengthunique(data$ID) #frequency of studies from Amazonia state in Brazil
reorder_size <- function(x) {
factor(x, levels = names(sort(table(data$country), decreasing = T)))
}
ggplot(data, aes(reorder_size(country))) + geom_bar(fill="grey80", colour="black") + ylab("Number of datasets") + xlab("") +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0, size = 15, colour = "black"), axis.text.y = element_text(size = 15), axis.ticks.x = element_blank(), panel.background = element_blank(), axis.title.y = element_text(size = 20), plot.margin = unit(c(1, 2, 1, 1), "cm"), panel.margin = unit(c(2,2,2,1), "cm") )
ggsave(filename, device ="tiff")
}
####Figure 4: which type of methods did authors use for studying phenology?####
figure4 = function(data = neolong, filename="figure4.tif"){
direct = aggregate(data.frame(nstu=data$ID), by = list(direct=data$DO, marked=data$marked),length)
indirect = aggregate(data.frame(nstu=data$ID), by = list(LT = data$LT, herbarium = data$herbarium, feces = data$feces, ground = data$ground.survey), length)
marked = length(which(data$marked == "marked"))
unmarked = length(which(data$marked == "unmarked"))
lt = length(which(data$LT == "yes"))
mean(data$trapsurface, na.rm = T) #mean surface of seed traps
sd(data$trapsurface, na.rm = T) #sd surface of seed traps
range(data$Ntraps, na.rm = T) #range of number of traps
mean(data$Ntraps, na.rm = T) #range of number of traps
sd(data$Ntraps, na.rm = T) #range of number of traps
herbarium = length(which(data$herbarium == "yes"))
feces = length(which(data$feces == "yes"))
ground = length(which(data$ground.survey == "yes"))
summaryvar = matrix(ncol=2,nrow=6, dimnames = list(c("marked","unmarked" ,"traps", "herbarium","faeces","ground surveys"), c("direct","indirect")))
summaryvar[,1] = c(marked,unmarked,0,0,0,0)
summaryvar[,2] = c(0,0,lt, herbarium,feces,ground)
percentages = (summaryvar/lengthunique(neolong$ID))*100
tiff(filename = filename, height = 900, width = 1200, pointsize = 30)
par(mar = c(3,5,3,1), cex = 1.5)
barplot(summaryvar, las = 1, ylim = c(0,200), ylab = "number of datasets", col = c("violet", "violetred4", "darkorange", "moccasin", "tan", "tan4"), width = c(10,10))
legend(12, 200, legend = rownames(summaryvar), bty="n", fill = c("violet", "violetred4", "darkorange", "moccasin", "tan", "tan4"))
dev.off()
}
####Figure6: how many species were studied by vegetation type?####
figure6 = function(data = spjoin, ests = ests, filename = "figure6.tif"){
tiff(filename = filename, height = 900, width = 1100, pointsize = 24)
par(mar = c(4,16,1,2), mfrow = c(2,1))
lm1 = lm(data$species ~ data$vegetation)
summary (lm1)
##SAMPLING EFFORT "se" calculates a ratio p with sampling effort per spp
se = merge(data, ests, by="ECO_ID",all.x=T)
se$p = se$species/se$sp_wfig
sum(se$sp_wfig) #estimated number of species
sum(se$species, na.rm = T) #total number of studied species
sum(se$species, na.rm = T)/sum(se$sp_wfig) #undersampling of plant species (1%)
summary(se$p)
meanratio = aggregate(data.frame(ratio=se$p), by=list(vegetation=se$vegetation),mean,na.rm=T)
mediannsp = aggregate(data.frame(nbspp=se$species), by=list(vegetation=se$vegetation), median,na.rm=T)
meansp = aggregate(data.frame(nbspp=se$species), by=list(vegetation=se$vegetation), mean,na.rm=T)
minsp = aggregate(data.frame(nbspp=se$species), by=list(vegetation=se$vegetation), min,na.rm=T)
maxsp = aggregate(data.frame(nbspp=se$species), by=list(vegetation=se$vegetation), max, na.rm=T)
sdratio = aggregate(data.frame(ratio=se$species), by=list(vegetation=se$vegetation), sd,na.rm=T)
medianratio = aggregate(data.frame(ratio=se$p), by=list(vegetation=se$vegetation), median,na.rm=T)
veg = meanratio$vegetatio[order(meanratio$ratio)]
veg2 = medianratio$vegetatio[order(medianratio$ratio)]
se$newveg=factor(as.character(se$vegetation),levels=as.character(medianratio$vegetation[order(medianratio$ratio)]))
b=boxplot(se$p~se$newveg,las=1,col=c("deeppink","brown","darkgreen","red","blue1","purple","orange","green1","bisque"),horizontal=T,cex.axis=1)
mtext(side=1,"sampling effort ratio",line=2.5,cex=1.3)
se$sppveg=factor(as.character(se$vegetation),levels=as.character(meansp$vegetation[order(meansp$nbspp)]))
#b=boxplot(se$s~se$sppGPC,las=1,col=c("brown","bisque","darkgreen","deeppink","purple","green1","blue1","red","orange"),horizontal=T,cex.axis=1)
b2=boxplot(se$species~se$newveg,las=1,col=c("deeppink","brown","darkgreen","red","blue1","purple","orange","green1","bisque"),horizontal=T,cex.axis=1)
mtext(side=1,"number of species sampled",line=2.5,cex=1.3)
dev.off()
}
####Figure S1: What is the monitoring length of datasets?####
#figureS1 plots a barplot with the frequency of studies according to their sampling length
figureS1 = function(data = neolong, filename = "figureS1.tif", cex = 2, ...){
meansampling = mean(data$studylength,na.rm = T)
oneyear = which(data$studylength <= 12)
twoyear = which(data$studylength <= 24 & data$studylength > 12)
threeyear = which(data$studylength <= 36 & data$studylength > 24)
fouryear = which(data$studylength <= 48& data$studylength > 36)
fiveyear = which(data$studylength < 120 & data$studylength > 48)
tenyear = which(data$studylength >= 120)
summarylength = data.frame(time = c("1 year", "2 years","3 years", "4 years", "5-9 years","10 or more years"), freq = c(length(oneyear),length(twoyear), length(threeyear), length(fouryear), length(fiveyear), length(tenyear)))
summarylength$perc = (summarylength$freq/sum(summarylength$freq))*100
par(mar = c(12,20,2,2), oma = c(8,25,8,8), cex = cex, ...)
tiff(filename = filename, height = 900, width = 1400, pointsize = 24)
barplot(summarylength$perc, names.arg = summarylength$time, las = 1, ylim = c(0,60), ylab = "", cex.axis = 1)
mtext (side = 2, text = "percentage of datasets (%)", line = 2.2, cex = 1.25)
dev.off()
}
####Figure S2:
#figureS2(data = neolong, filename="figureS2.tif")
figureS2 = function(data = neolong, filename="figureS2.tif",cex=2,...){
tiff(filename = filename,height=700,width=1000,pointsize=12) #
par(mar = c(4,4,4,4), cex = cex)
plot(sort(neolong$Nindiv[which(!is.na(data$Nindiv))]/neolong$species[which(!is.na(data$Nindiv))],decreasing=T),axes=F,ylab="",xlab="",xlim=c(0,120),pch=20)
#plot(sort(log(neolong$Nindiv[which(!is.na(data$Nindiv))]/sum(neolong$Nindiv[which(!is.na(data$Nindiv))])+1),decreasing=T))
abline(h=15,lty=2)
axis(side=1,at=seq(0,120,20),labels=seq(0,120,20))
mtext(side=1, text="Rank of datasets",line=3,cex=cex)
axis(side=2,at=seq(0,100,20),labels=seq(0,100,20),las=2)
mtext(side=2, text="number of individuals/number of species",line=3,cex=cex)
#proportion of studies with at least 15 individuals sampled per species
length(which(neolong$Nindiv[which(!is.na(data$Nindiv))]/neolong$species[which(!is.na(data$Nindiv))]>=15))/length(neolong$Nindiv[which(!is.na(data$Nindiv))])
dev.off()
}
| ab2222a3a3cbdda180c7667431e94071800b3f01 | [
"Markdown",
"R"
]
| 2 | Markdown | iremendoza/fruit-phenology | 4957f23695c38b86e18c378ae88f1e5fa27fe99e | 4fd51d74247e55d884d72882fe234c1f9c36aa37 |
refs/heads/main | <file_sep>package com.devsuperior.dsdevilver.comum.product.model;
import lombok.*;
import javax.persistence.*;
import java.io.Serializable;
import java.util.UUID;
@Entity
@Getter
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@NoArgsConstructor(access = AccessLevel.PACKAGE)
@AllArgsConstructor
@Builder
@Table(name = "tb_product")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Double price;
private String description;
private String imageUri;
}
<file_sep>package com.devsuperior.dsdevilver.order.api.model;
public class OrderNotEncontredException extends RuntimeException {
}
<file_sep>package com.devsuperior.dsdevilver.comum.product.api;
import com.devsuperior.dsdevilver.comum.product.api.model.ProductResponse;
import com.devsuperior.dsdevilver.comum.product.api.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping(value = "products")
public class ProductController {
@Autowired
private ProductService productService;
// @PostMapping
// @ApiOperation("Salvar um Produto")
// public ResponseEntity<ProductResponse> cadastrar(@RequestBody @Valid InclusaoProdutoRequest request,
// UriComponentsBuilder uriBuilder) {
//
// Product produto = request.toModel();
//
// if(produtoRepository.existsByCodigo(produto.getCodigo())) {
// throw new ProdutoDuplicadoException(request.getCodigo(), request.getDescricao());
// }
//
// Produto produtoCadastrado = produtoRepository.save(produto);
//
// return ResponseEntity.created(ServletUriComponentsBuilder
// .fromCurrentRequest()
// .path("/")
// .path(produtoCadastrado.getId().toString()).build().toUri())
// .body(produtoCadastrado);
// }
@GetMapping("/{id}")
public ResponseEntity<ProductResponse> buscarPorId(@PathVariable Long id){
return ResponseEntity.ok(productService.findById(id));
}
@GetMapping
public ResponseEntity<List<ProductResponse>> buscarTodos(){
return ResponseEntity
.ok()
.body(productService.findAll()
);
}
}
<file_sep>package com.devsuperior.dsdevilver.order.api.model;
import com.devsuperior.dsdevilver.order.Order;
import com.devsuperior.dsdevilver.order.OrderStatus;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
import java.time.Instant;
import java.util.HashSet;
import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class OrderRequest {
@NotNull
private String address;
@NotNull
private Double latitude;
@NotNull
private Double longitude;
@NotNull
private List<OrderProductRequest> productsId;
public Order toModel(){
return Order.builder()
.address(this.address)
.latitude(this.latitude)
.longitude(this.longitude)
.moment(Instant.now())
.status(OrderStatus.PENDING)
.products(new HashSet<>())
.build();
}
}
<file_sep><h1 align="center">DS Delivery</h1>
<p align="center">Projeto realizado durante a Semana DevSuperior 2.0</p>
### [Frontend: ReactJS com Axios (Netlify)](https://devsuperior.netlify.app/)
### [Backend: Java com Springboot Framework e JPA / Hibernate e PostgreSQL (Heroku/Swagger)](https://devsuperior-2021.herokuapp.com/swagger-ui.html)
- Endpoints:
- [GET] /products
- [GET] /orders
- [POST] /orders
- [PUT] /orders/{id}/delivered
### Mobile - React-Native e Expo - Para executar:
- Baixar o projeto e abrir a pasta mobile
- Executar npm install para instalar as dependências e npm start para iniciar o build com Expo.
- Baixar o Expo no celular com Android e Google Maps e scanear o QR-Code.
- Em seguida o aplicativo será inicializado no aparelho.
<p align="center">
<img src="https://github.com/wgcostta/dsdeliver-sds2/blob/main/assets/Home.png" height="250" width="125" alt="Tela Principal" />
<img src="https://github.com/wgcostta/dsdeliver-sds2/blob/main/assets/OrderList.png" height="250" width="125" alt="Listagem de Pedidos" />
<img src="https://github.com/wgcostta/dsdeliver-sds2/blob/main/assets/OrderCard.png" height="250" width="125" alt="Detalhes do Pedido" />
</p>
<br>
<p align="center">
<img src="https://img.shields.io/static/v1?label=springboot&message=2.4.1&color=6AAD3D&style=flat-square&logo=spring"/>
<img src="https://img.shields.io/static/v1?label=npm&message=6.14.9&color=C53534&style=flat-square&logo=npm"/>
<img src="https://img.shields.io/static/v1?label=react&message=^17.0.1&color=61D9FB&style=flat-square&logo=react"/>
<img src="https://img.shields.io/static/v1?label=react-native&message=0.63.2&color=61D9FB&style=flat-square&logo=react"/>
<img src="https://img.shields.io/static/v1?label=expo&message=40.0.0&color=F2F2F2&style=flat-square&logo=expo"/>
<img src="https://img.shields.io/static/v1?label=typescript&message=^4.1.3&color=2F74C0&style=flat-square&logo=typescript"/>
<a href="https://github.com/wgcostta" target="_new">
<img src="https://img.shields.io/badge/-Wagner%20Costa-000000?style=flat-square&labelColor=000000&logo=github&logoColor=white"/>
</a>
</p>
<file_sep>package com.devsuperior.dsdevilver.order.api;
import com.devsuperior.dsdevilver.order.api.model.OrderRequest;
import com.devsuperior.dsdevilver.order.api.model.OrderResponse;
import com.devsuperior.dsdevilver.order.api.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(value = "orders")
public class OrderController {
@Autowired
OrderService orderService;
@GetMapping("/{id}")
public ResponseEntity<OrderResponse> buscarPorId(@PathVariable Long id){
return ResponseEntity.ok(orderService.findById(id));
}
@GetMapping
public ResponseEntity<List<OrderResponse>> buscarTodos(){
return ResponseEntity
.ok()
.body(orderService.findAll()
);
}
@PostMapping
public ResponseEntity<OrderResponse> salvar(@RequestBody @Valid OrderRequest orderRequest){
OrderResponse orderResponse = orderService.save(orderRequest);
return ResponseEntity.created(ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/")
.path(orderResponse.getId().toString()).build().toUri())
.body(orderResponse);
}
@PutMapping("/{id}/delivered")
public ResponseEntity<OrderResponse> atualizarStatus(@PathVariable Long id){
return ResponseEntity
.ok()
.body(orderService.setDelivered(id)
);
}
}
<file_sep>package com.devsuperior.dsdevilver.comum.product.api.service;
import com.devsuperior.dsdevilver.comum.product.api.model.ProductNotEncontredException;
import com.devsuperior.dsdevilver.comum.product.api.model.ProductResponse;
import com.devsuperior.dsdevilver.comum.product.model.Product;
import com.devsuperior.dsdevilver.comum.product.model.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Transactional(readOnly = true)
public List<ProductResponse> findAll(){
return ProductResponse.fromModels(productRepository.findAllByOrderByNameAsc());
}
@Transactional(readOnly = true)
public ProductResponse findById(Long id){
Product produto = productRepository.findById(id)
.orElseThrow(() -> new ProductNotEncontredException());
return ProductResponse.fromModel(produto);
}
}
<file_sep>package com.devsuperior.dsdevilver.order.api.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class OrderProductRequest implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
}
<file_sep>package com.devsuperior.dsdevilver.comum.product.api.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public class ProductNotEncontredException extends RuntimeException {
}
| f8dd383c6fedf37d665f56de0a94dc8416f3403b | [
"Markdown",
"Java"
]
| 9 | Java | wgcostta/dsdeliver-sds2 | 288db9e6190280797e79103c15abfe89a5aeace8 | 716167641b7c3fdc82bdbff1fccdade4f535b9ab |
refs/heads/master | <file_sep>import React from 'react';
function TodoList(props) {
return (
<ul>
{props.todos.map(todo =>
<li
key={todo.id}
><a
href="" onClick={(e) => {
e.preventDefault();
props.onDELETEClick(todo.id);
}
}>
{todo.text}
</a> </li>,
)}
</ul>
);
}
export default TodoList;
<file_sep>import React from 'react';
// function addItem() {
// const text = taskInput.value;
// console.log(text);
// this.props.onAddClick(text);
// this.taskInput.value = '';
// }
function AddTodo(props) {
let taskInput;
return (<div className="todoListMain">
<div className="header">
<form
onSubmit={(e) => {
e.preventDefault();
if (taskInput.value !== '') {
props.onAddClick(taskInput.value.trim());
taskInput.value = '';
}
}}
>
<input ref={(el) => { taskInput = el; }} type="text" placeholder="enter task" />
<button type="submit">add</button>
</form>
</div>
</div>);
}
export default AddTodo;
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { addTodo, deleteTodo } from './actions/actions';
import AddTodo from './components/AddTodo';
import TodoList from './components/TodoList';
import './App.css';
class App extends Component {
render() {
const { dispatch, visibleTodos } = this.props;
return (
<div>
<AddTodo onAddClick={text => dispatch(addTodo(text))} />
<TodoList todos={visibleTodos} onDELETEClick={id => dispatch(deleteTodo(id))} />
</div>
);
}
}
function select(state) {
return {
visibleTodos: state.todos,
};
}
export default connect(select)(App);
<file_sep>export const ADD_TODO = 'ADD_TODO';
export const DELETE_TODO = 'DELETE_TODO';
export function addTodo(text) {
return {
type: 'ADD_TODO',
id: Date.now(),
text,
};
}
export function deleteTodo(id) {
return {
type: 'DELETE_TODO',
key: id,
};
}
<file_sep>import { combineReducers } from 'redux';
function todos(state = [], action) {
let list = [];
switch (action.type) {
case 'ADD_TODO':
return [
...state,
{
id: action.id,
text: action.text,
},
];
case 'DELETE_TODO':
list = state.filter(obj => obj.id !== action.key);
console.log(list);
return list;
default:
return state;
}
}
const todoApp = combineReducers({ todos });
export default todoApp;
| f647c2e3a51000d035902a4d653e6bd994378335 | [
"JavaScript"
]
| 5 | JavaScript | bhaskesaravanan/todo-redux | 5ee117ad1f2c571dd976d78cfdff250a4622e97e | 526b4874d343728366c215ae9392f9a70e0d9339 |
refs/heads/master | <file_sep>from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
'''Return Homepage '''
return render_template('home.html')
@app.route('/music')
def music():
'''Return Homepage '''
return render_template('music.html')
@app.route('/video')
def video():
'''Return Homepage '''
return render_template('videos.html')
@app.route('/gear')
def gear():
'''Return Homepage '''
return render_template('gear.html')
if __name__ == '__main__':
app.run(debug=True) | faa39a407c3bbcff03b0d7fe425339f08be97d63 | [
"Python"
]
| 1 | Python | shaannessy25/Capstone | bbcbf34ee0874572b6635d0914a7b3c0837d9484 | 2524ab3d8e32f08b4e0e6ec7eeed2b625e5533e5 |
refs/heads/main | <repo_name>voronindim/AudioPlayerController<file_sep>/AudioPlayerController/AudioPlayerFactory.swift
//
// AudioPlayerFactory.swift
// AudioPlayerController
//
// Created by <NAME> on 15.04.2021.
//
import Foundation
import AVFoundation
final class AudioPLayerFactory {
func avPlayer(url: URL) -> AVPlayer {
let avPlayerItem = AVPlayerItem(asset: AVAsset(url: url))
return AVPlayer(playerItem: avPlayerItem)
}
}
<file_sep>/AudioPlayerController/AudioPlayerController.swift
//
// AudioPlayerController.swift
// AudioPlayerController
//
// Created by <NAME> on 15.04.2021.
//
import Foundation
import AVFoundation
import RxSwift
protocol AudioPlayerController {
var duration: Observable<Float64?> { get }
var currentDuration: Observable<Float64?> { get }
var playerStatus: Observable<AudioPlayerStatus> { get }
var rate: Observable<Float> { get }
func play()
func pause()
func rollBack()
func rollForward()
func currentDurationDidChange(newValue value: Float64)
}
final class AudioPlayerControllerImpl {
// MARK: - Private properties
private let _duration = BehaviorSubject<Float64?>(value: nil)
private let _currentDuration = BehaviorSubject<Float64?>(value: nil)
private let _playerStatus = BehaviorSubject<AudioPlayerStatus>(value: .none)
private let _rate = BehaviorSubject<Float>(value: 1.0)
private let audioPlayerFactory: AudioPLayerFactory
private let kRateValues: [Float]
private let kRollTime: Float64
private var player: AVPlayer?
private var lastRate: Float = 1.0
// MARK: - Initialize
init(audioPlayerFactory: AudioPLayerFactory, kRateValues: [Float], kRollTime: Float64) {
self.audioPlayerFactory = audioPlayerFactory
self.kRateValues = kRateValues
self.kRollTime = kRollTime
}
}
// MARK: - AudioPlayerController
extension AudioPlayerControllerImpl: AudioPlayerController {
var duration: Observable<Float64?> {
_duration
}
var currentDuration: Observable<Float64?> {
_currentDuration
}
var playerStatus: Observable<AudioPlayerStatus> {
_playerStatus
}
var rate: Observable<Float> {
_rate
}
func play() {
guard let player = player else {
return
}
player.play()
player.rate = lastRate
_playerStatus.onNext(.play)
}
func pause() {
guard let player = player else {
return
}
lastRate = player.rate
player.pause()
_playerStatus.onNext(.pause)
}
func changeRate() {
guard let player = player else {
return
}
guard let newValue = nextRate else {
return
}
player.rate = newValue
_rate.onNext(newValue)
}
func rollBack() {
guard let player = player else {
return
}
let currentTime = CMTimeGetSeconds(player.currentTime())
let newTime = currentTime - kRollTime < 0 ? 0 : currentTime - kRollTime
let time2 = newTime.toCMTime
player.seek(to: time2, toleranceBefore: .zero, toleranceAfter: .zero)
_currentDuration.onNext(time2.toFloat64)
}
func rollForward() {
guard let player = player, let duration = player.currentItem?.duration else {
return
}
let currentTime = CMTimeGetSeconds(player.currentTime())
let newTime = currentTime + kRollTime
if newTime < CMTimeGetSeconds(duration) - kRollTime {
let time2 = newTime.toCMTime
player.seek(to: time2, toleranceBefore: .zero, toleranceAfter: .zero)
_currentDuration.onNext(time2.toFloat64)
}
}
func currentDurationDidChange(newValue value: Float64) {
guard let player = player else {
return
}
let newTime = value.toCMTime
player.seek(to: newTime)
_currentDuration.onNext(newTime.toFloat64)
}
// MARK: - Private methods
private func addPeriodicTimeObserver() {
guard let player = player else {
return
}
player.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 1), queue: DispatchQueue.main, using: { time in
self._currentDuration.onNext(time.toFloat64)
})
}
}
// MARK: - AudioPlayerController
extension AudioPlayerControllerImpl: AudioPlayerControllerStarter {
func startPlay(url: URL, startTime: CMTime) {
player = audioPlayerFactory.avPlayer(url: url)
player?.seek(to: startTime)
player?.play()
addPeriodicTimeObserver()
}
}
// MARK: -
extension AudioPlayerControllerImpl {
private var nextRate: Float? {
guard let currentRate = try? _rate.value() else {
return nil
}
guard let index = kRateValues.firstIndex(where: { $0 == currentRate }) else {
return nil
}
return index > kRateValues.count - 1 ? kRateValues.first : kRateValues[index + 1]
}
}
fileprivate extension Float64 {
var toCMTime: CMTime {
CMTimeMake(value: Int64(self * 1000 as Float64), timescale: 1000)
}
}
fileprivate extension CMTime {
var toFloat64: Float64 {
Float64(CMTimeGetSeconds(self))
}
}
<file_sep>/AudioPlayerController/ViewModel/AudioViewModel.swift
//
// AudioViewModel.swift
// AudioPlayerController
//
// Created by <NAME> on 15.04.2021.
//
import Foundation
import RxSwift
import UIKit
import AVFoundation
final class AudioViewModel {
// MARK: - Private properties
private let audioPlayerController: AudioPlayerController
private let _title = BehaviorSubject<String?>(value: nil)
private let _duration = BehaviorSubject<String?>(value: nil)
private let _currentDuration = BehaviorSubject<String?>(value: nil)
private let _rate = BehaviorSubject<String?>(value: nil)
private let _playButtonImage = BehaviorSubject<UIImage?>(value: nil)
private let disposeBag = DisposeBag()
private var playerStatus: AudioPlayerStatus = .none {
didSet {
if let image = createImageForAudioStatus() {
_playButtonImage.onNext(image)
}
}
}
// MARK: - Initialize
init(audioPlayerController: AudioPlayerController) {
self.audioPlayerController = audioPlayerController
}
// MARK: - Public methods
func play() {
audioPlayerController.play()
}
func pause() {
audioPlayerController.pause()
}
func rollBack() {
audioPlayerController.rollBack()
}
func rollForward() {
audioPlayerController.rollForward()
}
func currentDurationDidChange(newValue value: Float64) {
audioPlayerController.currentDurationDidChange(newValue: value)
}
// MARK: - Private methods
private func subscriveOnAudioPlayerController() {
audioPlayerController.duration.distinctUntilChanged().subscribe(onNext: { time in
self.setDuration(time: time)
}).disposed(by: disposeBag)
audioPlayerController.currentDuration.distinctUntilChanged().subscribe(onNext: {time in
self.setCurrentDuration(time: time)
}).disposed(by: disposeBag)
audioPlayerController.playerStatus.distinctUntilChanged().subscribe(onNext: { status in
self.playerStatus = status
}).disposed(by: disposeBag)
audioPlayerController.rate.distinctUntilChanged().subscribe(onNext: { rate in
self.setRate(rate: rate)
}).disposed(by: disposeBag)
}
private func setDuration(time: Float64?) {
guard let time = time else {
return
}
_duration.onNext(time.durationText)
}
private func setCurrentDuration(time: Float64?) {
guard let time = time else {
return
}
_currentDuration.onNext(time.durationText)
}
private func setRate(rate: Float?) {
guard let rate = rate else {
return
}
_rate.onNext("x \(rate)")
}
private func createImageForAudioStatus() -> UIImage? {
switch playerStatus {
case .pause:
return UIImage(named: "icon-play")!
case .play:
return UIImage(named: "icon-pause")!
default:
return nil
}
}
}
// MARK: -
extension AudioViewModel {
var title: Observable<String?> {
_title
}
var duration: Observable<String?> {
_duration
}
var currentDuration: Observable<String?> {
_currentDuration
}
var rate: Observable<String?> {
_rate
}
var playButtonImage: Observable<UIImage?> {
_playButtonImage
}
}
fileprivate extension Float64 {
var durationText: String {
let totalSeconds = Int(self)
let hours:Int = Int(totalSeconds / 3600)
let minutes:Int = Int(totalSeconds % 3600 / 60)
let seconds:Int = Int((totalSeconds % 3600) % 60)
return hours > 0 ?
String(format: "%i:%02i:%02i", hours, minutes, seconds) :
String(format: "%02i:%02i", minutes, seconds)
}
}
<file_sep>/AudioPlayerController/AudioPlayerControllerStarter.swift
//
// AudioPlayerControllerStarter.swift
// AudioPlayerController
//
// Created by <NAME> on 15.04.2021.
//
import Foundation
import AVFoundation
protocol AudioPlayerControllerStarter {
func startPlay(url: URL, startTime: CMTime)
}
<file_sep>/AudioPlayerController/AudioPlayerStatus.swift
//
// AudioPlayerStatus.swift
// AudioPlayerController
//
// Created by <NAME> on 15.04.2021.
//
import Foundation
enum AudioPlayerStatus {
case play
case pause
case none
}
| c4e8906b4a9c8799d02dedea9ccd42eb30a70506 | [
"Swift"
]
| 5 | Swift | voronindim/AudioPlayerController | 4a290b1abc7527be5d65e8d15915c725e7e356e9 | 692a0dcf4f479a4cfdb34691fe7a8b210ab41248 |
refs/heads/master | <repo_name>TheDeterminator/Sprint-Challenge--JavaScript<file_sep>/challenges/classes.js
// Copy and paste your prototype in here and refactor into class syntax.
class CuboidMaker {
constructor(props) {
this.length = props.length;
this.width = props.width;
this.height = props.height;
}
volume() {
return this.length * this.width * this.height;
}
surfaceArea() {
return 2 * (this.length * this.width + this.length * this.height + this.width * this.height);
}
}
class CubeMaker extends CuboidMaker {
constructor(props) {
super(props);
}
} //Volume and Surface Area formulas are the same, thus inherited Cuboid methods will suffice.
class TesseractMaker extends CuboidMaker {
constructor(props) {
super(props);
this.rotation = props.rotation;
this.power = props.power;
}
powerFour() {
return this.height * this.width * this.length * this.rotation;
}
binaryPowerFour() {
return 2 ** this.power;
}
} //Cubes are boring, so let's make a tesseract ;)
const cuboid = new CuboidMaker ({
'length': 4,
'width': 5,
'height': 5
});
const cube = new CubeMaker({
'length': -11,
'width': -12,
'height': -13
})
const tesseract = new TesseractMaker({
'length': 2,
'width': 2,
'height': 2,
'rotation': 2,
'power':4
})
// Test your volume and surfaceArea methods by uncommenting the logs below:
console.log(cuboid.volume()); // 100
console.log(cuboid.surfaceArea()); // 130
console.log(cube.volume());
console.log(cube.surfaceArea());
console.log(tesseract.powerFour());
console.log(tesseract.binaryPowerFour());
/* Stretch Task:
Extend the base class CuboidMaker with a sub class called CubeMaker. Find out the formulas for volume and surface area for cubes and create those methods as well. Create a new cube object and log out the results of your new cube.
*/
<file_sep>/ANSWERS.md
# Your responses to the short answer questions should be laid out here using Mark Down.
1. Describe the biggest difference between `.forEach` & `.map`.
-.map returns a newArray, .forEach works on an array in place
2. What is the difference between a function and a method?
-A function is a block of code that has an input or at least an output, a method is a function defined as a property of an object
3. What is closure?
-Closure is a function or when a function refers to a variable outside of itself.
4. Describe the four rules of the 'this' keyword.
1. Window/Global Object binding, to bind the window object to a function
2. Implicit binding in which 'this' refers binds an object which precedes a function call with obj.functionCall() syntax.
3. New binding in which this refers to an instance of an object created from a constructor class
4. Explicit binding in which 'this' changes the context of constructor object when .call() or .apply() are used
5. Why do we need super() in an extended class?
super() allows the extended class to reference the props of the parent class in its own class/object it is equivalent to the line Parent.call(this, props) in prototypical inheritance.
| 40de01f7d646224ca12abf8ee7854629ded20609 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | TheDeterminator/Sprint-Challenge--JavaScript | 8d6a87ac3ef2bb8960f0a015504a4eb8a00df742 | 5f6fda80c92ddfd7c22948ebcf31de15e8609450 |
refs/heads/main | <repo_name>dhong9/obj3Desmos<file_sep>/README.md
# obj3Desmos
Converts an OBJ file to a format that Desmos can read.
## How to use
After cloning the repo:
* Run `npm i` to install dependencies
* Run `npm start` to start the application
Use the Upload button to upload your OBJ file. The smaller the file, the quicker the processing time will be. Use the Parse button to get your output text file.
**Notes**
This will give you points without lines. You will need to change the settings manually after you paste the output into Desmos.<file_sep>/scripts/fileUpload.js
const { remote } = require('electron');
var objFile = "";
let types = [
{name: 'Models', extensions: ['obj']}
];
options = {filters:types, properties:['openFile']};
function openFile() {
remote.dialog.showOpenDialog(options).then(response => {
if (!response.canceled) {
objFile = response.filePaths[0]; // Get file name
document.getElementById("fileName").value = objFile; // Show selected file name
document.getElementById("parseBtn").disabled = false;
}
})
} | fd78197e436964193510ff44084d95dbfc8c1442 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | dhong9/obj3Desmos | 52840d64e0c112e33f8bb97e186ca899653160c5 | ee1cd400cf01c2b2e0b9164f70cd38c4d48f2b22 |
refs/heads/master | <repo_name>jpm61704/cuddly-lamp<file_sep>/config.js
/**
* Created by Jack on 09/21/2015.
*/
var config = {
databases: {
"development": "mongodb://admin:<EMAIL>:59672/voteapi",
"test": "mongodb://testmastergeneral:[email protected]:51923/vote-api-test"
},
secret: "inthebonds"
};
module.exports = config;<file_sep>/test/users/users.js
process.env.NODE_ENV = "test";
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require("../../app");
var should = chai.should();
var config = require('./config');
var User = require("../../models/user");
var mongoose = require('mongoose');
var userModel = mongoose.model("user");
describe("/users/", function() {
userModel.collection.drop();
before(function(done) {
var newUser = config.testData.tom;
User.functions.create(newUser, function(res) {
if(!res.completed){
console.error(res.description + "\n" + res.error);
}
done();
});
});
it("should return JSON and 200 status on GET", function (done) {
chai.request(server)
.get("/users/")
.end(function (err,res) {
res.should.have.status(200);
res.should.be.json;
res.body.should.not.be.empty;
res.body.should.be.a("array");
done();
});
});
it("should return 404 if not GET", function(done) {
chai.request(server)
.post("/users/")
.end(function (err,res) {
res.should.have.status(404);
chai.request(server)
.put("/users/")
.end(function (err,res) {
res.should.have.status(404);
chai.request(server)
.delete("/users/")
.end(function (err,res) {
res.should.have.status(404);
done();
});
});
});
})
var tests = config.tests;
for(test in tests){
require("./tests/" + tests[test]);
}
after(function(done) {
userModel.collection.drop();
done();
})
})
<file_sep>/commit.sh
#!/bin/bash
echo Committing Files
echo If new files were created then they must still be added
git commit -m "$1"
<file_sep>/routes/userRoutes.js
/**
* Created by Jack on 09/21/2015.
*/
var User = require("../models/user");
var userRoutes = {
'endpoint': "users",
'methods' : {
'get': [
{
"uri": '/table',
"route": function (req, res) {
User.functions.findAll(function (err, docs) {
res.render('users', {persons: docs});
});
}
},
{
"uri": '/',
"route": function (req, res) {
User.functions.findAll(function (err, docs) {
res.json(docs);
})
}
}
],
'post': [
{
"uri": '/new',
"route": function (req, res) {
var body = req.body;
body.date_joined = new Date().getTime();
User.functions.create(body, function (status) {
res.json(status);
});
}
}
],
'put': [
{
"uri": '/update',
"route": function (req, res) {
User.functions.update({_id: req.body.user_id}, req.body.updates, null, function (response) {
res.json(response);
});
}
}
],
'delete': [
{
"uri": '/delete',
"route": function (req, res) {
User.functions.delete(req.body.user_id, function(status){
res.json(status);
});
}
}
]
}
};
module.exports = userRoutes;<file_sep>/routes/router.js
/**
* Created by Jack on 09/21/2015.
*/
var router = require("express").Router();
//import all the routes
var indexRoutes = require("./index");
var userRoutes = require("./userRoutes");
var pollRoutes = require('./pollRoutes');
var routeFiles = [indexRoutes, userRoutes, pollRoutes];
for(file in routeFiles){
routefile = routeFiles[file];
for(method in routefile.methods){
for(route in routefile.methods[method]) {
var endpoint = "/" + routefile.endpoint + routefile.methods[method][route].uri;
var currentRoute = routefile.methods[method][route].route;
switch (method) {
case "get":
router.get(endpoint, currentRoute);
break;
case "post":
router.post(endpoint, currentRoute);
break;
case "put":
router.put(endpoint, currentRoute);
break;
case "delete":
router.delete(endpoint, currentRoute);
break;
}
}
}
}
module.exports = router;<file_sep>/test/runner.js
var chai = require('chai');
var config = require('./config');
describe("BEGIN TESTS", function() {
var tests = config.tests;
for(test in tests){
var testName = tests[test];
require("./" + testName + "/" + testName);
}
});
<file_sep>/test/polls/tests/new.js
/**
* Created by Jack on 09/26/2015.
*/
process.env.NODE_ENV = 'test';
var chai = require('chai');
var chaiHTTP = require('chai-http');
var server = require('../../../app.js');
var config = require('../config');
var should = chai.should();
var mongoose = require('mongoose');
chai.use(chaiHTTP);
var pollSample = config.sampleData.poll2;
var badPoll = config.sampleData.bad_poll;
describe("/polls/new", function () {
it("should create a new poll in the DB and return status 200", function (done) {
chai.request(server)
.post("/polls/new")
.send(pollSample)
.end(function (err,res) {
res.should.have.status(200);
res.body.completed.should.equal(true);
var Poll = mongoose.model("poll");
Poll.findById(pollSample._id, function(err, doc) {
doc.title.should.equal(pollSample.title);
})
done();
})
});
it("should return status 400 and error object when no body is passed in",function (done) {
chai.request(server)
.post("/polls/new")
.end(function (err,res) {
res.should.have.status(400);
done();
});
});
it("should return status 400 and error object when missing certain fields", function (done) {
chai.request(server)
.post("/polls/new")
.send(badPoll)
.end(function (err,res) {
res.should.have.status(400);
done();
});
});
it("should return status 400 if ivalid data is passed into a field", function(done){
var poll = config.util.copyRequest(pollSample);
poll.title = 124124;
chai.request(server)
.post("/polls/new")
.send(poll)
.end(function (err,res) {
res.should.have.status(400);
done();
});
});
});
<file_sep>/routes/pollRoutes.js
/**
* Created by Jack on 09/18/2015.
*/
//handle all required modules
var Poll = require("../models/poll");
var User = require("../models/user");
//post request for new polls
//see models\pollRoutes.js for the model format
//participants is empty at creation because that will be updated during a vote
var pollRoutes = {
'endpoint': "polls",
methods: {
'get': [
/*
* This route returns all the poll objects in the DB
*/
{
'uri': "/",
'route': function (req, res) {
Poll.functions.findAll(function (err, docs) {
res.json(docs);
});
}
},
{
'uri': "/:id",
'route': function (req, res) {
Poll.functions.findById(req.params.id, function (err, doc) {
if(doc === null){
res.status(404);
res.json({
completed: false,
description: "poll not found"
});
}else {
res.status(200);
res.json(doc);
}
});
}
}
],
'post': [
/*
* This route creates new poll from a json input
*/
{
'uri': "/new",
'route': function (req, res) {
var body = req.body; //make the request body a bit more accesible
body.participants = [];
Poll.functions.create(body, function (err, status) {
if(!status.completed){
res.status(400);
}
res.json(status);
});
}
}
],
'put': [
/*
* This route is responsible for casting a vote for a given user
*/
{
'uri': "/cast",
'route': function (req, res) {
var body = req.body;
User.functions.findById(body.user_id, function (status, user) {
if(status.completed === false){
res.status(400);
res.json(status);
}else{
var increment = {};
Poll.functions.update(
{"_id": body.poll_id, "options.name": body.vote},
{$inc: {"options.$.votes": 1}},
{upsert: true},
function (status, docs) {
res.json(status);
});
}
})
}
}
]
}
};
module.exports = pollRoutes;
<file_sep>/util/generate_test.sh
#!/bin/bash
#correct call is ./generate_test.sh <domain> <endpoint>
echo "
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../../../app');
var config = require('../config');
var should = chai.should;
describe(\"/$1/$2\", function() {
});
" >> ../test/$1/tests/$2.js
<file_sep>/README.md
<h1> GroupVote API </h1>
<p>
This is a personal project to learn node and express in a practical sense. The idea of the app is to allow for live polling in a group setting. The goal is to create an api that will permit for the app to exist on web and mobile as well as possibly a desktop app to allow for use with iclickers.
</p>
<h3>Notes</h3>
<ul>
<li> [In Progress] all models will be manipulated by using the controllers they export </li>
<ul>
<li> [In Progress] these functions will pass two parameters into their callbacks</li>
<ul>
<li>Error: any error thrown by the mongo server or by mongoose should be passed to the callback as the first argument</li>
<li>Status: the status is a json object with two fields, completed and description. These two fields will be used as a standard way of saying whether or not an operation was completed succesfully</li>
</ul>
</ul>
<li> [In Progress] The router and its routes will use the model's functions to manipulate or gather any and all data from the server</li>
<li>The router files are structured as json in a specific form. This form should be copied for all new routes</li>
</ul>
<file_sep>/docs/poll.js.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: poll.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: poll.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>/**
* this is a model for poll documents. Created on 09/18/2015.
* @author <NAME>
* @name Poll Model
*/
//require calls below
var mongoose = require("mongoose");
//create a new schema to act as a basis for all poll data.
var PollSchema = new mongoose.Schema({
title: {
type: String,
required: true,
maxLength: 200
},
start_time: Date,
end_time: Date,
options: {
type: Array,
required: true,
},
restrictions: Object
});
var Poll = mongoose.model("poll", PollSchema);
/**
* The controller for all poll data and the database
* @module models/poll
*
*
*/
module.exports = {
model: Poll,
functions: {
/**
* Create a new poll on the mongoDB Database
* @function create
* @param {Object} json - The json for the object to be created
* @param {createPollCallback} callback - the function to be called once the object is created
*
*/
create: function (json, callback) {
if(!json.hasOwnProperty("participants")){
json.participants = [];
}
var status = {completed: true};
var newPoll = new Poll(json);
newPoll.save(function (err) {
if(err){
status = {
completed: false,
description: "New poll did not save",
error: err
}
}
callback(err, status);
});
}
/**
* This callback responds to the model returning a succesful or unsuccessful creation response
* @callback createPollCallback
* @param err - an error thrown by mongoDB
* @param status - a GroupVote status object
*/
,
/**
* returns all polls from the server into the callback function
* @function findAll
* @param {findAllPollCallback} callback
*/
findAll: function (callback) {
Poll.find(function (err, docs) {
callback(err, docs);
});
}
/**
* This callback is used once all polls are returned from the database
* @callback findAllPollCallback
* @param err - any error thrown by the database
* @param docs - an array of all the polls on the server
*/
,
/**
* Updates a given query of polls with new information
* @function update
* @param {Object} query - an object containing query information (MongoDB Query data)
* @param {Object} update - an object containing all information to be added and updated
* @param {Object} options - an object containing MongoDB update options
* @param {updatePollCallback} callback - a callback to handle data returned from the update
*/
update: function (query, update, options, callback) {
Poll.update(query, update, options, function (err, modified) {
var status = {completed: true};
if(err) {
status.completed = false;
switch(err.code){
case 16836:
status.description ="Poll not found";
break;
default:
status.description = "DB Error, see error";
break;
}
status.error = err;
}
callback(status, modified);
})
}
/**
* This callback is used once all polls in the update are updated or an error is thrown
* @callback updatePollCallback
* @param status - a GroupVote status object
* @param modified - an object containing modification data
*/
,
/**
* finds a given poll by its ID
* @function findById
* @param {ObjectId} id - the ID to search for
* @param {findByIDPollCallback} callback - called when the query is completed
*/
findById: function(id, callback){
Poll.findById(id, function (err, poll) {
var status = {completed: true};
if(err){
status = {
completed: false,
description: "Poll not found",
error: err
}
poll = null;
}
callback(status, poll);
})
}
/**
* This callback is used once all polls in the update are updated or an error is thrown
* @callback findByIDPollCallback
* @param status - a GroupVote status object
* @param poll - The poll object that was queried for by ID
*/
}
};
</code></pre>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-models_poll.html">models/poll</a></li></ul><h3>Global</h3><ul><li><a href="global.html#PollModel">Poll Model</a></li></ul>
</nav>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.3</a> on Fri Oct 09 2015 04:03:50 GMT-0500 (Central Daylight Time)
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>
<file_sep>/test/polls/tests/id_param.js
/**
* Created by Jack on 09/26/2015.
*/
process.env.NODE_ENV = 'test';
var chai = require('chai');
var chaiHTTP = require('chai-http');
var server = require('../../../app.js');
var should = chai.should();
chai.use(chaiHTTP);
var poll_id = "507f191e810c19729de860ea"; //TODO: centralize this test data
describe("/polls/:id", function () {
it("should return json data for one poll object", function (done) {
chai.request(server)
.get("/polls/" + poll_id)
.end(function (err, res) {
res.should.have.status(200 || 304);
res.should.be.json;
res.body.should.be.a("object");
done();
});
});
it("should return a non-complete status if poll id is invalid", function (done) {
chai.request(server)
.get("/polls/" + poll_id + "fails")
.end(function (err, res) {
res.should.have.status(404);
res.body.should.have.property("completed");
res.body.should.have.property("description")
res.body.completed.should.be.false;
done();
})
});
});
<file_sep>/notes/todo.txt
write documentation for all code
write unit tests for users routes
automate documentation generation - cron job
| d8c82bbf4cfe4875dbcd850ac9c68a1e64075a46 | [
"HTML",
"JavaScript",
"Markdown",
"Text",
"Shell"
]
| 13 | JavaScript | jpm61704/cuddly-lamp | 40ef4e7b698b506b42678a162fc8b9e0fb05087c | 7fa27cb1fcec95cc0cc60a05a8c7de8bbdc4afe5 |
refs/heads/master | <file_sep># lambda-survey-deployment
<file_sep>import os
import boto3
from boto3.session import Session
from twilio.twiml.messaging_response import MessagingResponse
# Add DynamoDB session
session = Session()
# Add Twilio credentials
account_sid = os.environ['ACCOUNT_SID']
auth_token = os.environ['AUTH_TOKEN']
# Add DynamoDB
dynamodb = boto3.resource('dynamodb','us-west-2')
table_users = dynamodb.Table('User_Data')
def lambda_handler(event, context):
response = MessagingResponse()
welcome_message = 'Hi! Welcome to our Vize Survey about your workplace! Would you like to respond to this ' \
'survey? (Yes/No)'
twilio_send_number = '+17075959842'
with open('Survey-Numbers.txt', 'r') as number_file:
survey_location = number_file.readline()
for line in number_file:
table_users.put_item(Item={'Survey_Code': survey_location, 'Code': 1, 'Number': line.split(), 'Questions': [],
'Responded': 0, 'Completed': 0, })
response.message(welcome_message, to=line.split(), from_=twilio_send_number)
return str(response)
| 67474d9ca2e764a1d7af6e3679f6e3581d51aee4 | [
"Markdown",
"Python"
]
| 2 | Markdown | incentivizinggood/lambda-survey-deployment | 0121757d533b7e46dce795a215d303972ed1070b | 2952aa4aa79510cbe62823dc3d3650000136b7a3 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
from models import Desafio
def handle_uploaded_file(f):
l = [i.strip('\n') for i in f.readlines()[1:]]
for i in l:
(nome, desc, preco, ncompras, ende, comer) = i.split("\t")
data = Desafio(purchaser_name=nome, item_description=desc, item_price=preco, purchase_count=ncompras, merchant_address=ende,merchant_name=comer)
data.save()
print nome
<file_sep># -*- coding: utf-8 -*-
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from handleFile import handle_uploaded_file
from forms import UploadFileForm
def index(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['docfile'])
return HttpResponseRedirect('', {'form': form})
else:
form = UploadFileForm()
return render_to_response('index.html', {'form': form})
<file_sep>Desafio
=======
Desafio da pull4up
<file_sep>from django.db import models
class Desafio(models.Model):
purchaser_name = models.CharField(max_length=50)
item_description = models.CharField(max_length=80)
item_price = models.FloatField()
purchase_count = models.IntegerField()
merchant_address = models.CharField(max_length=50)
merchant_name = models.CharField(max_length=50)
<file_sep># -*- coding: utf-8 -*-
from django import forms
class UploadFileForm(forms.Form):
docfile = forms.FileField(
label='Selecione Arquivo',
help_text='max. 42 megabytes'
)
| 6017f2dabf510749147d4666285825b3b56a6ec4 | [
"Markdown",
"Python"
]
| 5 | Python | mrsantos/Desafio | 550fe7592bb28bde6b907bb10fafdcfdc09fefd0 | 49bcc261a84b19a58720190de0a2c01743365371 |
refs/heads/master | <file_sep>package com.example.android.courtcounter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView scoreViewA, scoreViewB;
private int scoreTeamA = 0, scoreTeamB = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scoreViewA = (TextView) findViewById(R.id.team_a_score);
scoreViewB = (TextView) findViewById(R.id.team_b_score);
//displayForTeamA(8);
}
/** This method is right before we change orientation, to preserve values */
@Override
protected void onSaveInstanceState (Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt("TeamA",scoreTeamA);
outState.putInt("TeamB",scoreTeamB);
}
/** This method is called to display values in the UI which were saved */
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
scoreTeamA = savedInstanceState.getInt("TeamA");
displayForTeamA(scoreTeamA);
scoreTeamB = savedInstanceState.getInt("TeamB");
displayForTeamB(scoreTeamB);
}
/** This Method is called when +3 Points button is clicked **/
public void threePointerA(View view){
scoreTeamA += 3;
displayForTeamA(scoreTeamA);
}
public void threePointerB(View view){
scoreTeamB += 3;
displayForTeamB(scoreTeamB);
}
/** This Method is called when +2 Points button is clicked **/
public void twoPointerA(View view){
scoreTeamA +=2;
displayForTeamA(scoreTeamA);
}
public void twoPointerB(View view){
scoreTeamB +=2;
displayForTeamB(scoreTeamB);
}
/** This Method is called when Free Throw button is clicked **/
public void freeThrowA(View view){
scoreTeamA +=1;
displayForTeamA(scoreTeamA);
}
public void freeThrowB(View view){
scoreTeamB +=1;
displayForTeamB(scoreTeamB);
}
/** Displays the given score for Team A */
public void displayForTeamA(int score) {
//TextView scoreView = (TextView) findViewById(R.id.team_a_score);
scoreViewA.setText(String.valueOf(score));
}
/** Displays the given score for Team B */
public void displayForTeamB(int score) {
scoreViewB.setText(String.valueOf(score));
}
/** This Method is called when Reset button is clicked **/
public void resetScore(View view){
scoreTeamA = 0;
scoreTeamB = 0;
displayForTeamA(scoreTeamA);
displayForTeamB(scoreTeamB);
}
}
| 12ff2571b142b582ff8f93d70fcd104e9821cd74 | [
"Java"
]
| 1 | Java | tanmaib/courtCounter | 4709a3845fd0d2fcecf780c2e10bc9a834c8ddac | 3b6e958f84a6711d8b3dfba8cc9fb2fcafd9cd0d |
refs/heads/master | <repo_name>badou11/marketintel-on-heroku<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { Route } from '@angular/compiler/src/core';
import { Routes, RouterModule } from '@angular/router';
import { FooterComponent } from './footer/footer.component';
import { NavbarComponent } from './navbar/navbar.component';
import { SidebarComponent } from './sidebar/sidebar.component';
import { EcoleComponent } from './layout/ecole/ecole.component';
import { UniversiteComponent } from './layout/universite/universite.component';
import { OffreComponent } from './layout/offre/offre.component';
const appRoutes:Routes=[
{path: 'header', component:HeaderComponent},
{path: 'footer', component:FooterComponent},
{path: 'navbar', component:NavbarComponent},
{path: 'sidebar', component:SidebarComponent},
{path: 'ecole', component:EcoleComponent},
{path: 'universite', component:UniversiteComponent},
{path: 'offre', component:OffreComponent}
];
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
NavbarComponent,
SidebarComponent,
EcoleComponent,
UniversiteComponent,
OffreComponent
],
imports: [
BrowserModule, RouterModule.forRoot(appRoutes), AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/layout/article/article.component.ts
import { Component, OnInit } from '@angular/core';
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Color, BaseChartDirective, Label } from 'ng2-charts';
declare var google : any;
@Component({
selector: 'app-article',
templateUrl: './article.component.html',
styleUrls: ['./article.component.css']
})
export class ArticleComponent implements OnInit {
constructor() { }
ngOnInit() {
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Visitations', { role: 'style' } ],
['', 30, 'color: gray; opacity: 0.8'],
['', 80, 'color: gray; opacity: 0.8'],
['', 46, 'color: gray; opacity: 0.8'],
['', 20, 'color: gray; opacity: 0.8'],
['', 34, 'color: gray; opacity: 0.8'],
['', 18, 'color: gray; opacity: 0.8']
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Taux de chaumage/Niveau",
width: 600,
height: 400,
bar: {groupWidth: "55%"},
legend: { position: "left" }
};
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
chart.draw(view, options);
}
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart1);
function drawChart1() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 47],
['Eat', 53]
]);
var options = {
title: 'Taux diplômé/Cycle',
pieHole: 0.7,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 77],
['Eat', 23]
]);
var options = {
title: 'Taux diplômé/Cycle',
pieHole: 0.7,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart1'));
chart.draw(data, options);
}
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['', ''],
["lorem ipsum ", 44],
["lorem ipsum", 31],
["lorem ipsum", 12],
["lorem ipsum", 10]
]);
var options = {
//title: 'Taux d apprenant',
width: 900,
legend: { position: 'none' },
//chart: { title: 'Taux d apprenant'},
// subtitle: 'popularity by percentage' },
bars: 'horizontal',
color: 'gray', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'Percentage'} // Top x-axis.
}
},
bar: { groupWidth: "5%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
};
/* function drawMultSeries() {
var data = new google.visualization.DataTable();
data.addColumn('timeofday', 'Time of Day');
data.addColumn('number', 'Motivation Level');
data.addColumn('number', 'Energy Level');
data.addRows([
[{v: [8, 0, 0], f: '8 am'}, 1, .25],
[{v: [9, 0, 0], f: '9 am'}, 2, .5],
[{v: [10, 0, 0], f:'10 am'}, 30, 34],
[{v: [11, 0, 0], f: '11 am'}, 98, 40],
[{v: [12, 0, 0], f: '12 pm'}, 5, 100],
[{v: [13, 0, 0], f: '1 pm'}, 6, 3],
[{v: [14, 0, 0], f: '2 pm'}, 7, 4],
[{v: [15, 0, 0], f: '3 pm'}, 8, 5.25],
[{v: [16, 0, 0], f: '4 pm'}, 9, 7.5],
[{v: [17, 0, 0], f: '5 pm'}, 10, 100],
]);
var options = {
title: 'Taux de Chômage / Niveau'
};
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
*/
google.charts.load('current', {'packages':['line', 'corechart']});
google.charts.setOnLoadCallback(drawChart);
/* function drawChart() {
var button = document.getElementById('change-chart');
var chartDiv = document.getElementById('chart2_div');
var data = new google.visualization.DataTable();
data.addColumn('date', 'Month');
data.addColumn('number', "Average Temperature");
data.addColumn('number', "Average Hours of Daylight");
data.addRows([
[new Date(2014, 0), -.5, 5.7],
[new Date(2014, 1), .4, 8.7],
[new Date(2014, 2), .5, 12],
[new Date(2014, 3), 2.9, 15.3],
[new Date(2014, 4), 6.3, 18.6],
[new Date(2014, 5), 9, 20.9],
[new Date(2014, 6), 10.6, 19.8],
[new Date(2014, 7), 10.3, 16.6],
[new Date(2014, 8), 7.4, 13.3],
[new Date(2014, 9), 4.4, 9.9],
[new Date(2014, 10), 1.1, 6.6],
[new Date(2014, 11), -.2, 4.5]
]);
var materialOptions = {
chart: {
title: 'Average Temperatures and Daylight in Iceland Throughout the Year'
},
width: 400,
height: 500,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: {axis: 'Temps'},
1: {axis: 'Daylight'}
},
axes: {
// Adds labels to each axis; they don't have to match the axis names.
}
};
var classicOptions = {
title: 'Average Temperatures and Daylight in Iceland Throughout the Year',
width: 900,
height: 500,
// Gives each series an axis that matches the vAxes number below.
series: {
0: {targetAxisIndex: 0},
1: {targetAxisIndex: 1}
},
vAxes: {
// Adds titles to each axis.
0: {title: 'Temps (Celsius)'},
1: {title: 'Daylight'}
},
hAxis: {
ticks: [new Date(2014, 0), new Date(2014, 1), new Date(2014, 2), new Date(2014, 3),
new Date(2014, 4), new Date(2014, 5), new Date(2014, 6), new Date(2014, 7),
new Date(2014, 8), new Date(2014, 9), new Date(2014, 10), new Date(2014, 11)
]
},
vAxis: {
viewWindow: {
max: 30
}
}
};
function drawMaterialChart() {
var materialChart = new google.charts.Line(chartDiv);
materialChart.draw(data, materialOptions);
button.innerText = 'Change to Classic';
button.onclick = drawClassicChart;
}
function drawClassicChart() {
var classicChart = new google.visualization.LineChart(chartDiv);
classicChart.draw(data, classicOptions);
button.innerText = 'Change to Material';
button.onclick = drawMaterialChart;
}
drawMaterialChart();
}*/
}
}
| bb150c3816ae805684162bd126ab00d7648c81fb | [
"TypeScript"
]
| 2 | TypeScript | badou11/marketintel-on-heroku | 7e4b212911f085af9f4287925fd95d12263d2ce4 | 760730bac1b1bbcf0171b6f3bd96ac6643ff3348 |
refs/heads/master | <file_sep>package com.hs.whocan.component.account.user.dao;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-24
* Time: 下午4:52
* To change this template use File | Settings | File Templates.
*/
public class UserInvitation {
private String invitationId;
private String userId;
private String friendId;
private String invitePhoneNo;
public UserInvitation() {
}
public String getInvitationId() {
return invitationId;
}
public void setInvitationId(String invitationId) {
this.invitationId = invitationId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFriendId() {
return friendId;
}
public void setFriendId(String friendId) {
this.friendId = friendId;
}
public String getInvitePhoneNo() {
return invitePhoneNo;
}
public void setInvitePhoneNo(String invitePhoneNo) {
this.invitePhoneNo = invitePhoneNo;
}
}
<file_sep>package com.hs.whocan.service.tasklist;
import com.hs.whocan.component.account.user.dao.User;
import com.hs.whocan.service.VerifySignInService;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by yinwenbo on 14-5-5.
*/
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class FindTasklistByGroupId extends VerifySignInService {
private String groupId;
@Resource
private TasklistQuery tasklistQuery;
@Override
public List<Object> execute(User user) {
return tasklistQuery.findListByGroupId(this);
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
}
<file_sep>package com.hs.whocan.component.account.user;
import com.hs.whocan.component.account.user.dao.DeviceToken;
import com.hs.whocan.external.push.PushComponent;
import com.hs.whocan.component.session.dao.MessageUserMapperDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-4-1
* Time: 下午3:44
* To change this template use File | Settings | File Templates.
*/
@Service
public class PushMessageComponent {
@Resource
private DeviceComponent deviceComponent;
@Resource
private MessageUserMapperDao messageUserMapperDao;
@Transactional
public void push(List<String> userIds, String message) {
List<DeviceToken> deviceTokens = deviceComponent.findDeviceTokenByUsers(userIds);
calculateUnreadNum(deviceTokens);
new Thread(new PushComponent(deviceTokens, message)).start();
}
public void calculateUnreadNum(List<DeviceToken> deviceTokens) {
for (DeviceToken deviceToken : deviceTokens) {
String userId = deviceToken.getUserId();
int unreadNum = messageUserMapperDao.findUnreadNum(userId);
deviceToken.setUnreadNum(unreadNum == 0 ? 1 : unreadNum);
}
}
}
<file_sep>package com.hs.whocan.component.session.dao.hbm;
import com.hs.whocan.component.account.user.dao.User;
import com.hs.whocan.component.account.user.dao.hbn.UserEntity;
import com.hs.whocan.component.session.dao.Session;
import com.hs.whocan.component.session.dao.SessionDao;
import com.hs.whocan.component.session.dao.SessionMapper;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-27
* Time: 上午10:33
* To change this template use File | Settings | File Templates.
*/
@Service
public class SessionRepository implements SessionDao {
@Resource
private SessionFactory sessionFactory;
@Override
public void createSession(Session session) {
sessionFactory.getCurrentSession().save(new SessionEntity(session));
}
@Override
public void createSessionMapper(SessionMapper sessionMapper) {
sessionFactory.getCurrentSession().save(sessionMapper);
}
@Override
public void modifySessionName(String sessionId, String sessionName) {
final String hql = "update SessionEntity e set e.sessionName = :sessionName where e.sessionId = :sessionId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("sessionName", sessionName);
query.setString("sessionId", sessionId);
query.executeUpdate();
}
@Override
public Session findSessionByUnionId(String sessionId1, String sessionId2) {
final String hql = "from SessionEntity e where e.sessionId = :sessionId1 or e.sessionId = :sessionId2";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("sessionId1", sessionId1);
query.setString("sessionId2", sessionId2);
SessionEntity entity = (SessionEntity) query.uniqueResult();
return entity != null ? entity.getSession() : null;
}
@Override
public void deleteSession(String sessionId) {
final String hql = "delete from SessionEntity e where e.sessionId = :sessionId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("sessionId", sessionId);
query.executeUpdate();
}
@Override
public void deleteSessionMapper(String sessionId) {
final String hql = "delete from SessionMapper m where m.sessionId = :sessionId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("sessionId", sessionId);
query.executeUpdate();
}
@Override
public List<Session> findSessionByUserId(String userId) {
final String hql = "from SessionEntity e where e.sessionId in (select m.sessionId from SessionMapper m where m.userId = :userId)";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("userId", userId);
List<SessionEntity> entities = (List<SessionEntity>) query.list();
List<Session> sessionList = new ArrayList<Session>();
for (SessionEntity sessionEntity : entities) {
sessionList.add(sessionEntity.getSession());
}
return sessionList;
}
@Override
public void deleteSessionMapperByUserId(String sessionId, String deleteUserId) {
final String hql = "delete from SessionMapper e where e.sessionId = :sessionId and e.userId = :userId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("userId", deleteUserId);
query.setString("sessionId", sessionId);
query.executeUpdate();
}
@Override
public List<String> findUserIdInSession(String sessionId) {
final String hql = "select e.userId from SessionMapper e where e.sessionId = :sessionId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("sessionId", sessionId);
return (List<String>) query.list();
}
@Override
public List<User> findUserInSession(String sessionId) {
final String hql = "from UserEntity e where e.userId in (select m.userId from SessionMapper m where m.sessionId = :sessionId)";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("sessionId", sessionId);
List<UserEntity> entities = (List<UserEntity>) query.list();
List<User> users = new ArrayList<User>();
for (UserEntity entity : entities) {
users.add(entity.getUser());
}
return users;
}
@Override
public List<String> findUserIdInSessionExcludeOwn(String sessionId, String userId) {
final String hql = "select m.userId from SessionMapper m where m.sessionId = :sessionId and m.userId != :userId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("sessionId", sessionId);
query.setString("userId", userId);
return (List<String>) query.list();
}
@Override
public int findUserNumInSession(String sessionId) {
final String hql = "select count(e.sessionId) from SessionMapper e where e.sessionId = :sessionId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("sessionId", sessionId);
String result = query.uniqueResult().toString();
return Integer.valueOf(result);
}
@Override
public SessionMapper findSessionMapper(String sessionId, String userId) {
final String hql = "from SessionMapper e where e.sessionId = :sessionId and e.userId = :userId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("sessionId", sessionId);
query.setString("userId", userId);
return (SessionMapper) query.uniqueResult();
}
@Override
public Session findSessionById(String sessionId) {
final String hql = "from SessionEntity e where e.sessionId = :sessionId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("sessionId", sessionId);
SessionEntity entity = (SessionEntity) query.uniqueResult();
return entity != null ? entity.getSession() : null;
}
@Override
public List<Session> findSessionByIds(List<String> sessionIds) {
final String hql = "from SessionEntity e where e.sessionId in (:sessionIds)";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setParameterList("sessionIds", sessionIds);
List<SessionEntity> entities = (List<SessionEntity>) query.list();
List<Session> sessions = new ArrayList<Session>();
for (SessionEntity entity : entities) {
sessions.add(entity.getSession());
}
return sessions;
}
}
<file_sep>package com.hs.whocan.service.security;
import com.hs.whocan.component.account.security.SecurityComponent;
import com.hs.whocan.component.account.user.DeviceComponent;
import com.hs.whocan.component.account.user.UserComponent;
import com.hs.whocan.component.account.user.dao.DeviceToken;
import com.hs.whocan.component.account.user.dao.User;
import com.hs.whocan.service.ServiceInterface;
import com.hs.whocan.service.security.transformer.UserTransformer;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-31
* Time: 上午10:40
* To change this template use File | Settings | File Templates.
*/
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class SecurityLoginAuthCode implements ServiceInterface {
private String phoneNo;
private int authCode;
private String deviceToken;
@Resource
private SecurityComponent securityComponent;
@Resource
private UserComponent userComponent;
@Resource
private UserTransformer userTransformer;
@Resource
private DeviceComponent deviceComponent;
@Transactional
public UserInfoResult doService() {
securityComponent.verifyAuthCode(phoneNo, authCode);
User user = userComponent.findUserByPhoneNo(phoneNo);
String token = null;
if (null == user) {
user = userComponent.createUserInfo(phoneNo);
token = securityComponent.createAccessInfo(user.getUserId());
userComponent.relateUserInvitationByPhoneNo(phoneNo, user.getUserId());
} else {
token = securityComponent.modifyAccessToken(user.getUserId());
}
deviceComponent.createDeviceToken(new DeviceToken(user.getUserId(),deviceToken,0));
return userTransformer.transform2UserInfo(user, token);
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public int getAuthCode() {
return authCode;
}
public void setAuthCode(int authCode) {
this.authCode = authCode;
}
public String getDeviceToken() {
return deviceToken;
}
public void setDeviceToken(String deviceToken) {
this.deviceToken = deviceToken;
}
}
<file_sep>package com.hs.whocan.component.account.user.dao.hbn;
import com.hs.whocan.component.account.user.dao.LinkMan;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-24
* Time: 下午6:25
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name = "user_linkman")
public class LinkmanEntity {
private LinkMan linkman;
public LinkmanEntity() {
this.linkman = new LinkMan();
}
public LinkmanEntity(LinkMan linkman) {
this.linkman = linkman;
}
public LinkmanEntity(String userId,String phoneNo) {
this.linkman = new LinkMan();
linkman.setUserId(userId);
linkman.setPhoneNo(phoneNo);
}
@Transient
public LinkMan getLinkman() {
return linkman;
}
@Id
@GenericGenerator(name = "idGenerator", strategy = "uuid")
@GeneratedValue(generator = "idGenerator")
public String getLinkmanId() {
return linkman.getLinkmanId();
}
@Column
public String getUserId() {
return linkman.getUserId();
}
public void setPhoneNo(String phoneNo) {
linkman.setPhoneNo(phoneNo);
}
@Column
public String getPhoneNo() {
return linkman.getPhoneNo();
}
public void setLinkmanId(String linkmanId) {
linkman.setLinkmanId(linkmanId);
}
public void setUserId(String userId) {
linkman.setUserId(userId);
}
}
<file_sep>package com.hs.whocan.exception;
import java.util.Map;
/**
* Created by yinwenbo on 14-5-5.
*/
public abstract class TranslatedException extends RuntimeException {
protected TranslatedException() {
}
protected TranslatedException(String message) {
super(message);
}
public Map<String, String> getData(){
return null;
}
}
<file_sep>package com.hs.whocan.component.session.dao.hbm;
import com.hs.whocan.component.session.dao.MessageUserMapper;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
/**
* User: fish
*/
@Entity
@Table(name = "message_user_mapper")
public class MessageUserMapperEntity {
private MessageUserMapper messageUserMapper;
public MessageUserMapperEntity() {
this.messageUserMapper = new MessageUserMapper();
}
public MessageUserMapperEntity(MessageUserMapper messageUserMapper) {
this.messageUserMapper = messageUserMapper;
}
@Id
@GenericGenerator(name = "idGenerator", strategy = "uuid")
@GeneratedValue(generator = "idGenerator")
public String getMapperId() {
return messageUserMapper.getMapperId();
}
public void setUserId(String userId) {
messageUserMapper.setUserId(userId);
}
public void setMapperId(String mapperId) {
messageUserMapper.setMapperId(mapperId);
}
public void setMessageId(String messageId) {
messageUserMapper.setMessageId(messageId);
}
@Column
public String getUserId() {
return messageUserMapper.getUserId();
}
@Column
public String getMessageId() {
return messageUserMapper.getMessageId();
}
@Column
public Date getReceiveTime() {
return messageUserMapper.getReceiveTime();
}
public void setReceiveTime(Date receiveTime) {
messageUserMapper.setReceiveTime(receiveTime);
}
public void setSessionId(String sessionId) {
messageUserMapper.setSessionId(sessionId);
}
@Column
public String getSessionId() {
return messageUserMapper.getSessionId();
}
}
<file_sep>USE `pm`;
CREATE TABLE pm.user (
userId VARCHAR(50),
userName VARCHAR(50),
phoneNo VARCHAR(50) NOT NULL UNIQUE,
mailAddress VARCHAR(50),
password VARCHAR(50),
authCode INT,
PRIMARY KEY (userId));
CREATE TABLE pm.project_detail (
detailId INT NOT NULL AUTO_INCREMENT,
detail VARCHAR(255),
operateTime DATETIME,
projectId INT NOT NULL,
PRIMARY KEY (detailId));
CREATE TABLE pm.project (
projectId INT NOT NULL AUTO_INCREMENT,
projectName VARCHAR(50),
content VARCHAR(50),
createTime DATETIME,
deadline DATETIME,
isDone BOOLEAN,
userId VARCHAR(50),
PRIMARY KEY (projectId));
CREATE TABLE pm.contact (
contactId VARCHAR(50),
projectId INT NOT NULL,
userId VARCHAR(50),
phoneNo VARCHAR(50),
mailAddress VARCHAR(50),
userName VARCHAR(50),
PRIMARY KEY (contactId));
CREATE TABLE pm.work (
workId INT NOT NULL AUTO_INCREMENT,
workName VARCHAR(50),
backup VARCHAR(255),
createTime DATETIME,
projectId INT NOT NULL,
userId VARCHAR(50),
contactId VARCHAR(50),
deadline DATETIME,
isDone BOOLEAN,
PRIMARY KEY (workId));
CREATE TABLE pm.message (
messageId INT NOT NULL AUTO_INCREMENT,
message VARCHAR(255),
fromUserName VARCHAR(50),
fromUserId VARCHAR(50),
projectId INT NOT NULL,
createTime DATETIME,
PRIMARY KEY (messageId));
CREATE TABLE pm.device_token (
tokenId INT NOT NULL AUTO_INCREMENT,
userId VARCHAR(50),
token VARCHAR(64),
PRIMARY KEY (tokenId));
#==============================================
DROP FUNCTION IF EXISTS `pm`.`save_project_detail`;
DELIMITER $$
CREATE DEFINER =`root`@`localhost` FUNCTION `save_project_detail`(operator_id VARCHAR(50), detail VARCHAR(50),
operate_time DATETIME, project_id VARCHAR(50))
RETURNS INT(11)
BEGIN
DECLARE operator VARCHAR(50);
DECLARE save_msg VARCHAR(255);
SELECT
userName
INTO operator
FROM user
WHERE userId = operator_id;
SET save_msg = if((operator IS null || operator = ''), detail, concat(detail, '--变更人--', operator));
INSERT INTO pm.project_detail (detail, operateTime, projectId) VALUES (save_msg, operate_time, project_id);
RETURN 1;
END$$
DELIMITER ;
#项目===================================================================================================================
DROP PROCEDURE IF EXISTS `create_project`;
DELIMITER $$
CREATE DEFINER =`root`@`localhost` PROCEDURE `create_project`(project_name VARCHAR(50), content VARCHAR(50),
create_time DATETIME, dead_line DATETIME,
create_user_id VARCHAR(50))
BEGIN
DECLARE project_id INT;
INSERT INTO project (projectName, content, createTime, deadline, userId)
VALUES (project_name, content, create_time, dead_line, create_user_id);
SET project_id = LAST_INSERT_ID();
SELECT
save_project_detail(create_user_id, concat('创建项目:', project_name), create_time, project_id);
END$$
DELIMITER ;
DROP PROCEDURE IF EXISTS `update_project`;
DELIMITER $$
USE `pm`$$
CREATE DEFINER =`root`@`localhost` PROCEDURE `update_project`(project_name VARCHAR(50), content VARCHAR(50),
create_time DATETIME, project_id INT,
create_user_id VARCHAR(50))
BEGIN
UPDATE project
SET projectName=project_name, content=content
WHERE projectId = project_id;
SELECT
save_project_detail(create_user_id, concat('更改项目名为:', project_name), create_time, project_id);
END$$
DELIMITER ;
DROP PROCEDURE IF EXISTS `delete_project`;
DELIMITER $$
CREATE DEFINER =`root`@`localhost` PROCEDURE `delete_project`(project_Id INT)
BEGIN
DELETE FROM pm.project
WHERE projectId = project_Id;
DELETE FROM pm.contact
WHERE projectId = project_Id;
DELETE FROM work
WHERE projectId = project_id;
END$$
DELIMITER ;
#用户===================================================================================================================
DROP PROCEDURE IF EXISTS `get_authCode`;
DELIMITER $$
CREATE DEFINER =`root`@`localhost` PROCEDURE `get_authCode`(IN phone_no VARCHAR(50), OUT auth_code INT,
OUT mobile VARCHAR(50))
BEGIN
SET mobile = phone_no;
SET auth_code = FLOOR(100000 + (RAND() * 888888));
IF ((SELECT
userId
FROM pm.user
WHERE phoneNo = phone_no) IS null)
THEN
INSERT INTO pm.user (userId, phoneNo, authCode) VALUES (uuid(), phone_no, auth_code);
ELSE
UPDATE pm.user
SET authCode=auth_code
WHERE phoneNo = phone_no;
END IF;
END$$
DELIMITER ;
DELIMITER $$
DROP PROCEDURE IF EXISTS `login_byAuthCode`;
CREATE DEFINER =`root`@`localhost` PROCEDURE `login_byAuthCode`(phone_no VARCHAR(50), auth_code VARCHAR(50),
OUT isSuccess BOOLEAN, OUT user_id VARCHAR(50))
BEGIN
DECLARE result VARCHAR(50);
SELECT
userId
INTO result
FROM user
WHERE phoneNo = phone_no AND authCode = auth_code;
IF (result IS NOT null)
THEN
UPDATE contact
SET userId=result
WHERE phoneNo = phone_no;
SET user_id = result;
SET isSuccess = 1;
ELSE
SET isSuccess = 0;
END IF;
END$$
DELIMITER ;
#工作===================================================================================================================
DROP PROCEDURE IF EXISTS `create_work`;
DELIMITER $$
CREATE DEFINER =`root`@`localhost` PROCEDURE `create_work`(operator_id VARCHAR(50), operate_time DATETIME,
work_name VARCHAR(50),
backup VARCHAR(255), create_time DATETIME,
project_id INT, create_user_id VARCHAR(50),
contact_id VARCHAR(50),
deadline DATETIME)
BEGIN
INSERT INTO work (workName, backup, createTime, projectId, userId, contactId, deadline, isDone)
VALUES (work_name, backup, create_time, project_id, create_user_id, contact_id, deadline, FALSE);
SELECT
save_project_detail(operator_id, concat('创建工作:', work_name), operate_time, project_id);
END$$
DELIMITER ;
#trigger===========================================
DROP TRIGGER IF EXISTS `t_contact`;
DELIMITER $$
CREATE TRIGGER t_contact BEFORE INSERT ON contact FOR EACH ROW
BEGIN
DECLARE user_id VARCHAR(50);
SET user_id = (SELECT
userId
FROM user
WHERE phoneNo = NEW.phoneNo);
SET NEW.userId = user_id;
END$$
DELIMITER ;<file_sep>package com.hs.whocan.component.account.user.dao.hbn;
import com.hs.whocan.component.account.user.dao.UserMapper;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-17
* Time: 上午10:14
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name = "user_mapper")
public class UserMapperEntity {
private UserMapper userMapper;
public UserMapperEntity() {
this.userMapper = new UserMapper();
}
public UserMapperEntity(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Transient
public UserMapper getUserMapper(){
return this.userMapper;
}
@Id
@GenericGenerator(name = "idGenerator", strategy = "uuid")
@GeneratedValue(generator = "idGenerator")
public String getMapperId() {
return userMapper.getMapperId();
}
public void setUserId(String userId) {
userMapper.setUserId(userId);
}
@Column
public String getFriendId() {
return userMapper.getFriendId();
}
@Column
public String getUserId() {
return userMapper.getUserId();
}
public void setMapperId(String mapperId) {
userMapper.setMapperId(mapperId);
}
public void setFriendId(String friendId) {
userMapper.setFriendId(friendId);
}
public void setAlias(String alias) {
userMapper.setAlias(alias);
}
public String getAlias() {
return userMapper.getAlias();
}
}
<file_sep>package com.hs.whocan.service;
import org.springframework.stereotype.Service;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
@Service
public class ValidatorService {
public void validate(Object obj) {
Set<ConstraintViolation<Object>> validate = getValidator().validate(obj);
if (validate.isEmpty()) {
return;
}
throw new ValidatorException(validate);
}
private static Validator getValidator() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
return factory.getValidator();
}
}<file_sep>package com.hs.whocan.component.account.security.dao.hbn;
import com.hs.whocan.component.account.security.dao.Access;
import javax.persistence.*;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-18
* Time: 上午9:20
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name = "security_access")
public class AccessEntity {
private Access access;
public AccessEntity() {
this.access = new Access();
}
public AccessEntity(Access access) {
this.access = access;
}
@Transient
public Access getAccess() {
return access;
}
@Id
public String getAccessId() {
return access.getAccessId();
}
@Column
public String getPassword() {
return access.getPassword();
}
public void setAliveTime(long aliveTime) {
access.setAliveTime(aliveTime);
}
public void setPassword(String password) {
access.setPassword(password);
}
@Column
public long getAliveTime() {
return access.getAliveTime();
}
public void setAccessId(String accessId) {
access.setAccessId(accessId);
}
@Column
public Date getAccessTime() {
return access.getAccessTime();
}
public void setAccessTime(Date accessTime) {
access.setAccessTime(accessTime);
}
public void setAccessToken(String accessToken) {
access.setAccessToken(accessToken);
}
@Column
public String getAccessToken() {
return access.getAccessToken();
}
}
<file_sep>package com.hs.whocan.component.session.dao;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-26
* Time: 下午7:34
* To change this template use File | Settings | File Templates.
*/
public class Session {
private String sessionId;
private String userId;
private String sessionName;
private Date createTime;
private String type;
public Session() {
}
public Session(String sessionId, String userId) {
this.sessionId = sessionId;
this.userId = userId;
this.createTime = new Date();
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getSessionName() {
return sessionName;
}
public void setSessionName(String sessionName) {
this.sessionName = sessionName;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
<file_sep>package com.hs.whocan.service.social;
import com.hs.whocan.component.account.user.UserMapperComponent;
import com.hs.whocan.component.account.user.dao.User;
import com.hs.whocan.service.VerifySignInService;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-31
* Time: 下午5:56
* To change this template use File | Settings | File Templates.
*/
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class SocialFindAll extends VerifySignInService {
@Resource
private UserMapperComponent userMapperComponent;
public List<FriendInfo> execute(User user) {
List<FriendInfo> alreadyFriends = userMapperComponent.findFriendByUserId(userId);
List<FriendInfo> inviteFriends = userMapperComponent.findFriendInvite(userId);
List<FriendInfo> invitedFriends = userMapperComponent.findFriendInvited(userId);
List<FriendInfo> notAddFriends = userMapperComponent.findFriendNotAdd(userId);
ArrayList<FriendInfo> list = new ArrayList<FriendInfo>();
list.addAll(alreadyFriends);
list.addAll(inviteFriends);
list.addAll(invitedFriends);
list.addAll(notAddFriends);
return list;
}
}
<file_sep>use whocan;
SET SQL_SAFE_UPDATES = 0;
DELETE FROM operate_record;
DELETE FROM project;
DELETE FROM project_user_mapper;
DELETE FROM project_work;
DELETE FROM security_access;
DELETE FROM security_authCode;
DELETE FROM security_deviceToken;
DELETE FROM session;
DELETE FROM session_mapper;
DELETE FROM session_message;
DELETE FROM user_info;
DELETE FROM user_invitation;
DELETE FROM user_linkman;
DELETE FROM user_mapper;<file_sep>package com.hs.whocan.component.session.dao.hbm;
import com.hs.whocan.component.session.dao.Message;
import javax.persistence.*;
import java.util.Date;
/**
* Created by fish on 14-3-17.
*/
@Entity
@Table(name = "session_message")
public class MessageEntity {
private Message message;
public MessageEntity() {
this.message = new Message();
}
public MessageEntity(Message message) {
this.message = message;
}
@Transient
public Message getMessage() {
return this.message;
}
@Id
public String getMessageId() {
return message.getMessageId();
}
public void setMessageId(String messageId) {
message.setMessageId(messageId);
}
@Column
public String getContent() {
return message.getContent();
}
public void setContent(String content) {
message.setContent(content);
}
public void setMessage(String message) {
this.message.setContent(message);
}
@Column
public Date getCreateTime() {
return message.getCreateTime();
}
public void setCreateTime(Date createTime) {
message.setCreateTime(createTime);
}
@Column
public String getSessionId() {
return message.getSessionId();
}
public void setSessionId(String sessionId) {
message.setSessionId(sessionId);
}
@Column
public String getMsgType() {
return message.getMsgType();
}
public void setMsgType(String msgType) {
message.setMsgType(msgType);
}
public void setFromUser(String fromUser) {
message.setFromUser(fromUser);
}
@Column
public String getFromUser() {
return message.getFromUser();
}
}
<file_sep>package com.hs.whocan.component.account.security;
import com.hs.whocan.component.account.security.dao.Access;
import com.hs.whocan.component.account.security.dao.AccessDao;
import com.hs.whocan.component.account.security.dao.PhoneAuthCode;
import com.hs.whocan.component.account.security.dao.PhoneAuthCodeDao;
import com.hs.whocan.component.account.security.exception.AuthCodeErrorException;
import com.hs.whocan.component.account.security.exception.TokenErrorException;
import com.hs.whocan.utils.RandomGenerator;
import com.hs.whocan.utils.UUIDGenerator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
/**
* Created by fish on 14-3-26.
*/
@Service
public class SecurityComponent {
private static final long VALID_TIME = 30000000000l;
@Resource
private PhoneAuthCodeDao phoneAuthCodeDao;
@Resource
private AccessDao accessDao;
@Resource
private UUIDGenerator uuidGenerator;
@Transactional
public int getAuthCode(String phoneNo) {
int authCode = getAuthCode();
PhoneAuthCode phoneAuthCode = phoneAuthCodeDao.findPhoneAuthCode(phoneNo);
if (null != phoneAuthCode) {
phoneAuthCode.setAuthCode(authCode);
phoneAuthCode.setCreateTime(new Date());
} else {
phoneAuthCode = new PhoneAuthCode(phoneNo, authCode);
phoneAuthCodeDao.createPhoneAuthCode(phoneAuthCode);
}
return authCode;
}
private int getAuthCode() {
return RandomGenerator.getRandom(111111, 999999);
}
public void verifyAuthCode(String phoneNo, int authCode) {
PhoneAuthCode phoneAuthCode = phoneAuthCodeDao.findPhoneAuthCode(phoneNo, authCode);
if(null == phoneAuthCode){
throw new AuthCodeErrorException();
}
//验证码超时
// long applyTime = System.currentTimeMillis()-phoneAuthCode.getCreateTime().getTime();
// if(applyTime>VALID_TIME){
// throw new AuthCodeDisableException();
// }
}
public String createAccessInfo(String accessId){
String token = uuidGenerator.shortUuid();
Access access = new Access(accessId, token);
accessDao.createAccess(access);
return token;
}
public String modifyAccessToken(String userId) {
String token = uuidGenerator.shortUuid();
accessDao.modifyAccessToken(userId,token);
return token;
}
public Access verifyAndUpdateToken(String token) {
Access access = tokenIsValid(token);
String newToken = uuidGenerator.shortUuid();
access.setAccessToken(newToken);
accessDao.modifyAccessToken(access.getAccessId(), access.getAccessToken());
return access;
}
public Access findAccessInfoByToken(String token) {
return tokenIsValid(token);
}
private Access tokenIsValid(String token){
Access access = accessDao.findAccessByToken(token);
if (null == access) {
throw new TokenErrorException();
}
//token超时
// if(System.currentTimeMillis()- access.getAccessTime().getTime() > access.getAliveTime()){
// throw new TokenDisableException();
// }
return access;
}
}
<file_sep>package com.hs.whocan.component.account.user.dao;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-24
* Time: 下午6:30
* To change this template use File | Settings | File Templates.
*/
public interface UserInvitationDao {
public void createUserInvitation(UserInvitation userInvitation);
public List<UserInvitation> findUserInvitation(String userId, String friendId);
public void deleteUserInvitation(String userId, String friendId);
public void relateUserInvitationByPhoneNo(String phoneNo, String friendId);
}
<file_sep>package com.hs.whocan.exception;
/**
* Created by yinwenbo on 13-12-25.
*/
public class FriendlyMessageException extends RuntimeException {
private Object data;
private String msg;
public FriendlyMessageException() {
}
public FriendlyMessageException(Object data) {
this.data = data;
}
public FriendlyMessageException(Throwable throwable) {
super(throwable);
}
public FriendlyMessageException(Throwable cause, Object data) {
super(cause);
this.data = data;
}
public FriendlyMessageException(Throwable cause, String msg, Object data) {
super(cause);
this.msg = msg;
this.data = data;
}
public String getErrorCode() {
return this.getClass().getSimpleName();
}
public String getFriendlyMessage() {
// return this.getClass().getSimpleName();
return this.msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
<file_sep>package com.hs.whocan.service.session.dto;
import com.hs.whocan.component.session.dao.Message;
import java.util.List;
/**
* User: fish
*/
public class SessionInfo {
private List<SessionUserInfo> sessionUserInfos;
private List<Message> messages;
public List<SessionUserInfo> getSessionUserInfos() {
return sessionUserInfos;
}
public void setSessionUserInfos(List<SessionUserInfo> sessionUserInfos) {
this.sessionUserInfos = sessionUserInfos;
}
public List<Message> getMessages() {
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
}
<file_sep>package com.hs.whocan.component.account.user.dao.hbn;
import com.hs.whocan.component.account.user.dao.LinkMan;
import com.hs.whocan.component.account.user.dao.LinkmanDao;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-25
* Time: 上午9:59
* To change this template use File | Settings | File Templates.
*/
@Service
public class LinkmanRepository implements LinkmanDao {
@Resource
private SessionFactory sessionFactory;
@Override
public void createLinkman(String userId,String[] phones) {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
for(String phoneNo : phones){
String sql = "select linkmanId from LinkmanEntity e where e.userId = :userId and e.phoneNo = :phoneNo";
Query query = session.createQuery(sql);
query.setString("userId",userId);
query.setString("phoneNo",phoneNo);
if(0==query.list().size()){
session.save(new LinkmanEntity(userId,phoneNo));
}
}
transaction.commit();
session.close();
}
@Override
public List<LinkMan> findLinkmanByUserId(String userId) {
final String hql = "from LinkmanEntity e where e.userId = :userId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("userId",userId);
return (List<LinkMan>)query.list();
}
}
<file_sep>package com.hs.whocan.component.account.security.dao.hbn;
import com.hs.whocan.component.account.security.dao.Access;
import com.hs.whocan.component.account.security.dao.AccessDao;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-18
* Time: 上午9:20
* To change this template use File | Settings | File Templates.
*/
@Service
public class AccessRepository implements AccessDao {
@Resource
private SessionFactory sessionFactory;
@Override
public Access findAccessByToken(String accessToken) {
final String hql = "from AccessEntity e where e.accessToken = :accessToken";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("accessToken", accessToken);
AccessEntity entity = (AccessEntity) query.uniqueResult();
return entity != null ? entity.getAccess() : null;
}
@Override
public void createAccess(Access access) {
sessionFactory.getCurrentSession().save(new AccessEntity(access));
}
@Override
public void modifyAccessToken(String accessId, String accessToken) {
final String hql = "update AccessEntity e set e.accessToken = :accessToken,e.accessTime = :accessTime where e.accessId = :accessId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("accessToken", accessToken);
query.setTimestamp("accessTime", new Date());
query.setString("accessId", accessId);
query.executeUpdate();
}
}
<file_sep>package com.hs.whocan.service.user;
import com.hs.whocan.component.account.user.UserComponent;
import com.hs.whocan.component.account.user.dao.User;
import com.hs.whocan.component.upload.FileReceiveComponent;
import com.hs.whocan.component.upload.SingleUploadedFile;
import com.hs.whocan.service.VerifySignInService;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
/**
* User: fish
*/
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class UserModifyPortrait extends VerifySignInService {
private MultipartFile file;
@Resource
private UserComponent userComponent;
@Resource
private FileReceiveComponent fileReceiveComponent;
@Override
public Boolean execute(User user) {
SingleUploadedFile singleUploadedFile = saveFile(file);
userComponent.modifyPortrait(userId,singleUploadedFile.getFilePath());
return true;
}
private SingleUploadedFile saveFile(MultipartFile file) {
SingleUploadedFile singleUploadedFile = new SingleUploadedFile();
singleUploadedFile.setFile(file);
return fileReceiveComponent.upload(singleUploadedFile);
}
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
<file_sep>package com.hs.whocan.service.session;
import com.hs.whocan.component.account.security.SecurityComponent;
import com.hs.whocan.component.account.user.dao.User;
import com.hs.whocan.component.session.SessionComponent;
import com.hs.whocan.service.VerifySignInService;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* User: fish
*/
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class SessionSendAck extends VerifySignInService {
private String readTag;
@Resource
private SessionComponent sessionComponent;
@Override
@Transactional
public Boolean execute(User user) {
sessionComponent.deleteReadMessage(userId,readTag);
return true;
}
public String getReadTag() {
return readTag;
}
public void setReadTag(String readTag) {
this.readTag = readTag;
}
}
<file_sep>package com.hs.whocan.component.account.security.dao.hbn;
import com.hs.whocan.component.account.security.dao.PhoneAuthCode;
import com.hs.whocan.component.account.security.dao.PhoneAuthCodeDao;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-20
* Time: 下午2:01
* To change this template use File | Settings | File Templates.
*/
@Service
public class PhoneAuthCodeRepository implements PhoneAuthCodeDao {
@Resource
private SessionFactory sessionFactory;
@Override
public PhoneAuthCode findPhoneAuthCode(String phoneNo) {
final String hql = "from PhoneAuthCodeEntity e where e.phoneNo = :phoneNo";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("phoneNo",phoneNo);
PhoneAuthCodeEntity entity = (PhoneAuthCodeEntity) query.uniqueResult();
return entity!=null?entity.getPhoneAuthCode():null;
}
@Override
public void createPhoneAuthCode(PhoneAuthCode phoneAuthCode) {
sessionFactory.getCurrentSession().save(new PhoneAuthCodeEntity(phoneAuthCode));
}
@Override
public PhoneAuthCode findPhoneAuthCode(String phoneNo, int authCode) {
final String hql = "from PhoneAuthCodeEntity e where e.phoneNo = :phoneNo and e.authCode = :authCode and e.authCode != 0";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("phoneNo",phoneNo);
query.setInteger("authCode", authCode);
PhoneAuthCodeEntity entity = (PhoneAuthCodeEntity) query.uniqueResult();
return entity!=null?entity.getPhoneAuthCode():null;
}
}
<file_sep>package com.hs.whocan.component.account.security.exception;
import com.hs.whocan.exception.FriendlyMessageException;
/**
* User: fish
*/
public class AuthCodeDisableException extends FriendlyMessageException {
@Override
public String getFriendlyMessage() {
return "验证码失效";
}
}
<file_sep>
CREATE TABLE `FriendInfo` (
`userId` varchar(255) NOT NULL,
`alias` varchar(255) DEFAULT NULL,
`gender` varchar(255) DEFAULT NULL,
`mailAddress` varchar(255) DEFAULT NULL,
`phoneNo` varchar(255) DEFAULT NULL,
`portrait` varchar(255) DEFAULT NULL,
`remark` varchar(255) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`userName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `message_user_mapper` (
`mapperId` varchar(255) NOT NULL,
`messageId` varchar(255) DEFAULT NULL,
`receiveTime` datetime DEFAULT NULL,
`sessionId` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`mapperId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `operate_record` (
`operateId` varchar(255) NOT NULL,
`operateContent` varchar(255) DEFAULT NULL,
`operateTime` datetime DEFAULT NULL,
`projectId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`operateId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `project` (
`projectId` varchar(255) NOT NULL,
`content` varchar(255) DEFAULT NULL,
`createTime` datetime DEFAULT NULL,
`deadline` datetime DEFAULT NULL,
`done` tinyint(1) DEFAULT NULL,
`projectName` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`projectId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `project_user_mapper` (
`mapperId` varchar(255) NOT NULL,
`phoneNo` varchar(255) DEFAULT NULL,
`projectId` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
`userName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`mapperId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `project_work` (
`workId` varchar(255) NOT NULL,
`createTime` datetime DEFAULT NULL,
`createUserId` varchar(255) DEFAULT NULL,
`deadline` datetime DEFAULT NULL,
`done` tinyint(1) NOT NULL,
`info` varchar(255) DEFAULT NULL,
`projectId` varchar(255) DEFAULT NULL,
`workName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`workId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `security_access` (
`accessId` varchar(255) NOT NULL,
`accessTime` datetime DEFAULT NULL,
`accessToken` varchar(255) DEFAULT NULL,
`aliveTime` bigint(20) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`accessId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `security_authCode` (
`phoneId` int(11) NOT NULL AUTO_INCREMENT,
`authCode` int(11) DEFAULT NULL,
`createTime` datetime DEFAULT NULL,
`phoneNo` varchar(255) DEFAULT NULL,
PRIMARY KEY (`phoneId`)
) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8
/
CREATE TABLE `security_deviceToken` (
`tokenId` int(11) NOT NULL AUTO_INCREMENT,
`token` varchar(255) NOT NULL,
`userId` varchar(255) NOT NULL,
PRIMARY KEY (`tokenId`)
) ENGINE=InnoDB AUTO_INCREMENT=37 DEFAULT CHARSET=utf8
/
CREATE TABLE `session` (
`sessionId` varchar(255) NOT NULL,
`createTime` datetime DEFAULT NULL,
`sessionName` varchar(255) DEFAULT NULL,
`type` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`sessionId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `session_mapper` (
`mapperId` varchar(255) NOT NULL,
`addTime` datetime DEFAULT NULL,
`sessionId` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`mapperId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `session_message` (
`messageId` varchar(255) NOT NULL,
`content` varchar(255) DEFAULT NULL,
`createTime` datetime DEFAULT NULL,
`fromUser` varchar(255) DEFAULT NULL,
`msgType` varchar(255) DEFAULT NULL,
`sessionId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`messageId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `task` (
`taskId` varchar(255) NOT NULL,
`createTime` datetime DEFAULT NULL,
`createUser` varchar(255) DEFAULT NULL,
`deadline` datetime DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`groupId` varchar(255) DEFAULT NULL,
`owner` varchar(255) DEFAULT NULL,
`parentId` varchar(255) DEFAULT NULL,
`rate` int(11) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`title` varchar(255) DEFAULT NULL,
`top` int(11) DEFAULT NULL,
`type` varchar(255) DEFAULT NULL,
PRIMARY KEY (`taskId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `user_info` (
`userId` varchar(255) NOT NULL,
`gender` varchar(255) DEFAULT NULL,
`mailAddress` varchar(255) DEFAULT NULL,
`phoneNo` varchar(15) NOT NULL,
`portrait` varchar(255) DEFAULT NULL,
`remark` varchar(255) DEFAULT NULL,
`userName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`userId`),
UNIQUE KEY `UK_d7j9fvecmdk2hrftn675bx6nd` (`phoneNo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `user_invitation` (
`invitationId` varchar(255) NOT NULL,
`friendId` varchar(255) DEFAULT NULL,
`invitePhoneNo` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`invitationId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `user_linkman` (
`linkmanId` varchar(255) NOT NULL,
`phoneNo` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`linkmanId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
CREATE TABLE `user_mapper` (
`mapperId` varchar(255) NOT NULL,
`alias` varchar(255) DEFAULT NULL,
`friendId` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`mapperId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/
<file_sep>package com.hs.whocan.si;
import org.springframework.integration.Message;
import org.springframework.integration.handler.advice.AbstractRequestHandlerAdvice;
import org.springframework.integration.support.MessageBuilder;
import java.util.ArrayList;
import java.util.Map;
import java.util.Objects;
/**
* User: yinwenbo
* Date: 13-9-16
* Time: 15:36
*/
public class QueryResultEmptyHandler extends AbstractRequestHandlerAdvice {
private Object emptyResult;
public Object getEmptyResult() {
return emptyResult;
}
public void setEmptyResult(Object emptyResult) {
this.emptyResult = emptyResult;
}
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
Object result = callback.execute();
if (result == null) {
return MessageBuilder.withPayload(emptyResult).copyHeaders(message.getHeaders()).build();
}
return result;
}
}
<file_sep>package com.hs.whocan.service.social;
import com.hs.whocan.component.account.user.PushMessageComponent;
import com.hs.whocan.component.account.user.UserMapperComponent;
import com.hs.whocan.component.account.user.dao.User;
import com.hs.whocan.service.ValidatorService;
import com.hs.whocan.service.VerifySignInService;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-31
* Time: 下午5:43
* To change this template use File | Settings | File Templates.
*/
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class SocialAddFriendRegister extends VerifySignInService {
@NotNull
private String friendId;
@Resource
private ValidatorService validatorService;
@Resource
private UserMapperComponent userMapperComponent;
@Resource
private PushMessageComponent pushMessageComponent;
@Transactional
public Boolean execute(User user) {
validatorService.validate(this);
if (userId.equals(friendId)) {
return true;
}
if (userMapperComponent.isExistInvitation(userId,friendId)) {
userMapperComponent.createFriend(userId, friendId);
} else {
userMapperComponent.createInvitation(userId, friendId, null);
}
List<String> users = new ArrayList<String>();
users.add(friendId);
pushMessageComponent.push(users, "新的好友邀请:来自" + operator);
return true;
}
public String getFriendId() {
return friendId;
}
public void setFriendId(String friendId) {
this.friendId = friendId;
}
}
<file_sep>package com.hs.whocan.service.session;
import com.hs.whocan.component.account.user.dao.User;
import com.hs.whocan.component.session.SessionComponent;
import com.hs.whocan.service.VerifySignInService;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-28
* Time: 下午5:12
* To change this template use File | Settings | File Templates.
*/
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class SessionFindUser extends VerifySignInService {
private String sessionId;
@Resource
private SessionComponent sessionComponent;
@Transactional
public List<User> execute(User user) {
return sessionComponent.findUserInSession(sessionId);
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
}
<file_sep>CREATE DATABASE IF NOT EXISTS `whocan` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `whocan`;
-- MySQL dump 10.13 Distrib 5.6.13, for osx10.6 (i386)
--
-- Host: 192.168.127.12 Database: whocan
-- ------------------------------------------------------
-- Server version 5.5.34-0ubuntu0.13.10.1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `FriendInfo`
--
DROP TABLE IF EXISTS `FriendInfo`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `FriendInfo` (
`userId` varchar(255) NOT NULL,
`alias` varchar(255) DEFAULT NULL,
`gender` varchar(255) DEFAULT NULL,
`mailAddress` varchar(255) DEFAULT NULL,
`phoneNo` varchar(255) DEFAULT NULL,
`portrait` varchar(255) DEFAULT NULL,
`remark` varchar(255) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`userName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `message_user_mapper`
--
DROP TABLE IF EXISTS `message_user_mapper`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `message_user_mapper` (
`mapperId` varchar(255) NOT NULL,
`messageId` varchar(255) DEFAULT NULL,
`receiveTime` datetime DEFAULT NULL,
`sessionId` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`mapperId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `operate_record`
--
DROP TABLE IF EXISTS `operate_record`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `operate_record` (
`operateId` varchar(255) NOT NULL,
`operateContent` varchar(255) DEFAULT NULL,
`operateTime` datetime DEFAULT NULL,
`projectId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`operateId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `project`
--
DROP TABLE IF EXISTS `project`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `project` (
`projectId` varchar(255) NOT NULL,
`content` varchar(255) DEFAULT NULL,
`createTime` datetime DEFAULT NULL,
`deadline` datetime DEFAULT NULL,
`done` tinyint(1) DEFAULT NULL,
`projectName` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`projectId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `project_user_mapper`
--
DROP TABLE IF EXISTS `project_user_mapper`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `project_user_mapper` (
`mapperId` varchar(255) NOT NULL,
`phoneNo` varchar(255) DEFAULT NULL,
`projectId` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
`userName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`mapperId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `project_work`
--
DROP TABLE IF EXISTS `project_work`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `project_work` (
`workId` varchar(255) NOT NULL,
`createTime` datetime DEFAULT NULL,
`createUserId` varchar(255) DEFAULT NULL,
`deadline` datetime DEFAULT NULL,
`done` tinyint(1) NOT NULL,
`info` varchar(255) DEFAULT NULL,
`projectId` varchar(255) DEFAULT NULL,
`workName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`workId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `security_access`
--
DROP TABLE IF EXISTS `security_access`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `security_access` (
`accessId` varchar(255) NOT NULL,
`accessTime` datetime DEFAULT NULL,
`accessToken` varchar(255) DEFAULT NULL,
`aliveTime` bigint(20) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`accessId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `security_authCode`
--
DROP TABLE IF EXISTS `security_authCode`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `security_authCode` (
`phoneId` int(11) NOT NULL AUTO_INCREMENT,
`authCode` int(11) DEFAULT NULL,
`createTime` datetime DEFAULT NULL,
`phoneNo` varchar(255) DEFAULT NULL,
PRIMARY KEY (`phoneId`)
) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `security_deviceToken`
--
DROP TABLE IF EXISTS `security_deviceToken`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `security_deviceToken` (
`tokenId` int(11) NOT NULL AUTO_INCREMENT,
`token` varchar(255) NOT NULL,
`userId` varchar(255) NOT NULL,
PRIMARY KEY (`tokenId`)
) ENGINE=InnoDB AUTO_INCREMENT=37 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `session`
--
DROP TABLE IF EXISTS `session`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `session` (
`sessionId` varchar(255) NOT NULL,
`createTime` datetime DEFAULT NULL,
`sessionName` varchar(255) DEFAULT NULL,
`type` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`sessionId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `session_mapper`
--
DROP TABLE IF EXISTS `session_mapper`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `session_mapper` (
`mapperId` varchar(255) NOT NULL,
`addTime` datetime DEFAULT NULL,
`sessionId` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`mapperId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `session_message`
--
DROP TABLE IF EXISTS `session_message`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `session_message` (
`messageId` varchar(255) NOT NULL,
`content` varchar(255) DEFAULT NULL,
`createTime` datetime DEFAULT NULL,
`fromUser` varchar(255) DEFAULT NULL,
`msgType` varchar(255) DEFAULT NULL,
`sessionId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`messageId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `task`
--
DROP TABLE IF EXISTS `task`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `task` (
`taskId` varchar(255) NOT NULL,
`createTime` datetime DEFAULT NULL,
`createUser` varchar(255) DEFAULT NULL,
`deadline` datetime DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`groupId` varchar(255) DEFAULT NULL,
`owner` varchar(255) DEFAULT NULL,
`parentId` varchar(255) DEFAULT NULL,
`rate` int(11) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`title` varchar(255) DEFAULT NULL,
`top` int(11) DEFAULT NULL,
`type` varchar(255) DEFAULT NULL,
PRIMARY KEY (`taskId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `user_info`
--
DROP TABLE IF EXISTS `user_info`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_info` (
`userId` varchar(255) NOT NULL,
`gender` varchar(255) DEFAULT NULL,
`mailAddress` varchar(255) DEFAULT NULL,
`phoneNo` varchar(15) NOT NULL,
`portrait` varchar(255) DEFAULT NULL,
`remark` varchar(255) DEFAULT NULL,
`userName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`userId`),
UNIQUE KEY `UK_d7j9fvecmdk2hrftn675bx6nd` (`phoneNo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `user_invitation`
--
DROP TABLE IF EXISTS `user_invitation`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_invitation` (
`invitationId` varchar(255) NOT NULL,
`friendId` varchar(255) DEFAULT NULL,
`invitePhoneNo` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`invitationId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `user_linkman`
--
DROP TABLE IF EXISTS `user_linkman`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_linkman` (
`linkmanId` varchar(255) NOT NULL,
`phoneNo` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`linkmanId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `user_mapper`
--
DROP TABLE IF EXISTS `user_mapper`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_mapper` (
`mapperId` varchar(255) NOT NULL,
`alias` varchar(255) DEFAULT NULL,
`friendId` varchar(255) DEFAULT NULL,
`userId` varchar(255) DEFAULT NULL,
PRIMARY KEY (`mapperId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2014-05-09 15:12:01
<file_sep>package com.hs.whocan.component.tasklist.dao;
import java.util.List;
/**
* Created by fish on 14-4-21.
*/
public interface TaskDao {
public List<Task> find(String sessionId);
public void create(Task task);
public void delete(String taskId);
public void modify(Task task);
}
<file_sep>package com.hs.whocan.component.session.dao;
import java.util.Date;
import java.util.List;
/**
* Created by fish on 14-3-17.
*/
public interface MessageDao {
public void createMessage(Message message);
public List<Message> findMessageBySessionId(String sessionId);
public void deleteMessage(String messageId);
public List<Message> findNewMessage(String userId);
public Message findMessage(String messageId);
public void deleteMessage(String userId, String sessionId, Date createTime);
}
<file_sep>package com.hs.whocan.component.session.dao.hbm;
import com.hs.whocan.component.session.dao.MessageUserMapper;
import com.hs.whocan.component.session.dao.MessageUserMapperDao;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
/**
* User: fish
*/
@Service
public class MessageUserMapperRepository implements MessageUserMapperDao {
@Resource
private SessionFactory sessionFactory;
@Override
public void createMessageUserMapper(MessageUserMapper messageUserMapper) {
sessionFactory.getCurrentSession().save(new MessageUserMapperEntity(messageUserMapper));
}
@Override
public void deleteReadMessage(String userId, String sessionId, Date receiveTime) {
final String hql = "delete from MessageUserMapperEntity e where e.userId = :userId " +
"and e.sessionId = :sessionId " +
"and e.receiveTime <= :receiveTime";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("userId", userId);
query.setString("sessionId", sessionId);
query.setTimestamp("receiveTime", receiveTime);
query.executeUpdate();
}
@Override
public int findUnreadNum(String userId) {
final String hql = "select count(e.mapperId) from MessageUserMapperEntity e where e.userId = :userId ";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString("userId", userId);
Long result = (Long) query.uniqueResult();
return result.intValue();
}
}
<file_sep>package com.hs.whocan.component.tasklist.dao;
import java.util.Date;
/**
* Created by fish on 14-4-21.
*/
public class Task {
private String taskId;
private String title;
private String groupId;
private String description;
private int rate;
private int top;
private String createUser;
private Date createTime;
private Date deadline;
private String owner;
private String status;
private String parentId;
private String type;
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public int getTop() {
return top;
}
public void setTop(int top) {
this.top = top;
}
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getDeadline() {
return deadline;
}
public void setDeadline(Date deadline) {
this.deadline = deadline;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
<file_sep>package com.hs.whocan.component.account.user.dao;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-24
* Time: 下午6:51
* To change this template use File | Settings | File Templates.
*/
public interface UserMapperDao {
public void createUserMapper(UserMapper userMapper);
public void modifyUserMapperAlias(UserMapper userMapper);
public void deleteUserMapper(String userId,String friendId);
public UserMapper findUserMapper(String userId, String friendId);
}
<file_sep>package com.hs.whocan.service.tasklist;
import com.hs.whocan.component.account.user.dao.User;
import com.hs.whocan.component.tasklist.TaskComponent;
import com.hs.whocan.component.tasklist.dao.Task;
import com.hs.whocan.service.VerifySignInService;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by fish on 14-4-21.
*/
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class TaskFind extends VerifySignInService {
private String sessionId;
@Resource
private TaskComponent taskComponent;
@Override
@Transactional
public List<Task> execute(User user) {
return taskComponent.find(sessionId);
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
}
<file_sep>package com.hs.whocan.component.account.user;
import com.hs.whocan.component.account.user.dao.*;
import com.hs.whocan.service.social.FriendInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-20
* Time: 下午4:35
* To change this template use File | Settings | File Templates.
*/
@Service
@Transactional
public class UserMapperComponent {
@Resource
private UserDao userInfoDao;
@Resource
private UserInvitationDao userInvitationDao;
@Resource
private UserMapperDao userMapperDao;
@Resource
private LinkmanDao linkmanDao;
@Transactional
public void createLinkman(String userId, String[] phones) {
linkmanDao.createLinkman(userId, phones);
}
public boolean isExistInvitation(String userId, String friendId) {
if (0 != userInvitationDao.findUserInvitation(friendId, userId).size()) {
return true;
} else {
return false;
}
}
public void createInvitation(String userId, String friendId, String phoneNo) {
UserInvitation userInvitation = new UserInvitation();
userInvitation.setUserId(userId);
userInvitation.setFriendId(friendId);
userInvitation.setInvitePhoneNo(phoneNo);
userInvitationDao.createUserInvitation(userInvitation);
}
public void createFriend(String userId, String friendId) {
userInvitationDao.deleteUserInvitation(friendId, userId);
userMapperDao.createUserMapper(new UserMapper(userId, friendId));
userMapperDao.createUserMapper(new UserMapper(friendId, userId));
}
public void modifyUserMapperAlias(UserMapper userMapper) {
userMapperDao.modifyUserMapperAlias(userMapper);
}
public List<FriendInfo> findFriendByUserId(String userId) {
return userInfoDao.findFriendByUserId(userId);
}
public List<FriendInfo> findFriendInvite(String userId) {
return userInfoDao.findFriendInvite(userId);
}
public List<FriendInfo> findFriendInvited(String userId) {
return userInfoDao.findFriendInvited(userId);
}
public List<FriendInfo> findFriendNotAdd(String userId) {
return userInfoDao.findFriendNotAdd(userId);
}
public List<User> findUserByProjectId(String projectId) {
return userInfoDao.findUserByProjectId(projectId);
}
public void deleteFriend(String userId, String friendId) {
userMapperDao.deleteUserMapper(userId, friendId);
userMapperDao.deleteUserMapper(friendId, userId);
}
}
<file_sep>package com.hs.whocan.external.sms;
import org.springframework.stereotype.Service;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-20
* Time: 上午9:40
* To change this template use File | Settings | File Templates.
*/
@Service
public class SmsServiceImpl implements SmsService {
@Override
public void sendAuthCode(String phoneNo, int authCode) {
new Thread(new MtService(phoneNo, authCode)).start();
}
}
<file_sep>package com.hs.whocan.component.session.dao.hbm;
import com.hs.whocan.component.session.dao.Session;
import javax.persistence.*;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-26
* Time: 下午7:45
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name = "session")
public class SessionEntity {
private Session session;
public SessionEntity() {
session = new Session();
}
public SessionEntity(Session session) {
this.session = session;
}
@Transient
public Session getSession() {
return session;
}
@Id
public String getSessionId() {
return session.getSessionId();
}
public void setSessionId(String sessionId) {
session.setSessionId(sessionId);
}
@Column
public String getSessionName() {
return session.getSessionName();
}
public void setSessionName(String sessionName) {
session.setSessionName(sessionName);
}
public void setCreateTime(Date createTime) {
session.setCreateTime(createTime);
}
public void setUserId(String userId) {
session.setUserId(userId);
}
@Column
public Date getCreateTime() {
return session.getCreateTime();
}
@Column
public String getUserId() {
return session.getUserId();
}
@Column
public String getType() {
return session.getType();
}
public void setType(String type) {
session.setType(type);
}
}
<file_sep>package com.hs.whocan.component.account.security.exception;
import com.hs.whocan.exception.FriendlyMessageException;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-20
* Time: 下午2:52
* To change this template use File | Settings | File Templates.
*/
public class AuthCodeErrorException extends FriendlyMessageException {
@Override
public String getErrorCode() {
return "1000";
}
@Override
public String getFriendlyMessage() {
return "验证码错误,请重新获取";
}
}
<file_sep>package com.hs.whocan.component.account.user.dao;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-24
* Time: 下午5:08
* To change this template use File | Settings | File Templates.
*/
public class LinkmanStatus {
public final static String FRIEND ="FRIEND";
public final static String MY_INVITE ="MY_INVITE";
public final static String INVITE_ME ="INVITE_ME";
public final static String NOT_FRIEND ="NOT_FRIEND";
}
<file_sep>package com.hs.whocan.service.user;
import com.hs.whocan.component.account.user.UserComponent;
import com.hs.whocan.component.account.user.dao.User;
import com.hs.whocan.service.VerifySignInService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-31
* Time: 下午12:11
* To change this template use File | Settings | File Templates.
*/
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class UserModify extends VerifySignInService {
private String userName;
private String mailAddress;
private String gender;
private String remark;
private String portrait;
@Resource
private UserComponent userComponent;
@Transactional
public Boolean execute(User user) {
BeanUtils.copyProperties(this, user);
userComponent.modifyUser(user);
return true;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMailAddress() {
return mailAddress;
}
public void setMailAddress(String mailAddress) {
this.mailAddress = mailAddress;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getPortrait() {
return portrait;
}
public void setPortrait(String portrait) {
this.portrait = portrait;
}
}
<file_sep>package com.hs.whocan.service.tasklist;
import com.hs.whocan.component.account.user.dao.User;
import com.hs.whocan.service.VerifySignInService;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by fish on 14-4-21.
*/
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class TaskModify extends VerifySignInService {
@Override
@Transactional
public Boolean execute(User user) {
return true;
}
}
<file_sep>package com.hs.whocan.component.account.user.dao;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-17
* Time: 上午10:12
* To change this template use File | Settings | File Templates.
*/
public class UserMapper {
private String mapperId;
private String userId;
private String friendId;
private String alias;
public UserMapper() {
}
public UserMapper(String userId, String friendId) {
this.userId = userId;
this.friendId = friendId;
}
public String getMapperId() {
return mapperId;
}
public String getUserId() {
return userId;
}
public String getFriendId() {
return friendId;
}
public void setMapperId(String mapperId) {
this.mapperId = mapperId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setFriendId(String friendId) {
this.friendId = friendId;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
}
<file_sep>package com.hs.whocan.component.account.security.dao;
import java.util.Date;
/**
* Created by fish on 14-3-17.
*/
public class Access {
private String accessId;
private String password;
private Date accessTime;
private long aliveTime;
private String accessToken;
private static long ALIVE_TIME = 1000 * 60 * 60 * 1;
public Access() {
}
public Access(String accessId, String accessToken) {
this.accessId = accessId;
this.accessToken = accessToken;
this.accessTime = new Date();
this.aliveTime = ALIVE_TIME;
}
public String getAccessId() {
return accessId;
}
public void setAccessId(String accessId) {
this.accessId = accessId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public Date getAccessTime() {
return accessTime;
}
public void setAccessTime(Date accessTime) {
this.accessTime = accessTime;
}
public long getAliveTime() {
return aliveTime;
}
public void setAliveTime(long aliveTime) {
this.aliveTime = aliveTime;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
}
<file_sep>package com.hs.whocan.service;
import com.hs.whocan.exception.TranslatedException;
import javax.validation.ConstraintViolation;
import java.util.Set;
/**
* User: fish
*/
public class ValidatorException extends TranslatedException {
private Set<ConstraintViolation<Object>> violations;
public ValidatorException(Set<ConstraintViolation<Object>> violations) {
this.violations = violations;
}
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder(super.getMessage());
for (ConstraintViolation<Object> violation : violations) {
sb.append(violation.getMessage()).append(", ");
}
return sb.toString();
}
}
<file_sep>package com.hs.whocan.si;
/**
* Created by yinwenbo on 14-5-6.
*/
public class EmptyResultBean {
}
<file_sep>jdbc.url=jdbc:mysql://127.0.0.1:3306/whocan?userUnicode=true&characterEncoding=utf-8&autoReconnect=true
jdbc.user=root
jdbc.password=<PASSWORD>
upload.file.image.path=D://github//pic
<file_sep>package com.hs.whocan.component.account.security.exception;
import com.hs.whocan.exception.FriendlyMessageException;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-20
* Time: 下午3:45
* To change this template use File | Settings | File Templates.
*/
public class TokenDisableException extends FriendlyMessageException {
@Override
public String getFriendlyMessage() {
return "请重新登陆";
}
}
<file_sep>package com.hs.whocan.service.social;
import com.hs.whocan.component.account.user.UserMapperComponent;
import com.hs.whocan.component.account.user.dao.User;
import com.hs.whocan.service.VerifySignInService;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-31
* Time: 下午5:34
* To change this template use File | Settings | File Templates.
*/
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class SocialUploadLinkman extends VerifySignInService {
private String phones;
@Resource
private UserMapperComponent userMapperComponent;
public Boolean execute(User user) {
String[] phoneArray = phones.split(",");
userMapperComponent.createLinkman(userId, phoneArray);
return true;
}
public String getPhones() {
return phones;
}
public void setPhones(String phones) {
this.phones = phones;
}
}
<file_sep>package com.hs.whocan.component.session.dao;
import com.hs.whocan.component.account.user.dao.User;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-26
* Time: 下午7:48
* To change this template use File | Settings | File Templates.
*/
public interface SessionDao {
public void createSession(Session session);
public void createSessionMapper(SessionMapper sessionMapper);
public void modifySessionName(String sessionId, String sessionName);
public Session findSessionByUnionId(String sessionId1, String sessionId2);
public void deleteSession(String sessionId);
public void deleteSessionMapper(String sessionId);
public List<Session> findSessionByUserId(String userId);
public void deleteSessionMapperByUserId(String sessionId, String deleteUserId);
public List<String> findUserIdInSession(String sessionId);
public List<User> findUserInSession(String sessionId);
public List<String> findUserIdInSessionExcludeOwn(String sessionId, String userId);
public int findUserNumInSession(String sessionId);
public SessionMapper findSessionMapper(String sessionId, String userId);
public Session findSessionById(String sessionId);
public List<Session> findSessionByIds(List<String> sessionIds);
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hs.pm</groupId>
<artifactId>progect_managerment</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<properties>
<spring.framework.version>3.2.5.RELEASE</spring.framework.version>
<spring.integration.version>3.0.1.RELEASE</spring.integration.version>
</properties>
<dependencies>
<dependency>
<groupId>com.github.fernandospr</groupId>
<artifactId>javapns-jdk16</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.17</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>tomcat</groupId>
<artifactId>jsp-api</artifactId>
<version>5.5.23</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.1</version>
</dependency>
<!-- DB Access -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.7.Final</version>
</dependency>
<!-- commons -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<!-- spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<!-- spring integration -->
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-http</artifactId>
<version>${spring.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-file</artifactId>
<version>${spring.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mail</artifactId>
<version>${spring.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-xml</artifactId>
<version>${spring.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-core</artifactId>
<version>${spring.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-jdbc</artifactId>
<version>${spring.integration.version}</version>
</dependency>
<!-- aspect -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.12</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.12</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<!-- json -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.5</version>
</dependency>
<!-- log -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.0.13</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
<version>1.0.13</version>
</dependency>
<!--test-->
<!--
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path-parent</artifactId>
<version>0.9.1</version>
<scope>test</scope>
</dependency>
-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-core</artifactId>
<version>3.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-dbunit</artifactId>
<version>3.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-easymock</artifactId>
<version>3.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-spring</artifactId>
<version>3.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-mock</artifactId>
<version>3.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-inject</artifactId>
<version>3.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.5.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.7</version>
<configuration>
<aggregate>true</aggregate>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
<finalName>pm</finalName>
</build>
<profiles>
<profile>
<id>deployPm2Tomcat</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<version>1.1</version>
<configuration>
<charset>UTF-8</charset>
<!--<server>tomcat7</server>-->
<update>true</update>
<url>http://localhost:8080/manager/text</url>
<username>weijinrong</username>
<password><PASSWORD>>
<warFile>${project.build.directory}/${project.build.finalName}.${project.packaging}
</warFile>
<path>/${project.build.finalName}</path>
</configuration>
<executions>
<execution>
<id>DeployToRemoteContainer</id>
<phase>install</phase>
<goals>
<goal>redeploy</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
<file_sep>package com.hs.whocan.external.sms;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-20
* Time: 上午9:36
* To change this template use File | Settings | File Templates.
*/
public interface SmsService {
public void sendAuthCode(String phoneNo, int authCode);
}
<file_sep>package com.hs.whocan.component.session;
import com.hs.whocan.component.account.user.dao.User;
import com.hs.whocan.component.session.dao.Session;
import com.hs.whocan.component.session.dao.SessionDao;
import com.hs.whocan.service.session.dto.SessionUserInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-31
* Time: 下午7:33
* To change this template use File | Settings | File Templates.
*/
@Service
public class SessionQuery {
@Resource
private SessionDao sessionDao;
@Transactional
public SessionUserInfo querySessionUserInfo(String userId, Session session) {
SessionUserInfo sessionUserInfo = new SessionUserInfo();
List<User> users = sessionDao.findUserInSession(session.getSessionId());
sessionUserInfo.setUserList(users);
sessionUserInfo.setSession(session);
setSessionInfoName(sessionUserInfo, userId, users);
return sessionUserInfo;
}
private void setSessionInfoName(SessionUserInfo sessionUserInfo, String userId, List<User> users) {
if (null == sessionUserInfo.getSessionName() || "".equals(sessionUserInfo.getSessionName())) {
int userNum = sessionDao.findUserNumInSession(sessionUserInfo.getSessionId());
sessionUserInfo.setSessionName("群聊(" + userNum + "人)");
}
}
}
<file_sep>package com.hs.whocan.component.session.dao;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-27
* Time: 上午10:31
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name="session_mapper")
public class SessionMapper {
private String mapperId;
private String sessionId;
private String userId;
private Date addTime;
public SessionMapper() {
}
public SessionMapper(String sessionId, String userId) {
this.sessionId = sessionId;
this.userId = userId;
this.addTime = new Date();
}
@Id
@GenericGenerator(name = "idGenerator", strategy = "uuid")
@GeneratedValue(generator = "idGenerator")
public String getMapperId() {
return mapperId;
}
public void setMapperId(String mapperId) {
this.mapperId = mapperId;
}
@Column
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
@Column
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Column
public Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
}
<file_sep>package com.hs.whocan.component.account.user.dao;
/**
* Created with IntelliJ IDEA.
* User: fish
* Date: 14-3-24
* Time: 下午6:22
* To change this template use File | Settings | File Templates.
*/
public class LinkMan {
private String linkmanId;
private String userId;
private String phoneNo;
public String getLinkmanId() {
return linkmanId;
}
public void setLinkmanId(String linkmanId) {
this.linkmanId = linkmanId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
}
| 10e677ed95db30462e2d29066d3cd4d3b224fe09 | [
"Java",
"Maven POM",
"SQL",
"INI"
]
| 57 | Java | fishbeyond/pm | 85fdc42361fb7baee4a74e447c44347fc6b49949 | 4bdf3eb716a5e6da06f0069ebcf279349c287744 |
refs/heads/master | <file_sep>import {StyleSheet} from "react-native";
export const ListScreen = StyleSheet.create({
screen: {
flex: 1,
alignItems: "center",
},
});
export const GeneralCardCharacters = StyleSheet.create({
listItem: {
marginVertical: "2%",
borderWidth: 1,
borderColor: '#f3f2f2',
borderRadius: 10,
}
});
export const DetailedCardCharacters = StyleSheet.create({
overlay: {
width: "90%",
padding: 0
},
card: {
borderWidth: 0,
elevation: 0
},
detail: {
flexDirection: "row",
marginBottom: "4%"
},
})
export const CardGeneralStyles = StyleSheet.create({
image: {
width: "100%",
marginBottom: "6%"
},
font: {
fontWeight: "bold"
},
font100:{
fontWeight: "100"
},
textMuted: {
fontWeight: "100",
color: "gray"
},
background: {
backgroundColor: 'gray'
},
dividerMargin2: {
backgroundColor: 'gray',
marginBottom: "2%"
},
dividerMargin6: {
backgroundColor: 'gray',
marginBottom: "6%"
}
});
export const CharacterScreen = StyleSheet.create({
container: {
flex: 1,
marginTop: '10%'
},
body: {
flex: 1,
justifyContent: "flex-start"
},
header: {
marginBottom: 10,
elevation: 1,
alignItems: "center"
},
content: {
borderTopWidth: 1,
borderTopColor: "#e3e3e3"
}
});
export const Filters = StyleSheet.create({
listItem: {
width: "95%",
marginTop: "2%",
borderRadius: 10,
justifyContent: "space-around",
alignItems: "flex-start",
flexDirection: "row",
backgroundColor: "white",
padding: 10
},
button: {
borderRadius: 20,
borderWidth: 1,
borderColor: "#63aee8",
width: 85
},
buttonCancel: {
borderRadius: 20,
borderWidth: 1,
backgroundColor: "red",
borderColor: 'red',
width: 85,
}
})
<file_sep>import {StyleSheet} from "react-native";
export const WelcomeScreen = StyleSheet.create({
screen: {
flex: 1,
alignItems: "center",
marginVertical: "15%",
},
tittleContainer: {
flex: 1
},
nameText: {
marginBottom: 10
},
imageContainer: {
flex: 2,
justifyContent: "center",
alignItems: "center",
flexDirection: "row"
},
buttonContainer: {
flex: 1,
justifyContent: "flex-end",
alignItems: "center",
borderBottomWidth: 1,
padding: 10,
borderBottomColor: 'gray'
},
button: {
width: 140,
height: 60,
justifyContent: 'center'
},
dateContainer: {
marginVertical: 20,
alignItems: "center"
}
});<file_sep>type WelcomeScreenProps = {
setWelcomePage: (visible: boolean) => void ;
}<file_sep>export interface ICharacter {
__typename?: string;
name: string;
image: string;
species: string;
type: string;
gender: string;
}
export interface ICharacterEpisodeLocation {
id: number;
name: string;
image: string;
}
export interface IEpisode {
__typename?: string;
id: number;
name: string;
air_date: string;
episode: string;
characters: ICharacterEpisodeLocation[]
}
export interface ILocation {
__typename?: string;
id: number;
name: string;
air_date: string;
type: string;
dimension: string;
residents: ICharacterEpisodeLocation[];
}
export type GeneralCardLocationProps = {
location: ILocation;
setLocation: (location: ILocation) => void;
setVisible: (visible: boolean) => void;
}
export type GeneralCardProps = {
type: string;
character?: ICharacter;
location?: ILocation;
episode?: IEpisode;
setCharacter?: (character: ICharacter) => void;
setEpisode?: (episode: IEpisode) => void;
setLocation?: (location: ILocation) => void;
setVisible: (visible: boolean) => void;
}
export type GeneralEpisodeProps = {
episode: IEpisode;
setVisible: (visible: boolean) => void;
setEpisode: (episode: IEpisode) => void;
}
export type DetailedCardProps = {
type: string;
character?: ICharacter;
episode?: IEpisode;
location?: ILocation;
visible: boolean;
setIsVisible: (visible: boolean) => void;
}
export type DetailedCardCharacterProps = {
character: ICharacter,
setIsVisible: (visible: boolean) => void
}
export type DetailedCardEpisodeProps = {
episode: IEpisode;
setIsVisible: (visible: boolean) => void;
}
export type DetailedCardLocationProps = {
location: ILocation;
setIsVisible: (visible: boolean) => void;
}
export type SearchBarProps = {
keySearch: string;
setKeySearch: (key: string) => void;
filter: boolean;
searchCharacterAction?: (key: string, type: boolean, refreshAll: boolean) => void;
searchEpisodeAction?: (key: string, type: boolean, refreshAll: boolean) => void;
searchLocationAction?: (key: string, type: boolean, refreshAll: boolean) => void;
type: string;
setFirstUpdate: (firstUpdate: boolean) => void;
}
interface btnNames {
first: string;
second: string;
}
export type FiltersProps = {
btnNames: btnNames;
filter: boolean;
setFilter: (filter: boolean) => void;
keySearch: string;
setKeySearch: (keySearch: string) => void
searchCharacterAction?: (key: string, type: boolean, refreshAll: boolean) => void;
searchEpisodeAction?: (key: string, type: boolean, refreshAll: boolean) => void;
searchLocationAction?: (key: string, type: boolean, refreshAll: boolean) => void;
setFirstUpdate: (firstUpdate: boolean) => void;
getCharactersAction?: (updatePage?: boolean, refreshAll?: boolean, page?: number) => void;
getEpisodesAction?: (updatePage?: boolean, refreshAll?: boolean, page?: number) => void;
getLocationsAction?: (updatePage?: boolean, refreshAll?: boolean, page?: number) => void;
setNextPageAction: (nextPage: number) => void;
type: string;
}<file_sep>export interface ICharacter {
id: number
name: string,
type: string,
species: string,
gender: string,
image: string
}
export type DetailCardCharacterProps = {
show: boolean,
character: ICharacter,
handleShow: (event: React.MouseEvent<HTMLButtonElement>) => void,
}
export interface IResidents {
name: string,
image?: string
}
export interface ILocations {
id: number,
name: string,
type: string,
dimension: string,
residents: IResidents[]
}
export type DetailCardLocationsProps = {
show: boolean,
location: ILocations,
handleShow: (event: React.MouseEvent<HTMLButtonElement>) => void,
}
export interface IEpisodes {
id: number,
name: string,
air_date: string,
episode: string,
characters: IResidents[]
}
export type DetaildCardEpisodesProps = {
show: boolean,
episode: IEpisodes,
handleShow: (event: React.MouseEvent<HTMLButtonElement>) => void,
}
export interface Idata {
fetching: boolean,
data: any,
current: object,
nextPage: number,
pages: number
}
export interface Iaction {
type: string;
payload: any;
}
export interface IApp {
current: string
}<file_sep># Rick Morty RNATIVE
## React Native - EXPO - Typescript - Redux - GraphQL - React Native Elements
Simple Wiki with information of characters, locations and episodes from "Rick & Morty"
### Data Shown in principal screens
| Characters | Locations | Episodes |
|------------|-----------|----------|
| Image | Name | Name |
| Name | Dimension | Episode |
| Species | | |
### Data shown in detailed views
| Characters | Locations | Episodes |
|------------|-----------|------------|
| Name | Name | Name |
| Image | Dimension | Episode |
| Specie | Type | Air_date |
| Type | Residents | Character |
| Genre | | |
### Welcome Screen
<img src="https://github.com/cframo/rick-morty-rnative/blob/master/screenshots/welcome.jpg" width="200">
### Characters' Page
#### Principal Screen
<img src="https://github.com/cframo/rick-morty-rnative/blob/master/screenshots/characters1.jpg" width="200">
#### Detailed Screen
<img src="https://github.com/cframo/rick-morty-rnative/blob/master/screenshots/characters2.jpg" width="200">
### Locations' Page
#### Principal Screen
<img src="https://github.com/cframo/rick-morty-rnative/blob/master/screenshots/locations1.jpg" width="200">
#### Detailed Screen
<img src="https://github.com/cframo/rick-morty-rnative/blob/master/screenshots/locations2.jpg" width="200">
### Episodes' Page
#### Principal Screen
<img src="https://github.com/cframo/rick-morty-rnative/blob/master/screenshots/episodes1.jpg" width="200">
#### Detailed Screen
<img src="https://github.com/cframo/rick-morty-rnative/blob/master/screenshots/episodes2.jpg" width="200">
### Demo Videos
#### Overview
[](https://www.youtube.com/watch?v=iHX4SguXwiQ)
### How to test?
#### 1 - Clone repo.
#### 2 - `yarn install`
#### 3 - `yarn android`
#### 4 - TEST!
| 441e5ee0b324b773eec0b200dfff65a03f5b59b1 | [
"Markdown",
"TypeScript"
]
| 6 | TypeScript | cframo/rick-morty-rnative | 1d52f02f09d557000ebc7fb753751dbeba901f88 | 346d90aa004fd592fe167eccb64984bac41b3a1b |
refs/heads/main | <file_sep>// require('dotenv').config('../.env')
const express = require('express')
const router = express.Router()
const fs = require('firebase-admin')
const db = fs.firestore();
// will recieve fileCode
router.post('/', async (request,response) => {
const code = request.body.filecode;
let fileData = null;
console.log(`Initiating file fetch for ${code}`)
try{
const file = await db.collection('postal').doc(code).get();
if (!file.exists) {
console.log('No such document present!');
} else {
console.log('Document data:', file.data());
fileData = file.data();
}
} catch(err) {
console.trace(`trace : ${err}`);
}
response.json({
status : (fileData === null) ? "failure" : "success",
file: fileData
})
})
module.exports = router
<file_sep>// require('dotenv').config()
const puppeteer = require('puppeteer');
const { scrapeQueue } = require('../messageQ/bull')
const fs = require('firebase-admin')
const serviceAccount = process.env.FIREBASE_AUTH_CONFIG_BASE64
fs.initializeApp({
credential: fs.credential.cert(JSON.parse(Buffer.from(serviceAccount, 'base64').toString('ascii'))),
databaseURL: process.env.FIREBASE_DATABASEURL
});
const db = fs.firestore();
function baseScrape (url,selector) {
return new Promise(async (resolve, reject) => {
try {
const browser = await puppeteer.launch({
args: [
'--no-sandbox',
'--disable-setuid-sandbox'
],
headless: true
})
console.log("Browser launched")
const page = await browser.newPage();
page.setCacheEnabled(true);
await page.setRequestInterception(true);
page.on('request', (request) => {
if (request.resourceType() === 'image') {
request.abort();
} else if (request.resourceType() === 'font'){
request.abort();
} else if (request.resourceType() === 'media'){
request.abort();
} else if (request.resourceType() === 'imageset'){
request.abort();
} else {
request.continue();
}
});
await page.goto(url);
console.log(`${url} opened`)
console.log(`Waiting for Selector ${selector} to load`)
await page.waitForSelector(selector);
console.log(`Selector ${selector} loaded`);
let scrappedData = await page.evaluate(selector => {
let results=[]
document.querySelectorAll(selector).forEach((item) => {
results.push({
url: item.getAttribute('href'),
fileName: item.innerText,
});
})
return results;
}, selector);
console.log(`Scrapping Successful. Scrapped Data `)
console.log(scrappedData)
browser.close();
console.log("Browser Closed successfully")
return resolve(scrappedData);
} catch (e) {
console.log(`Error occured at baseScraping: ${e}`)
return reject(e);
}
})
}
// TODO: add error ticket with all info
async function CallScrap( url, selector, code, fileName ){
//add for multiple files
const [{url: DDL,fileName: name}] = await baseScrape(url,selector).catch(err => {
console.log(`Error Occured retrieving DDL data: ${err}`)
});
console.log(`Scrapped Data ${fileName}:${DDL} `)
try{
const postalDB = db.collection('postal').doc(code);
await postalDB.set({
filecode: code,
fileName: name,
fileDownload: DDL,
createdAt: fs.firestore.FieldValue.serverTimestamp(),
status: 'Success',
statusInfo: "DDL added Success"
})
} catch(err) {
console.trace(`Error stack trace : ${err}`);
}
console.log("Data Posted in DB successfully");
}
scrapeQueue.process(async job => {
return await CallScrap(job.data.url, job.data.selector, job.data.fileCode, job.data.fileName).catch( (err) => {
console.log(`Error occured at scrapeQueue Process: ${err}`);
});
});
// async function testScraping (code){
// // console.log(`${process.env.PANTRY_ID}/basket/${code}`)
// const Data = await baseScrape("https://gofile.io/d/JL4Uqc","div.col-sm-6.text-center.text-sm-left > a").catch(err => {
// console.log(`Error Occured at retrieving test DDL: ${err}`)
// });
// console.log(`Data: ${JSON.stringify(Data)}`)
// }
// testScraping("1")
exports.scrapeQueue = scrapeQueue;
<file_sep>// require('dotenv').config('../.env')
const express = require('express')
const router = express.Router()
const crypto = require("crypto");
const { scrapeQueue } = require('../microservice/scrapper')
// TODO: add multiple css select feature with type
// TODO: docker redis
router.post('/', async (request,response) => {
const randfilecode = crypto.randomBytes(3).toString('hex');
const data = {
url: request.body.url,
selector: 'div.col-sm-6.text-center.text-sm-left > a' ,
fileCode: randfilecode,
fileName: request.body.fileName
};
const options = {
// delay: 10000, // 1 min in ms
attempts: 2
};
scrapeQueue.add(data, options)
response.json({
status : "success",
fileCode: randfilecode
})
})
// router.post('/', async (request,response) => {
// const randfilecode = crypto.randomBytes(3).toString('hex');
// const url = request.body.url
// const fileCode = randfilecode
// response.json({
// status : "success",
// fileCode: randfilecode
// })
// const res = await axios.post(`https://getpantry.cloud/apiv1/pantry/${process.env.PANTRY_ID}/basket/${fileCode}`, {
// filecode: fileCode,
// fileName: request.body.fileName,
// fileDownload: url,
// status: 'Success',
// statusInfo: "Direct Download Link successfully Fetched"
// }).catch( err => {
// console.log(`Error Occured posting data to DB: ${err}`)
// });
// console.log(`Data uploaded data to DB`)
// console.log(res.data)
// })
module.exports = router
<file_sep>// require('dotenv').config
const express = require('express')
const cors = require('cors')
const app = express()
app.use(express.json())
app.use(cors())
const fetchCloudRouter = require('./routes/fetchcloud')
const fetchFileRouter = require('./routes/fetchfile')
const cleanDBRouter = require('./routes/cleanDB')
app.get("/api/health", async (req,res) => {
res.json({ message: "API working" })
})
app.use('/fetchcloud', fetchCloudRouter)
app.use('/fetchfile', fetchFileRouter)
app.use('/cleanDB', cleanDBRouter)
app.listen(process.env.PORT || 3000, () => console.log("Clair Service Started"))
process.on('uncaughtException', function(err) {
console.log("uncaughtException application Closed " + err);
});
process.on('uncaughtRejection', function(err) {
console.log("uncaughtException application Closed " + err);
console.trace("stack trace");
});<file_sep>const express = require('express')
const router = express.Router()
const { scrapeQueue } = require('../microservice/scrapper')
const fs = require('firebase-admin')
const db = fs.firestore();
router.get('/', async (request,response) => {
console.log(`Initiating DB cleanup`);
const now = Date.now();
const MS_PER_HOUR = 1000 * 60 * 60 ;
let error = "";
try {
const postalRef = await db.collection('postal');
var allfiles = postalRef.get()
.then(snapshot => {
snapshot.forEach(file => {
const hoursdiff = Math.floor((now - file.data().createdAt.toDate())/MS_PER_HOUR);
console.log(`${file.id} => `,file.data() ,hoursdiff, 'Created before (in Hours)');
if (hoursdiff >= 24){
console.log(`${file.id} => ${hoursdiff} getting deleted`);
(async function(){
const k = await db.collection('postal').doc(file.id).delete().catch(err => {
`Error while Deleting Document: ${err}`
})
})()
}
})
})
} catch(err){
console.log('Error retrieving/Deleting documents: ', err);
error = err;
}
response.json({
status : "successfully Triggered",
})
})
module.exports = router | 59dbe5b31d902add85a820426d427bf0850b1073 | [
"JavaScript"
]
| 5 | JavaScript | ae6ec/clair | eb4e0472f2bd3ff8751976a3c123cfb82c631bfd | e083c147e49597113fa1c68a09aec4ebf7207f6b |
refs/heads/master | <repo_name>oscarlazala/phpstartup<file_sep>/printer.php
<?php
class Printer
{
private $queue = [];
private $maxQueuedDocuments = 10;
public function print(Document $document)
{
return $this->pushToQueue($document);
}
private function pushToQueue(Document $newDocument)
{
if( count($this->queue) < $this->maxQueuedDocuments) {
$this->queue[] = $newDocument;
return true;
}
return false;
}
}
class MultiFunctionPrinter extends Printer
{
public function copy()
{
}
public function scan()
{
}
}
// print()
// copy()
// scan()
//
// events:
// onPaperJammed()
// onLowInk()
interface Document
{
}
class Print
{
protected $printerName = 'Printer01';
public static function print(Document $document, ?String $printer)
{
$printJob = new static;
if ($printer) {
$printJob->setPrinter($printer);
}
return $printJob->getPrinter()
->print($document)
->then(function () {
});
}
protected function getPrinter(): Printer
{
$printer = new $this->printerName();
if ( ! ($printer instanceof Printer)) {
throw new Exception("Not a valid printer selected.", 1);
}
return $printer;
}
protected function setPrinter(String $printer)
{
$this->printerName = $printer;
}
}
$document1 = new Document();
Print::print($document1);
Printer::worker();
$document2 = new Document();
Print::print($document2);
$document3 = new Document();
Print::print($document3);
Printer::worker();
echo Printer::getQueuedJobs();
| bb026a51949adb4a8d77f1fc022d50d2209d7b51 | [
"PHP"
]
| 1 | PHP | oscarlazala/phpstartup | f94429eb2fd639b9373f9129e3f38b4b8ac9b329 | 8b6ff73a022aa4bfa26118666ea677940e791b25 |
refs/heads/main | <file_sep>-- @block counts
SELECT
count(distinct id) as total_nb_lars,
SUM(case when assignement_date__c is not null then 1 else 0 end) as nb_lars_not_in_backlog,
SUM(case when assignement_date__c is not null and owner_relation__c is null then 1 else 0 end) as nb_lars_to_fix
FROM data.staging_salesforce.batchaccountrelation__c
WHERE
NOT isdeleted;<file_sep>-- @block Get LARs to mark as lost (to execute after all lars that could be fixed actually have been)
SELECT
distinct id
FROM data.staging_salesforce.batchaccountrelation__c
WHERE
not isdeleted
and assignement_date__c IS NOT NULL
and owner_relation__c IS NULL;<file_sep>-- @block Nb lars to fix after join
WITH lars_to_fix AS (
SELECT
id,
account__c,
assignement_date__c,
end_relation_date__c,
owner_relation__c
FROM data.staging_salesforce.batchaccountrelation__c
WHERE
NOT isdeleted
AND assignement_date__c IS NOT NULL
AND owner_relation__c IS NULL
),
history AS (
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string <> newvalue__string
and oldvalue__string not like '0053X%'
and newvalue__string <> 'Outbound Database'
and newvalue__string not like '%Reassignment%'
)
SELECT
count(*) tot_nb_lines,
count(distinct lars_to_fix.id) nb_lars_to_fix
FROM lars_to_fix
JOIN history
on lars_to_fix.account__c = history.accountid;
-- @block How many LARs associated to accounts with no history
WITH lars_to_fix AS (
SELECT
id,
account__c,
assignement_date__c,
end_relation_date__c,
owner_relation__c
FROM data.staging_salesforce.batchaccountrelation__c
WHERE
NOT isdeleted
AND assignement_date__c IS NOT NULL
AND owner_relation__c IS NULL
),
history AS (
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string <> newvalue__string
and oldvalue__string not like '0053X%'
and newvalue__string <> 'Outbound Database'
and newvalue__string not like '%Reassignment%'
)
SELECT
count(distinct lars_to_fix.id) nb_lars_w_no_history
FROM lars_to_fix
LEFT JOIN history
on lars_to_fix.account__c = history.accountid
WHERE history.accountid is null;
-- @block Is lar owner account first owner when no account history?
WITH lars_w_owner AS (
SELECT
id,
account__c,
assignement_date__c,
end_relation_date__c,
owner_relation__c
FROM data.staging_salesforce.batchaccountrelation__c
WHERE
NOT isdeleted
AND owner_relation__c IS NOT NULL
),
history1 AS (
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string <> newvalue__string
and oldvalue__string not like '0053X%'
and newvalue__string <> 'Outbound Database'
and newvalue__string not like '%Reassignment%'
),
lars_w_owner_no_history AS (
SELECT
lars_w_owner.id,
lars_w_owner.account__c,
lars_w_owner.owner_relation__c
FROM lars_w_owner
LEFT JOIN history1
on lars_w_owner.account__c = history1.accountid
WHERE history1.accountid is null
),
history2 AS (
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string not like '0053X%'
and oldvalue__string <> 'Outbound Database'
and oldvalue__string not like '%Reassignment%'
)
SELECT
lars_w_owner_no_history.*,
history2.*
FROM lars_w_owner_no_history
JOIN history2
ON lars_w_owner_no_history.account__c = history2.accountid
;<file_sep>-- @block Select account history
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string <> newvalue__string
and oldvalue__string not like '0053X%'
and newvalue__string <> 'Outbound Database'
and newvalue__string not like '%Reassignment%';
-- @block count_distinct_accounts
SELECT
count(distinct accountid)
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string <> newvalue__string
and oldvalue__string not like '0053X%'
and newvalue__string <> 'Outbound Database'
and newvalue__string not like '%Reassignment%';<file_sep>-- @block lars_to_fix
SELECT
count(id) lars_to_fix,
count(distinct account__c) accounts_w_lar_to_fix
FROM data.staging_salesforce.batchaccountrelation__c
WHERE
NOT isdeleted
AND assignement_date__c IS NOT NULL
AND owner_relation__c IS NULL;<file_sep># Purpose
The purpose of this document is to guide readers through our multiple sql requests and to present our key results.
# Acknowledgements
- All LARs that need a fix **have an assignment date**,
- All LARs that need a fix **have an end relation date**
Because Lucas and I made sure of it during previous LAR recovery sessions.
# Vocabulary
- **backlog**: LARs waiting for an assignment. Those LARs are characterized by the absence of owner AND assignment date on their record (simultaneously).
___
>If you're already bored and in a for-the-love-of-god-what-did-you-guys-actually-do mood, then jump to [this part](#Final-Results).
# Walkthrough
### **1. Lars to fix**
Find LARs to fix by executing the queries in `lars_to_fix.sql`. _LARs to fix are those not in [backlog](#Vocabulary) with no owner_.
### **2. Counts**
Execute the queries in `counts.sql` to grasp the volumes we're dealing with and how many lars we have to fix. You'll find the following:
- **Total number of LARs**: 79 796
- **Number of LARs not in backlog**: 71 552
- **Number of LARs in backlog**: 8 244
- **Number of LARs to fix**: 17 904
### **3. Account history**
To find missing owners, we thought about using `accounthistory`. Meaning that, for a given LAR, active on a given time frame, we want to find the owner of the account linked to the LAR on the given time frame.
First, look at the account history by executing queries in `account_history.sql`. You'll notice that we excluded changes that did not occur on the *owner* field, and changes to 'Outbound database' or any 'Reassignment Pools' (because these changes do not alter the owner of the LAR).
### **4. Join LARs & Account History**
If we want to find missing LAR owners, we have to join LARs and Account History and we should have as many LARs to fix (17 904) even after the join with the account history. Unfortunately, that's not the case...
When we execute this query 👇 in `lars_to_fix_&_account_history.sql` we find only 8 388 LARs to fix.
```sql
WITH lars_to_fix AS (
SELECT
id,
account__c,
assignement_date__c,
end_relation_date__c,
owner_relation__c
FROM data.staging_salesforce.batchaccountrelation__c
WHERE
NOT isdeleted
AND assignement_date__c IS NOT NULL
AND owner_relation__c IS NULL
),
history AS (
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string <> newvalue__string
and oldvalue__string not like '0053X%'
and newvalue__string <> 'Outbound Database'
and newvalue__string not like '%Reassignment%'
)
SELECT
count(*) tot_nb_lines,
count(distinct lars_to_fix.id) nb_lars_to_fix
FROM lars_to_fix
JOIN history
on lars_to_fix.account__c = history.accountid;
```
That means that some LARs to fix are linked to accounts with no history available in accounthistory - assertion confirmed by the following query in `lars_to_fix_&_account_history.sql`👇
```sql
WITH lars_to_fix AS (
SELECT
id,
account__c,
assignement_date__c,
end_relation_date__c,
owner_relation__c
FROM data.staging_salesforce.batchaccountrelation__c
WHERE
NOT isdeleted
AND assignement_date__c IS NOT NULL
AND owner_relation__c IS NULL
),
history AS (
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string <> newvalue__string
and oldvalue__string not like '0053X%'
and newvalue__string <> 'Outbound Database'
and newvalue__string not like '%Reassignment%'
)
SELECT
count(distinct lars_to_fix.id) nb_lars_w_no_history
FROM lars_to_fix
LEFT JOIN history
on lars_to_fix.account__c = history.accountid
WHERE history.accountid is null;
```
We find that 9 516 LARs are linked to accounts with no available history on their owners. Thorough readers will notice that 8 388 + 9 516 = 17 904, the total number of LARs left to fix.
> "Dear Lord, isn't there anything we can do?"
> "There might..."
___
Gauvain suggested that those 9 516 LARs had no owner changes recorded in accounthistory merely because the owner on the associated accounts had never changed since their creation.
Consequently, on those LARs, the LAR owner would be the only owner there ever was on the associated account. If we're to validate this hypothesis, we must try it on **LARs that already have an owner but no owner change recorded in the account history of their associated account**.
Therefore, switch back to the next query of `lars_to_fix_&_account_history.sql` - let's break it down!
1. First, we select LARs that already have an owner:
```sql
WITH lars_w_owner AS (
SELECT
id,
account__c,
assignement_date__c,
end_relation_date__c,
owner_relation__c
FROM data.staging_salesforce.batchaccountrelation__c
WHERE
NOT isdeleted
AND owner_relation__c IS NOT NULL
),
```
2. Then the account history of a change of owner:
```sql
history1 AS (
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string <> newvalue__string
and oldvalue__string not like '0053X%'
and newvalue__string <> 'Outbound Database'
and newvalue__string not like '%Reassignment%'
),
```
3. Then LARs that have an owner but no owner changes recorded in their account history:
```sql
lars_w_owner_no_history AS (
SELECT
lars_w_owner.id,
lars_w_owner.account__c,
lars_w_owner.owner_relation__c
FROM lars_w_owner
LEFT JOIN history1
on lars_w_owner.account__c = history1.accountid
WHERE history1.accountid is null
),
```
4. Then all the account history available (*we don't filter on owner changes anymore*, compare it to history1 if you're not sure):
```sql
history2 AS (
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string not like '0053X%'
and oldvalue__string <> 'Outbound Database'
and oldvalue__string not like '%Reassignment%'
)
```
5. Finally we join LARs with an owner, and no owner changes recorded, to the whole unfiltered account history:
```sql
SELECT
lars_w_owner_no_history.*,
history2.*
FROM lars_w_owner_no_history
JOIN history2
ON lars_w_owner_no_history.account__c = history2.accountid
;
```
And... **HURRAY**! The LAR owners match the *oldvalue__string* of the accounthistory after the join 🎉 Run the query and see for yourself!
___
Let's sum it up!
In this scenario, for all 17 904 LARs to fix, there would be two distinct outcomes:
- If we have owner changes recorded in the account history, then we use the method envisioned hitherto,
- If not, we take the first recorded owner in the account history.
In other words, the 8 388 LARs will be fixed with the first method, and the 9 516 others with the latter. Consequently, we have to make sure that all 9 516 LARs that *would be* fixed with the second method actually have a first owner recorded in *accounthistory*.
### **5. Finding owners that have owner changes recorded**
Let's move on to `lar_owners.sql` and execute its multiple queries.
You will find this particular query interesting 👇
```sql
-- @block Ower comparison
WITH lars AS (
SELECT
id,
account__c,
assignement_date__c,
end_relation_date__c,
owner_relation__c
FROM data.staging_salesforce.batchaccountrelation__c
WHERE
NOT isdeleted
AND assignement_date__c is not null
AND owner_relation__c is not null
),
history AS (
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string <> newvalue__string
and oldvalue__string not like '0053X%'
and newvalue__string <> 'Outbound Database'
and newvalue__string not like '%Reassignment%'
)
SELECT
COUNT(distinct lars.id) total,
SUM(case when lars.owner_relation__c = history.newvalue__string then 1 else 0 end) lar_owner_is_account_owner
FROM lars
JOIN history
on lars.account__c = history.accountid
and history.createddate >= lars.assignement_date__c
and (history.createddate <= lars.end_relation_date__c or lars.end_relation_date__c is null);
```
We find that on all LARs that already have an owner (there are 34 135 of them), the LAR owner name matches the owner we found in account history in only 32 389 cases (that's still more than 90% - fair enough).
Then, we'd run this query to make sure that - this time - there's only one owner on the assignment time frame of the LAR 👇 (You'll notice that 72 LARs have been excluded in the long list at the end of the query - check [this message](https://payfit.slack.com/archives/C019JGWPHSR/p1619018500009500) on Slack if that makes no sense)
```sql
-- @block Nb owners per LAR to fix
WITH lars_to_fix AS (
SELECT
id,
account__c,
assignement_date__c,
end_relation_date__c,
owner_relation__c
FROM data.staging_salesforce.batchaccountrelation__c
WHERE
NOT isdeleted
AND assignement_date__c IS NOT NULL
AND owner_relation__c IS NULL
),
history AS (
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string <> newvalue__string
and oldvalue__string not like '0053X%'
and newvalue__string <> 'Outbound Database'
and newvalue__string not like '%Reassignment%'
)
SELECT
distinct lars_to_fix.id,
count(*) nb_attribution
FROM lars_to_fix
JOIN history
on lars_to_fix.account__c = history.accountid
and history.createddate >= lars_to_fix.assignement_date__c
and (history.createddate <= lars_to_fix.end_relation_date__c or lars_to_fix.end_relation_date__c is null)
WHERE
lars_to_fix.id not in ('a0v3X00000f1e16QAA','a0v3X00000f1fyfQAA','a0v3X00000f3qJhQAI','a0v3X00000f3qJcQAI','a0v3X00000f3pwCQAQ','a0v3X00000f3pwHQAQ','a0v3X00000f3og7QAA','a0v3X00000f3ogHQAQ','a0v3X00000f4QmwQAE','a0v3X00000f4QmrQAE','a0v3X00000f4R3sQAE','a0v3X00000f4R3tQAE','a0v3X00000f4UwTQAU','a0v3X00000f4Uw7QAE','a0v3X00000f3ouJQAQ','a0v3X00000f3ouOQAQ','a0v3X00000f4UwGQAU','a0v3X00000f4UwHQAU','a0v3X00000f3ot6QAA','a0v3X00000f3otBQAQ','a0v3X00000f1kWlQAI','a0v3X00000f1kWoQAI','a0v3X00000f3o7SQAQ','a0v3X00000f3o7XQAQ','a0v3X00000f4PjiQAE','a0v3X00000f4PkFQAU','a0v3X00000f2okrQAA','a0v3X00000f2ooPQAQ','a0v3X00000f3qGEQAY','a0v3X00000f3qG9QAI','a0v3X00000f3qDtQAI','a0v3X00000f3qDyQAI','a0v3X00000f2pRaQAI','a0v3X00000f2pRQQAY','a0v3X00000f2ww9QAA','a0v3X00000f2wzSQAQ','a0v3X00000f4QXzQAM','a0v3X00000f4QXZQA2','a0v3X00000f4PlYQAU','a0v3X00000f4PlDQAU','a0v3X00000f4T3EQAU','a0v3X00000f4T3JQAU','a0v3X00000f4PLkQAM','a0v3X00000f4PLpQAM','a0v3X00000f2oWpQAI','a0v3X00000f2oWuQAI','a0v3X00000f2oWkQAI','a0v3X00000f2wNrQAI','a0v3X00000f2wIgQAI','a0v3X00000f3oNIQAY','a0v3X00000f3oREQAY','a0v3X00000f4PkBQAU','a0v3X00000f4PkdQAE','a0v3X00000f4TBRQA2','a0v3X00000f4TFoQAM','a0v3X00000f4PjcQAE','a0v3X00000f4PjTQAU','a0v3X00000f4PjLQAU','a0v3X00000f4PkQQAU','a0v3X00000f4OijQAE','a0v3X00000f4OioQAE','a0v3X00000f4PjfQAE','a0v3X00000f4PjxQAE','a0v3X00000f2ySYQAY','a0v3X00000f2yTMQAY','a0v3X00000f2ySdQAI','a0v3X00000f4QiiQAE','a0v3X00000f4QinQAE','a0v3X00000f2u0aQAA','a0v3X00000f2uDDQAY','a0v3X00000f4PbaQAE','a0v3X00000f4PbVQAU')
GROUP BY 1;
```
Then you'll notice that **there are still a few LARs without owners that have multiple owners in the associated account history** on the given assignment time frame. Once again, that should raise some eyebrows, like it id on the meeting of April, 14th.
We can even go a step further and execute this query 👇
```sql
-- @block Nb lars x Nb of owners
WITH lars_to_fix AS (
SELECT
id,
account__c,
assignement_date__c,
end_relation_date__c,
owner_relation__c
FROM data.staging_salesforce.batchaccountrelation__c
WHERE
NOT isdeleted
AND assignement_date__c IS NOT NULL
AND owner_relation__c IS NULL
),
history AS (
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string <> newvalue__string
and oldvalue__string not like '0053X%'
and newvalue__string <> 'Outbound Database'
and newvalue__string not like '%Reassignment%'
),
nb_owners AS (
SELECT
distinct lars_to_fix.id as lar_id,
count(*) nb_assignments
FROM lars_to_fix
JOIN history
on lars_to_fix.account__c = history.accountid
and history.createddate >= lars_to_fix.assignement_date__c
and (history.createddate <= lars_to_fix.end_relation_date__c or lars_to_fix.end_relation_date__c is null)
WHERE
lars_to_fix.id not in ('a0v3X00000f1e16QAA','a0v3X00000f1fyfQAA','a0v3X00000f3qJhQAI','a0v3X00000f3qJcQAI','a0v3X00000f3pwCQAQ','a0v3X00000f3pwHQAQ','a0v3X00000f3og7QAA','a0v3X00000f3ogHQAQ','a0v3X00000f4QmwQAE','a0v3X00000f4QmrQAE','a0v3X00000f4R3sQAE','a0v3X00000f4R3tQAE','a0v3X00000f4UwTQAU','a0v3X00000f4Uw7QAE','a0v3X00000f3ouJQAQ','a0v3X00000f3ouOQAQ','a0v3X00000f4UwGQAU','a0v3X00000f4UwHQAU','a0v3X00000f3ot6QAA','a0v3X00000f3otBQAQ','a0v3X00000f1kWlQAI','a0v3X00000f1kWoQAI','a0v3X00000f3o7SQAQ','a0v3X00000f3o7XQAQ','a0v3X00000f4PjiQAE','a0v3X00000f4PkFQAU','a0v3X00000f2okrQAA','a0v3X00000f2ooPQAQ','a0v3X00000f3qGEQAY','a0v3X00000f3qG9QAI','a0v3X00000f3qDtQAI','a0v3X00000f3qDyQAI','a0v3X00000f2pRaQAI','a0v3X00000f2pRQQAY','a0v3X00000f2ww9QAA','a0v3X00000f2wzSQAQ','a0v3X00000f4QXzQAM','a0v3X00000f4QXZQA2','a0v3X00000f4PlYQAU','a0v3X00000f4PlDQAU','a0v3X00000f4T3EQAU','a0v3X00000f4T3JQAU','a0v3X00000f4PLkQAM','a0v3X00000f4PLpQAM','a0v3X00000f2oWpQAI','a0v3X00000f2oWuQAI','a0v3X00000f2oWkQAI','a0v3X00000f2wNrQAI','a0v3X00000f2wIgQAI','a0v3X00000f3oNIQAY','a0v3X00000f3oREQAY','a0v3X00000f4PkBQAU','a0v3X00000f4PkdQAE','a0v3X00000f4TBRQA2','a0v3X00000f4TFoQAM','a0v3X00000f4PjcQAE','a0v3X00000f4PjTQAU','a0v3X00000f4PjLQAU','a0v3X00000f4PkQQAU','a0v3X00000f4OijQAE','a0v3X00000f4OioQAE','a0v3X00000f4PjfQAE','a0v3X00000f4PjxQAE','a0v3X00000f2ySYQAY','a0v3X00000f2yTMQAY','a0v3X00000f2ySdQAI','a0v3X00000f4QiiQAE','a0v3X00000f4QinQAE','a0v3X00000f2u0aQAA','a0v3X00000f2uDDQAY','a0v3X00000f4PbaQAE','a0v3X00000f4PbVQAU')
GROUP BY 1
)
SELECT
COUNT(nb_owners.lar_id),
SUM(case when nb_assignments = 1 then 1 else 0 end) nb_one_assignment,
SUM(case when nb_assignments = 2 then 1 else 0 end) nb_two_assignments,
SUM(case when nb_assignments = 3 then 1 else 0 end) nb_three_assignments,
SUM(case when nb_assignments > 3 then 1 else 0 end) nb_more_than_three_assignments
FROM nb_owners;
```
Among LARs that need a fix on their owner:
- We find a single owner on the time frame for **6323** of them,
- We find two owners on the time frame for **596** of them,
- We find a three owners on the time frame for **61** of them,
- And finally, we find more than three owners for **19** of them.
**That's not enough**
At this point, one should ask:
> Is there still something going on with end_relation_dates?
We were supposed to fix them with Lucas but I guess we'll have to double check (see this [this section](7.-Do-we-have-all-the-end-relation-dates-we-need?)).
### **6. Finding owners when no owner changes recorded**
Let's ignore the end_relation_date issue for the moment and move on to the last request of `lar_owners.sql` 👇
You'll note that LARs to fix (with no owner) with no history are all encompassed in the first temporary table:
```sql
-- @block Can we find missing owners in unfiltered account history when no owner changes recorded
WITH lars_to_fix AS (
SELECT
id,
account__c,
assignement_date__c,
end_relation_date__c,
owner_relation__c
FROM data.staging_salesforce.batchaccountrelation__c
WHERE
NOT isdeleted
AND assignement_date__c IS NOT NULL
AND owner_relation__c IS NULL
),
history1 AS (
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string <> newvalue__string
and oldvalue__string not like '0053X%'
and newvalue__string <> 'Outbound Database'
and newvalue__string not like '%Reassignment%'
),
lars_to_fix_no_history AS (
SELECT
lars_to_fix.id,
lars_to_fix.account__c,
lars_to_fix.owner_relation__c
FROM lars_to_fix
LEFT JOIN history1
on lars_to_fix.account__c = history1.accountid
WHERE history1.accountid is null
),
history2 AS (
SELECT
accountid,
createddate,
oldvalue__string,
newvalue__string
FROM staging_salesforce.accounthistory
WHERE
field = 'Owner'
and oldvalue__string not like '0053X%'
and oldvalue__string <> 'Outbound Database'
and oldvalue__string not like '%Reassignment%'
)
SELECT
count(distinct lars_to_fix_no_history.id)
FROM lars_to_fix_no_history
JOIN history2
ON lars_to_fix_no_history.account__c = history2.accountid
;
```
We find an owner for only 4 872 of the 9 516 remaining LARs. In an ideal world,
**that's not enough**
### 7. Do we have all the end relation dates we need?
It's time to roll back to the end_relation_date issue. Go to `end_relation_dates.sql` and its queries. First, we find 20 lars for which we found more than 2 owners in the accounthistory 👇
```sql
-- @block Find a few lar ids for which we discovered more than two owners.
WITH lars_to_fix AS (
...
SELECT
lar_id
FROM nb_owners
WHERE nb_assignments > 1
LIMIT 20;
```
Then we find the accounts associated to those specific lars 👇
```sql
-- @block find accounts associated to the dozen of lars above
SELECT
distinct account__c
FROM staging_salesforce.batchaccountrelation__c bc
WHERE bc.id in ('a0v3X00000f1eE3QAI','a0v3X00000f1jTsQAI','a0v3X00000f4UnBQAU','a0v3X00000f4WKxQAM','a0v3X00000f1kDoQAI','a0v3X00000f3q0YQAQ','a0v3X00000f4UlDQAU','a0v3X00000f4UuQQAU','a0v3X00000f4WLIQA2','a0v3X00000f29VAQAY','a0v3X00000f4UrMQAU','a0v3X00000f4UnVQAU','a0v3X00000f4UsFQAU','a0v3X00000gEwOtQAK','a0v3X00000f1jckQAA','a0v3X00000f1g0sQAA','a0v3X00000gExvqQAC','a0v3X00000f28HXQAY','a0v3X00000f4QfWQAU','a0v3X00000f4QfOQAU');
```
Finally - and that concludes our investigation - we find all the lars associated to one of the accounts found thanks to the query above 👇
```sql
-- @block end_relation_dates on lars associated to one of the accounts found above ('0013X00002wGVyCQAW')
SELECT
id,
account__c,
assignement_date__c,
end_relation_date__c,
owner_relation__c
FROM staging_salesforce.batchaccountrelation__c bc
WHERE
bc.account__c ='0013X00002wGVyCQAW'
ORDER BY assignement_date__c DESC;
```
👉 We find 4 LARs on this account ([also on Salesforce](https://payfit.lightning.force.com/lightning/r/Account/0013X00002wGVyCQAW/view?ws=%2Flightning%2Fr%2FBatchAccountRelation__c%2Fa0v3X00000f1eE3QAI%2Fview)) and most importantly, we find that the first LAR does not have an end relation date.
> Lucas and I did not manage to recover every end relation dates after all...
# Key findings
1. Among the 17 904 LARs to fix, only 8 388 of them have an account history ([cf. section 4](4.-Join-LARs-&-Account-History)) and among the remaining 9 516, only 4 872 have a first owner we can recover. That's 4.5K+ we can't account for.
2. Among the 8 388, some still don't have end relation dates when they should ([cf. previous section](6.-Do-we-have-all-the-end-relation-dates-we-need?))
# Final Results
1. Lucas and I recovered **all** end relation dates. There's a series of queries in `fix_end_relation_dates.sql` 👉 we proceeded on a few extra steps in GSheet that provides a better UI than mere sql requests. [Here's the document](https://docs.google.com/spreadsheets/d/1GJt3Q4QNuSGhMAPgw6mfu8Qq7b-W3NIvXdwKK1U19yk/edit#gid=150558237) with updated LARs' end relation dates.
2. Then, we fixed all LARs with recorded owner changes. Among the 8 388 in total, **we could fix only 6 451** because others still had multiple owner possibilities, even after the end relation date fix. The only query is the first one in `fix_owners.sql` and [here's the final document](https://docs.google.com/spreadsheets/d/1FJIPSPy-fnwKtHAAqse3GMzgGc5UspaxjBdIJShWr5c/edit#gid=61716283).
3. Afterwards, we fixed LARs with no recorded owner changes, just by taking the oldest value there was in the account history for an owner. The only query is the second one in `fix_owners.sql`. The final document is [here](https://docs.google.com/spreadsheets/d/1FJIPSPy-fnwKtHAAqse3GMzgGc5UspaxjBdIJShWr5c/edit#gid=898532762). As stated above, among the 9 516 LARs with no owner changes recorded, **we could only fix 4 872** of them.
4. Finally, we came up with a solution to exclude LARs to fix that could not be fixed from future dashboards. We forced the values of all these LARs to "LOST". The only query can be found in `mark_lost_lars.sql` and the final gsheet is [here](https://docs.google.com/spreadsheets/d/1zcL6iYQ1Uo1MECo4l3FLLfh9At0p27j44M9M7PjM5FA/edit#gid=0). It was easy to query these LARs, they were the only ones to fix that still didn't have an owner name, 24h after the last fix.
___
All in all, we've been able to fix owners on 6 451 + 4 872 = 11 323 LARs and we marked the 6 624 others for a total of 11 323 + 6 624 = 17 947 ~ 17 504 LARs to fix (originally). | 950e775f6d1eb029b83f3a25e18a98fab5727a88 | [
"Markdown",
"SQL"
]
| 6 | SQL | bastien-payfit/lars-fix | 6206e2fcb88efc02a273b8b15bf553b9a4d0d8aa | b3f33c266a299172128523dd0f384e03d0af36be |
refs/heads/master | <repo_name>Fromalaska49/parallax-star-background<file_sep>/matrix.php
<!DOCTYPE html>
<html>
<head>
<?php
require('common/head-includes.php');
?>
<title>
Test
</title>
<script type="text/javascript">
$(document).ready(function(){
var $contentHeight = $("#content").outerHeight(true) + "px";
$("#group1").css("height", $contentHeight);
$("#group1").css("overflow", "hidden");
$("#content").css("position", "relative");
$("#content").css("top", "-"+$contentHeight);
$("#page-overflow-border").css("height", $contentHeight);
});
</script>
<style type="text/css">
* { box-sizing: border-box; }
.video-background {
background: #000;
position: fixed;
top: 0; right: 0; bottom: 0; left: 0;
z-index: -99;
}
.video-foreground,
.video-background iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
#vidtop-content {
top: 0;
}
@media (min-aspect-ratio: 16/9) {
.video-foreground { height: 300%; top: -100%; }
}
@media (max-aspect-ratio: 16/9) {
.video-foreground { width: 300%; left: -100%; }
}
</style>
</head>
<body>
<?php
require('common/menu.php');
?>
<div id="page-container" style="background-color:;background:transparent;">
<div id="page-overflow-border">
<div class="video-background">
<div class="video-foreground">
<iframe src="https://www.youtube.com/embed/rpWrtXyEAN0?controls=0&showinfo=0&rel=0&autoplay=1&loop=1&playlist=W0LHTWG-UmQ" frameborder="0" allowfullscreen></iframe>
</div>
</div>
<div id="vidtop-content">
<div id="group1">
</div>
<div id="content" class="container" style="">
<div class="row" style="overflow-y:hidden;">
<div class="col-sm-12" style="overflow-x:visible;">
<div class="row section-container">
<div class="col-sm-12">
It’s official! Come join us at RowdyHacks as we build apps, games, and many other neat projects in 24 hours. Whether you’re a seasoned hacker or new to the hackathon community, we’ve got your back through the whole hacking experience.
<br />
If you aren’t familiar, a hackathon is where you turn your crazy ideas into real projects. Plenty of your fellow peers gather to build something they’re passionate about so get involved in making incredible things.
</div>
</div>
<div class="row section-container">
<div class="col-sm-12">
It’s official! Come join us at RowdyHacks as we build apps, games, and many other neat projects in 24 hours. Whether you’re a seasoned hacker or new to the hackathon community, we’ve got your back through the whole hacking experience.
<br />
If you aren’t familiar, a hackathon is where you turn your crazy ideas into real projects. Plenty of your fellow peers gather to build something they’re passionate about so get involved in making incredible things.
</div>
</div>
<div class="row section-container" id="home-page-cover-image">
<div class="col-sm-12">
</div>
</div>
<div class="row partial-section-container">
<div class="col-sm-12 col-md-4">
<div class="partial-section">
<h3>
<img src="images/icons/ic_event_black_48px.svg" class="partial-section-h-icon" />
</h3>
Market Events
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="partial-section">
<h3>
<img src="images/icons/ic_schedule_black_48px.svg" class="partial-section-h-icon" />
</h3>
Send Notifications
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="partial-section">
<h3>
<img src="images/icons/ic_room_black_48px.svg" class="partial-section-h-icon" />
</h3>
Collect Leads
</div>
</div>
</div>
</div>
</div>
<!--
<div class="row" id="earth-container">
<div class="col-sm-12" id="earth">
</div>
</div>
-->
</div>
</div>
</div>
</div>
<?php
require('common/footer.php');
?>
</body>
</html>
<file_sep>/confetti.php
<!DOCTYPE html>
<html>
<head>
<?php
require('common/head-includes.php');
?>
<title>
Test
</title>
<script type="text/javascript">
$(document).ready(function(){
var $contentHeight = $("#content").outerHeight(true) + "px";
$("#group1").css("height", $contentHeight);
$("#group1").css("overflow", "hidden");
$("#content").css("position", "relative");
$("#content").css("top", "-"+$contentHeight);
$("#page-overflow-border").css("height", $contentHeight);
});
</script>
</head>
<body>
<?php
require('common/menu.php');
?>
<div id="page-container" style="background-color:;background:transparent;">
<div id="page-overflow-border">
<div id="group1" style="background-color:#fff;">
<div class="star-layer-3">
<div id="star-layer-3">
<?php
$num_shapes = 250;
function get_style(){
$width = rand(50,250).'px';
$height = rand(100,400).'px';
$opacity = rand(4,8)/10.0;
$rotation = 'rotate('.rand(0,360).'deg)';
$color = 'hsl('.(220+rand(-50,50)).', '.rand(50,100).'%, '.rand(33,67).'%)';
$top = rand(-10,1010).'vh';
$left = rand(-10,110).'vw';
$style = '
position: absolute;
top: '.$top.';
left: '.$left.';
opacity: '.$opacity.';
transform: '.$rotation.';
width: '.$width.';
height: '.$height.';
background-color: '.$color.';
';
return $style;
}
for($i = 0; $i < $num_shapes*0.4; $i++){
echo('<div style="'.get_style().'"></div>');
}
?>
<!--
<div id="box-3-1"></div>
<div id="box-3-2"></div>
<div id="box-3-3"></div>
<div id="box-3-4"></div>
<div id="box-3-5"></div>
-->
</div>
</div>
<div class="star-layer-2">
<div id="star-layer-2">
<?php
for($i = 0; $i < $num_shapes*0.35; $i++){
echo('<div style="'.get_style().'"></div>');
}
?>
</div>
</div>
<div class="star-layer-1">
<div id="star-layer-1">
<?php
for($i = 0; $i < $num_shapes*0.25; $i++){
echo('<div style="'.get_style().'"></div>');
}
?>
</div>
</div>
</div>
<div id="content" class="container" style="">
<div class="row" style="overflow-y:hidden;">
<div class="col-sm-12" style="overflow-x:visible;">
<div class="row section-container">
<div class="col-sm-12">
It’s official! Come join us at RowdyHacks as we build apps, games, and many other neat projects in 24 hours. Whether you’re a seasoned hacker or new to the hackathon community, we’ve got your back through the whole hacking experience.
<br />
If you aren’t familiar, a hackathon is where you turn your crazy ideas into real projects. Plenty of your fellow peers gather to build something they’re passionate about so get involved in making incredible things.
</div>
</div>
<div class="row section-container">
<div class="col-sm-12">
It’s official! Come join us at RowdyHacks as we build apps, games, and many other neat projects in 24 hours. Whether you’re a seasoned hacker or new to the hackathon community, we’ve got your back through the whole hacking experience.
<br />
If you aren’t familiar, a hackathon is where you turn your crazy ideas into real projects. Plenty of your fellow peers gather to build something they’re passionate about so get involved in making incredible things.
</div>
</div>
<div class="row section-container" id="home-page-cover-image">
<div class="col-sm-12">
</div>
</div>
<div class="row partial-section-container">
<div class="col-sm-12 col-md-4">
<div class="partial-section">
<h3>
<img src="images/icons/ic_event_black_48px.svg" class="partial-section-h-icon" />
</h3>
Market Events
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="partial-section">
<h3>
<img src="images/icons/ic_schedule_black_48px.svg" class="partial-section-h-icon" />
</h3>
Send Notifications
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="partial-section">
<h3>
<img src="images/icons/ic_room_black_48px.svg" class="partial-section-h-icon" />
</h3>
Collect Leads
</div>
</div>
</div>
</div>
</div>
<!--
<div class="row" id="earth-container">
<div class="col-sm-12" id="earth">
</div>
</div>
-->
</div>
</div>
</div>
<?php
require('common/footer.php');
?>
</body>
</html>
<file_sep>/schedule.php
<!DOCTYPE html>
<html>
<head>
<?php
require('common/head-includes.php');
?>
<title>
Test
</title>
<style type="text/css">
.sponsor-logo {
display: block;
margin: 15px;
max-width: 80%;
}
</style>
</head>
<body>
<?php
require('common/menu.php');
?>
<div id="page-container" style="height:100vh;">
<div id="group1" style="">
<div class="star-layer-3">
<div id="star-layer-3">
</div>
</div>
<div class="star-layer-2">
<div id="star-layer-2">
</div>
</div>
<div class="star-layer-1">
<div id="star-layer-1">
</div>
</div>
</div>
<div id="content" class="container" style="">
<div class="row section-container">
<div class="col-sm-12">
<h1 style="margin:20px 30px 70px 30px;">
Schedule
</h1>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<p>
TBA
</p>
</div>
</div>
<div class="row" id="earth-container">
<div class="col-sm-12" id="earth">
</div>
</div>
</div>
</div>
<?php
require('common/footer.php');
?>
</body>
</html>
| 85c32366a40e983bbfb9d02d732008f12e56a18b | [
"PHP"
]
| 3 | PHP | Fromalaska49/parallax-star-background | ce24a36b333306dd17db778975c38135e0f25c53 | 4230e79b7ac9db53b99aeaf96aca8c1fd9a162b0 |
refs/heads/master | <repo_name>milesnardi/stockscreener<file_sep>/src/App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
class App extends Component {
constructor(props) {
super(props);
this.makerequest = this.makerequest.bind(this);
this.state = {
close: 'Click Submit!'
}
}
makerequest(){
var params = {
apikey: "5NO4O6TFSS7HI49J",
symbol: "MSFT",
function: "GLOBAL_QUOTE"
};
var axiosInstance = axios.create({
baseURL: "https://www.alphavantage.co/query",
params: params
});
// Start a spinner
axiosInstance.get().then (response => {
console.log(JSON.stringify(response.data["Global Quote"]["08. previous close"]));
this.setState({
close: JSON.stringify(response.data["Global Quote"]["08. previous close"])
})
// stop the spinner
})
}
render() {
var closeVariable = this.state.close
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Hello World.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
<button onClick={this.makerequest} >S u b m i t</button>
<p>MSFT: {closeVariable}</p>
</header>
</div>
);
}
}
export default App;
// Git instructions
// git add * --- Adds files youwant to commit
// git status --- check to see if all the files you want to commit is green
// git commit -m "YOUR MESSAGE HERE, what did you change" --- add message to your commit
// git push origin <branch> --- push to a particular branch. Master is the default
// git checkout -b <unique_branch_name> -- creates a new branch
// git branch --- see what branch you're in
// git config user.name "<username>"
// git config user.email "<git_email>"
//<ESC> :wq --- to quit terminal text editor(VIM) | 2667cbb90e27685a1554504abbf4b31cda07085a | [
"JavaScript"
]
| 1 | JavaScript | milesnardi/stockscreener | 0340006613ca15722f6335d6bfc55e34971b98b1 | a07f265b3b0caa3ce09e5f7344683b1da855b451 |
refs/heads/master | <repo_name>AndrejSperling/CycleComponentsTest<file_sep>/lib/AwesomeButton/index.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var xstream_1 = require("xstream");
var dom_1 = require("@cycle/dom");
function AwesomeButton(sources) {
var action$ = xstream_1.default.merge(sources.DOM.select('.dec').events('click').mapTo(-1), sources.DOM.select('.inc').events('click').mapTo(+1));
var count$ = action$.fold(function (x, y) { return x + y; }, 0);
var vdom$ = count$.map(function (count) {
return dom_1.div([
dom_1.button('.dec', 'Decrement'),
dom_1.button('.inc', 'Increment'),
dom_1.p('Counter: ' + count)
]);
});
return { DOM: vdom$ };
}
<file_sep>/src/AwesomeButton2/index.ts
import xs, {Stream} from "xstream";
import {button, div, DOMSource, p} from "@cycle/dom";
import {VNode} from "snabbdom/vnode";
export interface AwesomeButton2 {
(sources: Sources): Sinks
}
export interface Sources {
DOM: DOMSource
}
export interface Sinks {
DOM: Stream<VNode>
}
function AwesomeButton2(sources: Sources): Sinks {
const action$ = xs.merge(
sources.DOM.select('.dec').events('click').mapTo(-10),
sources.DOM.select('.inc').events('click').mapTo(+10)
);
const count$ = action$.fold((x, y) => x + y, 0);
const vdom$ = count$.map(count =>
div([
button('.dec', 'Decrement'),
button('.inc', 'Increment'),
p('Counter: ' + count)
])
);
return {DOM: vdom$}
}<file_sep>/src/index.ts
export {AwesomeButton} from "./AwesomeButton/index";
export {AwesomeButton2} from "./AwesomeButton2/index";
<file_sep>/lib/AwesomeButton/index.d.ts
import { Stream } from "xstream";
import { DOMSource } from "@cycle/dom";
import { VNode } from "snabbdom/vnode";
export interface AwesomeButton {
(sources: Sources): Sinks;
}
export interface Sources {
DOM: DOMSource;
}
export interface Sinks {
DOM: Stream<VNode>;
}
<file_sep>/lib/index.d.ts
export { AwesomeButton } from "./AwesomeButton/index";
export { AwesomeButton2 } from "./AwesomeButton2/index";
| 6d7f32f80aa752a4524df223f647362c56c8a54e | [
"JavaScript",
"TypeScript"
]
| 5 | JavaScript | AndrejSperling/CycleComponentsTest | cb4189749a79421ff931f5f4b369976ebb538c45 | 808768bdecd9c238e617a356a660ecd130939b16 |
refs/heads/master | <file_sep>class AddArchivalContainerFormatToRecord < ActiveRecord::Migration
def change
add_column :records, :archival_container_format_id, :integer
add_index :records, :archival_container_format_id
end
end
<file_sep>class AddSourceToRecord < ActiveRecord::Migration
def change
add_column :records, :source_id, :integer
add_index :records, :source_id
end
end
<file_sep>metadata_editor
===============
<file_sep>class Creator < ActiveRecord::Base
attr_accessible :name, :repository_id
has_and_belongs_to_many :records
belongs_to :repository
validates :name, uniqueness: { scope: :repository_id,
message: "should be unique for a repository"
}
end
<file_sep># Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
MetadataEditor::Application.initialize!
<file_sep>class Language < ActiveRecord::Base
attr_accessible :name, :name_fr, :alpha3_bib, :alpha3_term, :alpha2
has_and_belongs_to_many :records
end
<file_sep>class ChangeFieldTypeInRecord < ActiveRecord::Migration
def change
change_column :records, :creator, :string
change_column :records, :source, :string
end
end
<file_sep>MetadataEditor::Application.routes.draw do
devise_for :users
mount LcshSuggest::Engine, at: '/lcsh_suggest'
resources :creators
resources :repositories
resources :records
resources :sources
resources :members do
member do
put 'toggle_manager'
put 'toggle_activity'
end
end
resources :spatial_coverages
root :to => 'high_voltage/pages#show', id: 'home'
end
<file_sep>class Record < ActiveRecord::Base
attr_accessible :archival_container_format_id, :archival_container2_format_id, :archival_container3_format_id, :container_number_1, :container_number_2, :container_number_3, :creator_ids, :date, :description, :format_id, :kentucky_topic_ids, :language_ids, :publisher, :repository_id, :resource_type_id, :retention_date, :retention_id, :series_statement, :source_ids, :spatial_coverage_ids, :subject_ids, :subjects_used, :title
belongs_to :format
belongs_to :resource_type
has_and_belongs_to_many :languages
has_and_belongs_to_many :subjects
has_and_belongs_to_many :kentucky_topics
belongs_to :repository
belongs_to :retention
has_and_belongs_to_many :sources
has_and_belongs_to_many :spatial_coverages
has_and_belongs_to_many :creators
belongs_to :archival_container_format
belongs_to :archival_container2_format, foreign_key: 'archival_container2_format_id', class_name: 'ArchivalContainerFormat'
belongs_to :archival_container3_format, foreign_key: 'archival_container3_format_id', class_name: 'ArchivalContainerFormat'
validates :format_id, :language_ids, :resource_type_id, :title, presence: true
def subjects_used
self.subjects.map(&:name).join('::')
end
def subjects_used=(list)
self.subjects = list.split('::').collect do |item|
Subject.find_or_create_by_name(item)
end
end
end
<file_sep>class DropRecordsCreatorTable < ActiveRecord::Migration
def change
drop_table :records_creators
end
end
<file_sep>class AddRepositoryToSource < ActiveRecord::Migration
def change
add_column :sources, :repository_id, :integer
end
end
<file_sep>class AddContainerNumbersToRecords < ActiveRecord::Migration
def change
add_column :records, :container_number_1, :string
add_column :records, :container_number_2, :string
add_column :records, :container_number_3, :string
end
end
<file_sep>class CreateRecords < ActiveRecord::Migration
def change
create_table :records do |t|
t.text :abstract
t.date :date
t.string :department
t.string :depositor
t.string :depositor_email
t.string :email
t.string :phone
t.string :street_address
t.string :title
t.string :url
t.references :archival_container_format
t.references :file_format
t.references :format
t.references :kytopic
t.references :repository
t.references :type
t.timestamps
end
add_index :records, :archival_container_format_id
add_index :records, :file_format_id
add_index :records, :format_id
add_index :records, :kytopic_id
add_index :records, :repository_id
add_index :records, :type_id
end
end
<file_sep>class RemoveRightsFromRecord < ActiveRecord::Migration
def up
remove_column :records, :rights
end
def down
add_column :records, :rights, :text
end
end
<file_sep>class RenameTypeIndex < ActiveRecord::Migration
def change
rename_index :records, :index_records_on_type_id, :index_records_on_resource_type_id
end
end
<file_sep>class ArchivalContainerFormat < ActiveRecord::Base
attr_accessible :name
has_many :records
end
<file_sep>class KentuckyTopic < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :records
end
<file_sep>class RenameType < ActiveRecord::Migration
def change
rename_table :types, :resource_types
rename_column :records, :type_id, :resource_type_id
end
end
<file_sep>class CreateKentuckyTopicsRecordsTable < ActiveRecord::Migration
def change
create_table :kentucky_topics_records, :id=> false do |t|
t.references :kentucky_topic
t.references :record
end
add_index :kentucky_topics_records, [:kentucky_topic_id, :record_id]
add_index :kentucky_topics_records, :record_id
end
end
<file_sep>class AddFieldsToRecords < ActiveRecord::Migration
def change
add_column :records, :description, :string
add_column :records, :publisher, :string
add_column :records, :series_statement, :string
end
end
<file_sep>class Retention < ActiveRecord::Base
attr_accessible :name
has_many :records
def self.temporal
Retention.where(:name => 'temporal').first
end
end
<file_sep>class CreateLanguagesRecordsTable < ActiveRecord::Migration
def self.up
create_table :languages_records, :id => false do |t|
t.references :language
t.references :record
end
add_index :languages_records, [:language_id, :record_id]
add_index :languages_records, :record_id
end
def self.down
drop_table :languages_records
end
end
<file_sep>class DropKentuckyTopicsFromRecords < ActiveRecord::Migration
def up
remove_column :records, :kentucky_topic_id
end
def down
add_column :records, :kentucky_topic_id, :integer
add_index :records, :kentucky_topic_id
end
end
<file_sep>class CreateCreatorsRecordsTable < ActiveRecord::Migration
def self.up
create_table :creators_records, :id => false do |t|
t.references :record
t.references :creator
end
add_index :creators_records, [:record_id, :creator_id]
add_index :creators_records, :creator_id
end
def self.down
drop_table :creators_records
end
end
<file_sep>class SpatialCoveragesController < ApplicationController
# GET /spatial_coverages
# GET /spatial_covearages.json
def index
@spatial_coverages = SpatialCoverage.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @spatial_coverages }
end
end
# GET /spatial_coverages/1
# GET /spatial_coverages/1.json
def show
@spatial_coverage = SpatialCoverage.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @spatial_coverage }
end
end
# GET /spatial_coverages/new
# GET /spatial_coverages/new.json
def new
@spatial_coverage = SpatialCoverage.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @spatial_coverage}
end
end
# GET /spatial_coverages/1/edit
def edit
@spatial_coverage = SpatialCoverage.find(params[:id])
end
# POST /spatial_coverages
# POST /spatial_coverages.json
def create
@spatial_coverage = SpatialCoverage.new(params[:spatial_coverage])
respond_to do |format|
if @spatial_coverage.save
format.html { redirect_to @spatial_coverage, notice: 'Spatial Coverage was successfully created.' }
format.json { render json: @spatial_coverage, status: :created, location: @spatial_coverage }
else
format.html { render action: "new" }
format.json { render json: @spatial_coverage.errors, status: :unprocessable_entity }
end
end
end
# PUT /spatial_coverages/1
# PUT /spatial_coverages/1.json
def update
@spatial_coverage = SpatialCoverage.find(params[:id])
respond_to do |format|
if @spatial_coverage.update_attributes(params[:spatial_coverage])
format.html { redirect_to @spatial_coverage, notice: 'Spatial Coverage was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @spatial_coverage.errors, status: :unprocessable_entity }
end
end
end
# DELETE /spatial_coverages/1
# DELETE /spatial_coverages/1.json
def destroy
@spatial_coverages = SpatialCoverages.find(params[:id])
@spatial_coverages.destroy
respond_to do |format|
format.html { redirect_to spatial_coverage_url }
format.json { head :no_content }
end
end
end
<file_sep>class Repository < ActiveRecord::Base
attr_accessible :abstract, :email, :name, :phone, :rights, :street_address, :url
has_many :creators
has_many :records
has_many :sources
has_many :members
has_many :spatial_coverages
has_many :users, through: :members
after_initialize :add_default_values
def add_default_values
if self.new_record?
self.rights = RecordConfig[:rights]
end
end
end
<file_sep>class RemoveFieldFromRecord < ActiveRecord::Migration
def change
remove_column :records, :creator
end
end
<file_sep>#class DatePickerInput < SimpleForm::Inputs::StringInput
# def input
# value = input_html_options[:value]
# value ||= object.send(attribute_name) if object.respond_to? attribute_name
# input_html_options[:value] ||= I18n.localize(value) if value.present?
# input_html_classes << "date_picker"
#
# super
# end
#end
#module SimpleForm
# module Inputs
# class DatePickerInput < Base
# def input
# @builder.text_field(attribute_name, input_html_options)
# end
# end
# end
#end
class DatePickerInput < SimpleForm::Inputs::Base
def input
@builder.text_field(attribute_name, input_html_options)
end
end
<file_sep>class Subject < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :records
validates :name, uniqueness: true
end
<file_sep>class Member < ActiveRecord::Base
belongs_to :user
belongs_to :repository
attr_accessible :user_id, :repository_id, :manager
validates :repository_id, uniqueness: { scope: :user_id }
validates :user_id, uniqueness: { scope: :repository_id }
end
<file_sep>class AddPhoneToRepository < ActiveRecord::Migration
def change
add_column :repositories, :phone, :string
end
end
<file_sep>class ChangeRightsTypeInRecords < ActiveRecord::Migration
def self.up
change_column :records, :rights, :text
end
def self.down
change_column :records, :rights, :string
end
end
<file_sep>class DropArchivalContainer2FormatTable < ActiveRecord::Migration
def change
drop_table :archival_container2_formats
end
end
<file_sep>class MembersController < InheritedResources::Base
load_and_authorize_resource
before_filter :set_user, only: :create
def set_user
@member.user ||= current_user
unless can? :manage, Member
@member.user = current_user
end
end
def toggle_activity
if can? :toggle, Member
@member.toggle!(:active)
@member.save
redirect_to members_path
end
end
def toggle_manager
if can? :toggle, Member
@member.toggle!(:manager)
@member.save
redirect_to members_path
end
end
end
<file_sep>class RenameKytopic < ActiveRecord::Migration
def change
rename_table :kytopics, :kentucky_topics
rename_column :records, :kytopic_id, :kentucky_topic_id
rename_index :records, :index_records_on_kytopic_id, :index_records_on_kentucky_topic_id
end
end
<file_sep>class CreateMembers < ActiveRecord::Migration
def change
create_table :members, id: false do |t|
t.references :user
t.references :repository
t.boolean :manager
t.timestamps
end
add_index :members, [:repository_id, :user_id], :unique => true
add_index :members, :user_id
end
end
<file_sep>class CreateRecordsSpatialCoveragesTable < ActiveRecord::Migration
def self.up
create_table :records_spatial_coverages, :id => false do |t|
t.references :record
t.references :spatial_coverage
end
add_index :records_spatial_coverages, [:record_id, :spatial_coverage_id], :name => 'rsc_index'
add_index :records_spatial_coverages, :spatial_coverage_id
end
def self.down
drop_table :records_spatial_coverages
end
end
<file_sep>class AddArchivalContainer3FormatToRecord < ActiveRecord::Migration
def change
add_column :records, :archival_container3_format_id, :integer
add_index :records, :archival_container3_format_id
end
end
<file_sep>class AddTextfieldsToRecord < ActiveRecord::Migration
def change
add_column :records, :creator, :text, :limit => 255
add_column :records, :source, :text, :limit => 255
end
end
<file_sep>class AddFieldsToRepository < ActiveRecord::Migration
def change
add_column :repositories, :abstract, :text
add_column :repositories, :street_address, :string
add_column :repositories, :email, :string
add_column :repositories, :url, :string
end
end
<file_sep>class CreateRecordsCreatorTable < ActiveRecord::Migration
def self.up
create_table :records_creators, :id => false do |t|
t.references :record
t.references :creator
end
add_index :records_creators, [:record_id, :creator_id]
add_index :records_creators, :creator_id
end
def self.down
drop_table :records_creators
end
end
<file_sep>FIXTURES = File.join 'db', 'fixtures'
class Seed
def initialize(options)
@symbol = options[:symbol]
@file = File.join FIXTURES, "#{@symbol.to_s.pluralize}.xml"
@query = options[:query] || '//xs:enumeration'
@model = @symbol.to_s.camelcase.constantize
@field = options[:field] || 'value'
end
def plant
Nokogiri::XML(IO.read @file).
xpath(@query).each do |node|
@model.find_or_create_by_name(node[@field])
end
end
end
[
:archival_container_format,
:format,
:kentucky_topic,
:repository, # TODO give repository its own seed method
:resource_type,
].each do |symbol|
seed = Seed.new :symbol => symbol
seed.plant
end
file = File.join FIXTURES, 'ISO-639-2_utf-8.txt'
IO.readlines(file).each do |line|
line.strip!
alpha3_bib,
alpha3_term,
alpha2,
english,
french = line.split('|')
Language.where(
name: english,
name_fr: french,
alpha3_bib: alpha3_bib,
alpha3_term: alpha3_term,
alpha2: alpha2
).first_or_create
end
[
'preservation',
'temporal',
].each do |name|
Retention.where(
name: name
).first_or_create
end
[ '38.031912, -84.495327',
'39.103215, -84.511828',
].each do |spatial_coverage|
SpatialCoverage.find_or_create_by_name(spatial_coverage)
end
[ 'University of Kentucky',
'University of Louisville',
].each do |creator|
Creator.find_or_create_by_name(creator)
end
[ 'University of Kentucky',
'University of Louisville',
].each do |source|
Source.find_or_create_by_name(source)
end
<file_sep>class RemoveSourceFromRecord < ActiveRecord::Migration
def up
remove_column :records, :source
end
def down
add_column :records, :source, :string
end
end
<file_sep>class DropFileFormat < ActiveRecord::Migration
def up
drop_table :file_formats
remove_column :records, :file_format_id
end
def down
create_table :file_formats do |t|
t.string :name
t.timestamps
end
add_column :records, :file_format_id, :integer
add_index :records, :file_format_id
end
end
<file_sep>class AddRetentionToRecord < ActiveRecord::Migration
def change
add_column :records, :retention_id, :integer
add_index :records, :retention_id
add_column :records, :retention_date, :date, :default => '0000-00-00'
end
end
<file_sep>class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :lockable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
attr_accessible :roles
has_many :members
has_many :repositories, through: :members
has_many :active_repositories, through: :members,
class_name: "Repository",
source: :repository,
conditions: ['members.active = ?', true]
has_many :manageable_repositories, through: :members,
class_name: "Repository",
source: :repository,
conditions: ['members.manager = ?', true]
has_many :records, through: :active_repositories
ROLES = [:admin, :site_manager]
def roles=(roles)
self.roles_mask = (roles.map(&:to_sym) & ROLES).map {|r| 2**ROLES.index(r)}.sum
end
def roles
ROLES.reject {|r| ((roles_mask || 0) & 2**ROLES.index(r)).zero?}
end
def role_symbols
roles.map(&:to_sym)
end
def is?(role)
roles.include? role
end
def to_s
email
end
end
<file_sep>class AddArchivalContainer2FormatToRecord < ActiveRecord::Migration
def change
add_column :records, :archival_container2_format_id, :integer
add_index :records, :archival_container2_format_id
end
end
<file_sep>class RecordsController < InheritedResources::Base
load_and_authorize_resource
end
<file_sep>class AddRightsToRepository < ActiveRecord::Migration
def change
add_column :repositories, :rights, :text
end
end
<file_sep>class AddDefaultForManagerInMember < ActiveRecord::Migration
def change
change_column_default :members, :manager, false
end
end
<file_sep>class RemovePhoneFromRecord < ActiveRecord::Migration
def up
remove_column :records, :phone
end
def down
add_column :records, :phone, :string
end
end
<file_sep>class AddCreatorToRecord < ActiveRecord::Migration
def change
add_column :records, :creator_id, :integer
add_index :records, :creator_id
end
end
<file_sep>class CreateRecordsSourcesTable < ActiveRecord::Migration
def self.up
create_table :records_sources, :id => false do |t|
t.references :record
t.references :source
end
add_index :records_sources, [:record_id, :source_id]
add_index :records_sources, :source_id
end
def self.down
drop_table :records_sources
end
end
<file_sep>require "bundler/capistrano"
# These settings will change from app to app.
set :application, "metadata_editor"
set :repository, "git://github.com/uklibraries/metadata_editor.git"
# These settings might need to be extracted from this file.
server "nyx.uky.edu", :app, :web, :db, :primary => true
set :deploy_to, "/opt/pdp/services/apps/rack/#{application}"
set :asset_env, "#{asset_env} RAILS_RELATIVE_URL_ROOT=/#{application}"
set :default_environment, {
'PATH' => "/usr/local/rbenv/shims:/usr/local/rbenv/bin:$PATH"
}
# You should not need to change anything below this line.
set :bundle_flags, "--deployment --without development test"
set :scm, :git
set :user, "deploy"
set :use_sudo, false
ssh_options[:forward_agent] = true
default_run_options[:pty] = true
set :deploy_via, :remote_cache
after 'deploy:update_code', 'deploy:migrate'
after 'deploy:migrate', 'deploy:seed'
set :keep_releases, 5
after "deploy:restart", "deploy:cleanup"
namespace :deploy do
task :start do ; end
task :stop do ; end
task :restart, :roles => :app, :except => { :no_release => true } do
run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
end
task :seed do
run "cd #{release_path} && bundle exec rake db:seed RAILS_ENV=#{rails_env}"
end
end
before "deploy:assets:precompile" do
run [
"ln -nfs #{shared_path}/config/database.yml #{release_path}/config/database.yml",
"ln -nfs #{shared_path}/config/initializers/devise.rb #{release_path}/config/initializers/devise.rb",
"rm #{release_path}/config/initializers/secret_token.rb",
"ln -nfs #{shared_path}/config/initializers/secret_token.rb #{release_path}/config/initializers/secret_token.rb",
].join(" && ")
end
<file_sep>class DropArchivalContainer3FormatTable < ActiveRecord::Migration
def change
drop_table :archival_container3_formats
end
end
<file_sep>class CreateLanguages < ActiveRecord::Migration
def change
create_table :languages do |t|
t.string :name
t.string :name_fr
t.string :alpha2
t.string :alpha3_bib
t.string :alpha3_term
t.timestamps
end
end
end
<file_sep>class RemoveFieldsFromRecord < ActiveRecord::Migration
def up
remove_column :records, :abstract
remove_column :records, :department
remove_column :records, :street_address
remove_column :records, :email
remove_column :records, :url
remove_column :records, :depositor
remove_column :records, :depositor_email
end
def down
add_column :records, :depositor_email, :string
add_column :records, :depositor, :string
add_column :records, :url, :string
add_column :records, :email, :string
add_column :records, :street_address, :string
add_column :records, :department, :string
add_column :records, :abstract, :text
end
end
| 05938882a192f7683c8c4df02e21def2ccf71396 | [
"Markdown",
"Ruby"
]
| 57 | Ruby | uklibraries/metadata_editor | a3f20f809adc6fae067d853ee7a7e6d888940627 | 9c626706df7e528f6086b4ae57d3a22324d0c4e0 |
refs/heads/master | <file_sep># import libraries here
import numpy as bb8
import handle_data as hd
import handle_image as hi
import neural_network as nn
import cv2
def train_or_load_character_recognition_model(train_image_paths, serialization_folder):
"""
Procedura prima putanje do fotografija za obucavanje (dataset se sastoji iz razlicitih fotografija alfabeta), kao i
putanju do foldera u koji treba sacuvati model nakon sto se istrenira (da ne trenirate svaki put iznova)
Procedura treba da istrenira model i da ga sacuva u folder "serialization_folder" pod proizvoljnim nazivom
Kada se procedura pozove, ona treba da trenira model ako on nije istraniran, ili da ga samo ucita ako je prethodno
istreniran i ako se nalazi u folderu za serijalizaciju
:param train_image_paths: putanje do fotografija alfabeta
:param serialization_folder: folder u koji treba sacuvati serijalizovani model
:return: Objekat modela
"""
# TODO - Istrenirati model ako vec nije istreniran, ili ga samo ucitati iz foldera za serijalizaciju
prepared_letters = hi.get_letters_train(train_image_paths[0])
x_train = hd.prepare_data_for_network(prepared_letters)
y_train = hd.convert_output()
model = nn.load_trained_model(serialization_folder)
if model is None:
model = nn.train_model(x_train, y_train, serialization_folder)
return model
def extract_text_from_image(trained_model, image_path, vocabulary):
"""
Procedura prima objekat istreniranog modela za prepoznavanje znakova (karaktera), putanju do fotografije na kojoj
se nalazi tekst za ekstrakciju i recnik svih poznatih reci koje se mogu naci na fotografiji.
Procedura treba da ucita fotografiju sa prosledjene putanje, i da sa nje izvuce sav tekst koriscenjem
openCV (detekcija karaktera) i prethodno istreniranog modela (prepoznavanje karaktera), i da vrati procitani tekst
kao string.
Ova procedura se poziva automatski iz main procedure pa nema potrebe dodavati njen poziv u main.py
:param trained_model: <Model> Istrenirani model za prepoznavanje karaktera
:param image_path: <String> Putanja do fotografije sa koje treba procitati tekst.
:param vocabulary: <Dict> Recnik SVIH poznatih reci i ucestalost njihovog pojavljivanja u tekstu
:return: <String> Tekst procitan sa ulazne slike
"""
# TODO - Izvuci tekst sa ulazne fotografije i vratiti ga kao string
letters, k_means = hi.get_letters_k_means_test(image_path)
inputs = hd.prepare_data_for_network(letters)
result = trained_model.predict(bb8.array(inputs, bb8.float32))
if k_means is not None:
text = hd.display_result(result, k_means)
else:
text="Error in šegmentation"
extracted = hd.do_fuzzywuzzy_stuff(vocabulary,text)
print(extracted)
return extracted
<file_sep>import numpy as bb8
from keras.layers.core import Dense
from keras.models import Sequential
from keras.models import model_from_json
from keras.optimizers import SGD
def train_model(x_train, y_train, serialization_folder):
trained_model = None
neural_network = create_network()
trained_model = train_network(neural_network, x_train, y_train)
serialize_ann(trained_model, serialization_folder)
return trained_model
def serialize_ann(nn, serialization_folder):
print("Saving network...")
model_json = nn.to_json()
with open(serialization_folder + "/neuronska.json", "w") as json_file:
json_file.write(model_json)
nn.save_weights(serialization_folder + "/neuronska.h5")
print("Network saved successfully!")
def train_network(neural_network, x_train, y_train):
print("Training network...")
x_train = bb8.array(x_train, bb8.float32)
y_train = bb8.array(y_train, bb8.float32)
sgd = SGD(lr=0.01, momentum=0.9)
neural_network.compile(loss='categorical_crossentropy', optimizer=sgd)
neural_network.fit(x_train, y_train, epochs=6000, batch_size=1, verbose=1, shuffle=False)
print("Network trained successfully!")
return neural_network
def create_network():
print("Creating network...")
neural_network = Sequential()
neural_network.add(Dense(128, input_dim=784, activation='sigmoid'))
neural_network.add(Dense(60, activation='sigmoid'))
print("Network created successfully!")
return neural_network
def load_trained_model(serialization_folder):
try:
print("Loading trained model....")
json_file = open(serialization_folder + "/neuronska.json", 'r')
loaded_model_json = json_file.read()
json_file.close()
network = model_from_json(loaded_model_json)
network.load_weights(serialization_folder + "/neuronska.h5")
print("Trained model found successfully!")
return network
except Exception as e:
print("Warning: No model found!")
return None
<file_sep>import cv2
import matplotlib.pyplot as plt
import image_operations as iop
def select_roi(image_orig, img_bin):
a = 255 - img_bin
img, contours, hierarchy = cv2.findContours(a.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (255, 0, 0), 1)
plt.imshow(img, 'gray')
plt.show()
regions_array = []
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
area = cv2.contourArea(contour)
if area > 100:
region = img_bin[y:y + h + 1, x:x + w + 1]
regions_array.append([iop.resize_region(region), (x, y, w, h)])
regions_array = sorted(regions_array, key=lambda item: item[1][0])
sorted_regions = [region[0] for region in regions_array]
sorted_rectangles = [region[1] for region in regions_array]
try:
new_sorted_rectangles = deal_with_hooks_rectangles(sorted_regions, sorted_rectangles)
except Exception as e:
new_sorted_rectangles = sorted_rectangles
new_sorted_regions = []
img_before_hooks = image_orig.copy()
for rectangle in sorted_rectangles:
cv2.rectangle(img_before_hooks, (rectangle[0], rectangle[1]),
(rectangle[0] + rectangle[2], rectangle[1] + rectangle[3]), (0, 255, 0), 2)
cv2.imwrite('hukovi.png', img_before_hooks)
for rectangle in new_sorted_rectangles:
region = img_bin[rectangle[1]:rectangle[1] + rectangle[3] + 2, rectangle[0]:rectangle[0] + rectangle[2] + 2]
new_sorted_regions.append(iop.resize_region(region))
cv2.rectangle(image_orig, (rectangle[0], rectangle[1]),
(rectangle[0] + rectangle[2], rectangle[1] + rectangle[3]), (0, 255, 0), 2)
region_distances = []
for i in range(0, len(new_sorted_rectangles) - 1):
current = new_sorted_rectangles[i]
next_rect = new_sorted_rectangles[i + 1]
distance = next_rect[0] - (current[0] + current[2])
region_distances.append(distance)
# plt.imshow(image_orig)
# plt.show()
cv2.imwrite('rects.png', image_orig)
print("asda:", len(new_sorted_rectangles))
return image_orig, new_sorted_regions, region_distances, new_sorted_rectangles
def deal_with_hooks_rectangles(sorted_regions, sorted_rectangles):
new_sorted_rectangles = sorted_rectangles.copy()
rectangles_2b_removed = []
for i in range(0, len(sorted_rectangles) - 1):
current = sorted_rectangles[i]
next_rect = sorted_rectangles[i + 1]
if isHook(current[0], next_rect[0], current[2], next_rect[2]):
rectangles_2b_removed.append(next_rect)
new_rect = (current[0], next_rect[1], current[2], current[3] + next_rect[3] + 5)
new_sorted_rectangles[i] = new_rect
if len(rectangles_2b_removed) > 0:
for rect in rectangles_2b_removed:
new_sorted_rectangles.remove(rect)
return new_sorted_rectangles
def isHook(x0, x1, w0, w1):
return x0 < x1 and x0 + w0 + 5 > x1 + w1
<file_sep>import cv2
import matplotlib.pylab as plt
import numpy as bb8
def brightness_up(img):
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
lim = 255 - 30
v[v > lim] = 255
v[v <= lim] += 30
final_hsv = cv2.merge((h, s, v))
img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
return img
def resize_region(region):
return cv2.resize(region, (28, 28), interpolation=cv2.INTER_NEAREST)
def resize_photo(img):
old_height = img.shape[0]
old_width = img.shape[1]
#print(old_width, old_height)
aspectRatio = (old_height / old_width)
#print(aspectRatio)
scale_percent = 150
newWidth = int(img.shape[1] * scale_percent / 100)
newHeight = int(img.shape[0] * scale_percent / 100)
#newHeight = (new_width * aspectRatio)
#newWidth = (new_width / aspectRatio)
resized_img = cv2.resize(img, (int(newWidth), int(newHeight)), interpolation=cv2.INTER_NEAREST)
return resized_img
def select_roi_separation(image_orig, img_bin):
a = 255-img_bin
img, contours, hierarchy = cv2.findContours(a.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (255, 0, 0), 1)
plt.imshow(img,'gray')
plt.show()
regions_array = []
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
area = cv2.contourArea(contour)
if area >= 100:
region = img_bin[y:y + h + 1, x:x + w + 1]
regions_array.append([resize_region(region), (x, y, w, h)])
regions_array = sorted(regions_array, key=lambda item: item[1][0])
sorted_regions = [region[0] for region in regions_array]
sorted_rectangles = [region[1] for region in regions_array]
try:
new_sorted_rectangles = deal_with_hooks_rectangles(sorted_regions, sorted_rectangles)
except Exception as e:
new_sorted_rectangles = sorted_rectangles
new_sorted_regions = []
img_before_hooks = image_orig.copy()
for rectangle in sorted_rectangles:
cv2.rectangle(img_before_hooks, (rectangle[0], rectangle[1]),
(rectangle[0] + rectangle[2], rectangle[1] + rectangle[3]), (0, 255, 0), 2)
cv2.imwrite('hukovi.png', img_before_hooks)
for rectangle in new_sorted_rectangles:
region = img_bin[rectangle[1]:rectangle[1] + rectangle[3] + 2, rectangle[0]:rectangle[0] + rectangle[2] + 2]
new_sorted_regions.append(resize_region(region))
cv2.rectangle(image_orig, (rectangle[0], rectangle[1]),
(rectangle[0] + rectangle[2], rectangle[1] + rectangle[3]), (0, 255, 0), 3)
region_distances = []
for i in range(0, len(new_sorted_rectangles) - 1):
current = new_sorted_rectangles[i]
next_rect = new_sorted_rectangles[i + 1]
distance = next_rect[0] - (current[0] + current[2])
region_distances.append(distance)
# plt.imshow(image_orig)
# plt.show()
cv2.imwrite('rects.png', image_orig)
print("asda:", len(new_sorted_rectangles))
return image_orig, new_sorted_regions, region_distances, new_sorted_rectangles
def deal_with_hooks_rectangles(sorted_regions, sorted_rectangles):
new_sorted_rectangles = sorted_rectangles.copy()
rectangles_2b_removed = []
for i in range(0, len(sorted_rectangles) - 1):
current = sorted_rectangles[i]
next_rect = sorted_rectangles[i + 1]
if isHook(current[0], next_rect[0], current[2], next_rect[2]):
rectangles_2b_removed.append(next_rect)
new_rect = (current[0], next_rect[1], current[2], current[3] + next_rect[3] + 5)
new_sorted_rectangles[i] = new_rect
if len(rectangles_2b_removed) > 0:
for rect in rectangles_2b_removed:
new_sorted_rectangles.remove(rect)
return new_sorted_rectangles
def isHook(x0, x1, w0, w1):
return x0 < x1 and x0 + w0 + 3 > x1 + w1
def contrastLAB(img):
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(lab)
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
cl = clahe.apply(l)
limg = cv2.merge((cl,a,b))
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
return final
def detect_rotation_and_rotate_separation_water(img_bin, img):
a = 255 - img_bin
coords = bb8.column_stack(bb8.where(a> 0))
angle = cv2.minAreaRect(coords)[-1]
#print(angle)
# the `cv2.minAreaRect` function returns values in the
# range [-90, 0); as the rectangle rotates clockwise the
# returned angle trends to 0 -- in this special case we
# need to add 90 degrees to the angle
if angle < -45:
angle = -(90 + angle)
# otherwise, just take the inverse of the angle to make
# it positive
else:
angle = -angle
#image = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR)
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated_bgr = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
#print(angle)
#plt.imshow(rotated_bgr)
#plt.show()
return rotated_bgr
def separate_water(img_bgr):
img = contrastLAB(img_bgr)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#
# plt.imshow(img_rgb)
# plt.show()
img_hsv = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2HSV)
lower_blue = bb8.array([110, 50, 50])
upper_blue = bb8.array([130, 255, 255])
mask = cv2.inRange(img_hsv, lower_blue, upper_blue)
blue_lower = bb8.array([70, 10, 20])
blue_upper = bb8.array([110, 255, 255])
blue_mask = cv2.inRange(img_hsv, blue_lower, blue_upper)
blue_mask = 255 - blue_mask
# plt.imshow(blue_mask, 'gray')
# plt.show()
res = cv2.bitwise_and(img_rgb, img_rgb, mask=blue_mask)
plt.imshow(res)
plt.show()
s = 1 - cv2.cvtColor(res, cv2.COLOR_RGB2GRAY)
# plt.imshow(s, 'gray')
# plt.show()
ret, thresh = cv2.threshold(s, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# plt.imshow(thresh, 'gray')
# plt.show()
return thresh
def get_letters_and_distances_water(path):
img_bgr = cv2.imread(path)
img_bgr = brightness_up(img_bgr)
img_bgr = resize_photo(img_bgr)
img_bin_before_rotation = separate_water(img_bgr)
img_bgr_rotated = detect_rotation_and_rotate_separation_water(img_bin_before_rotation,img_bgr)
img_rgb_rotated = cv2.cvtColor(img_bgr_rotated,cv2.COLOR_BGR2RGB)
img_bin_after_rotation = separate_water(img_bgr_rotated)
image_orig, letters, region_distances, new_sorted_rectangles = select_roi_separation(img_rgb_rotated, img_bin_after_rotation)
return letters, region_distances
<file_sep>import cv2
import matplotlib.pyplot as plt
import numpy as bb8
from sklearn.cluster import KMeans
import deal_with_water as dww
import deal_with_bricks as dwb
import image_operations as iop
import roi_handler as roi
def morhpological_operations(img_bin):
# img = bb8.uint8(img_bin)
img = img_bin
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
kernel_e = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
kernel_c = cv2.getStructuringElement(cv2.MORPH_CROSS, (4, 4))
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
erosion = cv2.erode(closing, kernel_e, iterations=4)
dilation = cv2.dilate(erosion, kernel_c, iterations=2)
# dilation = cv2.erode(dilation,kernel_c,iterations = 2)
# img = erosion
return dilation
def select_roi(image_orig, img_bin):
img, contours, hierarchy = cv2.findContours(img_bin.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
regions_array = []
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
area = cv2.contourArea(contour)
if area > 100:
region = img_bin[y:y + h + 1, x:x + w + 1]
regions_array.append([resize_region(region), (x, y, w, h)])
regions_array = sorted(regions_array, key=lambda item: item[1][0])
sorted_regions = [region[0] for region in regions_array]
sorted_rectangles = [region[1] for region in regions_array]
try:
new_sorted_rectangles = deal_with_hooks_rectangles(sorted_regions, sorted_rectangles)
except Exception as e:
new_sorted_rectangles = sorted_rectangles
new_sorted_regions = []
img_before_hooks = image_orig.copy()
for rectangle in sorted_rectangles:
cv2.rectangle(img_before_hooks, (rectangle[0], rectangle[1]),
(rectangle[0] + rectangle[2], rectangle[1] + rectangle[3]), (0, 255, 0), 2)
cv2.imwrite('hukovi.png', img_before_hooks)
for rectangle in new_sorted_rectangles:
region = img_bin[rectangle[1]:rectangle[1] + rectangle[3] + 2, rectangle[0]:rectangle[0] + rectangle[2] + 2]
new_sorted_regions.append(resize_region(region))
cv2.rectangle(image_orig, (rectangle[0], rectangle[1]),
(rectangle[0] + rectangle[2], rectangle[1] + rectangle[3]), (0, 255, 0), 2)
region_distances = []
for i in range(0, len(new_sorted_rectangles) - 1):
current = new_sorted_rectangles[i]
next_rect = new_sorted_rectangles[i + 1]
distance = next_rect[0] - (current[0] + current[2])
region_distances.append(distance)
# plt.imshow(image_orig)
# plt.show()
return image_orig, new_sorted_regions, region_distances, new_sorted_rectangles
def deal_with_hooks_rectangles(sorted_regions, sorted_rectangles):
new_sorted_rectangles = sorted_rectangles.copy()
rectangles_2b_removed = []
for i in range(0, len(sorted_rectangles) - 1):
current = sorted_rectangles[i]
next_rect = sorted_rectangles[i + 1]
if isHook(current[0], next_rect[0], current[2], next_rect[2]):
rectangles_2b_removed.append(next_rect)
new_rect = (current[0], next_rect[1], current[2], current[3] + next_rect[3] + 5)
new_sorted_rectangles[i] = new_rect
if len(rectangles_2b_removed) > 0:
for rect in rectangles_2b_removed:
new_sorted_rectangles.remove(rect)
return new_sorted_rectangles
def isHook(x0, x1, w0, w1):
return x0 < x1 and x0 + w0 + 3 > x1 + w1
def split2hsv(img):
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(img_hsv)
return h, s, v
# code for brightness taken from https://stackoverflow.com/questions/32609098/how-to-fast-change-image-brightness-with-python-opencv
def brightness_up(img):
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
lim = 255 - 30
v[v > lim] = 255
v[v <= lim] += 30
final_hsv = cv2.merge((h, s, v))
img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
return img
# code for contrast enhancement taken from https://stackoverflow.com/questions/39308030/how-do-i-increase-the-contrast-of-an-image-in-python-opencv
def contrastLab(img):
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(lab)
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
cl = clahe.apply(l)
limg = cv2.merge((cl, a, b))
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
return final
def make_bin_and_rgb(img):
img_contrast = contrastLab(img)
img_rgb = img_contrast.copy()
img_rgb = cv2.cvtColor(img_contrast, cv2.COLOR_BGR2RGB)
s_channel = split2hsv(img_contrast)[1]
img_enhanced_s_channel = cv2.equalizeHist(255 - s_channel)
# plt.imshow(img_enhanced_s_channel, 'gray')
# plt.show()
img_bin = img_gs2bin(img_enhanced_s_channel)
# plt.imshow(img_bin, 'gray')
# plt.show()
return img_bin, img_rgb
def prepare_img_for_roi(img):
img_bin = make_bin_and_rgb(img)[0]
img_prepared = morhpological_operations(img_bin)
return img_prepared
# code for detecting skew taken from: https://www.pyimagesearch.com/2017/02/20/text-skew-correction-opencv-python/
def detect_rotation_and_rotate(img):
thresh = prepare_img_for_roi(img)
coords = bb8.column_stack(bb8.where(thresh > 0))
angle = cv2.minAreaRect(coords)[-1]
#print(angle)
# the `cv2.minAreaRect` function returns values in the
# range [-90, 0); as the rectangle rotates clockwise the
# returned angle trends to 0 -- in this special case we
# need to add 90 degrees to the angle
if angle < -45:
angle = -(90 + angle)
# otherwise, just take the inverse of the angle to make
# it positive
else:
angle = -angle
#image = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR)
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated_bgr = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
#print(angle)
#plt.imshow(rotated_bgr)
#plt.show()
return rotated_bgr
def prepare_train(paths):
img_stacked = stack_photos(paths)
# img_stacked = stack_photos(path)
plt.imshow(img_stacked)
plt.show()
img_bin, img_rgb = make_bin_and_rgb(img_stacked)
img_prepared = prepare_img_for_roi(img_stacked)
selected_regions, letters, region_distances, new_sorted_rectangles = select_roi(img_rgb.copy(), img_prepared)
plt.imshow(selected_regions)
plt.show()
cv2.imwrite('training.png',selected_regions)
return letters
# code for most dominant color taken from: https://stackoverflow.com/questions/50899692/most-dominant-color-in-rgb-image-opencv-numpy-python
def get_most_dominant_color(a):
a2D = a.reshape(-1, a.shape[-1])
col_range = (256, 256, 256)
a1D = bb8.ravel_multi_index(a2D.T, col_range)
return bb8.unravel_index(bb8.bincount(a1D).argmax(), col_range)
def get_highest_peak(peaks,bins):
max_peak = max(list(peaks))
max_bin = 0
for i in range(len(bins)):
if peaks[i]==max_peak:
max_bin = i
return [max(list(peaks)),max_bin]
return [max(list(peaks)),max(list(bins))]
# histogram explained: https://numpy.org/doc/stable/reference/generated/numpy.histogram.html
# opencv: https://docs.opencv.org/master/d1/db7/tutorial_py_histogram_begins.html
def histogram_img(img_rgb):
max_peaks = []
for i in range(0,3):
value_array = img_rgb.mean(axis=i).flatten()
hist, bin_edges = bb8.histogram(value_array, range(257))
bin_edges=bin_edges[1:]
max_peaks.append(get_highest_peak(hist,bin_edges))
print("Hist")
print(hist)
print("Bin_edges")
print(bin_edges)
bin_edges=bin_edges[1:]
#print(bin_edges)
#peaks, _ = find_peaks(hist)
print("Peaks")
print(max_peaks)
print("-------------------------------------------")
#plt.plot(bin_edges[peaks], hist[peaks], ls='dotted')
#plt.show()
#peaks.append(find_peaks(hist, bin_edges))
#print(peaks)
print(get_most_dominant_color(img_rgb))
return max_peaks
def prepare_test(path):
img = cv2.imread(path)
img = brightness_up(img)
#print("h ",img.shape[0]," i w ",img.shape[1])
img = resize_photo(img)
# plt.imshow(img)
# plt.show()
img_rotated_bgr = detect_rotation_and_rotate(img)
img_prepared_rotated = prepare_img_for_roi(img_rotated_bgr)
img_orig, letters, region_distances, new_sorted_rectangles = select_roi(img_rotated_bgr.copy(), img_prepared_rotated)
distances = bb8.array(region_distances).reshape(len(region_distances), 1)
k_means = KMeans(n_clusters=2, max_iter=2000, tol=0.00001, n_init=10)
k_means.fit(distances)
# plt.imshow(img_orig)
# plt.show()
print(len(letters))
return letters, k_means
def prepare_test_rotation(path):
img = cv2.imread(path)
img = brightness_up(img)
img_bin, img_rgb = make_bin_and_rgb(img)
rotated = detect_rotation_and_rotate(img_bin)
# rotated = cv2.resize(rotated,(8000, 800), interpolation=cv2.INTER_NEAREST)
# plt.imshow(rotated)
# plt.show()
# img_rgb = cv2.resize(img_rgb,(8000, 800), interpolation=cv2.INTER_NEAREST)
img_prepared = prepare_img_for_roi(rotated)
image_orig, letters, region_distances, new_sorted_rectangles = select_roi(rotated.copy(), img_prepared)
# region = img_bin[y:y + h + 1, x:x + w + 1]
# (x, y, w, h)])
"""
i=1
for rect in new_sorted_rectangles:
cv2.imwrite('test_imwrite/letter'+str(i)+'.png',img[rect[1]:rect[1] + rect[3] + 1, rect[0]:rect[0] + rect[2] + 1])
i+=1
"""
distances = bb8.array(region_distances).reshape(len(region_distances), 1)
try:
k_means = KMeans(n_clusters=2, max_iter=2000, tol=0.00001, n_init=10)
k_means.fit(distances)
except:
return letters, None
# plt.imshow(image_orig,'gray')
# plt.show()
print(len(letters))
return letters, k_means
def testing():
img = cv2.imread('dataset/validation/train86.png')
img = brightness_up(img)
lower_orange = bb8.array([0, 50, 50], bb8.uint8)
upper_orange = bb8.array([255, 255, 255], bb8.uint8)
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
test = cv2.inRange(hsv_img, lower_orange, upper_orange)
plt.imshow(test)
plt.show()
return 255-test, img
def test_testing():
img_bin,img_bgr = testing()
img_prepared_rotated = morhpological_operations(img_bin)
img_orig, letters, region_distances, new_sorted_rectangles = select_roi(img_bgr.copy(),
img_prepared_rotated)
plt.imshow(img_orig)
plt.show()
distances = bb8.array(region_distances).reshape(len(region_distances), 1)
try:
k_means = KMeans(n_clusters=2, max_iter=2000, tol=0.00001, n_init=10)
k_means.fit(distances)
except:
return letters, None
# plt.imshow(image_orig,'gray')
# plt.show()
print(len(letters))
return letters, k_means
"""
orange_paths = []
orange_paths.append('dataset/validation/train95.png')
orange_paths.append('dataset/validation/train91.png')
orange_paths.append('dataset/validation/train86.png')
orange_paths.append('dataset/validation/train82.png')
orange_paths.append('dataset/validation/train77.png')
orange_paths.append('dataset/validation/train75.png')
orange_paths.append('dataset/validation/train69.png')
orange_paths.append('dataset/validation/train57.png')
orange_paths.append('dataset/validation/train56.png')
dominant_colors=[]
for path in orange_paths:
img1 = cv2.imread(path)
img1 = brightness_up(img1)
dominant_colors.append([get_most_dominant_color(cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)),path])
#plt.imshow(mask1, 'gray')
#plt.show()
#print("-----------")
#print(orange_paths)
orange_first_try=[]
for dominant in dominant_colors:
colors = dominant[0]
if colors[1]>140:
#95,91,69
img1 = cv2.imread(dominant[1])
img1 = brightness_up(img1)
lower_orange_mask = bb8.array([0, 50, 50], bb8.uint8)
upper_orange_mask = bb8.array([28, 255, 255], bb8.uint8)
hsv_img = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)
frame_threshed = cv2.inRange(hsv_img, lower_orange_mask, upper_orange_mask)
mask1 = 255 - frame_threshed
lower_orange = bb8.array([0, 50, 50], bb8.uint8)
upper_orange = bb8.array([19, 255, 255], bb8.uint8)
hsv_img = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)
frame_threshed = cv2.inRange(hsv_img, lower_orange, upper_orange)
test = frame_threshed - (255 - mask1)
orange_first_try.append([test,dominant[1]])
#plt.imshow(test, 'gray')
#plt.show()
elif colors[1]<12:
#86
img1 = cv2.imread(dominant[1])
img1 = brightness_up(img1)
lower_orange_mask = bb8.array([0, 50, 50], bb8.uint8)
upper_orange_mask = bb8.array([28, 255, 255], bb8.uint8)
hsv_img = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_img, lower_orange_mask, upper_orange_mask)
lower_orange = bb8.array([0, 50, 50], bb8.uint8)
upper_orange = bb8.array([255, 255, 255], bb8.uint8)
hsv_img = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)
frame_threshed = cv2.inRange(hsv_img, lower_orange, upper_orange)
plt.imshow(frame_threshed,'gray')
plt.show()
img_bin, img_rgb = make_bin_and_rgb(img1)
#img_rgb_rotated = detect_rotation_and_rotate(frame_threshed, img_rgb)
#plt.imshow(img_rgb_rotated)
#plt.show()
#img_prepared_rotated = prepare_img_for_roi(img_rgb_rotated)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
kernel_e = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
kernel_c = cv2.getStructuringElement(cv2.MORPH_CROSS, (4, 4))
frame_threshed = cv2.morphologyEx(frame_threshed, cv2.MORPH_CLOSE, kernel)
erosion = cv2.erode(frame_threshed, kernel_e, iterations=4)
dilation = cv2.dilate(erosion, kernel_c, iterations=2)
img_orig, letters, region_distances, new_sorted_rectangles = select_roi(cv2.cvtColor(img1,cv2.COLOR_BGR2RGB).copy(),
dilation)
print(len(letters))
distances = bb8.array(region_distances).reshape(len(region_distances), 1)
k_means = KMeans(n_clusters=2, max_iter=2000, tol=0.00001, n_init=10)
k_means.fit(distances)
plt.imshow(img_orig)
plt.show()
print(len(letters))
return letters, k_means
elif colors[1]<100 and colors[1]>12:
img1 = cv2.imread(dominant[1])
img1 = brightness_up(img1)
lower_orange_mask = bb8.array([5, 50, 50], bb8.uint8)
upper_orange_mask = bb8.array([30, 255, 255], bb8.uint8)
hsv_img = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_img, lower_orange_mask, upper_orange_mask)
plt.imshow(255-mask,'gray')
plt.show()
lower_orange = bb8.array([0, 50, 50], bb8.uint8)
upper_orange = bb8.array([50, 255, 255], bb8.uint8)
hsv_img = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)
frame_threshed = cv2.inRange(hsv_img, lower_orange, upper_orange)
#plt.imshow(frame_threshed,'gray')
#plt.show()
for dominant in dominant_colors:
print(dominant)
"""
def detect_rotation_and_rotate_separation(img):
img = brightness_up(img)
plt.imshow(img)
plt.show()
# img_ctr = hi.contrastLab(img)
# plt.imshow(img_ctr)
plt.show()
# grayscale = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# h,s,v = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
#
# img_bin = cv2.adaptiveThreshold(s, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 3)
# plt.imshow(img_bin,'gray')
# plt.show()
# img_res = hi.resize_photo(img_bin)
# plt.imshow(img_res,'gray')
# plt.show()
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
img_bgr = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR)
img_gs = cv2.cvtColor(img_bgr, cv2.COLOR_RGB2GRAY)
img_t = 1 - img_gs
thresh = cv2.adaptiveThreshold(img_t, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 39, 3)
img_bin = 255 - thresh
ret, img_bin = cv2.threshold(img_bin, 30, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
coords = bb8.column_stack(bb8.where(255-img_bin > 0))
angle = cv2.minAreaRect(coords)[-1]
#print(angle)
# the `cv2.minAreaRect` function returns values in the
# range [-90, 0); as the rectangle rotates clockwise the
# returned angle trends to 0 -- in this special case we
# need to add 90 degrees to the angle
if angle < -45:
angle = -(90 + angle)
# otherwise, just take the inverse of the angle to make
# it positive
else:
angle = -angle
#image = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR)
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated_bgr = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
#print(angle)
#plt.imshow(rotated_bgr)
#plt.show()
return rotated_bgr
def select_roi_separation(image_orig, img_bin):
a = 255-img_bin
img, contours, hierarchy = cv2.findContours(a.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (255, 0, 0), 1)
plt.imshow(img,'gray')
plt.show()
regions_array = []
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
area = cv2.contourArea(contour)
if area > 100:
region = img_bin[y:y + h + 1, x:x + w + 1]
regions_array.append([resize_region(region), (x, y, w, h)])
regions_array = sorted(regions_array, key=lambda item: item[1][0])
sorted_regions = [region[0] for region in regions_array]
sorted_rectangles = [region[1] for region in regions_array]
try:
new_sorted_rectangles = deal_with_hooks_rectangles_train(sorted_regions,sorted_rectangles)
except Exception as e:
new_sorted_rectangles = sorted_rectangles
new_sorted_regions = []
img_before_hooks = image_orig.copy()
for rectangle in sorted_rectangles:
cv2.rectangle(img_before_hooks, (rectangle[0], rectangle[1]),
(rectangle[0] + rectangle[2], rectangle[1] + rectangle[3]), (0, 255, 0), 2)
cv2.imwrite('hukovi.png', img_before_hooks)
for rectangle in new_sorted_rectangles:
region = img_bin[rectangle[1]:rectangle[1] + rectangle[3] + 2, rectangle[0]:rectangle[0] + rectangle[2] + 2]
new_sorted_regions.append(resize_region(region))
cv2.rectangle(image_orig, (rectangle[0], rectangle[1]),
(rectangle[0] + rectangle[2], rectangle[1] + rectangle[3]), (0, 255, 0), 2)
region_distances = []
for i in range(0, len(new_sorted_rectangles) - 1):
current = new_sorted_rectangles[i]
next_rect = new_sorted_rectangles[i + 1]
distance = next_rect[0] - (current[0] + current[2])
region_distances.append(distance)
# plt.imshow(image_orig)
# plt.show()
cv2.imwrite('rects.png', image_orig)
print("asda:", len(new_sorted_rectangles))
return image_orig, new_sorted_regions, region_distances, new_sorted_rectangles
def deal_with_hooks_rectangles_train(sorted_regions, sorted_rectangles):
new_sorted_rectangles = sorted_rectangles.copy()
rectangles_2b_removed = []
for i in range(0, len(sorted_rectangles) - 1):
current = sorted_rectangles[i]
next_rect = sorted_rectangles[i + 1]
if isHook_train(current[0], next_rect[0], current[2], next_rect[2]):
rectangles_2b_removed.append(next_rect)
new_rect = (current[0], next_rect[1], current[2], current[3] + next_rect[3] + 5)
new_sorted_rectangles[i] = new_rect
if len(rectangles_2b_removed) > 0:
for rect in rectangles_2b_removed:
new_sorted_rectangles.remove(rect)
return new_sorted_rectangles
def isHook_train(x0, x1, w0, w1):
return x0 < x1 and x0 + w0 + 5 > x1 + w1
def get_letters_k_means_test(path):
img = cv2.imread(path)
print(iop.determine_color(path)+" "+path)
dominant_color = iop.determine_color(path)
# ako je plava dominantna boja, pozivace se modul dww
if dominant_color == 'BLUE':
letters, region_distances = dww.get_letters_and_distances_water(path)
distances = bb8.array(region_distances).reshape(len(region_distances), 1)
try:
k_means = KMeans(n_clusters=2, max_iter=2000, tol=0.00001, n_init=10)
k_means.fit(distances)
except:
return letters, None
print(len(letters))
return letters, k_means
#ako je crvena dominantna poziva se modul iz dwb
elif dominant_color == 'RED':
letters, region_distances = dwb.get_letters_and_distances_bricks(path)
distances = bb8.array(region_distances).reshape(len(region_distances), 1)
try:
k_means = KMeans(n_clusters=2, max_iter=2000, tol=0.00001, n_init=10)
k_means.fit(distances)
except:
return letters, None
print(len(letters))
return letters, k_means
else:
img = iop.resize_photo(img)
img = iop.brightness_up(img)
rotated_img = detect_rotation_and_rotate_separation(img)
img_t = iop.image_preparation_for_thresh(img)
ret, img_bin = cv2.threshold(img_t, 250, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# plt.imshow(img_bin)
# plt.show()
image_orig, letters, region_distances, new_sorted_rectangles = roi.select_roi(rotated_img, img_bin)
# plt.imshow(image_orig)
# plt.show()
distances = bb8.array(region_distances).reshape(len(region_distances), 1)
try:
k_means = KMeans(n_clusters=2, max_iter=2000, tol=0.00001, n_init=10)
k_means.fit(distances)
except:
return letters, None
print(len(letters))
return letters, k_means
def get_letters_train(path):
img = cv2.imread(path)
img = iop.brightness_up(img)
img_t = iop.image_preparation_for_thresh(img)
ret, img_bin = cv2.threshold(img_t, 254, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# plt.imshow(img_bin)
# plt.show()
image_orig, letters, region_distances, new_sorted_rectangles = roi.select_roi(img, img_bin)
# plt.imshow(image_orig)
# plt.show()
return letters
#test_testing()
def paper_test(path):
img = cv2.imread(path)
img = brightness_up(img)
img = resize_photo(img)
#img = contrastLab(img)
#plt.imshow(img)
#plt.show()
print(img.shape)
h = img.shape[0]
w = img.shape[1]
blank_image = bb8.zeros((h, w,3), bb8.uint8)
blank_image[:, :] = (0, 0,3)
blank_image = cv2.cvtColor(blank_image, cv2.COLOR_BGR2GRAY)
# plt.imshow(blank_image)
# plt.show()
img_gs = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_bin = img_gs > 215
img_bin = 255 - img_bin
# plt.imshow(img_bin,'gray')
# plt.show()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
mask = cv2.morphologyEx(bb8.uint8(img_bin), cv2.MORPH_CLOSE, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2))
mask = cv2.dilate(mask, kernel, iterations=2)
plt.imshow(mask,'gray')
plt.show()
mask = 255 - mask
img_test = mask + blank_image
plt.imshow(img_test)
plt.show()
#
#plt.imshow(1-img_gs,'gray')
#plt.show()
# ret, mask = cv2.threshold(img_gs, 220, 255, cv2.THRESH_OTSU)
# #
# # img1 = cv2.bitwise_not(255-mask,img_gs)
# mask = 255-mask
# #plt.imshow(mask,'gray')
# #plt.show()
# src1_mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) # change mask to a 3 channel image
# plt.imshow(src1_mask)
# plt.show()
#
# dst = cv2.addWeighted(img, 0.9, src1_mask, 0.3,0)
# plt.imshow(dst)
# plt.show()
#
#
# img_gs = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)
# plt.imshow(img_gs,'gray')
# plt.show()
# ret, mask = cv2.threshold(img_gs, 220, 255, cv2.THRESH_OTSU)
# plt.imshow(mask)
# plt.show()
#
# imgg = cv2.bitwise_not(img,img1)
# plt.imshow(imgg)
# plt.show()
#
# kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(2,2))
# mask = cv2.erode(bb8.uint8(mask),kernel,iterations=2)
# plt.imshow(mask)
# plt.show()
# mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
# plt.imshow(mask)
# plt.show()
#
#h,s,v = split2hsv(img)
#plt.imshow(v,'gray')
#plt.show()
<file_sep>from __future__ import print_function
import numpy as bb8
import handle_image as hi
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
import image_operations as iop
def prepare_data_for_network(letters):
data_for_network = []
for letter in letters:
scaled = iop.scale_image(letter)
data_for_network.append(iop.image_to_vector(scaled))
return data_for_network
def convert_output():
alphabet = create_alphabet()
outputs = []
for i in range(len(alphabet)):
output = bb8.zeros(len(alphabet))
output[i] = 1
outputs.append(output)
return bb8.array(outputs)
def winner(output):
return max(enumerate(output), key=lambda x: x[1])[0]
def display_result(outputs, k_means):
alphabet = create_alphabet()
w_space_group = max(enumerate(k_means.cluster_centers_), key=lambda x: x[1])[0]
result = alphabet[winner(outputs[0])]
for idx, output in enumerate(outputs[1:, :]):
if (k_means.labels_[idx] == w_space_group):
result += ' '
result += alphabet[winner(output)]
return result
def do_fuzzywuzzy_stuff(vocabulary, extracted_text):
new_string = ""
for extracted_word in list(extracted_text.split(' ')):
# print(extracted_word)
found_word = find_closest_word(vocabulary, extracted_word)
# print(found_word)
if found_word is None:
new_string += extracted_word + ""
else:
new_string += found_word + " "
new_string.rstrip()
return new_string
def find_closest_word(vocabulary, extracted_word):
list_of_words = list(vocabulary.keys())
closest_word =""
closest_words = []
lowest_distance=100000
for word in list_of_words:
if word == extracted_word:
return word
else:
distance = fuzz.ratio(word,extracted_word)
if distance < lowest_distance:
lowest_distance = distance
closest_word = word
elif distance == lowest_distance:
closest_words.append([word, distance, vocabulary[word]])
highest_occurance = 0
final_word = ""
for word_distance_occur in closest_words:
if int(word_distance_occur[2])>highest_occurance:
final_word=word_distance_occur[0]
highest_occurance=int(word_distance_occur[2])
return final_word
# code for levenshein taken from https://www.datacamp.com/community/tutorials/fuzzy-string-python
def levenshtein_ratio_and_distance(s, t, ratio_calc = False):
""" levenshtein_ratio_and_distance:
Calculates levenshtein distance between two strings.
If ratio_calc = True, the function computes the
levenshtein distance ratio of similarity between two strings
For all i and j, distance[i,j] will contain the Levenshtein
distance between the first i characters of s and the
first j characters of t
"""
# Initialize matrix of zeros
rows = len(s)+1
cols = len(t)+1
distance = bb8.zeros((rows,cols),dtype = int)
# Populate matrix of zeros with the indeces of each character of both strings
for i in range(1, rows):
for k in range(1,cols):
distance[i][0] = i
distance[0][k] = k
# Iterate over the matrix to compute the cost of deletions,insertions and/or substitutions
for col in range(1, cols):
for row in range(1, rows):
if s[row-1] == t[col-1]:
cost = 0 # If the characters are the same in the two strings in a given position [i,j] then the cost is 0
else:
# In order to align the results with those of the Python Levenshtein package, if we choose to calculate the ratio
# the cost of a substitution is 2. If we calculate just distance, then the cost of a substitution is 1.
if ratio_calc == True:
cost = 2
else:
cost = 1
distance[row][col] = min(distance[row-1][col] + 1, # Cost of deletions
distance[row][col-1] + 1, # Cost of insertions
distance[row-1][col-1] + cost) # Cost of substitutions
if ratio_calc == True:
# Computation of the Levenshtein Distance Ratio
Ratio = ((len(s)+len(t)) - distance[row][col]) / (len(s)+len(t))
return Ratio
else:
# print(distance) # Uncomment if you want to see the matrix showing how the algorithm computes the cost of deletions,
# insertions and/or substitutions
# This is the minimum number of edits needed to convert string a to string b
return distance[row][col]
def create_alphabet():
alphabet_upper = ['A', 'B', 'C', 'Č', 'Ć', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'Š', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'Ž']
alphabet = []
for char in alphabet_upper:
alphabet.append(char)
for char in alphabet_upper:
alphabet.append(char.lower())
return alphabet
<file_sep>import cv2
import numpy as bb8
# code for this method is taken from first challenge
def image_preparation_for_thresh(img):
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
img_bgr = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR)
img_gs = cv2.cvtColor(img_bgr, cv2.COLOR_RGB2GRAY)
img_t = 1 - img_gs
return img_t
# code for resize taken from https://www.tutorialkart.com/opencv/python/opencv-python-resize-image/
def resize_photo(img):
scale_percent = 150
newWidth = int(img.shape[1] * scale_percent / 100)
newHeight = int(img.shape[0] * scale_percent / 100)
resized_img = cv2.resize(img, (int(newWidth), int(newHeight)), interpolation=cv2.INTER_NEAREST)
return resized_img
# code for brightness taken from https://stackoverflow.com/questions/32609098/how-to-fast-change-image-brightness-with-python-opencv
def brightness_up(img):
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
lim = 255 - 30
v[v > lim] = 255
v[v <= lim] += 30
final_hsv = cv2.merge((h, s, v))
img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
return img
# code for most dominant color taken from: https://stackoverflow.com/questions/50899692/most-dominant-color-in-rgb-image-opencv-numpy-python
def get_most_dominant_color(a):
a2D = a.reshape(-1, a.shape[-1])
col_range = (256, 256, 256)
a1D = bb8.ravel_multi_index(a2D.T, col_range)
return bb8.unravel_index(bb8.bincount(a1D).argmax(), col_range)
def get_highest_peak_att_255(peaks, k):
max_peak = peaks[255]
return [max_peak, k]
def arrange_histogram_array(max_peaks):
new_array = []
for peak in max_peaks:
color = peak[1]
pair = peak[0]
max_hist = pair[0]
new_array.append([max_hist, color])
return new_array
def is_color(max_peaks):
max_peak = [0, ""]
for peak in max_peaks:
if peak[0] > max_peak[0]:
max_peak = [peak[0], peak[1]]
return max_peak
# histogram explained: https://numpy.org/doc/stable/reference/generated/numpy.histogram.html
# code for getting histogram taken from opencvs documenataion: https://docs.opencv.org/master/d1/db7/tutorial_py_histogram_begins.html
def determine_color(path):
if get_most_dominant_color(brightness_up(cv2.imread(path))) != (255, 255, 255):
img = cv2.imread(path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
color = ('r', 'g', 'b')
max_peaks = []
for i, col in enumerate(color):
histr = cv2.calcHist([img], [i], None, [256], [0, 256])
max_peaks.append(get_highest_peak_att_255(histr, color[i]))
# plt.plot(histr, color=col)
# plt.xlim([0, 256])
# plt.show()
max_hist_array = arrange_histogram_array(max_peaks)
if is_color(max_hist_array)[1] == 'b':
return 'BLUE'
elif is_color(max_hist_array)[1] == 'r':
return 'RED'
elif is_color(max_hist_array)[1] == 'g':
return 'GREEN'
else:
return "white"
def image_to_vector(img):
return img.flatten()
def resize_region(region):
return cv2.resize(region, (28, 28), interpolation=cv2.INTER_NEAREST)
def scale_image(img):
return img / 255
<file_sep># Captcha detection (OCR)
### Description
Reading text from easy and relatively hard surfaces is simple project made for Soft computing course.
Recognition and reading from images using computer vision techniques
is performed through the OpenCV library and machine learning models through Keras and Scikit-Learn
libraries, as well as the Python programming language.
### How to use project
To run the solution on your machine and check how accurate it is, you need to do the following:
1. Methods are implemented in process.py.
2. To start program, run main.py. Running the main.py file will generate a result.csv file by calling the previously implemented method for all instances in the dataset.
3. To evaluate accuracy run the evaluate.py file. This file will load the result.csv previously generated and calculate the accuracy. The output of this file is just a number that shows the percentage of accuracy of the current solution.
### Libraries
As part of this project, the following libraries are being used with Python 3.6:
* numpy
* openCV version 3.x.y
* matplotlib
* scikit-learn
* keras version 2.1.5
* for FeedForward fully connected NN (Conv layers weren't used)
* fuzzywuzzy<file_sep>U ovaj folder sacuvati serijalozovani model u slucaju da ste koristili serijalizaciju.
Platforma ne vrsi download "dataset" foldera, posto njega studenti nece modifikovati (statican je), ali ce vrsiti download "serialized_model" foldera. Zbog toga je u njega potrebno sacuvati fajlove vec istreniranih modela.
| 93dc0f544967bb8c2f729a2982270e791df9e497 | [
"Markdown",
"Python"
]
| 9 | Python | OakenKnight/WeirdCaptchaRecognition | c8093343d6b8f672380baab4baf0bc8f1c0e639f | 39d19953bb3480f357fd8478cf3b1a9490750171 |
refs/heads/master | <file_sep>import React, { Component, PropTypes } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { findDOMNode } from "react-dom";
import fetch from "isomorphic-fetch";
import Force from "../components/Force.js";
class forceByD3 extends Component {
constructor(props) {
super(props);
this.state = {
data: {
nodes: [],
links: []
}
};
this.getData();
}
componentDidMount() {
const el = findDOMNode(this);
this.chart = new Force(el, {});
this.chart.create(this.state.data);
}
componentDidUpdate() {
this.chart.update(this.state.data);
}
componentWillUnmount() {
this.chart.unmount();
}
getData() {
fetch("/json?file=test2.json")
.then(response => response.json())
.then(json => {
if (json.type) {
this.setState({
data: {
nodes: json.data.nodes,
links: json.data.edges
}
});
}
});
}
render() {
return <div className="chart" />;
}
}
function mapStateToProps(state) {
return {};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(forceByD3);
<file_sep>import React, { Component, PropTypes } from 'react'
import { Table, Icon } from 'antd';
import { dataFormat } from '../base/index';
class UserList extends Component {
render() {
const { userlist , onDelete } = this.props;
const columns = [{
title: 'id',
dataIndex: 'id',
key: 'id',
render: (text) => <a href="#">{text}</a>,
},{
title: '姓名',
dataIndex: 'name',
key: 'name',
render: (text) => <a href="#">{text}</a>,
}, {
title: '颜色',
dataIndex: 'color',
key: 'color',
}, {
title: '注册时间',
dataIndex: 'registered',
key: 'registered',
render: (text) => (dataFormat(text,'yyyy-MM-dd hh:mm:ss'))
}, {
title: '操作',
key: 'operation',
render: (text,record) => (
<span>
<a href="#">操作一{record.name}</a>
<span className="ant-divider"></span>
<a href="javascript:;" onClick={() => onDelete(record.id)}>删除</a>
<span className="ant-divider"></span>
<a href="#" className="ant-dropdown-link">
更多 <Icon type="down" />
</a>
</span>
),
}];
return (
<Table columns={columns} dataSource={userlist} />
)
}
}
// { "_id" : ObjectId("5756874df92420a87cc6999f"), "time" : 1465288525389, "color" : "pink", "name" : "王小飞", "id" : 9201, "type" : "disconnect" }
UserList.propTypes = {
userlist: PropTypes.array.isRequired,
onDelete: PropTypes.func.isRequired
}
export default UserList
<file_sep>import React, { Component, PropTypes } from 'react'
import { Button, Form, Modal, Input } from 'antd';
class UserList extends Component {
constructor(props){
super(props);
this.state = {
isAdd:false,
validateStatus:"",
value:""
}
this.doAdd = this.doAdd.bind(this);
this.handleOk = this.handleOk.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.handleFocusBlur = this.handleFocusBlur.bind(this);
this.handleFocusFocus = this.handleFocusFocus.bind(this);
}
doAdd(){
this.setState({
isAdd:true
});
}
handleOk() {
if(this.state.value){
this.props.onSubmitFun(this.state.value);
this.setState({
isAdd:false
});
}else{
this.setState({
validateStatus:"error"
});
}
}
handleInputChange(e){
this.setState({ value: e.target.value });
}
handleFocusBlur(e) {
if(!e.target.value){
this.setState({
validateStatus:"error"
});
}
}
handleFocusFocus(e) {
this.setState({
validateStatus:""
});
}
render() {
// const { userlist , onDelete } = this.props;
return(
<div>
<Button type="primary" onClick={this.doAdd} style={{marginBottom:'20px'}}>添加用户</Button>
<Modal ref="modal"
visible={this.state.isAdd}
title="输入用户名"
closable={false}
footer="">
<Form horizontal>
<Form.Item
label="用户名:"
labelCol={{ span: 5 }}
wrapperCol={{ span: 12 }}
validateStatus={this.state.validateStatus}
help="请输入用户名"
>
<Input value={this.state.value} onFocus={this.handleFocusFocus} onBlur={this.handleFocusBlur} onChange={this.handleInputChange} id="error"/>
</Form.Item>
<Form.Item wrapperCol={{ span: 16, offset: 6 }} style={{ marginTop: 24 }}>
<Button type="primary" htmlType="submit" onClick={this.handleOk}>确定</Button>
</Form.Item>
</Form>
</Modal>
</div>
)
};
}
// { "_id" : ObjectId("5756874df92420a87cc6999f"), "time" : 1465288525389, "color" : "pink", "name" : "王小飞", "id" : 9201, "type" : "disconnect" }
UserList.propTypes = {
// userlist: PropTypes.array.isRequired,
onSubmitFun: PropTypes.func.isRequired
}
export default UserList
<file_sep>// var users = require('../api/db').users;
// var base = require('../base');
import formidable from 'formidable'
import { users } from '../api/db'
import { getTime, getColor, getId } from '../../common/base/index'
/* users */
export function getAllUser(callback){
users.find()
.sort({'_id':-1}).exec(function(err, result) {
var callbackJson = {};
if(err){
console.error(err);
callbackJson.type = 0;
callbackJson.msg = "数据库操作失败";
}else{
callbackJson.type = 1;
callbackJson.msg = "请求成功";
callbackJson.attr = result;
}
callback(callbackJson);
})
}
export function addUser(json,callback){
json.id = getId();
json.color = getColor();
json.registered = getTime();
var u = new users(json);
u.save(function(err,result){
var callbackJson = {};
if(err){
console.error(err);
callbackJson.type = 0;
callbackJson.msg = "数据库操作失败";
}else{
callbackJson.type = 1;
callbackJson.msg = "请求成功";
callbackJson.attr = result;
}
callback(callbackJson);
});
}
export function deleteUserById(id,callback){
users.remove({id:id},function(err,result){
var callbackJson = {};
console.log(result);
if(err){
// console.error(err);
callbackJson.type = 0;
callbackJson.msg = "数据库操作失败";
}else{
callbackJson.type = 1;
callbackJson.msg = "请求成功";
callbackJson.attr = result;
}
callback(callbackJson);
});
}
export function checkUserByName(name,callback){
users.find({name:name},function(err,result){
var callbackJson = {};
if(err){
console.error(err);
callbackJson.type = 0;
callbackJson.msg = "数据库操作失败";
}else{
callbackJson.type = 1;
callbackJson.msg = "请求成功";
callbackJson.attr = result;
}
callback(callbackJson);
});
}
export function fun(app){
// users
app.get('/user/getAll',function(req,res){
getAllUser(function(result){
res.json(result);
})
});
app.get('/user/login',function(req,res){
var params = require("url").parse(req.url, true).query;
if(params&¶ms.username){
checkUserByName(params.username,function(result){
// res.json(result);
if(result.type){
if(result.attr.length > 0){
var attr = result.attr;
result.attr = attr[0];
res.json(result);
}else{
addUser({
"name": params.username
},function(result) {
res.json(result);
})
}
}else{
res.json(result);
}
})
}else{
res.json({
type: 0,
msg: "用户名不能为空"
});
}
});
app.get('/user/save',function(req,res){
var params = require("url").parse(req.url, true).query;
if(params&¶ms.username){
addUser({
"name": params.username
},function(result) {
res.json(result);
})
}else{
res.json({
type: 0,
msg: "用户名不能为空"
});
}
});
app.post('/user/save', function(req,res){
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
console.log(JSON.stringify(fields));
console.log(JSON.stringify(files));
if(fields&&fields.username){
addUser({
"name": fields.username
},function(result) {
res.json(result);
})
}else{
res.json({
type: 0,
msg: "用户名不能为空"
});
}
})
});
app.get('/user/delete',function(req,res){
var params = require("url").parse(req.url, true).query;
if(params&¶ms.id){
deleteUserById(params.id,function(result) {
res.json(result);
})
}else{
res.json({
type: 0,
msg: "id不能为空"
});
}
});
}
<file_sep>import React, { Component, PropTypes } from 'react'
import { Menu, Badge, message } from 'antd'
class ChatUserList extends Component {
constructor(props) {
super(props)
this.state = {
current: '1',
}
this.menuHandleClick = this.menuHandleClick.bind(this);
}
menuHandleClick(e){
if(e.key == this.props.user.id){
message.info('本人本人本人');
return;
}else if(e.key != 1){
var have = false;
for (var i = 0; i < this.props.userlist.length; i++) {
var t = this.props.userlist[i];
if(e.key == t.id){
have = t;
break;
}
}
if(have){
this.props.changeUser({
name:have.name,
id:have.id
});
}
}else{
this.props.changeUser({
name:'all',
id:'1'
});
}
this.setState({
current: e.key
});
// 设置信息已读
// this.infoNumChange(e.key,0);
}
render() {
return (
<Menu onClick={this.menuHandleClick}
selectedKeys={[this.state.current]}
mode="inline">
{
this.props.userlist.map(function(user,index){
if(user.id == this.state.id){
return (<Menu.Item key={user.id}>
<Badge count={user.infoNum}>
<a href="javascript:;" className="head-example" style={{background:user.color}}></a>
</Badge>
本人
</Menu.Item>)
}else{
return (<Menu.Item key={user.id}>
<Badge count={user.infoNum}>
<a href="javascript:;" className="head-example" style={{background:user.color}}></a>
</Badge>
{user.name}
</Menu.Item>)
}
}.bind(this))
}
</Menu>
)
}
}
ChatUserList.propTypes = {
changeUser: PropTypes.func.isRequired,
// incrementIfOdd: PropTypes.func.isRequired,
// incrementAsync: PropTypes.func.isRequired,
// onSubmitFun: PropTypes.func.isRequired,
// login: PropTypes.bool.isRequired
}
export default ChatUserList
<file_sep>import React, { Component, PropTypes } from "react";
import { Form, Row, Col, Button, Checkbox } from "antd";
const FormItem = Form.Item;
class UserList extends Component {
constructor(props) {
super(props);
this.handleReset = this.handleReset.bind(this);
this.getData = this.getData.bind(this);
}
componentWillMount() {}
handleReset() {
this.props.form.resetFields(["master"]);
}
getData() {
console.log(this.props.form.getFieldsValue());
}
render() {
const { getFieldDecorator } = this.props.form;
const formItemLayout = {
labelCol: { span: 10 },
wrapperCol: { span: 14 }
};
return (
<div>
<Row gutter={10}>
<Col span={4}>
<FormItem {...formItemLayout} label="是否户主">
{getFieldDecorator("master")(<Checkbox />)}
</FormItem>
</Col>
</Row>
<Row gutter={10}>
<Col span={8} style={{ textAlign: "right" }}>
<Button type="primary" htmlType="submit" onClick={this.getData}>
查询
</Button>
<Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
重置
</Button>
</Col>
</Row>
</div>
);
}
}
export default Form.create()(UserList);
<file_sep>import url from 'url'
import request from 'request'
import cheerio from 'cheerio'
import _ from 'lodash'
export default class reptile {
constructor(res, url, maxNum) {
this.regex = /^http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?$/i;
this.res = res;
this.back = [];
this.linkNum = 0;
this.isResponse = false;
this.maxNum = maxNum||30;
if(url&&this.isLink(url)){
this.getData(url, 1);
}else{
this.responseError('请提供正确的网页地址')
}
}
isLink(str){
return this.regex.test(str)
}
getData(link, index){
var that = this;
that.linkNum++;
request(link, function (error, response, body) {
that.linkNum--;
if(that.back.length > that.maxNum){
return
}
var aArr = [];
if (!error && response.statusCode == 200) {
// console.log(body);
var $ = cheerio.load(body);
$('img').each(function(){
var img = $(this).attr('src');
if(img&&!_.find(that.back, function(chr) {
return chr.img == url.resolve(link, img);
})){
that.back.push({
from: link,
img: url.resolve(link, img),
index: index
});
}
});
$('a').each(function(){
var aLink = $(this).attr('href');
aLink&&aArr.push(url.resolve(link, aLink));
});
}
if(that.back.length > that.maxNum||that.linkNum == 0&&aArr.length == 0){
that.responseData()
}else{
_.each(aArr,function(link){
// console.log(link)
link&&that.isLink(link)&&that.getData(link, index + 1);
});
}
})
}
responseData(){
var that = this;
if(that.isResponse){
return
}
that.isResponse = true;
if(that.back.length > 0){
if(that.back.length > that.maxNum){
that.back.length = that.maxNum
}
that.res.json({
type: 1,
msg: "请求成功",
data: that.back
});
}else{
that.responseError();
}
}
responseError(msg){
this.res.json({
type: 0,
msg: msg||"请求失败"
});
}
}
<file_sep>import { SET_USERS, DELETE_USER, ADD_USER } from '../actions'
export default function userlist(state = [], action) {
console.log(action);
switch (action.type) {
case SET_USERS:
return action.userlist
case DELETE_USER:
return state.filter((s) => s.id != action.id)
case ADD_USER:
return [
action.user,
...state
]
default:
return state
}
}
<file_sep>import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from '../reducers'
export default function configureStore(preloadedState) {
const store = createStore(
rootReducer,
preloadedState,
applyMiddleware(thunk)
)
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers').default
store.replaceReducer(nextRootReducer)
})
}
return store
}
/*
{
user:{
name:"游客",
color:"red",
id:""
}
messages:"",
userlist:[]
}
*/ <file_sep>import d3 from "d3-old";
import _ from "lodash";
import D3Base from "./D3Base";
const chartConfig = {
color: (function(){
var arr = [d3.scale.category20(),d3.scale.category20b(),d3.scale.category20c(),d3.scale.category20(),d3.scale.category20b(),d3.scale.category20c()];
return function(key){
var num = parseInt(key);
// console.log(num,arr[Math.floor(num/20)](num%20));
return arr[Math.floor(num/20)](num%20);
}
})(),
zoomRange:[0.2, 4],
zoomScale:[0.9,1.1],
width: 1500,
height: 600,
margin: {
left: 0,
top: 0,
right: 0,
bottom: 0
},
zoom: true,
drag: true
};
export default class Force extends D3Base {
constructor(el, props) {
super(props);
this.el = el;
this.props = props;
Object.keys(chartConfig).forEach(configKey => {
// If a prop is defined, let's just use it, otherwise
// fall back to the default.
if (this.props[configKey] !== undefined) {
this[configKey] = this.props[configKey];
} else {
this[configKey] = chartConfig[configKey];
}
});
// this.nodes = [{value:1,category:1},{value:2,category:4},{value:3,category:2}];
// this.links = [{source:0,target:1},{source:0,target:2}];
this.nodes = [];
this.links = [];
}
create(data) {
var that = this;
const width = this.width + this.margin.left + this.margin.right;
const height = this.height + this.margin.top + this.margin.bottom;
this.width = width;
this.height = height;
this.svg = d3.select(this.el).append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", `translate(${this.margin.left}, ${this.margin.top})`);
this.svgg = this.svg.append("svg:g").attr('class','outg');
this.svgline = this.svgg.append("svg:g").attr('class','lines');
this.svgnode = this.svgg.append("svg:g").attr('class','nodes');
this.dataFormat(data);
this.force = d3.layout.force()
.nodes(this.nodes)
.links(this.links)
.linkDistance(60)
.charge(-400)
.size([width, height]);
this.force.on("tick", function(e){ //对于每一个时间间隔
//更新连线坐标
that.svg_edges.attr("x1",function(d){ return d.source.x; })
.attr("y1",function(d){ return d.source.y; })
.attr("x2",function(d){ return d.target.x; })
.attr("y2",function(d){ return d.target.y; });
//更新节点坐标
that.svg_nodes.attr('transform',function(d){ return `translate(${d.x}, ${d.y})`});
});
if(this.drag){
that.force.drag()
.on("dragstart",function(d,i){
d3.event.sourceEvent.stopPropagation();
})
.on("drag", function(d) {
})
.on("dragend",function(d){
});
}
if(this.zoom){
var zoomObj = d3.behavior.zoom()
.scaleExtent(that.zoomRange)
.on("zoom", function(){
that.svgg.attr("transform",
"translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
})
.on('zoomend', function(){
});
this.svgg.call(zoomObj);
}
this.drew();
}
update(data) {
// this.nodes = data.nodes;
// this.links = [];
this.dataFormat(data)
this.drew();
}
dataFormat(data){
var that = this;
this.nodes.length = 0;
this.links.length = 0;
Object.assign(this.nodes, data.nodes);
_.each(data.links,function(obj){
var source = that.nodes.find(function(n){ return n.name == obj.source});
var target = that.nodes.find(function(n){ return n.name == obj.target});
if(source&&target){
that.links.push({
source: source,
target: target
});
}
});
}
drew(){
var that = this;
//添加连线
this.svg_edges = this.svgline.selectAll("line")
.data(this.links);
this.svg_edges.exit().remove();
this.svg_edges.enter()
.append("line")
.attr('class','line')
.style('stroke-width',function(d){ return d.linkNum||1 });
//添加节点
this.svg_nodes = this.svgnode.selectAll(".node")
.data(this.nodes);
this.svg_nodes.exit().remove();
this.svg_nodes.enter()
.append('g')
.attr('class', 'node')
.attr('transform', function(d) {
return 'translate(' + (d.x||that.width/2) + ',' + (d.y||that.height/2) + ')';
})
.call(that.force.drag)
.each(function(d){
var _this = d3.select(this);
_this.append('circle')
.attr("r", 10)
.style("fill", function(d) { return that.color(d.category)});
});
this.force.start();
}
}
<file_sep>import React, { Component, PropTypes } from 'react'
import { Form, Input, Button } from 'antd'
class InputMessage extends Component {
constructor(props) {
super(props)
this.state = {
value: ""
}
this.handleInputChange = this.handleInputChange.bind(this);
this.handleOk = this.handleOk.bind(this);
}
handleOk() {
if(this.state.value){
// this.props.onSubmitMsg({
// toId:this.props.toId,
// toName:this.props.toName,
// msg:this.state.value
// });
this.props.onSubmitMsg(this.state.value);
!this.props.save&&this.setState({ value: "" });
}
}
handleInputChange (e){
this.setState({ value: e.target.value });
}
render() {
return (
<div>
<Form inline>
<Form.Item label="">
<Input style={{width:'400px'}} value={this.state.value} onChange={this.handleInputChange} placeholder="请输入"/>
</Form.Item>
<Button type="primary" htmlType="submit" onClick={this.handleOk}>提交</Button>
</Form>
</div>
);
}
}
InputMessage.propTypes = {
// changeUser: PropTypes.func.isRequired,
// incrementIfOdd: PropTypes.func.isRequired,
// incrementAsync: PropTypes.func.isRequired,
onSubmitMsg: PropTypes.func.isRequired,
save: PropTypes.bool
// login: PropTypes.bool.isRequired
}
export default InputMessage
<file_sep>import url from 'url';
import fs from 'fs';
export function jsonApi(app){
app.get('/json',function(req,res){
var params = url.parse(req.url, true).query;
if(params&¶ms.file){
if(params.file != "test1.json"&¶ms.file != "test2.json"){
res.json({
type: 0,
msg: "文件不存在"
});
}else{
fs.readFile('./common/json/' + params.file,function(err,data){
if(err){
res.json({
type: 0,
msg: "文件读取失败"
});
throw err
}else{
var data = JSON.parse(data);
res.json({
type: 1,
msg: "文件读取成功",
data
})
}
});
}
}else{
res.json({
type: 0,
msg: "文件名不能为空"
});
}
});
}<file_sep>import { combineReducers } from 'redux'
import { routerReducer as routing } from 'react-router-redux'
import counter from './counter'
import userlist from './userlist'
import user from './user'
const rootReducer = combineReducers({
counter,
userlist,
user,
routing
})
export default rootReducer
<file_sep>import socketio from 'socket.io'
import { addMessage } from '../server/api/messageApi'
import { addSyslog } from '../server/api/syslogApi'
import { getTime } from '../common/base/index'
export function createSocket(server,post){
var clientList = {};
function getLinkNum(){
return Object.keys(clientList).length;
}
function getUserList(){
// 用户列表
var arr = [];
var keys = Object.keys(clientList);
for (var i = 0; i < keys.length; i++) {
var key = keys[i]
arr.push({
id : clientList[key].id,
name : clientList[key].name,
color: clientList[key].color
});
}
return arr
}
var io = socketio(server);
io.on('connection', function (socket) {
console.log('建立连接');
socket.emit('open');//通知客户端已连接
// 打印握手信息
// console.log(socket.handshake);
// 构造客户端对象
var client = {
socket:socket,
name:"游客",
color:"red",
id:""
}
// 对message事件的监听
socket.on('message', function(data){
var obj = {
'time': getTime(),
'color': client.color,
'text': data.msg,
'fromName': client.name,
'fromId': client.id,
'toName': data.toName,
'toId': data.toId
}
console.log(client.name + ' say: ' + data.msg);
if(data.toId&&data.toId != 1 &&clientList[data.toId]){
socket.emit('message',obj);
clientList[data.toId].socket.emit('message',obj);
}else{
socket.emit('message',obj);
socket.broadcast.emit('message',obj);
}
addMessage(obj,function(){
console.log("插入聊天记录成功");
});
});
// 登录
socket.on('userLogin', function(obj){
client.name = obj.name;
client.color = obj.color;
client.id = obj.id;
console.log("登录信息:"+JSON.stringify(obj))
var obj = {
time:getTime(),
color:client.color,
name:client.name,
id:client.id,
type:'login'
};
clientList[client.id] = client;
addSyslog(obj,function(){
console.log('添加登录记录成功');
});
socket.broadcast.emit('system',obj);
// 用户列表
var arr = getUserList();
socket.emit('users', arr);
socket.broadcast.emit('users', arr);
console.log(client.name + ' login');
console.log('在线人数:' + arr.length);
})
// 拉取用户
socket.on('getUserlist', (id) => {
var arr = getUserList();
if(id){
clientList[id]&&clientList[id].socket.emit('users', arr);
}else{
socket.emit('users', arr);
socket.broadcast.emit('users', arr);
}
})
//监听出退事件
socket.on('disconnect', function () {
var obj = {
time:getTime(),
color:client.color,
name:client.name,
id:client.id,
type:'disconnect'
};
// 广播用户已退出
socket.broadcast.emit('system',obj);
console.log(client.name + ' Disconnect');
delete clientList[client.id];
// 用户列表
var arr = getUserList();
addSyslog(obj,function(){});
socket.broadcast.emit('users',arr);
console.log('在线人数:' + arr.length);
});
});
}<file_sep>var messageApi = require('../api/messageApi').fun;
var userApi = require('../api/userApi').fun;
var syslogApi = require('../api/syslogApi').fun;
var fileApi = require('../api/fileApi').fun;
import { jsonApi } from '../api/jsonApi';
import * as reptileApi from '../api/reptileApi';
export function createServer(app){
userApi(app);
messageApi(app);
syslogApi(app);
fileApi(app);
jsonApi(app);
reptileApi.fun(app);
}<file_sep>import React, { Component, PropTypes } from 'react'
import { Table, Icon } from 'antd';
class ImageList extends Component {
constructor(props) {
super(props)
this.state = {
show: 'none',
img: ""
}
this.showPic = this.showPic.bind(this);
this.hidePic = this.hidePic.bind(this);
}
showPic(img){
this.setState({
show: 'block',
img
});
}
hidePic(){
this.setState({
show: 'none'
});
}
render() {
const { imgList } = this.props;
const columns = [{
title: '几层查找',
dataIndex: 'index',
key: 'index',
},{
title: '来自网址',
dataIndex: 'from',
key: 'from',
// render: (link) => <a href={ link }>{link}</a>,
},{
title: '图片',
dataIndex: 'img',
key: 'img',
// render: (img) => <a href="#"><img src={ img }/></a>,
},{
title: '缩略图',
dataIndex: 'img',
key: 'imgM',
render: (img) => <img style={{ width:"40px",height:'40px'}} src={ img } onClick={this.showPic.bind(this,img)}/>,
},{
title: '操作',
key: 'operation',
render: (text,record) => (
<span>
<a href="javascript:;" onClick={this.showPic.bind(this,record.img)}>查看大图</a>
</span>
),
}];
return (
<div>
<Table columns={columns} dataSource={imgList} />
<div className="showPic" style={{display: this.state.show}}>
<div className="cover" onClick={this.hidePic}></div>
<img src={this.state.img} alt=""/>
</div>
</div>
)
}
}
// { "_id" : ObjectId("5756874df92420a87cc6999f"), "time" : 1465288525389, "color" : "pink", "name" : "王小飞", "id" : 9201, "type" : "disconnect" }
ImageList.propTypes = {
imgList: PropTypes.array.isRequired,
// onDelete: PropTypes.func.isRequired
}
export default ImageList
<file_sep>import React, { Component } from "react";
import { findDOMNode } from "react-dom";
import fetch from "isomorphic-fetch";
// import d3, { schemeCategory20, schemeCategory20b, schemeCategory20c, forceSimulation, select, event, forceLink, forceManyBody, forceCenter} from "d3";
import * as d3 from "d3";
import _ from "lodash";
import Force from "../components/Force.js";
import "../css/force.css";
class forceByD3Svg extends Component {
constructor(props) {
super(props);
console.log(d3.schemeCategory20);
this.state = {
width: 1400,
height: 600,
update: 0,
color: d3.scaleOrdinal(d3.schemeCategory20)
};
this.nodes = [];
this.links = [];
this.transform = {
x: 0,
y: 0,
k: 1
};
this.getData();
this.start = this.start.bind(this);
}
start() {
var self = this;
self.force = d3
.forceSimulation(self.nodes)
.force(
"link",
d3.forceLink(self.links).id(function(d) {
return d.name;
})
)
.force("charge", d3.forceManyBody())
.force(
"center",
d3.forceCenter(self.state.width / 2, self.state.height / 2)
)
.on("tick", function() {
self.drew();
});
// drag
d3.select(self.refs.canvas).call(
d3
.drag()
.container(self.refs.canvas)
.subject(function() {
var node = self.force.find(d3.event.x, d3.event.y);
var length = Math.sqrt(
(node.x - d3.event.x) * (node.x - d3.event.x) +
(node.y - d3.event.y) * (node.y - d3.event.y)
);
console.log(length);
if (length > 5) {
return undefined;
} else {
return node;
}
})
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
);
function dragstarted() {
if (!d3.event.active) self.force.alphaTarget(0.3).restart();
d3.event.subject.fx = d3.event.subject.x;
d3.event.subject.fy = d3.event.subject.y;
}
function dragged() {
d3.event.subject.fx = d3.event.x;
d3.event.subject.fy = d3.event.y;
}
function dragended() {
if (!d3.event.active) self.force.alphaTarget(0);
d3.event.subject.fx = null;
d3.event.subject.fy = null;
}
// zoom
d3.select(self.refs.canvas).call(
d3
.zoom()
.scaleExtent([0.3, 2])
.on("zoom", function() {
var transform = d3.zoomTransform(this);
// console.log(transform)
self.transform = transform;
self.drew();
})
);
}
componentDidUpdate() {
// this.chart.update(this.state.data);
}
componentWillUnmount() {
// this.chart.unmount();
this.force.stop();
}
getData() {
var self = this;
fetch("/json?file=test2.json")
.then(response => response.json())
.then(json => {
if (json.type) {
self.dataFormat(json.data);
}
});
}
dataFormat(data) {
var self = this;
this.nodes.length = 0;
this.links.length = 0;
Object.assign(self.nodes, data.nodes);
Object.assign(self.links, data.edges);
this.start();
}
zoom(transform) {
var self = this;
var ctx = self.refs.canvas.getContext("2d");
ctx.translate(transform.x, transform.y);
ctx.scale(transform.k, transform.k);
}
drew() {
var self = this;
var ctx = self.refs.canvas.getContext("2d");
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, 100000, 100000);
ctx.translate(self.transform.x, self.transform.y);
ctx.scale(self.transform.k, self.transform.k);
ctx.beginPath();
ctx.lineWidth = 1;
ctx.strokeStyle = "#ccc";
self.links.forEach(function(d) {
ctx.moveTo(d.source.x, d.source.y);
ctx.lineTo(d.target.x, d.target.y);
});
ctx.stroke();
self.nodes.forEach(function(d) {
var radius = Math.min(d.score + 3, 30);
radius = radius < 15 ? radius : radius - 4;
var color = self.state.color(d.category);
ctx.beginPath();
ctx.moveTo(d.x + radius, d.y);
ctx.arc(d.x, d.y, radius, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
if (radius >= 15) {
ctx.beginPath();
ctx.strokeStyle = color;
ctx.arc(d.x, d.y, radius + 4, 0, 2 * Math.PI);
ctx.stroke();
}
});
}
render() {
var defaultWidth = this.state.width / 2,
defaultHeight = this.state.height / 2;
return (
<div className="chart" style={{ height: 1200 }}>
<div>{this.state.update}</div>
<canvas
width={this.state.width}
ref="canvas"
height={this.state.height}
/>
</div>
);
}
}
export default forceByD3Svg;
<file_sep>import React from 'react'
import { Route } from 'react-router'
import App from '../containers/App'
import UserList from '../containers/UsersList'
import Message from '../containers/Message'
import ForceByD3 from '../containers/ForceByD3'
import forceByD3Svg from '../containers/forceByD3Svg'
import forceByD3Svg2 from '../containers/forceByD3Svg2'
import forceByD3Canvas from '../containers/forceByD3Canvas'
import forceByD3CanvasV4 from '../containers/forceByD3CanvasV4'
import ReptilePic from '../containers/ReptilePic'
import FileUpload from '../containers/FileUpload'
import FileUpload2 from '../containers/FileUpload2'
import FileUpload3 from '../containers/FileUpload3'
export default (
<Route path="/" component={App}>
<Route path="/userlist" component={UserList} />
<Route path="/Message" component={Message} />
<Route path="/forceByD3" component={ForceByD3} />
<Route path="/forceByD3Svg" component={forceByD3Svg} />
<Route path="/forceByD3Svg2" component={forceByD3Svg2} />
<Route path="/forceByD3Canvas" component={forceByD3Canvas} />
<Route path="/forceByD3CanvasV4" component={forceByD3CanvasV4} />
<Route path="/reptile" component={ReptilePic} />
<Route path="/fileUpload" component={FileUpload} />
<Route path="/fileUpload2" component={FileUpload2} />
<Route path="/fileUpload3" component={FileUpload3} />
<Route path="*" component={App} />
</Route>
)
<file_sep>import React, { Component, PropTypes } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import $ from "jquery";
import { getUserList, fetchDeleteUser, fetchAddUser } from "../actions";
import UserTable from "../components/UserList";
import AppendUser from "../components/AppendUser";
class UserList extends Component {
componentWillMount() {
const { getUserList } = this.props;
getUserList();
}
saveUser(name) {
$.ajax({
type: "POST",
url: "/user/save",
data: {
username: name
},
success: function(data) {
console.log(data);
}
});
}
render() {
const { userlist, fetchDeleteUser, fetchAddUser } = this.props;
return (
<div>
get:<AppendUser onSubmitFun={fetchAddUser} />
post:<AppendUser onSubmitFun={this.saveUser} />
<UserTable userlist={userlist} onDelete={fetchDeleteUser} />
</div>
);
}
}
function mapStateToProps(state) {
return {
userlist: state.userlist || []
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{ getUserList, fetchDeleteUser, fetchAddUser },
dispatch
);
}
export default connect(mapStateToProps, mapDispatchToProps)(UserList);
<file_sep>import React, { Component, PropTypes } from 'react'
import { Menu } from 'antd'
import { Link } from 'react-router'
class Nav extends Component {
constructor(props) {
super(props)
this.state = {
current: 'home'
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(e){
this.setState({
current: e.key,
});
}
render() {
return (
<Menu onClick={this.handleClick}
selectedKeys={[this.state.current]}
mode="horizontal"
>
<Menu.Item key="home">
<Link to="/">首页</Link>
</Menu.Item>
<Menu.Item key="userlist">
<Link to="/userlist">用户列表</Link>
</Menu.Item>
<Menu.Item key="message">
<Link to="/message">消息列表</Link>
</Menu.Item>
<Menu.Item key="forceByD3">
<Link to="/forceByD3">力导图</Link>
</Menu.Item>
<Menu.Item key="forceByD3Svg">
<Link to="/forceByD3Svg">力导图svg</Link>
</Menu.Item>
<Menu.Item key="forceByD3Svg2">
<Link to="/forceByD3Svg2">力导图svg2</Link>
</Menu.Item>
<Menu.Item key="forceByD3Canvas">
<Link to="/forceByD3Canvas">力导图canvas</Link>
</Menu.Item>
<Menu.Item key="forceByD3CanvasV4">
<Link to="/forceByD3CanvasV4">d3 v4 canvas</Link>
</Menu.Item>
<Menu.Item key="reptile">
<Link to="/reptile">抓图</Link>
</Menu.Item>
<Menu.Item key="fileUpload">
<Link to="/fileUpload">传图</Link>
</Menu.Item>
<Menu.Item key="fileUpload2">
<Link to="/fileUpload2">传图2</Link>
</Menu.Item>
<Menu.Item key="fileUpload3">
<Link to="/fileUpload3">传图3</Link>
</Menu.Item>
</Menu>
)
}
}
Nav.propTypes = {
// user: PropTypes.object.isRequired
}
export default Nav
<file_sep>import fetch from 'isomorphic-fetch'
import { message } from 'antd'
export const SET_COUNTER = 'SET_COUNTER'
export const INCREMENT_COUNTER = 'INCREMENT_COUNTER'
export const DECREMENT_COUNTER = 'DECREMENT_COUNTER'
export const SET_USERS = 'SET_USERS'
export const DELETE_USER = 'DELETE_USER'
export const ADD_USER = 'ADD_USER'
export const LOGIN_USER = 'LOGIN_USER'
export const SET_SOCKET = 'SET_SOCKET'
export function set(value) {
return {
type: SET_COUNTER,
payload: value
}
}
export function increment() {
return {
type: INCREMENT_COUNTER
}
}
export function decrement() {
return {
type: DECREMENT_COUNTER
}
}
export function incrementIfOdd() {
return (dispatch, getState) => {
const { counter } = getState()
if (counter % 2 === 0) {
return
}
dispatch(increment())
}
}
export function incrementAsync(delay = 1000) {
return dispatch => {
setTimeout(() => {
dispatch(increment())
}, delay)
}
}
// 获取用户列表
const fetchUser = function(){
return dispatch => {
return fetch('/user/getAll')
.then(response => response.json())
.then(json => {
console.log(json);
dispatch(setUsers(json.attr))
})
};
}
// 删除用户
const fetchDUser = function(id){
return dispatch => {
return fetch('/user/delete?id='+id)
.then(response => response.json())
.then(json => {
console.log(json);
if(json.type){
dispatch(deleteUser(id));
message.info(json.msg);
}else{
message.error(json.msg);
}
})
};
}
// 保存用户
const fetchAUser = function(username){
return dispatch => {
return fetch('/user/save?username='+username)
.then(response => response.json())
.then(json => {
console.log(json);
if(json.type){
dispatch(addUser(json.attr));
message.info(json.msg);
}else{
message.error(json.msg);
}
})
};
}
// 用户登录
const fetchLUser = function(username){
return dispatch => {
return fetch('/user/login?username='+username)
.then(response => response.json())
.then(json => {
console.log(json);
if(json.type){
dispatch(loginUser(json.attr));
message.info(json.msg);
}else{
message.error(json.msg);
}
})
};
}
/* 设置用户列表 */
export function setUsers(json){
return {
type :SET_USERS,
userlist :json
}
}
/* 获取用户列表-服务器 */
export function getUserList(){
return dispatch => {
return dispatch(fetchUser());
}
}
/* 删除用户 */
export function deleteUser(id){
// console.log(id);
return{
type: DELETE_USER,
id
}
}
/* 删除用户-服务器 */
export function fetchDeleteUser(id){
return dispatch => {
return dispatch(fetchDUser(id));
}
}
/* 添加用户 */
export function addUser(user){
return{
type: ADD_USER,
user
}
}
/* 添加用户-服务器 */
export function fetchAddUser(name){
return dispatch => {
return dispatch(fetchAUser(name));
}
}
/* 用户登录 */
export function loginUser(user){
return{
type: LOGIN_USER,
user
}
}
/* 用户登录-服务器 */
export function fetchLoginUser(name){
return dispatch => {
return dispatch(fetchLUser(name));
}
}
/* socket设置 */
export function setSocket(socket){
return{
type: SET_SOCKET,
socket
}
}
<file_sep>import url from 'url'
import reptile from '../common/reptile'
export function fun(app){
app.get('/reptileApi',function(req,res){
var params = url.parse(req.url, true).query;
if(params.file){
new reptile(res, params.file, params.num||30);
}
});
}
<file_sep>import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { browserHistory, Router } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import configureStore from '../common/store/configureStore'
import App from '../common/containers/App'
import routes from '../common/routes/index'
import '../common/css/main.css'
import 'antd/dist/antd.css';
const preloadedState = {};
const store = configureStore(preloadedState)
const rootElement = document.getElementById('root')
const history = syncHistoryWithStore(browserHistory, store)
// 注意 subscribe() 返回一个函数用来注销监听器
let unsubscribe = store.subscribe(() =>
console.log(store.getState())
)
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>,
rootElement
)
<file_sep>import React, { Component, PropTypes } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import client from "socket.io-client";
import antd, { Row, Col, Card } from "antd";
import { fetchLoginUser, setSocket } from "../actions";
import Login from "../components/Login";
import ChatUserList from "../components/ChatUserList";
import MessageList from "../components/MessageList";
import InputMessage from "../components/InputMessage";
class Chat extends Component {
constructor(props) {
super(props);
this.state = {
login: !this.props.user.id,
userlist: [],
chatList: { name: "all", id: "1" },
messages: []
};
this.commitName = this.commitName.bind(this);
this.changeUser = this.changeUser.bind(this);
this.sendMessage = this.sendMessage.bind(this);
this.infoNumChange = this.infoNumChange.bind(this);
this.createSocket = this.createSocket.bind(this);
this.socket = false;
if (props.user.id && !this.socket) {
this.createSocket();
}
}
componentDidMount() {
// // socket已存在拉取用户
// if(this.props.user.socket&&this.props.user.id){
// this.props.user.socket.emit('getUserlist',this.props.user.id);
// }
}
componentWillUnmount() {
this.socket.destroy();
}
componentWillUpdate(props) {
if (props.user.id && !this.socket) {
this.createSocket();
}
}
createSocket() {
var that = this;
//建立websocket连接
var socket = client();
this.socket = socket;
//收到server的连接确认
socket.on("open", function() {
socket.emit("userLogin", that.props.user);
});
//监听system事件,判断welcome或者disconnect,打印系统消息信息
socket.on("system", function(json) {
if (json.type == "login") {
antd.notification.info({
message: "用户登录",
description: "welcome: " + json.name
});
} else {
antd.notification.info({
message: "用户退出",
description: "goodbye: " + json.name
});
}
});
//监听message事件,打印消息信息
socket.on("message", function(json) {
console.log(json);
json.messageType = "message";
that.setState({
messages: that.state.messages.concat([json])
});
// all
that.infoNumChange(json);
});
// 监听用户列表
// socket.off()
socket.on("users", function(json) {
json.unshift({ name: "全部", id: "1" });
var userlist = [];
for (var i = 0; i < json.length; i++) {
var t = json[i];
t.infoNum = 0;
for (var j = 0; j < that.state.userlist.length; j++) {
var ht = that.state.userlist[j];
if (ht.id == t.id) {
t.infoNum = ht.infoNum;
break;
}
}
userlist.push(t);
}
that.setState({
userlist
});
});
}
commitName(value) {
console.log(value);
this.setState({
login: false
});
this.props.fetchLoginUser(value);
}
changeUser(chatList) {
var userlist = this.state.userlist;
for (var i = 0; i < userlist.length; i++) {
var t = userlist[i];
if (t.id == chatList.id) {
t.infoNum = 0;
}
}
this.setState({
chatList,
userlist
});
}
sendMessage(msg) {
this.socket.emit("message", {
toId: this.state.chatList.id,
toName: this.state.chatList.name,
msg
});
}
infoNumChange(json) {
console.log(json);
var userlist = this.state.userlist;
for (var i = 0; i < userlist.length; i++) {
var t = userlist[i];
if (t.id == "1" && this.state.chatList.id != "1") {
t.infoNum = (t.infoNum || 0) + 1;
}
if (
t.id != this.props.user.id &&
t.id != "1" &&
this.state.chatList.id != json.fromId &&
json.fromId == t.id &&
json.toId == this.props.user.id
) {
t.infoNum = (t.infoNum || 0) + 1;
}
}
this.setState({
userlist
});
}
render() {
// const {userlist, fetchDeleteUser, fetchAddUser} = this.props;
return (
<div>
<Login onSubmitFun={this.commitName} login={this.state.login} />
<div
className="content"
style={{ display: this.state.login ? "none" : "block" }}
>
<Row>
<Col span={5}>
<ChatUserList
changeUser={this.changeUser}
user={this.props.user}
userlist={this.state.userlist}
/>
</Col>
<Col span={19}>
<Card
title={this.props.user.name + "-to-" + this.state.chatList.name}
>
<MessageList
myName={this.props.user.name}
myId={this.props.user.id}
toName={this.state.chatList.name}
toId={this.state.chatList.id}
messages={this.state.messages}
/>
<InputMessage onSubmitMsg={this.sendMessage} />
</Card>
</Col>
</Row>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
user: state.user || {
name: "游客",
color: "red",
id: "",
socket: false
}
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ fetchLoginUser, setSocket }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Chat);
<file_sep>import React, { Component, PropTypes } from 'react'
import $ from 'jquery'
import QueueAnim from 'rc-queue-anim';
class MessageList extends Component {
constructor(props) {
super(props)
this.state = {
current: '1',
}
this.timeFormat = this.timeFormat.bind(this);
}
timeFormat(a,b){
var c = b
, d = new Date(a)
, e = {
"M+": d.getMonth() + 1,
"d+": d.getDate(),
"h+": d.getHours(),
"m+": d.getMinutes(),
"s+": d.getSeconds(),
"q+": Math.floor((d.getMonth() + 3) / 3),
S: d.getMilliseconds()
};
/(y+)/.test(c) && (c = c.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length)));
for (var f in e)
new RegExp("(" + f + ")").test(c) && (c = c.replace(RegExp.$1, 1 == RegExp.$1.length ? e[f] : ("00" + e[f]).substr(("" + e[f]).length)));
return c
}
componentDidUpdate(){
setTimeout(() => $('#scroll').scrollTop(100000), 200)
}
render() {
return (
<div className="oh" id="scroll">
<QueueAnim component="div" type={['right', 'left']}>
{
this.props.messages.map(function (message,index) {
if(this.props.toId == 1||message.toId == this.props.myId&&message.fromId == this.props.toId){
return (<div className="p" key={index}>
<span className="icon" style={{background:message.color}}></span>
<div className="r">
<div className="name">{ message.fromName } --to-- {message.toName}</div>
<div className="msg">
<span className="arrow"></span>
<p>{ message.text }</p>
<p className="c-9">{this.timeFormat(message.time,'yyyy-MM-dd hh:mm:ss')}</p>
</div>
</div>
</div>)
}else if(message.fromId == this.props.myId&&message.toId == this.props.toId){
return (<div className="p self" key={index}>
<div className="r">
<div className="name">{ message.fromName } --to-- {message.toName}</div>
<div className="msg">
<span className="arrow"></span>
<p>{ message.text }</p>
<p className="c-9">{this.timeFormat(message.time,'yyyy-MM-dd hh:mm:ss')}</p>
</div>
</div>
<span className="icon" style={{background:message.color}}></span>
</div>)
}
}.bind(this))
}
</QueueAnim>
</div>
)
}
}
MessageList.propTypes = {
// changeUser: PropTypes.func.isRequired,
// incrementIfOdd: PropTypes.func.isRequired,
// incrementAsync: PropTypes.func.isRequired,
// onSubmitFun: PropTypes.func.isRequired,
// login: PropTypes.bool.isRequired
}
export default MessageList
<file_sep># chat-v2
<file_sep>// var mongoose = require("mongoose");
// var base = require("../../common/base/index");
import mongoose from 'mongoose'
import base from '../../common/base/index'
// 连接字符串格式为mongodb://主机/数据库名
mongoose.connect('mongodb://localhost/chat');
// 数据库连接后,可以对open和error事件指定监听函数。
var db = mongoose.connection;
db.on('error', console.error);
db.once('open', function() {
console.log('Mongo连接成功')
//在这里创建你的模式和模型
});
var Schema = mongoose.Schema;
module.exports.users = mongoose.model('users', new Schema({
"name" : String,
"id" : String,
"color" : String,
"registered" : Number
}));
module.exports.messages = mongoose.model('messages', new Schema({
"time" : Number,
"color" : String,
"text" : String,
"fromName" : String,
"formId" : String,
"toName" : String,
"toId" : String
}));
module.exports.syslog = mongoose.model('syslog', new Schema({
"time" : Number,
"color" : String,
"name" : String,
"id" : String,
"type" : String
})); | 800b2e08238f5f6aab061f42b53c5db58846eab4 | [
"JavaScript",
"Markdown"
]
| 27 | JavaScript | wangxiaofeid/chat-v2 | b7a98a4ad683175997cc2d4cffb9a4aae85ba759 | 1c61076d99606a61cc3b104c28d3495e7faa474a |
refs/heads/master | <repo_name>adriano0488/test-dev<file_sep>/models/CarrosModel.php
<?php
class CarrosModel extends ActiveRecord\Model {
public static $table_name = 'carro';
}<file_sep>/autoloader.php
<?php
function loadClasses ($pClassName) {
$file_name = __DIR__ . "/classes/" . $pClassName . ".php";
if(file_exists($file_name)){
require_once($file_name);
}
}
function loadModels ($pClassName) {
$file_name = __DIR__ . "/models/" . $pClassName . ".php";
if(file_exists($file_name)){
require_once($file_name);
}
}
spl_autoload_register("loadClasses");
spl_autoload_register("loadModels");
require_once __DIR__.'/ActiveRecord.php';
#class Book extends ActiveRecord\Model { }
#$b = new Book;
#$b->test = 'teste';
<file_sep>/classes/Carros.php
<?php
class Carros{
public function __construct(){
}
public function add(){
}
public function index($id = null){
$req = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
if(method_exists($this, $id)){
return $this->$id();
}
if($req == 'DELETE'){
return $this->delete($id);
}
if($req == 'POST'){
return $this->create();
}
if($req == 'PUT'){
return $this->update($id);
}
$car_list = CarrosModel::all();
require_once APP_DIR . '/views/carros.php';
}
public function delete($id){
header('Content-type: application/json');
if(empty($id)){
return json_encode([
'sucess'=>false,
'message'=>'UM ID deve ser informado'
]);
}
$carro = CarrosModel::find($id);
$carro->delete();
try{
return json_encode([
'success'=>true,
'message'=>'CARRO: '.$id . ' removido com sucesso'
]);
}catch(\Exception $e){
return json_encode([
'success'=>false,
'message'=>'Carro nao existe na base'
]);
}
}
public function create(){
header('Content-type: application/json');
$m = new CarrosModel;
$m->marca = $_POST['marca'];
$m->modelo = $_POST['modelo'];
$m->ano = $_POST['ano'];
try{
$m->save();
}catch(\Exception $e){
return json_encode([
'success'=>false,
'message'=>'Ocorreu um erro ao salvar os dados'
]);
}
$id = $m->id;
return json_encode([
'success'=>true,
'message'=>'CARRO: '.$id . 'criado com sucesso'
]);
}
public function update($id){
header('Content-type: application/json');
$m = CarrosModel::find($id);
$data = file_get_contents('php://input');
parse_str($data, $data);
$m->marca = $data['marca'];
$m->modelo = $data['modelo'];
$m->ano = $data['ano'];
try{
$m->save();
}catch(\Exception $e){
return json_encode([
'sucess'=>false,
'message'=>'Ocorreu um erro ao salvar os dados'
]);
}
return json_encode([
'sucess'=>true,
'message'=>'CARRO: '.$id . 'atualizado com sucesso.'
]);
}
public function listCars(){
$carros = CarrosModel::all();
$html = '';
ob_start();
foreach($carros as $carro){?>
<tr data-id="<?php echo $carro->id; ?>">
<td><?php echo $carro->id; ?></td>
<td><?php echo $carro->marca; ?></td>
<td><?php echo $carro->modelo; ?></td>
<td><?php echo $carro->ano; ?></td>
<td>
<a href="javascript:void(0);" onclick="removeCar(<?php echo $carro->id; ?>)"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a> | <a href="javascript:void(0);" onclick="showEditForm(this)" data-id='<?php echo $carro->id ?>' data-marca='<?php echo $carro->marca ?>' data-modelo='<?php echo $carro->modelo ?>' data-ano='<?php echo $carro->ano ?>'><span class="glyphicon glyphicon-edit" aria-hidden="true"></span></a>
</td>
</tr>
<?php
}
$html = ob_get_contents();
ob_end_clean();
return $html;
}
}<file_sep>/README.md
Introdução
==============================
Este é um sistema simples de cadastro de carros baseado em PHP com MYSQL.
Para desenvolvimento em backend foi utilizado o plugin ActiveRecord:
https://github.com/jpfuentes2/php-activerecord/tree/master
Baseado em PDO
Para FRONTEND foi utilizado bootstrap.
Instalação
==============================
ROTAS:
CONFIGURAR REWRITE BASE no arquivo .htacess
se o acesso for http://localhost/estadao
A configuração deverá ser:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /estadao/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?_url=$1 [L]
# RewriteRule
</IfModule>
A condição "RewriteBase /estadao/" poderá ser alterada conforme necessidade
Configuração:
Arquivo config.php
#CONSTANTE que define URL base do projeto
define('BASE_URL', '/estadao' );
#CONEXAO COM BANCO DE DADOS
$config_database = [
'host'=>'127.0.0.1',
'driver'=>'mysql',
'user' => 'estadao',
'password'=>'<PASSWORD>',
'default_database'=>'carros',
];
Teste para desenvolvedor do Estadão
==============================
Olá Desenvolvedor,
Esse teste consiste em 2 etapas para avaliarmos seu conhecimento em PHP e Front-End (HTML5, CSS e JavaScript)
Para realizar o teste, você deve dar um fork neste repositório e depois clona-lo na pasta <document_root> da máquina que está realizando o teste.
Crie um branch com seu nome, e quando finalizar todo o desenvolvimento, você deverá enviar um pull-request com sua versão.
O teste
--------
###Back-End/PHP
A primeira etapa será o desenvolvimento **backend/PHP**:
**Descrição:**
- Você deverá desenvolver uma 'mini api' para que seja possível realizar operações CRUD do objeto Carro.
> **Obs:**
> - Você pode usar a sessão como banco de dados.
> - Cada carro deve ter ID, Marca, Modelo, Ano.
- Você deve alterar o arquivo `.htaccess` para criar as seguintes rotas:
- `/carros` - [GET] deve retornar todos os carros cadastrados.
- `/carros` - [POST] deve cadastrar um novo carro.
- `/carros/{id}`[GET] deve retornar o carro com ID especificado.
- `/carros/{id}`[PUT] deve atualizar os dados do carro com ID especificado.
- `/carros/{id}`[DELETE] deve apagar o carro com ID especificado.
### Front-End
Para a segunda etapa do teste, você deverá desenvolver uma SPA (Single Page Application) e nela deve ser possível:
- Ver a lista de carros cadastrados
- Criar um novo carro
- Editar um carro existente
- Apagar um carro existente
> **Obs:**
> - A página deve ser responsiva.
> - A página deve funcionar 100% via AJAX, sem outros carregamentos de páginas.
> - Ao criar/editar um carro, o campo "marca" deverá ser um `SELECT`
### Outras observações
- Você não deve se prender aos arquivos do repositório. Fique a vontade para criar outros.
- Você pode usar frameworks, tanto para o front-end, quanto para o back-end, mas um código limpo será melhor avaliado.
- Você pode usar ferramentas de automação (Grunt, Gulp), mas deverá informar o uso completo para funcionamento do teste.
- Desenvolver em JavaScript puro será considerado um plus.
- Criar rotinas de teste será considerado um plus.<file_sep>/views/header.php
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Registro de carros</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="<?php echo BASE_URL ?>">Início</a></li>
</ul>
</div>
</div>
</nav><file_sep>/classes/CarrosModel.php
<?php
class CarrosModel extends ActiveRecord\Model {
public static $table_name = 'carro';
}
/**
* $carro = new Carro;
#var_dump($carro,get_class_methods($carro),$carro->table_name());die;
$carro->ano = 2015;
$carro->marca = 'TOYOTA';
$carro->modelo = 'COROLLA';
$carro->save();
*/
<file_sep>/views/default.php
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.8.3.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script> var BASE_URL = '<?php echo BASE_URL; ?>';</script>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Web Dev Academy</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Início</a></li>
<li><a href="#">Opções</a></li>
<li><a href="#">Perfil</a></li>
<li><a href="#">Ajuda</a></li>
</ul>
</div>
</div>
</nav>
<div class='container-fluid'>
<div id='content-wrapper'>
<div class='container'>
<div id="main" class="container-fluid">
<h3 class="page-header">Ver registro de carros</h3>
<a href='<?php echo BASE_URL ?>/carros'>Ver registro de todos os carros</a>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.3.min.js"><\/script>')</script>
<script src="js/main.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
<file_sep>/index.php
<?php
require_once('autoloader.php');
require_once('config.php');
require_once('router.php');
require_once(APP_DIR.DS.'views'.DS.'default.php');
<file_sep>/views/carros.php
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.8.3.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script> var BASE_URL = '<?php echo BASE_URL; ?>';</script>
</head>
<body>
<?php require_once(APP_DIR . DS . 'views' . DS . 'header.php') ?>
<div class='container-fluid'>
<div id='content-wrapper'>
<div class='container'>
<div id="main" class="container-fluid">
<h3 class="page-header">Meu Registros de carros</h3>
<div class="col-md-7">
<div id="content">
<div>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Marca</th>
<th>Modelo</th>
<th>Ano</th>
<th>Ações</th>
</tr>
</thead>
<tbody id='tbody-cars'>
<?php foreach ($car_list as $carro): ?>
<tr data-id="<?php echo $carro->id; ?>">
<td><?php echo $carro->id; ?></td>
<td><?php echo $carro->marca; ?></td>
<td><?php echo $carro->modelo; ?></td>
<td><?php echo $carro->ano; ?></td>
<td>
<a href="javascript:void(0);" onclick="removeCar(<?php echo $carro->id; ?>)"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a> | <a href="javascript:void(0);" onclick="showEditForm(this)" data-id='<?php echo $carro->id ?>' data-marca='<?php echo $carro->marca ?>' data-modelo='<?php echo $carro->modelo ?>' data-ano='<?php echo $carro->ano ?>'><span class="glyphicon glyphicon-edit" aria-hidden="true"></span></a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-md-5">
<div class="panel panel-default">
<div class="panel-heading">Criar/Atualizar </div>
<div class="panel-body" id="content-form">
<form action="<?php echo BASE_URL . '/carros' ?>" method="POST" id='form-cars'>
<input type='hidden' id='id_car' value='' name='id' />
<div class="form-group">
<label for="ano">Ano:</label>
<input type="text" class="form-control" id="ano" maxlength="4" name='ano'>
</div>
<div class="form-group">
<label for="marca">Marca:</label>
<select name="marca" class='form-control' id='marca'>
<option value=''>Selecionar Marca</option>
<option value='Fiat'>Fiat</option>
<option value='Ford'>Ford</option>
<option value='Chevrolet'>Chevrolet</option>
</select>
</div>
<div class="form-group">
<label >Modelo:</label>
<input type="text" class="form-control" id="modelo" name='modelo'>
</div>
<button type="button" onclick="saveOrUpdate()" class="btn btn-default">Enviar</button>
<button type="reset" onclick="jQuery('#form-cars').attr('METHOD','POST');jQuery('#id_car').val('');" class="btn btn-default">Limpar</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.3.min.js"><\/script>')</script>
<script src="js/main.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
<file_sep>/config.php
<?php
define('APP_DIR', __DIR__ );
define('BASE_URL', '/estadao' );
define('DS', DIRECTORY_SEPARATOR );
$config_database = [
'host'=>'127.0.0.1',
'driver'=>'mysql',
'user' => 'estadao',
'password'=>'<PASSWORD>',
'default_database'=>'carros',
];
ActiveRecord\Config::initialize(function($cfg) use ($config_database)
{
$cfg->set_model_directory('.');
$cfg->set_connections(array('development' => "{$config_database['driver']}://{$config_database['user']}:{$config_database['password']}@{$config_database['host']}/{$config_database['default_database']}"));
});
<file_sep>/models/Model.php
<?php
abstract class Model{
public function save(){
}
public static function find($id){
}
public static function all(){
}
}
<file_sep>/carros.sql
-- phpMyAdmin SQL Dump
-- version 4.5.0.2
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: 24-Nov-2015 às 00:53
-- Versão do servidor: 10.0.17-MariaDB
-- PHP Version: 5.5.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `carros`
--
-- --------------------------------------------------------
--
-- Estrutura da tabela `carro`
--
CREATE TABLE `carro` (
`id` int(11) NOT NULL,
`marca` varchar(255) NOT NULL,
`modelo` varchar(255) NOT NULL,
`ano` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `carro`
--
INSERT INTO `carro` (`id`, `marca`, `modelo`, `ano`) VALUES
(4, 'TOYOTA', 'COROLLA', 2015),
(5, 'Ford', 'corolla', 2015),
(6, 'Ford', 'corolla', 2015),
(7, 'Chevrolet', '123', 2013),
(8, 'Ford', 'TESTE', 2015),
(9, 'Chevrolet', '123', 2015),
(10, 'Chevrolet', '123', 2015),
(11, 'Chevrolet', '123', 2014),
(12, 'Ford', 'TESTE', 2014),
(13, 'Fiat', 'Pálio', 200),
(14, 'Fiat', 'Pálio', 2000);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `carro`
--
ALTER TABLE `carro`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `carro`
--
ALTER TABLE `carro`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/router.php
<?php
$url_router = isset($_GET['_url']) ? $_GET['_url'] : '';
$url_router = !empty($url_router) ? trim($url_router, '/') : '';
$route_array = explode('/', $url_router);
$controller = $route_array[0] ? $route_array[0] : '';
$params = count($route_array) > 1 ? array_slice($route_array, 1) : [];
if (class_exists(ucfirst($controller))) {
$controller = new $controller();
$result = call_user_func_array([$controller, 'index'], $params);
echo $result;
exit;
}
| 975f5f1382bf47599c0853267f60e624ba503fe3 | [
"Markdown",
"SQL",
"PHP"
]
| 13 | PHP | adriano0488/test-dev | 277d35afc3db8ae00e9dcc6a8bbe19b1816d81c6 | 7624ab26a4d6317da762a5004ca6e6719378d911 |
refs/heads/master | <repo_name>Yayayay218/livematch-backend<file_sep>/controllers/votes.js
var mongoose = require('mongoose');
var apn = require('apn');
mongoose.Promise = global.Promise;
var HTTPStatus = require('../helpers/lib/http_status');
var constant = require('../helpers/lib/constant');
var CryptoJS = require('crypto-js')
var encrypt = require('../helpers/lib/encryptAPI')
var Votes = mongoose.model('Votes');
var sendJSONResponse = function (res, status, content) {
res.status(status);
res.json(content);
};
// GET all Votes
module.exports.voteGetAll = function (req, res) {
var query = req.query || {};
const id = req.query.id;
delete req.query.id;
var sort = req.query.sort || '-createdAt';
delete req.query.sort;
var channel = req.query.channel;
delete req.query.channel;
var user = req.payload._id;
var comment = req.query.comment;
delete req.query.comment;
if (id)
query = {
"_id": {$in: id}
};
else if (channel)
query = {
"channel": channel,
"user": user
};
else if (comment)
query = {
"comment": comment,
"user": user
};
else
query = {};
Votes.paginate(
query,
{
sort: sort,
page: Number(req.query.page),
limit: Number(req.query.limit)
}, function (err, vote) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var results = {
data: vote.docs,
total: vote.total,
limit: vote.limit,
page: vote.page,
pages: vote.pages
};
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results));
}
)
};
var checkVoteChannelExist = function (user, channel) {
return new Promise(function (resolve, reject) {
Votes.findOne({
user: user,
channel: channel,
}, function (err, vote) {
if (err)
reject(err);
if (!vote)
reject(err);
resolve(vote)
})
})
};
module.exports.voteUpChannel = function (req, res) {
req.body.type = 0;
req.body.user = req.payload._id;
req.body.channel = req.params.id;
checkVoteChannelExist(req.body.user, req.params.id).then(function (docs) {
if (docs.status == -1) {
req.body.status = 1;
Votes.findByIdAndUpdate(docs._id, req.body, {'new': true}, function (err, vote) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!vote)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: "vote's not founded"
});
var results = {
success: true,
message: 'Update vote successful!',
data: vote
}
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
}
else
Votes.findByIdAndRemove(docs._id, function (err) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
return sendJSONResponse(res, HTTPStatus.OK, {
success: true,
message: 'OK',
})
})
}).catch(function (err) {
console.log(err);
req.body.status = 1;
var data = req.body;
var vote = new Votes(data);
vote.save(function (err, vote) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, err);
var results = {
success: true,
message: 'Update vote successful!',
data: vote
}
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
})
};
module.exports.voteDownChannel = function (req, res) {
req.body.type = 0;
req.body.user = req.payload._id;
req.body.channel = req.params.id;
checkVoteChannelExist(req.body.user, req.params.id).then(function (docs) {
if (docs.status == 1) {
req.body.status = -1;
Votes.findByIdAndUpdate(docs._id, req.body, {'new': true}, function (err, vote) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!vote)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: "vote's not founded"
});
var results = {
success: true,
message: 'Update vote successful!',
data: vote
}
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
}
else
Votes.findByIdAndRemove(docs._id, function (err) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
return sendJSONResponse(res, HTTPStatus.OK, {
success: true,
message: 'OK',
})
})
}).catch(function (err) {
console.log(err);
req.body.status = -1;
var data = req.body;
var vote = new Votes(data);
vote.save(function (err, vote) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, err);
var results = {
success: true,
message: 'Update vote successful!',
data: vote
}
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
})
};
var checkVoteCommentExist = function (user, comment) {
return new Promise(function (resolve, reject) {
Votes.findOne({
user: user,
comment: comment,
}, function (err, vote) {
if (err)
reject(err);
if (!vote)
reject(err);
resolve(vote)
})
})
};
module.exports.voteUpComment = function (req, res) {
req.body.type = 0;
req.body.user = req.payload._id;
req.body.comment = req.params.id;
checkVoteCommentExist(req.body.user, req.params.id).then(function (docs) {
if (docs.status == -1) {
req.body.status = 1;
Votes.findByIdAndUpdate(docs._id, req.body, {'new': true}, function (err, vote) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!vote)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: "vote's not founded"
});
var results = {
success: true,
message: 'Update vote successful!',
data: vote
}
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
}
else
Votes.findByIdAndRemove(docs._id, function (err) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
return sendJSONResponse(res, HTTPStatus.OK, {
success: true,
message: 'OK',
})
})
}).catch(function (err) {
console.log(err);
req.body.status = 1;
var data = req.body;
var vote = new Votes(data);
vote.save(function (err, vote) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, err);
var results = {
success: true,
message: 'Update vote successful!',
data: vote
}
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
})
};
module.exports.voteDownComment = function (req, res) {
req.body.type = 0;
req.body.user = req.payload._id;
req.body.comment = req.params.id;
checkVoteCommentExist(req.body.user, req.params.id).then(function (docs) {
if (docs.status == 1) {
req.body.status = -1;
Votes.findByIdAndUpdate(docs._id, req.body, {'new': true}, function (err, vote) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!vote)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: "vote's not founded"
});
var results = {
success: true,
message: 'Update vote successful!',
data: vote
}
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
}
else
Votes.findByIdAndRemove(docs._id, function (err) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
return sendJSONResponse(res, HTTPStatus.OK, {
success: true,
message: 'OK',
})
})
}).catch(function (err) {
console.log(err);
req.body.status = -1;
var data = req.body;
var vote = new Votes(data);
vote.save(function (err, vote) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, err);
var results = {
success: true,
message: 'Update vote successful!',
data: vote
}
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
})
};
<file_sep>/compose/node/Dockerfile
FROM node:6.11.0
RUN useradd --user-group --create-home --shell /bin/false app &&\
npm install -g pm2
ENV HOME=/home/app
COPY package.json $HOME/livematch-backend/
RUN chown -R app:app $HOME/*
USER app
WORKDIR $HOME/livematch-backend
RUN npm install --production
USER root
COPY . $HOME/livematch-backend
RUN chown -R app:app $HOME/*
USER app
CMD ["pm2", "start", "--no-daemon", "processes.json"]
<file_sep>/client/channel/index.js
import React from 'react';
import {
Create,
Edit,
List,
SimpleForm,
FormTab,
TabbedForm,
DisabledInput,
TextInput,
DateInput,
LongTextInput,
ReferenceManyField,
Datagrid,
TextField,
DateField,
EditButton,
DeleteButton,
ImageInput,
ImageField,
BooleanField,
SelectInput,
BooleanInput,
ReferenceInput,
ReferenceField,
Filter,
} from 'admin-on-rest';
import {required} from 'admin-on-rest'
import StatusField from '../channel/StatusField'
import ActiveButton from '../channel/ActiveButton'
const ChannelFilter = (props) => (
<Filter {...props}>
<TextInput label="Search" source="q" alwaysOn/>
</Filter>
)
export const ChannelList = (props) => (
<List {...props} filters={<ChannelFilter/>}>
<Datagrid>
<ReferenceField label="Match" source="match._id" reference="matches" allowEmpty>
<TextField source="name"/>
</ReferenceField>
<TextField source="name"/>
<TextField source="link"/>
<StatusField source="status" label="Status"/>
<ActiveButton/>
<EditButton/>
<DeleteButton/>
</Datagrid>
</List>
);
export const ChannelCreate = (props) => (
<Create {...props}>
<SimpleForm label="Channel's Information">
<TextInput source="name" label="Channel Name" validate={[required]}/>
<TextInput source="link" validate={[required]}/>
<SelectInput source="status" choices={[
{id: '0', name: 'inactive'},
{id: '1', name: 'active'}
]}/>
<BooleanInput label="Show Link" source="isShow"/>
<ReferenceInput label="Assign to" source="match" reference="matches"
allowEmpty>
<SelectInput optionText="name"/>
</ReferenceInput>
</SimpleForm>
</Create>
);
const ChannelTitle = ({record}) => {
return <span>Channel {record ? `"${record.name}"` : ''}</span>;
};
export const ChannelEdit = (props) => (
<Edit title={<ChannelTitle/>} {...props}>
<SimpleForm>
<DisabledInput label="Channel Id" source="id"/>
<TextInput source="name" label="Channel Name" validate={[required]}/>
<TextInput source="link" validate={[required]}/>
<BooleanInput label="Show Link" source="isShow"/>
<ReferenceInput label="Assign to" source="match._id" reference="matches"
allowEmpty>
<SelectInput optionText="name"/>
</ReferenceInput>
<SelectInput source="status" allowEmpty choices={[
{id: '0', name: 'inactive'},
{id: '1', name: 'active'}
]}/>
</SimpleForm>
</Edit>
);<file_sep>/client/matches/TimeField.js
import React from 'react';
import PropTypes from 'prop-types';
const TimeField = ({record = {}}) => {
let time = record.time;
time = parseInt(time/100) + ":" + (time % 100 ? time % 100 : '00');
return <span>{time}</span>
};
TimeField.PropTypes = {
label: PropTypes.string,
record: PropTypes.object,
source: PropTypes.string.isRequired
};
export default TimeField;
<file_sep>/models/posts.js
var mongoose = require('mongoose'), Schema = mongoose.Schema;
var mongoosePaginate = require('mongoose-paginate');
var postSchema = new mongoose.Schema({
name: String,
description: String,
link: String,
label: String,
status: Number,
isRequired: Boolean,
type: Number,
coverPhoto: String,
isShow: {
type: Boolean,
default: false
},
showDis: {
type: Boolean,
default: true
},
match: {type: Schema.Types.ObjectId, ref: 'Matches'},
createdAt: {
type: Date,
default: Date.now()
},
updatedAt: Date
});
postSchema.plugin(mongoosePaginate);
mongoose.model('Posts', postSchema);<file_sep>/controllers/posts.js
var mongoose = require('mongoose');
var apn = require('apn');
mongoose.Promise = global.Promise;
var HTTPStatus = require('../helpers/lib/http_status');
var constant = require('../helpers/lib/constant');
var CryptoJS = require('crypto-js')
var encrypt = require('../helpers/lib/encryptAPI');
var Posts = mongoose.model('Posts');
var Notifications = mongoose.model('Notifications');
var sendJSONResponse = function (res, status, content) {
res.status(status);
res.json(content);
};
var pushNotification = function (name, image, type, token) {
var apnProvider = new apn.Provider(constant.DEV_OPTS);
var note = new apn.Notification();
note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge = 1;
note.sound = "default";
note.topic = 'com.astralerapps.livematchios';
// note.alert = "\uD83D\uDCE7 \u2709 " + data.alert;
if (type === 0)
note.title = 'Full match replay of ' + name + ' is now available. Watch it now!';
else
note.title = 'A video highlights of ' + name + ' is now available. Watch it now!';
note.body = image;
console.log(note);
token.forEach(function (token) {
apnProvider.send(note, token).then(function (result) {
console.log("sent:", result.sent.length);
console.log("failed:", result.failed.length);
console.log(result.failed);
});
});
apnProvider.shutdown();
};
// Config upload photo
var multer = require('multer');
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, 'uploads/posts')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1]);
}
});
var upload = multer({
storage: storage
}).single('file');
var getListTokens = function (id, status) {
return new Promise(function (resolve, reject) {
var token = [];
Notifications.find({
match: id,
status: status
}, function (err, data) {
if (err)
reject(err);
else {
data.forEach(function (noti) {
token.push(noti.token)
});
resolve(token);
}
});
})
};
// POST a post
module.exports.newPost = function (req, res) {
upload(req, res, function (err) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var data = req.body;
var post = new Posts(data);
post.save(function (err, post) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var results = {
success: true,
data: post
}
return sendJSONResponse(res, HTTPStatus.CREATED, encrypt.jsonObject(results))
})
});
};
module.exports.newFullMatch = function (req, res) {
upload(req, res, function (err) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
req.body.type = 0;
var data = req.body;
var post = new Posts(data);
post.save(function (err, post) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
getListTokens(post.match, 1).then(function (data) {
console.log(data);
pushNotification(post.name, post.coverPhoto, 0, data);
}).catch(function (err) {
sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
})
});
var results = {
success: true,
data: post
}
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(results), constant.SECRET_KEY);
return sendJSONResponse(res, HTTPStatus.CREATED, encrypt.jsonObject(results))
})
});
};
module.exports.newHighlight = function (req, res) {
upload(req, res, function (err) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
req.body.type = 1;
var data = req.body;
var post = new Posts(data);
post.save(function (err, post) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
getListTokens(post.match, 2).then(function (data) {
pushNotification(post.name, post.coverPhoto, 1, data);
}).catch(function (err) {
sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
})
});
var results = {
success: true,
data: post
}
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(results), constant.SECRET_KEY);
return sendJSONResponse(res, HTTPStatus.CREATED, encrypt.jsonObject(results))
})
});
};
// GET all Posts UnAuthorize
module.exports.postGetAllUnAuthorize = function (req, res) {
var query = req.query || {};
const id = req.query.id;
delete req.query.id;
const match = req.query.match;
delete req.query.match;
const type = req.query.type;
delete req.query.type;
if (id)
query = {
"_id": {$in: id},
"status": 1
};
else if (match)
query = {
"match": {$in: match},
"status": 1
};
else if (type)
query = {
"type": {$in: type},
"status": 1
};
else
query = {
"status": 1
};
Posts.paginate(
query,
{
sort: req.query.sort,
populate: 'match',
page: Number(req.query.page),
limit: Number(req.query.limit)
}, function (err, post) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var results = {
data: post.docs,
total: post.total,
limit: post.limit,
page: post.page,
pages: post.pages
};
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(results), constant.SECRET_KEY);
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results));
}
)
};
// GET all Posts
module.exports.postGetAll = function (req, res) {
var query = req.query || {};
const id = req.query.id;
delete req.query.id;
const match = req.query.match;
delete req.query.match;
const type = req.query.type;
delete req.query.type;
if (id)
query = {
"_id": {$in: id}
};
else if (match)
query = {
"match": {$in: match}
};
else if (type)
query = {
"type": {$in: type}
};
else
query = {};
Posts.paginate(
query,
{
sort: req.query.sort,
populate: 'match',
page: Number(req.query.page),
limit: Number(req.query.limit)
}, function (err, post) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var results = {
data: post.docs,
total: post.total,
limit: post.limit,
page: post.page,
pages: post.pages
};
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(results), constant.SECRET_KEY);
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results));
}
)
};
module.exports.postGetOne = function (req, res) {
Posts.findById(req.params.id)
.populate('match')
.exec(function (err, post) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!post)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: 'post not founded'
});
var results = {
success: true,
data: post
}
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(results), constant.SECRET_KEY);
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
};
// PUT a post
module.exports.postPUT = function (req, res) {
req.body.updatedAt = Date.now();
upload(req, res, function (err) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var data = req.body;
Posts.findByIdAndUpdate(req.params.id, data, {'new': true}, function (err, post) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!post)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: "post's not founded"
});
var results = {
success: true,
data: post
}
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(results), constant.SECRET_KEY);
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
});
};
// DEL a post
module.exports.postDEL = function (req, res) {
if (req.params.id)
Posts.findByIdAndRemove(req.params.id, function (err) {
if (err)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: err
});
return sendJSONResponse(res, HTTPStatus.NO_CONTENT, {
success: true,
message: 'post was deleted'
})
});
};<file_sep>/models/notifications.js
var mongoose = require('mongoose'), Schema = mongoose.Schema;
var mongoosePaginate = require('mongoose-paginate');
var notificationSchema = new mongoose.Schema({
token: String,
match: {type: Schema.Types.ObjectId, ref: 'Matches'},
status: Number,
createdAt: {
type: Date,
default: Date.now()
},
updatedAt: Date
});
notificationSchema.plugin(mongoosePaginate);
mongoose.model('Notifications', notificationSchema);<file_sep>/routes/share.js
var express = require('express');
var router = express.Router();
var matchCtrl = require('../controllers/matches');
router.get('/:id', matchCtrl.matchGetOne);
module.exports = router;
<file_sep>/controllers/channels.js
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var HTTPStatus = require('../helpers/lib/http_status');
var constant = require('../helpers/lib/constant');
var _ = require('lodash');
var async = require('async');
var CryptoJS = require('crypto-js');
var encrypt = require('../helpers/lib/encryptAPI');
var Channels = mongoose.model('Channels');
var Matches = mongoose.model('Matches');
var Users = mongoose.model('Users');
var Votes = mongoose.model('Votes');
var sendJSONResponse = function (res, status, content) {
res.status(status);
res.json(content);
};
var checkVoteChannelExist = function (user, channel) {
return new Promise(function (resolve, reject) {
Votes.findOne({
user: user,
channel: channel,
}, function (err, vote) {
if (err)
reject(err);
if (!vote)
reject(err);
resolve(vote)
})
})
};
var sumVote = function (channel, user) {
return new Promise(function (resolve, reject) {
Votes.aggregate([
{
$match:
{
channel: mongoose.Types.ObjectId(channel)
}
},
{
$addFields: {
isVote: {$eq: ['$user', mongoose.Types.ObjectId(user)]},
}
},
{
$group: {
_id: null,
isVote: {$push: '$isVote'},
total: {$sum: "$status"}
}
}
], function (err, result) {
if (err)
reject(err);
else
resolve(result)
})
})
}
// Config upload photo
// var multer = require('multer');
//
// var storage = multer.diskStorage({ //multers disk storage settings
// destination: function (req, file, cb) {
// cb(null, 'uploads/channel')
// },
// filename: function (req, file, cb) {
// var datetimestamp = Date.now();
// cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1]);
// }
// });
// var upload = multer({
// storage: storage
// }).single('file');
// POST a channel
module.exports.channelPOST = function (req, res) {
var data = req.body;
var channel = new Channels(data);
channel.save(function (err, channel) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var results = {
success: true,
data: channel
}
return sendJSONResponse(res, HTTPStatus.CREATED, encrypt.jsonObject(results))
});
};
// GET all Channels
module.exports.channelGetAll = function (req, res) {
var query = req.query || {};
const id = req.query.id;
delete req.query.id;
const match = req.query.match;
delete req.query.match;
const status = req.query.status;
delete req.query.status;
var search = req.query.q;
var userId = '59f046feace52e03554a47b9';
if (req.query.userId)
userId = req.query.userId;
else
userId = '59f046feace52e03554a47b9';
if (id) {
query = {
"_id": {$in: id}
};
}
else if (match)
query = {
"match": {$in: match}
};
else if (search) {
query = {
$or: [{
matchName: {
$regex: search,
$options: 'i'
}
}]
}
}
else if (status)
query = {
"status": {$in: status}
};
else
query = {};
Channels.paginate(
query,
{
sort: req.query.sort,
page: Number(req.query.page),
limit: Number(req.query.limit),
lean: true
}, function (err, channel) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var tmp = [];
async.each(channel.docs, function (data, callback) {
sumVote(data._id, userId).then(function (votes) {
var newChannel = [];
if (!votes[0])
newChannel = _.assign(data, {votes: 0});
else {
newChannel = _.assign(data, {votes: votes[0].total, isVote: votes[0].isVote});
}
tmp.push(newChannel);
callback();
})
}, function (err) {
if (err) {
var results = {
data: channel.docs,
total: channel.total,
limit: channel.limit,
page: channel.page,
pages: channel.pages,
};
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results));
}
else {
channel.docs = tmp;
var results = {
data: channel.docs,
total: channel.total,
limit: channel.limit,
page: channel.page,
pages: channel.pages,
};
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results));
}
})
}
)
};
module.exports.channelGetOne = function (req, res) {
Channels.findById(req.params.id, function (err, channel) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!channel)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: 'channel not founded'
});
var results = {
success: true,
data: channel
}
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
};
// DEL a channelz
module.exports.channelDEL = function (req, res) {
if (req.params.id)
Channels.findByIdAndRemove(req.params.id, function (err) {
if (err)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: err
});
return sendJSONResponse(res, HTTPStatus.NO_CONTENT, {
success: true,
message: 'channel was deleted'
})
});
};
// PUT a channel
module.exports.channelPUT = function (req, res) {
req.body.updatedAt = Date.now();
var data = req.body;
Channels.findByIdAndUpdate(req.params.id, data, {'new': true}, function (err, channel) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!channel)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: "channel's not founded"
});
var results = {
success: true,
data: channel
}
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
});
};<file_sep>/client/admin.js
import React from 'react';
import {render} from 'react-dom';
import {
Admin, Resource, fetchUtils, Delete
} from 'admin-on-rest';
import authClient from './authClient'
import {MatchList, MatchCreate, MatchEdit} from './matches/index';
import {FullMatchList, FullMatchEdit, FullMatchCreate} from './posts/FullMatch'
import {HighlightCreate, HighlightEdit, HighlightList } from "./posts/Highlight"
import {ChannelCreate, ChannelEdit, ChannelList} from "./channel/index"
import {NotificationsCreate} from "./notifications/index"
import {SettingList, SettingCreate, SettingEdit} from "./settings/index"
// import {Dashboard} from './dashboard';
// Import REST APIs
import customRestClient from './rest/restClient';
import addUploadFeature from './rest/addUploadFeature';
const httpClient = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' })
}
const token = localStorage.getItem('token');
options.headers.set('Authorization', token);
return fetchUtils.fetchJson(url, options);
};
const apiUrl = '/api';
const restClient = customRestClient(apiUrl, httpClient);
const uploadCapableClient = addUploadFeature(restClient);
render(
<Admin authClient={authClient} restClient={uploadCapableClient} title="My Dashboard">
<Resource name="matches" list={MatchList} edit={MatchEdit} create={MatchCreate} remove={Delete}/>
<Resource name="fullMatches" list={FullMatchList} create={FullMatchCreate} edit={FullMatchEdit} options={{ label: 'Full Matches'}} remove={Delete}/>
<Resource name="highlights" list={HighlightList} create={HighlightCreate} edit={HighlightEdit} options={{ label: 'Highlights'}} remove={Delete}/>
{/*<Resource name="channels" list={ChannelList} create={ChannelCreate} edit={ChannelEdit} remove={Delete}/>*/}
<Resource name="customNotification" list={NotificationsCreate} options={{label: 'Notifications'}}/>
<Resource name="settings" list={SettingList} edit={SettingEdit} create={SettingCreate}/>
</Admin>,
document.getElementById('root')
);
<file_sep>/controllers/comments.js
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var HTTPStatus = require('../helpers/lib/http_status');
var constant = require('../helpers/lib/constant');
var _ = require('lodash');
var async = require('async');
var CryptoJS = require('crypto-js')
var encrypt = require('../helpers/lib/encryptAPI')
var Comments = mongoose.model('Comments');
var Matches = mongoose.model('Matches');
var Votes = mongoose.model('Votes');
var Reports = mongoose.model('Reports')
var sendJSONResponse = function (res, status, content) {
res.status(status);
res.json(content);
};
var sumVote = function (comment, user) {
return new Promise(function (resolve, reject) {
Votes.aggregate([
{
$match:
{
comment: mongoose.Types.ObjectId(comment)
}
},
{
$addFields: {
isVote: {$eq: ['$user', mongoose.Types.ObjectId(user)]},
}
},
{
$group: {
_id: null,
isVote: {$push: '$isVote'},
total: {$sum: "$status"}
}
}], function (err, result) {
if (err)
reject(err);
else
resolve(result)
})
})
}
var sumReport = function (comment, user) {
return new Promise(function (resolve, reject) {
Reports.aggregate([
{
$match:
{
comment: mongoose.Types.ObjectId(comment)
}
},
{
$addFields: {
isReport: {$eq: ['$user', mongoose.Types.ObjectId(user)]},
}
},
{
$group: {
_id: null,
isReport: {$push: '$isReport'},
total: {$sum: "$status"}
}
}], function (err, result) {
if (err)
reject(err);
else
resolve(result)
})
})
}
// POST a comment
module.exports.commentPOST = function (req, res) {
req.body.createdAt = new Date();
req.body.user = req.payload._id;
var data = req.body;
var comment = new Comments(data);
comment.save(function (err, comment) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, err);
var results = {
success: true,
data: comment
}
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
};
// GET all Comments
module.exports.commentGetAll = function (req, res) {
var query = req.query || {};
const id = req.query.id;
delete req.query.id;
var sort = req.query.sort || '-createdAt';
delete req.query.sort;
var match = req.query.match;
delete req.query.match;
if (id)
query = {
"_id": {$in: id}
};
else if (match)
query = {
"match": {$in: match}
};
else
query = {};
var userId = '59f046feace52e03554a47b9';
if (req.query.userId)
userId = req.query.userId;
else
userId = '59f046feace52e03554a47b9';
Comments.paginate(
query,
{
populate: 'user',
sort: sort,
page: Number(req.query.page),
limit: Number(req.query.limit),
lean: true
}, function (err, comment) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var tmp = [];
async.each(comment.docs, function (data, callback) {
sumVote(data._id, userId).then(function (votes) {
var newComment = [];
if (!votes[0])
newComment = _.assign(data, {votes: 0});
else
newComment = _.assign(data, {votes: votes[0].total, isVote: votes[0].isVote});
tmp.push(newComment);
callback();
})
}, function (err) {
if (err) {
var results = {
data: comment.docs,
total: comment.total,
limit: comment.limit,
page: comment.page,
pages: comment.pages,
};
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results));
}
else {
var tmpReport = [];
async.each(tmp, function (data, callback) {
sumReport(data._id, userId).then(function (reports) {
var newComment = [];
if (!reports[0])
newComment = _.assign(data, {reports: 0});
else
newComment = _.assign(data, {reports: reports[0].total, isReport: reports[0].isReport});
tmpReport.push(newComment);
callback();
})
}, function (err) {
if (err)
console.log(err)
else {
comment.docs = tmpReport;
var results = {
data: comment.docs,
total: comment.total,
limit: comment.limit,
page: comment.page,
pages: comment.pages,
};
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results));
}
})
}
})
}
)
};
module.exports.commentGetOne = function (req, res) {
Comments.findById(req.params.id, function (err, comment) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!comment)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: 'comment not founded'
});
return sendJSONResponse(res, HTTPStatus.OK, {
success: true,
data: comment
})
})
};
// DEL a commentz
module.exports.commentDEL = function (req, res) {
if (req.params.id)
Comments.findByIdAndRemove(req.params.id, function (err) {
if (err)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: err
});
return sendJSONResponse(res, HTTPStatus.NO_CONTENT, {
success: true,
message: 'comment was deleted'
})
});
};
// PUT a comment
module.exports.commentPUT = function (req, res) {
req.body.updatedAt = Date.now();
var data = req.body;
Comments.findByIdAndUpdate(req.params.id, data, {'new': true}, function (err, comment) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!comment)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: "comment's not founded"
});
var results = {
success: true,
data: comment
}
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results));
});
};<file_sep>/controllers/settings.js
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var HTTPStatus = require('../helpers/lib/http_status');
var constant = require('../helpers/lib/constant');
var CryptoJS = require('crypto-js');
var encrypt = require('../helpers/lib/encryptAPI')
var Settings = mongoose.model('Settings');
var sendJSONResponse = function (res, status, content) {
res.status(status);
res.json(content);
};
module.exports.settingPOST = function (req, res) {
var data = req.body;
var setting = new Settings(data);
setting.save(function (err, setting) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var results = {
success: true,
data: setting
}
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(results), constant.SECRET_KEY);
return sendJSONResponse(res, HTTPStatus.CREATED, encrypt.jsonObject(results))
});
};
// GET all Settings
module.exports.settingGetAll = function (req, res) {
var query = req.query || {};
const id = req.query.id;
delete req.query.id;
const name = req.query.name;
delete req.query.name;
if (id)
query = {
"_id": {$in: id}
};
else if (name) {
query = {
"name": {$in: name}
}
}
else
query = {};
Settings.paginate(
query,
{
sort: req.query.sort,
page: Number(req.query.page),
limit: Number(req.query.limit)
}, function (err, setting) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var results = {
data: setting.docs,
total: setting.total,
limit: setting.limit,
page: setting.page,
pages: setting.pages
};
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(results), constant.SECRET_KEY);
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results));
}
)
};
// Setting Get One
module.exports.settingGetOne = function (req, res) {
Settings.findById(req.params.id, function (err, setting) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
})
if (!setting)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: 'Setting not Founded'
})
var results = {
success: true,
data: setting
}
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(results), constant.SECRET_KEY);
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
};
// Setting PUT
module.exports.settingPUT = function (req, res) {
var data = req.body;
Settings.findByIdAndUpdate(req.params.id, data, {new: true}, function (err, setting) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err,
})
if (!setting)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: err
})
var results = {
success: true,
message: 'Update successful!!',
data: setting
}
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(results), constant.SECRET_KEY);
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
};<file_sep>/client/channel/ActiveButton.js
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import RaisedButton from 'material-ui/RaisedButton';
import {showNotification as showNotificationAction} from 'admin-on-rest';
import {push as pushAction} from 'react-router-redux';
import {UPDATE} from 'admin-on-rest';
class ActiveButton extends Component {
handleClick = () => {
const {push, record, showNotification} = this.props;
console.log(this.props);
const updatedRecord = {...record, status: record.status == 0 ? 1 : 0};
fetch(`/api/channels/${record.id}`,
{
method: 'PUT',
body: JSON.stringify(updatedRecord),
headers: {
"Content-Type": "application/json",
"accept": "application/json"
}
})
.then(() => {
showNotification('Channel Status Active');
push('/channels');
window.location.reload();
})
.catch((e) => {
console.error(e);
showNotification('Error: comment not approved', 'warning')
});
}
render() {
return (this.props.record.status == 0 ? <RaisedButton label="Activate" onClick={this.handleClick}/> :
<RaisedButton label="Deactivate" onClick={this.handleClick}/>);
}
}
ActiveButton.propTypes = {
push: PropTypes.func,
record: PropTypes.object,
showNotification: PropTypes.func,
};
export default connect(null, {
showNotification: showNotificationAction,
push: pushAction,
})(ActiveButton);<file_sep>/models/comments.js
var mongoose = require('mongoose'), Schema = mongoose.Schema;
var mongoosePaginate = require('mongoose-paginate');
var commentSchema = new mongoose.Schema({
content: String,
user: {type: Schema.Types.ObjectId, ref: 'Users'},
image: String,
match: {type: Schema.Types.ObjectId, ref: 'Matches'},
createdAt: {
type: Date,
// default: Date.now()
},
updatedAt: Date
});
commentSchema.plugin(mongoosePaginate);
mongoose.model('Comments', commentSchema);<file_sep>/controllers/report.js
var mongoose = require('mongoose');
var apn = require('apn');
mongoose.Promise = global.Promise;
var HTTPStatus = require('../helpers/lib/http_status');
var constant = require('../helpers/lib/constant');
var encrypt = require('../helpers/lib/encryptAPI');
var Reports = mongoose.model('Reports');
var sendJSONResponse = function (res, status, content) {
res.status(status);
res.json(content);
};
// GET all Reports
module.exports.reportGetAll = function (req, res) {
var query = req.query || {};
const id = req.query.id;
delete req.query.id;
var sort = req.query.sort || '-createdAt';
delete req.query.sort;
var user = req.payload._id;
var comment = req.query.comment;
delete req.query.comment;
if (id)
query = {
"_id": {$in: id}
};
else if (comment)
query = {
"comment": comment,
"user": user
};
else
query = {};
Reports.paginate(
query,
{
sort: sort,
page: Number(req.query.page),
limit: Number(req.query.limit)
}, function (err, report) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var results = {
data: report.docs,
total: report.total,
limit: report.limit,
page: report.page,
pages: report.pages
};
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results));
}
)
};
var checkReportCommentExist = function (user, comment) {
return new Promise(function (resolve, reject) {
Reports.findOne({
user: user,
comment: comment,
}, function (err, report) {
if (err)
reject(err);
if (!report)
reject(err);
resolve(report)
})
})
};
module.exports.reportComment = function (req, res) {
req.body.user = req.payload._id;
req.body.comment = req.params.id;
checkReportCommentExist(req.body.user, req.params.id).then(function (docs) {
Reports.findByIdAndRemove(docs._id, function (err, report) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var results = {
success: true,
message: 'Delete report successful!',
}
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
}).catch(function (err) {
console.log(err);
req.body.status = 1;
var data = req.body;
var report = new Reports(data);
report.save(function (err, report) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, err);
var results = {
success: true,
message: 'Update report successful!',
data: report
};
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
})
})
};<file_sep>/controllers/matches.js
var mongoose = require('mongoose');
var apn = require('apn');
mongoose.Promise = global.Promise;
var HTTPStatus = require('../helpers/lib/http_status');
var constant = require('../helpers/lib/constant');
var encrypt = require('../helpers/lib/encryptAPI')
var slug = require('slug');
var fs = require('fs');
var CryptoJS = require("crypto-js");
var Matches = mongoose.model('Matches');
var Notifications = mongoose.model('Notifications');
var sendJSONResponse = function (res, status, content) {
res.status(status);
res.json(content);
};
var pushNotification = function (name, token) {
var apnProvider = new apn.Provider(constant.DEV_OPTS);
var note = new apn.Notification();
note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge = 1;
note.sound = "default";
// note.alert = "\uD83D\uDCE7 \u2709 " + data.alert;
note.title = name + ' is now on live. Watch it now!';
note.body = name + ' is now on live. Watch it now!';
note.topic = 'com.astralerapps.livematchios';
console.log(note);
token.forEach(function (token) {
apnProvider.send(note, token).then(function (result) {
console.log("sent:", result.sent.length);
console.log("failed:", result.failed.length);
console.log(result.failed);
});
});
apnProvider.shutdown();
};
var getListTokens = function (id, status) {
return new Promise(function (resolve, reject) {
var token = [];
Notifications.find({
match: id,
status: status
}, function (err, data) {
if (err)
reject(err);
else {
data.forEach(function (noti) {
token.push(noti.token)
});
resolve(token);
}
});
})
};
// POST a match
module.exports.matchPOST = function (req, res) {
req.body.slug = slug(req.body.name);
var data = req.body;
var match = new Matches(data);
match.save(function (err, match) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var results = {
success: true,
message: "Add a new match successful!",
data: match
}
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(results), constant.SECRET_KEY);
return sendJSONResponse(res, HTTPStatus.CREATED, encrypt.jsonObject(results))
});
};
// GET all Matches
module.exports.matchGetAll = function (req, res) {
var query = req.query || {};
const id = req.query.id;
delete req.query.id;
const status = req.query.status;
delete req.query.status;
var sort = req.query.sort || 'index';
delete req.query.sort;
if (id)
query = {
"_id": {$in: id}
};
else if (status)
query = {
"status": {$in: status}
}
else
query = {};
Matches.paginate(
query,
{
populate: {
path: 'comments',
populate: {
path: 'user'
}
},
sort: sort,
page: Number(req.query.page),
limit: Number(req.query.limit),
// lean: true
}, function (err, match) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var results = {
data: match.docs,
total: match.total,
limit: match.limit,
page: match.page,
pages: match.pages
};
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(results), constant.SECRET_KEY);
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results));
}
)
};
module.exports.matchGetOne = function (req, res) {
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
if (checkForHexRegExp.test(req.params.id)) {
Matches.findById(req.params.id, function (err, match) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!match)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: 'match not founded'
});
var results = {
success: true,
data: match,
};
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results))
// return sendJSONResponse(res, HTTPStatus.OK, {
// data: match
// })
});
}
else
Matches.findOne({slug: req.params.id}, function (err, match) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!match)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: 'match not founded'
});
var html = '' + '<!DOCTYPE html> ' +
'<html> ' +
'<title>Livematch</title>' +
'<head><meta property="og:url" content="getlivematch.com/"/>' +
'<meta property="og:type" content="website"/>' +
'<meta property="og:title" content="' + match.name + '" />' +
'<meta property="og:description" content="' + match.description + '" />' +
'<meta property="og:image" content="' + '' + '"/>' +
'<meta property="al:ios:app_store_id" content="1292121995"/>' +
'<meta property="al:ios:url" content="com.astralerapps.livematchios://"/>' +
'<meta property="al:ios:app_name" content="Livematch"/>' +
' </head>' +
'<body>' +
'<script>var isMobile = {Android: function(){return navigator.userAgent.match(/Android/i);},BlackBerry: function() {return navigator.userAgent.match(/BlackBerry/i);},' +
'iOS: function() {return navigator.userAgent.match(/iPhone|iPad|iPod/i);},Opera: function(){return navigator.userAgent.match(/Opera Mini/i);},' +
'Windows:function(){return navigator.userAgent.match(/IEMobile/i);},any: function()' +
'{return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());}};' +
'if(isMobile.iOS()) { ' +
'document.location.href="https://itunes.apple.com/vn/app/facebook/id284882215?mt=8"; } ' +
'else {document.location.href="https://matchdaytoday.com/"; }' +
'</script>' +
'</body>' +
'</html>';
return res.send(html)
})
};
// DEL a matchz
module.exports.matchDEL = function (req, res) {
if (req.params.id)
Matches.findByIdAndRemove(req.params.id, function (err) {
if (err)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: err
});
return sendJSONResponse(res, HTTPStatus.NO_CONTENT, {
success: true,
message: 'match was deleted'
})
});
};
// PUT a match
module.exports.matchPUT = function (req, res) {
req.body.updatedAt = Date.now();
req.body.slug = slug(req.body.name);
var data = req.body;
Matches.findByIdAndUpdate(req.params.id, data, {'new': true}, function (err, match) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!match)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: "match's not founded"
});
if (match.status == 3)
getListTokens(match._id, 0).then(function (data) {
pushNotification(match.name, data);
}).catch(function (err) {
console.log(err);
});
var results = {
success: true,
message: 'Update match successful!',
data: match
}
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(results), constant.SECRET_KEY);
return sendJSONResponse(res, HTTPStatus.OK, encrypt.jsonObject(results));
});
};<file_sep>/models/votes.js
var mongoose = require('mongoose'), Schema = mongoose.Schema;
var mongoosePaginate = require('mongoose-paginate');
var voteSchema = new mongoose.Schema({
user: {type: Schema.Types.ObjectId, ref: 'Users'},
comment: {type: Schema.Types.ObjectId, ref: 'Comments'},
channel: {type: Schema.Types.ObjectId, ref: 'Channels'},
type: Number,
status: {
type: Number,
default: 0
},
createdAt: {
type: Date,
default: Date.now()
},
updatedAt: Date
});
voteSchema.plugin(mongoosePaginate);
mongoose.model('Votes', voteSchema);<file_sep>/client/matches/Channel.js
import React from 'react';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';
import RaisedButton from 'material-ui/RaisedButton';
const styles={
headLine: {
fontSize: 16,
fontWeight: 400
},
addNewButton: {
float: 'right',
marginTop: '-30px',
}
}
/**
* A simple table demonstrating the hierarchy of the `Table` component and its sub-components.
*/
const TableExampleSimple = () => (
<div>
<h2 style={styles.headLine}>CHANNELS</h2>
<RaisedButton label="Add New" style={styles.addNewButton}/>
<Table>
<TableHeader>
<TableRow>
<TableHeaderColumn>Name</TableHeaderColumn>
<TableHeaderColumn>Link</TableHeaderColumn>
<TableHeaderColumn>Status</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableRowColumn><NAME></TableRowColumn>
<TableRowColumn>Employed</TableRowColumn>
<TableRowColumn>Employed</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn><NAME></TableRowColumn>
<TableRowColumn>Unemployed</TableRowColumn>
<TableRowColumn>Employed</TableRowColumn>
</TableRow>
</TableBody>
</Table>
</div>
);
export default TableExampleSimple;<file_sep>/controllers/notifications.js
var mongoose = require('mongoose');
var apn = require('apn');
mongoose.Promise = global.Promise;
var HTTPStatus = require('../helpers/lib/http_status');
var constant = require('../helpers/lib/constant');
var Tokens = mongoose.model('Tokens');
var Notifications = mongoose.model('Notifications');
var sendJSONResponse = function (res, status, content) {
res.status(status);
res.json(content);
};
// module.exports.pushNotification = function (req, res) {
// var data = req.body;
// // if (process.env.NODE_ENV === 'production')
// // var apnProvider = new apn.Provider(cfgNotification.PRD_OPTS);
// // else
// var apnProvider = new apn.Provider(constant.DEV_OPTS);
// let notification = 'da9439cdb782dd8eed71ea5bec5f4c199492eeb5a6b35ab9dfb1d0de3b6462d6';
// Posts.findById(req.params.id)
// .populate('match')
// .exec(function (err, post) {
// if (err)
// return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
// success: false,
// message: err
// });
// if (!post)
// return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
// success: false,
// message: 'post not founded'
// });
// // console.log(post);
// var note = new apn.Notification();
//
// note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
// note.badge = 1;
// note.sound = "default";
// // note.alert = "\uD83D\uDCE7 \u2709 " + data.alert;
// if (post.type === 0)
// note.title = 'Full match replay of ' + post.match.name + ' is now available. Watch it now!';
// else
// note.title = 'A video highlights of ' + post.match.name + ' is now available. Watch it now!';
// note.body = post.coverPhoto;
// console.log(note);
// apnProvider.send(note, notification).then(function (result) {
//
// console.log("sent:", result.sent.length);
// console.log("failed:", result.failed.length);
// console.log(result.failed);
// });
// sendJSONResponse(res, 200, 'OK');
// });
// apnProvider.shutdown();
// };
module.exports.pushNotification = function (req, res) {
var data = req.body;
var notification = new Notifications(data);
notification.save(function (err, data) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
return sendJSONResponse(res, HTTPStatus.CREATED, {
success: true,
message: 'OK',
data: data
})
});
};
module.exports.notificationGetAll = function (req, res) {
var query = req.query || {};
const id = req.query.id;
delete req.query.id;
const match = req.query.match;
delete req.query.match;
const token = req.query.token;
delete req.query.token;
if (id)
query = {
"_id": {$in: id}
};
else if (match && token)
query = {
'match': match,
'token': token
};
else
query = {};
Notifications.paginate(
query,
{
sort: req.query.sort,
populate: 'match',
page: Number(req.query.page),
limit: Number(req.query.limit)
}, function (err, notification) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
var results = {
data: notification.docs,
total: notification.total,
limit: notification.limit,
page: notification.page,
pages: notification.pages
};
return sendJSONResponse(res, HTTPStatus.OK, results);
}
)
};
module.exports.notificationDEL = function (req, res) {
Notifications.find(
{
token: req.body.token,
match: req.body.match,
status: req.body.status
}, function (err, data) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
if (!data)
return sendJSONResponse(res, HTTPStatus.NOT_FOUND, {
success: false,
message: 'Not Found'
});
Notifications.findByIdAndRemove(data[0]._id, function (err) {
if (err)
return sendJSONResponse(res, HTTPStatus.BAD_REQUEST, {
success: false,
message: err
});
console.log('OK')
return sendJSONResponse(res, HTTPStatus.NO_CONTENT, {
success: true,
message: 'OK'
})
})
})
};
module.exports.pushCustomNotification = function (req, res) {
var data = req.body;
// if (process.env.NODE_ENV === 'production')
// var apnProvider = new apn.Provider(cfgNotification.PRD_OPTS);
// else
var apnProvider = new apn.Provider(constant.DEV_OPTS);
Tokens.find(function (err, token) {
if (err)
sendJSONResponse(res, 500, {
success: false,
message: err
})
token.forEach((token) => {
var note = new apn.Notification();
note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge = 1;
note.sound = "default";
// note.alert = "\uD83D\uDCE7 \u2709 " + data.alert;
note.title = data.title;
note.topic = 'com.astralerapps.livematchios'
apnProvider.send(note, token.token).then(function (result) {
// sendJSONResponse(res, 200, {
// sent: result.sent.length,
// failed: result.failed.length,
// fail: result.failed
// })
console.log("sent:", result.sent.length);
console.log("failed:", result.failed.length);
console.log(result.failed);
});
});
});
apnProvider.shutdown();
};<file_sep>/client/matches/index.js
import React from 'react';
import {
Create,
Edit,
List,
SimpleForm,
FormTab,
TabbedForm,
DisabledInput,
TextInput,
DateInput,
LongTextInput,
ReferenceManyField,
Datagrid,
TextField,
DateField,
EditButton,
DeleteButton,
ImageInput,
ImageField,
BooleanField,
SelectInput,
BooleanInput,
NumberInput
} from 'admin-on-rest';
import {required} from 'admin-on-rest'
import StatusField from "./StatusField";
import DateTimeInput from './DateTimeInput'
import EmbeddedManyInput from './AddManyChannels';
export const TimeFormat = v => {
// console.log("OpenTimeFormat: ", v);
if (typeof v != 'undefined') {
return parseInt(v / 100) + ":" + (v % 100 ? v % 100 : '00');
} else {
return '00:00';
}
}
export const TimeParse = v => {
var ar = v.split(":");
return ar[0] + ar[1]
}
export const MatchList = (props) => (
<List {...props} sort={{field: 'index', order: 'ASC'}}>
<Datagrid>
<TextField source="index" label="Order Number"/>
<TextField source="name" label="Match"/>
<TextField source="date" label="Date"/>
{/*<TimeField source="time" label="Time"/>*/}
<StatusField source="status" label="Status"/>
<BooleanField source="isRequired" label="Premium Required"/>
<EditButton/>
<DeleteButton/>
</Datagrid>
{/*<CustomDragGrid/>*/}
</List>
);
export const MatchCreate = (props) => (
<Create {...props}>
<SimpleForm label="Match's Information">
<NumberInput source="index" label="Order Number"/>
<TextInput source="name" label="Match Name" validate={[required]}/>
<TextInput source="description" validate={[required]}/>
<DateTimeInput source="date"/>
<SelectInput source="status" choices={[
{id: '0', name: 'Unpublished'},
{id: '1', name: 'Postponed'},
{id: '2', name: 'Upcoming'},
{id: '3', name: 'Live'}
]}/>
<EmbeddedManyInput source="channels">
<TextInput source="name" label="Channel Name" validate={[required]}/>
<TextInput source="link" validate={[required]}/>
<SelectInput source="status" choices={[
{id: '0', name: 'inactive'},
{id: '1', name: 'active'}
]}/>
<BooleanInput label="Show Link" source="isShow"/>
<BooleanInput label="Show Dis" source="showDis"/>
</EmbeddedManyInput>
<BooleanInput label="Premium Required" source="isRequired"/>
{/*<Channel/>*/}
</SimpleForm>
</Create>
);
const MatchTitle = ({record}) => {
return <span>Match {record ? `"${record.name}"` : ''}</span>;
};
export const MatchEdit = (props) => (
<Edit title={<MatchTitle/>} {...props}>
<SimpleForm>
<DisabledInput label="Match Id" source="id"/>
<NumberInput source="index" label="Order Number"/>
<TextInput source="name" validate={[required]}/>
<TextInput source="description"/>
<DateTimeInput source="date"/>
<EmbeddedManyInput source="channels">
<TextInput source="name" label="Channel Name" validate={[required]}/>
<TextInput source="link" validate={[required]}/>
<SelectInput source="status" choices={[
{id: '0', name: 'inactive'},
{id: '1', name: 'active'}
]}/>
<BooleanInput label="Show Link" source="isShow"/>
<BooleanInput label="Show Dis" source="showDis"/>
</EmbeddedManyInput>
<SelectInput source="status" choices={[
{id: '0', name: 'Unpublished'},
{id: '1', name: 'Postponed'},
{id: '2', name: 'Upcoming'},
{id: '3', name: 'Live'}
]} optionText="name"/>
<BooleanInput label="Premium Required" source="isRequired"/>
</SimpleForm>
</Edit>
); | 372afa43455f02b90ff8f28c84fb7332522249fa | [
"JavaScript",
"Dockerfile"
]
| 20 | JavaScript | Yayayay218/livematch-backend | 6ca387c4e4c7e97b07819439c097fe57ebe8a3eb | caa8681c2200b848ec5c7a3c81b85a7720c52d21 |
refs/heads/master | <repo_name>alexandergogl/URL-to-TiddlyWiki-image-reference<file_sep>/README.md
# Alfred workflow. URL to TiddlyWiki5 image reference
[Alfred](https://www.alfredapp.com/) workflow that converts the url of an image to a [TiddlyWiki5](https://tiddlywiki.com/) image URL. If the image URL is followed by a space, then all the subsequent text is transformed into a figure caption. For example an Alfred command like

becomes an TiddlyWiki expression like this:
```
[img[https://dask.org/_images/dask-array-black-text.svg]]
<figcaption>
Dask arrays scale Numpy workflows, enabling multi-dimensional data analysis in earth science, satellite imagery, genomics, biomedical applications, and machine learning algorithms.
</figcaption>
```
What looks like this in TiddlyWiki:

<file_sep>/scr/url_to_tiddly_imgref.py
"""
Alfred script: Convert an image url to a tiddly url.
"""
import sys
def url_to_tiddly_imgref(Text, Delimiter=' '):
splitted = Text.split(Delimiter, 1)
# Format URL
imgref = '[img[%s]]' % splitted[0]
# Format caption
if len(splitted) > 1:
caption = "<figcaption>\n%s\n</figcaption>" % splitted[1].replace("\n", " ")
# Compose TiddlyWiki entry
entry = "%s\n%s" % (imgref, caption)
else:
# Compose TiddlyWiki entry
entry = "%s" % imgref
return entry
input = sys.argv[1]
entry = url_to_tiddly_imgref(input)
print(entry)
| 1ec11063f210af144bd93f21de63cecc7c9ead09 | [
"Markdown",
"Python"
]
| 2 | Markdown | alexandergogl/URL-to-TiddlyWiki-image-reference | 27c191e09b48410f641d012fe58c904fdb82545d | ec3aed9fdb14b02312183fb6d238a4ca9e3fcb2e |
refs/heads/master | <repo_name>cangaruu/noticiasReact<file_sep>/src/componentes/Noticia.js
import React from 'react';
import PropTypes from 'prop-types';
const Noticia = (props) => {
const {title, description,urlToImage, url, source} = props.noticiosa
const imagen = (urlToImage)
?
<div className="card-image">
<img src={urlToImage} alt={title} />
<span className="card-title">{source.name}</span>
</div>
: 'No existe imagen';
return(
<div className="col s12 m6 l4">
<div className="card">
{imagen}
<div className="card-content">
<h3>{title}</h3>
<p>{description}</p>
</div>
<div className="card-action">
<a href={url} target="_blank" className="waves-effects btn" rel="noopener noreferrer">
Leer el notición
</a>
</div>
</div>
</div>
)
}
Noticia.propTypes = {
noticiosa : PropTypes.shape({
urlToImage : PropTypes.string,
title : PropTypes.string,
description : PropTypes.string,
url : PropTypes.string,
source : PropTypes.object
})
}
export default Noticia; | 816cbee11e65e560bcad7f0f95f0f7f91d32fd11 | [
"JavaScript"
]
| 1 | JavaScript | cangaruu/noticiasReact | c302c71c777c0b96cad035347e707f57e77096d8 | e0b61d57f46e658389555f062bf0d902d3e2d2fc |
refs/heads/master | <repo_name>j4afar/algorithms<file_sep>/01.ProblemSolving/02.multiple_pointers.js
// Write a function called sumZero which accepts a sorted array of integers.
// The func should find the first pair where the sum is 0. Return an Array that includes both values that sum to zero o undefined if a pair does not exists
// ******************************* Naïve Solution O(N^2) *******************************
function sumZero(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (arr[i] + arr[j] == - 0) {
return [arr[i], arr[j]]
}
}
}
}
let result = sumZero([-4, -3, -1, 0, 1, 3, 4])
console.log(result)
// ******************************* Optimized Solution O(N) *******************************
function sumZero(arr) {
let i = 0
let j = arr.length - 1
while (j > 0 && i < arr.length) {
if (arr[i] + arr[j] === 0) {
return [arr[i], arr[j]]
} else if (arr[i] + arr[j] > 0) {
j--
} else {
i++
}
}
}
let result = sumZero([0, 1, 3, 4])
console.log(result)<file_sep>/01.ProblemSolving/01.frequency_counter.js
// Write a function called same, which accepts two arrays.
// The function should return true if every value in the array has it's corresponding value squared in the second array.
// The frequency of values must be the same.
// ******************************* Naïve Solution O(N^2) *******************************
function same(arr1, arr2) {
if (arr1.length != arr2.length) {
return false
}
for (let i = 0; i < arr1.length; i++) {
let correctIndex = arr2.indexOf(arr1[i] ** 2)
if (correctIndex === -1) {
return false
} else {
arr2.splice(correctIndex, 1)
}
}
return true
}
// // ******************************* Optimized Solution O(3N) *******************************
function same(arr1, arr2) {
if (arr1.length != arr2.length) {
return false
}
arr1Frequency = {}
arr2Frequency = {}
//fill the first array with its freq
for (let i = 0; i < arr1.length; i++) {
if (!arr1Frequency[arr1[i]]) {
arr1Frequency[arr1[i]] = 1
} else {
arr1Frequency[arr1[i]] += 1
}
}
//fill the second array with its freq
for (let i = 0; i < arr2.length; i++) {
if (!arr2Frequency[arr2[i]]) {
arr2Frequency[arr2[i]] = 1
} else {
arr2Frequency[arr2[i]] += 1
}
}
// Check if each element in the first object exists with the same frequency in the second
for (element in arr1Frequency) {
if (arr1Frequency[element] != arr2Frequency[element ** 2]) {
return false
}
}
return true
}
arr1 = [1, 2, 3, 2]
arr2 = [9, 4, 1, 4]
console.log(same(arr1, arr2))<file_sep>/01.ProblemSolving/02.2.unique_values.js
// Implement a function called countUniqueValues, which acceptes a sorted array, and cout the unique values in the Array.
// There can be negative numbers in the arram but it always sorted.
function countUniqueValues(arr) {
let unique = 0
if (arr.length == 0) {
return unique
}
let j = 1
for (let i = 0; i < arr.length; i++) {
if (arr[i] == arr[j]) {
j++
} else {
unique += 1
j++
}
}
return unique
}
r = countUniqueValues([-1, -1, -1, 0, 2, 4])
console.log(r)
| d1c472165c54ca9e6ece30d5240daeebb61cf950 | [
"JavaScript"
]
| 3 | JavaScript | j4afar/algorithms | f569856708c304ecb2bc7a2fa79e43cba09345a5 | 3838ad3a7bb9ce5f96442e692c840323c14cb060 |
refs/heads/master | <file_sep># figure
what is figure ?
Why there is a need of figure ?
how figure is responsible for earth survival ?
Can we ignore figure?
so coming to 1st question ....those whose banana respond like 2g can leave this repo
and can purchase some kind of medicine to boost banana
so what is figure ?
you have one tower ..which recieves signal ..based on signal strength
...your tower emit something...Which produce many thing ..i.e earth survival
satisfaction via banana and orange cant be perform in fraction so be prepared
while doing injection of banana in to orange ..i.e mixed juice recipe
You can give ample amount of frequency in mango as intake of mango
boost ohh yeah mechanismm
so these are essential of ohhh yeahhh...which everyone shoul know
and perform as it is the pleasure for sure recipe
overall kiss >100 times i.e keep it super sexy mechanism
as satisfaction matter ...
| c458e605f26e54d504454e8631e52569dc82d9cc | [
"JavaScript"
]
| 1 | JavaScript | skybye02/figure | fedefa85b790d6c33dc9d93231c1a8f5556dc29a | df690cb1ef279785fb678ca3e0af2da82738c024 |
refs/heads/master | <repo_name>sganon/my-dot-files<file_sep>/README.md
# Dots
## VIM
### Prerequisites
* [vim-plug](https://github.com/junegunn/vim-plug)
* Node with npm for (for [coc.nvim](https://github.com/neoclide/coc.nvim))
* Go (This conf was made primary for Go development, you could drop it if you remove `vim-go` conf)
This conf is aim to work with nvim (neovim). It could work with vim 8.
Though it aims to work with nvim it's configured to work with a vim standard structure (i.e. using `$HOME/.vim/` not `$HOME/.config/nvim`).
To use this structure with nvim add this to `$HOME/.config/nvim/init.vim`:
```vim
set runtimepath^=/.vim runtimepath+=~/.vim/after
let &packpath = &runtimepath
source ~/.vimrc
```
### Install
```shell
$ cd
$ ln -s <REPO_DIR>/vim/.vimrc .vimrc
$ mkdir -p .vim/
$ ln -s <REPO_DIR>/vim/myplugins/ .vim/myplugins/
```
Now you can `nvim` a file and type command `:PlugInstall` this will install all needed plugins.
**NB**: `vim-go` take quit long time to install all needed binaries. You could remove `{ 'do': ':GoUpdateBinaries' }` from `myplugins/vim-plug.vim L22`
and do `:GoUpdateBinaries` afterwards
Coc extra steps:
* For go completion install [gopls](https://github.com/saibing/tools)
* Open coc confiq `:CocConfig`
* Add:
```json
{
"languageserver": {
"golang": {
"command": "gopls",
"rootPatterns": ["go.mod", ".vim/", ".git/", ".hg/"],
"filetypes": ["go"]
}
}
}
```
* For TS completion `:CocInstall coc-tsserver`
<file_sep>/oh-my-zsh/docker-machine/docker-machine.plugin.zsh
function docker_machine_info() {
name=""
if [[ "$DOCKER_MACHINE_NAME" == "" ]]; then
name="%{$fg_bold[green]%}local"
else
name="%{$fg_bold[red]%}$DOCKER_MACHINE_NAME"
fi
echo "%{$fg_bold[blue]%}docker:($name%{$fg_bold[blue]%})%{$reset_color%}"
}
<file_sep>/polybar/layout.ini
[layout]
module-padding = 1
icon-font = 2
bar-format = %{T4}%fill%%indicator%%empty%%{F-}%{T-}
bar-fill-icon = ﭳ
separator =
spacing = 0
dim-value = 1.0
wm-name =
locale =
tray-position = none
tray-detached = false
tray-maxsize = 16
tray-transparent = false
tray-background = ${color.bg}
tray-offset-x = 0
tray-offset-y = 0
tray-padding = 0
tray-scale = 1.0
click-left =
click-middle =
click-right =
scroll-up =
scroll-down =
double-click-left =
double-click-middle =
double-click-right =
cursor-click =
cursor-scroll =
<file_sep>/polybar/config
; # vim: set syntax=dosini:
include-file = ~/.config/polybar/colors.ini
[bar/main]
width = 100%
height = 35
background = ${color.bg}
line-size = 4
padding = 4
override-redirect = false
wm-restack = bspwm
fixed-center = true
border-size = 0
border-color = #00000000
;; Main font
font-0 = "Ubuntu Nerd Font:pixelsize=16;3"
;; For bigger icons
font-1 = "Ubuntu Nerd Font:pixelsize=21;3"
;; For weather module
font-2 = "Weather Icons:pixelsize=14;3"
modules-left = launcher ws
modules-center = checknetwork xwindow weather
modules-right = cpu memory battery volume date power
enable-ipc = true
monitor = ${env:MONITOR}
;;tray-position = right
;;tray-padding = 0
;;tray-background = ${color.bg}
[module/date]
type = internal/date
interval = 1
label = %time%
label-padding = 1
label-background = ${color.bg}
time = %H:%M
time-alt = %d/%M/%Y
[module/launcher]
type = custom/text
content =
content-font = 2
content-padding = 4
content-background = ${color.bg}
content-foreground = ${color.orange}
click-left = ~/.config/rofi/launcher.sh
click-right = ~/.config/rofi/launcher.sh
[module/power]
type = custom/text
content = 拉
content-padding = 1
content-margin = 0
content-underline = ${color.orange}
content-background = ${color.bg}
content-foreground = ${color.orange}
click-left = ~/.config/rofi/power.sh
click-right = ~/.config/rofi/power.sh
[module/ws]
type = internal/bspwm
strip-wsnumbers = true
enable-click = true
enable-scroll = true
label-focused = %name%
label-focused-font = 2
label-focused-padding = 2
label-focused-margin = 0
label-focused-underline = ${color.orange}
label-focused-foreground = ${color.orange}
label-occupied = %name%
label-occupied-font = 2
label-occupied-padding = 2
label-occupied-margin = 0
label-occupied-foreground = ${color.fg}
label-empty = %name%
label-empty-font = 2
label-empty-padding = 2
label-empty-margin = 0
label-empty-foreground = ${color.fg-alt}
label-urgent = %name%
label-urgent-font = 2
label-urgent-padding = 2
label-urgent-foreground = ${color.red}
[module/volume]
type = internal/pulseaudio
format-volume = <ramp-volume> <label-volume>
format-volume-padding = 1
format-volume-background = ${color.bg}
label-volume = %percentage%%
label-muted = "婢%percentage%%"
label-muted-background = ${color.red}
label-muted-padding = 1
ramp-volume-0 =
ramp-volume-1 =
ramp-volume-2 =
[module/xwindow]
type = internal/xwindow
label = %{T2}%title:0:40:...%%{T-}
label-underline = ${color.orange}
label-padding = 4
label-margin = 0
[module/battery]
type = internal/battery
full-at = 99
battery = BAT0
adapter = AC
poll-interval = 2
time-format = %H:%M
format-charging = <animation-charging> <label-charging>
format-charging-background = ${color.bg}
;;format-charging-padding = ${layout.module-padding}
format-charging-padding = 1
format-discharging = <ramp-capacity> <label-discharging>
format-discharging-background = ${color.bg}
format-discharging-padding = 1
label-charging = %percentage%%
label-discharging = %percentage%%
label-full =
label-full-background = ${color.bg}
label-full-padding = 1
ramp-capacity-0 =
ramp-capacity-1 =
ramp-capacity-2 =
ramp-capacity-3 =
ramp-capacity-4 =
ramp-capacity-5 =
ramp-capacity-6 =
ramp-capacity-7 =
ramp-capacity-8 =
ramp-capacity-9 =
animation-charging-0 =
animation-charging-1 =
animation-charging-2 =
animation-charging-3 =
animation-charging-4 =
animation-charging-5 =
animation-charging-6 =
animation-charging-framerate = 350
[module/memory]
type = internal/memory
interval = 3
format = <label>
format-prefix =
format-background = ${color.bg}
format-padding = 1
label = " %gb_used%"
[module/cpu]
type = internal/cpu
interval = 0.5
format = <label>
format-prefix =
format-background = ${color.bg}
format-padding = 1
label = " %percentage%%"
[module/weather]
type = custom/script
exec = /home/sganon/.config/polybar/scripts/polybar-forecast
exec-if = ping openweathermap.org -c 1
interval = 600
label-font = 3
label-underline = ${color.orange}
[module/checknetwork]
type = custom/script
exec = ~/.config/polybar/scripts/check-network
tail = true
interval = 5
label-underline = ${color.orange}
format-background = ${color.bg}
;;format-padding = 1
click-left = networkmanager_dmenu &
click-middle = networkmanager_dmenu &
click-right = networkmanager_dmenu &
<file_sep>/rofi/power.sh
#!/bin/bash
## Created By <NAME>
MENU="$(rofi -sep "|" -dmenu -i -p 'System' -location 2 -yoffset 35 -font "SauceCodePro Nerd Font Mono 11" <<< " Lock| Logout| Reboot| Shutdown")"
case "$MENU" in
*Lock) betterlockscreen -l blur ;;
*Logout) bspc quit;;
*Reboot) systemctl reboot ;;
*Shutdown) systemctl -i poweroff
esac
<file_sep>/rofi/launcher.sh
rofi -width 50 -location 2 -yoffset 35 -modi "window" -show drun
<file_sep>/polybar/colors.ini
[color]
trans = #00000000
white = #FFFFFF
black = #000000
cyan = #00acc1
orange = #fb8c00
red = #e53935
;bg = #1F1F1F
bg = #282C34
fg = #EFEFEF
fg-alt = #A9ABB0
| bdebe042d9daa6f97ab1c97c69e65f2059a76550 | [
"Markdown",
"INI",
"Shell"
]
| 7 | Markdown | sganon/my-dot-files | 123d1cfc1105e2e907cda583420a695a72a1ebc9 | 9f925fc4fe297b5a999bdc9ebbf13444bdb879fc |
refs/heads/master | <repo_name>krivard/mturk-geotags-template<file_sep>/gal/make_input.sh
#!/bin/bash
cut -f 20,33,34 $1 | sed -n '/:/ s/"//gp'
#cut -f 20,30,31,32,33,34 $1 | sed 's/"//g' | awk 'BEGIN{OFS="\t"}{if ($1 != "") print $1,$5,$6 "," $3 "," $2 "," $4}'<file_sep>/www/save.safe.php
<?php
$index = $_POST['index'];
$concept = $_POST['concept'];
$eval = $_POST['eval'];
$data = "$index $concept $eval\n";
$fh = fopen("save.results.txt","a");
fwrite($fh,$data);
fclose($fh);
print "{ message: \"success\"}"
?><file_sep>/gal/run_galfiles.sh
#!/bin/bash
if [ -z "$1" ]; then
echo "Usage: $0 profilename"
exit
fi
set -x
#for f in A B best; do
bin/get-another-label.sh --categories $1.categories --input $1.input --cost $1.costs --gold $1.gold
#cat results/worker-statistics-summary.txt
sed 's/%//g' results/worker-statistics-summary.txt > results/wss.txt
rm -rf $1.results
mv results $1.results
#done
<file_sep>/gal/make.sh
#!/bin/bash
if [ $# -lt 2 ]; then
echo "Usage: $0 datasetName Batch_xxxx.csv";
exit 0;
fi
NEW=${2/%.csv/.tsv}
csv2tsv.pl $2 > $NEW
awk '{print $2 "\t" $3}' ../www/save.results.txt > $1.gold
./make_galfiles.sh $NEW $1
./run_galfiles.sh $1
./make_approvalfile.sh $2 $1
<file_sep>/make.sh
#!/bin/bash
if [ $# -lt 2 ]; then
echo "Usage: $0 datasetName Locator-xxxx.tsv minCategoryCount maxVarInMiles sampleSize";
exit 0;
fi
./make_categories.sh $2 $3 > categoryList.txt
SRC=${2%.tsv}
PRO=$SRC.promoted.tsv
awk --assign M=$4 '{ if ($2<=M) print }' $2 > $PRO
./makedata_js.sh $1 $PRO categoryList.txt $5 > www/all.js
./makedata_hitinput.sh categoryList.txt $1 > hitinput.txt
mkdir -p hitinput
mv *.hitinput hitinput/<file_sep>/makedata_js.sh
#!/bin/bash
if [ $# -lt 4 ]; then
echo "Usage: $0 dataset Locator-out.txt categoryList.txt X > randomXperCategory.txt";
exit 0;
fi
echo "single = {data:["
while read line; do
grep "^$line" $2 | shuf -n $4 > $1.$line.hitinput
awk --assign D=$1 '{print "{ label:\"" $1 "\", lat:" $5 ", lon:" $6 ", varMi:" $2 ", dataset:\"" D "\" },"}' $1.$line.hitinput
done < $3
echo "]};"<file_sep>/make_categories.sh
#!/bin/bash
if [ $# -lt 2 ]; then
echo "Usage: $0 Locator-xxxx.tsv minCategoryCount > categoryList.txt";
exit 0;
fi
cut -f 1 $1 | sed 's/:.*//' | sort | uniq -c | awk --assign C=$2 '{if ($1>C) print $2}'
<file_sep>/gal/make_galfiles.sh
#!/bin/bash
if [ -z "$2" ]; then
echo "Usage: $0 results.tsv profilename"
echo "Where ${profilename}.gold exists"
exit
fi
set -x
WF=`head -1 $1 | sed 's/\t/\n/g' | grep -n WorkerId | sed 's/:.*//'`
CF=`head -1 $1 | sed 's/\t/\n/g' | grep -n category | sed 's/:.*//'`
NF=`head -1 $1 | sed 's/\t/\n/g' | grep -n na_me | sed 's/:.*//'`
QF=`head -1 $1 | sed 's/\t/\n/g' | grep -n quality | sed 's/:.*//'`
ACF=`head -1 $1 | sed 's/\t/\n/g' | grep -n comment | sed 's/:.*//'`
N=`wc -l $1 | awk '{print $1}'`
N=$((N-1))
awk -F "\t" -v kWF=$WF -v kCF=$CF -v kNF=$NF -v QF=$QF -v ACF=$ACF 'BEGIN{OFS="\t"} {split($0,L); print L[kWF],L[kCF] ":" L[kNF], L[QF]}' $1 | tail -$N > $2.input
#cut -f 1,2 $3 > $2.gold
#for f in A B best; do
cut -f 3 $2.input | sort | uniq > $2.categories
./make_costs.pl $2.categories > $2.costs
#done
<file_sep>/www/geotags.js
//var predictions_map = {};
//var mymap;
//var locIndex;
//var opacityFlag = 1;
var geotags = {
zoomLevels: function() {
var a=5; var b=10; var c=11; var d=13; var e=15;
return {
country: a,
mountain: b,
river: b+2,
stateorprovince: b,
city: c,
lake: e,
stadiumoreventvenue: d,
university: d,
building: e,
hotel: e+1,
monument: e-1,
museum: e,
park: e,
radiostation: e,
restaurant: e,
sportsteam: e,
street: e,
televisionstation: e
};}()
};
//var filename = "";
var key = "<KEY>"; // kmr
//var key = "<KEY>"; // dmv
function loadScript() {
opacityFlag = 1;
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key="+key+"&sensor=false&callback=loadMap";
document.body.appendChild(script);
}
function loadMap() {
var cat = geotags.data[0].title.split(":")[0];
var typeid = google.maps.MapTypeId.ROADMAP;
if (cat === "mountain" || cat === "river" ) { typeid = google.maps.MapTypeId.TERRAIN; }
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891),
mapTypeId: typeid
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
console.log("Map loaded.");//console.log(map);
geotags.map = map;
geotags.infoWindow = new google.maps.InfoWindow({
pixelOffset:new google.maps.Size(-1,36)
});
google.maps.event.addListener(geotags.map, 'click', function() {
geotags.infoWindow.close();
});
//console.log(geotags.data[0]);
addMarker(geotags.data[0]);
var bounds = new google.maps.LatLngBounds();
//var clusterer = new MarkerClusterer(map,[],{gridSize:50});
//for (var i=0;i<geotags.data.length;i++) {
// var marker = addMarker(geotags.data[i]);//,geotags.icons[i],geotags.shadows[i]);
//clusterer.addMarker(marker);
bounds.extend(geotags.data[0].marker.getPosition());
//}
//map.setZoom(map.getBoundsZoomLevel(bounds));
//map.setCenter(bounds.getCenter());
//for (var l=0;l<geotags.loaders.length;l++) { geotags.loaders[l](bounds); }
var newzoom = geotags.zoomLevels[cat];
if (!bounds.isEmpty()) {
map.fitBounds(bounds);
google.maps.event.addListenerOnce(map,"idle",function() { map.setZoom(newzoom); });
//{ if (map.getZoom() > 9) map.setZoom(9); });
}
console.log("Zoom:"+map.getZoom());
}
function addMarker(data) { //,icon,shadow) {
var marker = new google.maps.Marker({
map: geotags.map,
position: new google.maps.LatLng(data.lat, data.lng),
draggable: false,
title: data.title,
//icon: icon,
//shadow: shadow,
zIndex: data.zIndex
});
google.maps.event.addListener(marker, 'click', function() {
zoomOnLocation(data);
});
data.marker = marker;
return marker;
}
function zoomOnLocation(data){
var zoomLevel;
// open info window
geotags.infoWindow.setContent(
'<table id="geotags-info">'+
'<tr class="heading"><th colspan="2" class="instance">'+ data.title +'</th></tr>' +
'<tr><td class="label">Latitude</td><td class="label">Longitude</td></tr>'+
'<tr><td> '+data.lat+'</td><td> '+data.lng+'</td></tr>'+
'</table>');
geotags.infoWindow.open(geotags.map, data.marker);
}
/*
function loadPredictionData(filename){
predictions_map = {};
if(filename == ""){
filename = "prediction.txt";
}
var txtFile = new XMLHttpRequest();
//txtFile.open("GET", "http://www.cs.cmu.edu/~dmovshov/GeoTags/prediction.txt", false);
txtFile.open("GET", "http://www.cs.cmu.edu/~dmovshov/GeoTags/"+filename, false);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
var allText = txtFile.responseText;
var lines = txtFile.responseText.split("\n"); // Will separate each line into an array
for (var i=0; i < lines.length-1; i++) {
var line = lines[i];
if(i == 0){
document.getElementById("location").innerHTML = line;
continue;
}
var parts = line.split("\t");
predictions_map[i] = {
name: parts[0],
lat: parts[1],
lng: parts[2],
distance: parseFloat(parts[3])*1000,
prior: parts[4],
alignProb: parts[5],
adjustedPrior: parts[6],
combined: parts[7],
relative: parts[8],
cleanName: parts[9]
}
}
} //status
} //ready
//txtFile.close();
} //state change
txtFile.send(null);
}
function toggleOpacity(){
if(opacityFlag == 1){
opacityFlag = 0;
}
else{
opacityFlag = 1;
}
displayPrediction();
}
function loadFile(){
var filename = document.getElementById("query").value;
loadScript();
}
function loadMe(file){
var filename = file;
loadScript();
}
function addCellToRow(oRow, cellType, text){
var oCell = document.createElement(cellType);
oCell.innerHTML = text;
oRow.appendChild(oCell);
}
// not in use - kmr june 2012
function displayPrediction(filename) {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
mymap = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
loadPredictionData(filename);
var circleOptions;
var locationCircle;
var marker;
var area;
infoWindow = new google.maps.InfoWindow;
google.maps.event.addListener(mymap, 'click', function() {
infoWindow.close();
});
if(document.getElementById("resultsTableContainer").childNodes.length > 0){
document.getElementById("resultsTableContainer").removeChild(document.getElementById("resultsTableContainer").firstChild);
}
var oTable = document.createElement("table");
var oTHead = document.createElement("thead");
var oTBody = document.createElement("tbody");
var oCaption = document.createElement("caption");
var oRow;
document.getElementById("demo").innerHTML = "";
if(Object.keys(predictions_map).length == 0){
document.getElementById("demo").innerHTML = "Oops, can't find this place :( <br>";
}
else{
document.getElementById("demo").innerHTML = "";
oCaption.innerHTML = "Predicted locations"
oTable.appendChild(oTHead);
oTable.appendChild(oTBody);
oTable.appendChild(oCaption);
oTable.cellPadding = 5;
oTable.border = 1;
oTable.className = "results";
oRow = document.createElement("TR");
oTHead.appendChild(oRow);
addCellToRow(oRow, "TH", "#");
addCellToRow(oRow, "TH", "Name");
addCellToRow(oRow, "TH", "Lat");
addCellToRow(oRow, "TH", "Lng");
addCellToRow(oRow, "TH", "Prior");
addCellToRow(oRow, "TH", "Adj_P");
addCellToRow(oRow, "TH", "Combined");
addCellToRow(oRow, "TH", "Relative");
addCellToRow(oRow, "TH", "Distance");
addCellToRow(oRow, "TH", "p(Align)");
addCellToRow(oRow, "TH", "Action");
}
var keyByProb = Object.keys(predictions_map);
keyByProb.sort(function(a, b) {return predictions_map[b].combined - predictions_map[a].combined});
//keyByProb.sort(function(a, b) {return predictions_map[b].relative - predictions_map[a].relative});
for (var l=0;l<keyByProb.length;l++){
index = keyByProb[l];
document.getElementById("demo").innerHTML = "<a href=\"http://dbpedia.org/resource/"+predictions_map[index].name+"> link </a>";//+predictions_map[index].name"\"> "+predictions_map[index].name+" </a>";
oRow = document.createElement("TR");
oTBody.appendChild(oRow);
addCellToRow(oRow, "TD", l);
addCellToRow(oRow, "TD", "<a href=http://dbpedia.org/resource/"+predictions_map[index].name+"> \""+predictions_map[index].cleanName+"\" </a>");
addCellToRow(oRow, "TD", parseFloat(predictions_map[index].lat).toFixed(2));
addCellToRow(oRow, "TD", parseFloat(predictions_map[index].lng).toFixed(2));
addCellToRow(oRow, "TD", parseFloat(predictions_map[index].prior).toFixed(2));
addCellToRow(oRow, "TD", parseFloat(predictions_map[index].adjustedPrior).toFixed(2));
addCellToRow(oRow, "TD", parseFloat(predictions_map[index].combined).toFixed(2));
addCellToRow(oRow, "TD", parseFloat(predictions_map[index].relative).toFixed(4));
addCellToRow(oRow, "TD", parseFloat(predictions_map[index].distance).toFixed(2));
addCellToRow(oRow, "TD", parseFloat(predictions_map[index].alignProb));
addCellToRow(oRow, "TD", "<a href=\"javascript: zoomOnLocation("+index+")\"> Zoom In </a>");
predictions_map[index].rank = l;
//area = Math.PI*Math.pow(pred_dist,2);
var currOpacity = Math.min(predictions_map[index].adjustedPrior, .7);
if(opacityFlag == 0){
currOpacity = 0;
}
circleOptions = {
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
//fillOpacity: Math.min(predictions_map[index].combined, .7),
fillOpacity: currOpacity,
map: mymap,
center: new google.maps.LatLng(predictions_map[index].lat, predictions_map[index].lng),
radius: parseFloat(predictions_map[index].distance)
};
locationCircle = new google.maps.Circle(circleOptions);
marker = new google.maps.Marker({
map: mymap,
position: new google.maps.LatLng(predictions_map[index].lat, predictions_map[index].lng),
draggable: false,
//title: 'Click to zoom',
title: index,
// icon: index
zIndex: keyByProb.length-l
});
google.maps.event.addListener(marker, 'click', function() {
zoomOnLocation(this.getTitle());
});
predictions_map[index].marker = marker;
}
if(keyByProb.length > 0){
zoomOnLocation(keyByProb[0]);
}
document.getElementById("resultsTableContainer").appendChild(oTable);
}
function zoomOut(){
var mapOptions = {
zoom: 4,
};
mymap.setOptions(mapOptions);
infoWindow.close();
}
*/
//function zoomOnLocation(){
// zoomOnLocation(locIndex);
//}
<file_sep>/makedata_hitinput.sh
#!/bin/bash
if [ $# -lt 2 ]; then
echo "Usage: $0 categoryList.txt dataset1 [dataset2 ...] > hitinput.txt";
exit 0;
fi
catfile=$1
shift;
start=0
#set -x
for dataset in $@; do
while read cat; do
nl -v $start $dataset.$cat.hitinput | awk 'BEGIN {OFS="\t"}{foo=$3; gsub("_"," ",foo); print $1,$2,$3,foo}'
len=`wc -l $dataset.$cat.hitinput | awk '{print $1}'`
let start=start+len
done < $catfile
done
| d56a098dbad7c1cac92a1d49f61dc153b5e7e03e | [
"JavaScript",
"PHP",
"Shell"
]
| 10 | Shell | krivard/mturk-geotags-template | 722da0db95c84416e110bf98be65c904ea05a631 | 884515fea0c27382a206949f489ae89c659f3984 |
refs/heads/master | <repo_name>SuperSomny/GNN<file_sep>/README.md
## 输入数据的格式
### 符号表
|符号|含义|
|:---:|:---:|
|$V$|整个图的点集|
|$V_{train}$|训练集|
|$V_{test}$|测试集|
|$V_s$|有监督的点集|
|$V_u$|无监督的点集|
|$N$|整个图的节点数|
|$N_{train}$|训练集节点数|
|$N_{test}$|测试集节点数|
|$N_s$|有监督的节点数|
|$N_u$|无监督的节点数|
|$F$|每个节点的特征数|
|$C$|分类的类数(此问题中是2)|
### 点集的划分
所有节点被划分为训练集和测试集,即$V=V_{train}\cup V_{test}$。训练集用于训练模型,测试集用于评估模型。
其中训练集中节点被划分为有监督和无监督,即$V_{train}=V_s\cup V_u$。有监督的节点数应当远少于训练集的总节点数,即$N_s<<N_{train}$。所有节点都有标签,无监督的节点和测试集的标签用于评估模型。
### 输入的描述
输入包含x,tx,allx,y,ty,ally,graph,test.index,它们可以被分为:
1. 特征矩阵
2. 标签矩阵
3. 邻接矩阵
4. 索引集合
#### 特征矩阵
特征矩阵的每一行表示一个节点,每一列表示一个特征。
所有特征矩阵的类型均为`scipy.sparse.csr.csr_matrix`。
1. x是一个$N_s\times F$的矩阵,表示有监督节点的特征矩阵
2. tx是一个$N_{test}\times F$的矩阵,表示测试集的特征矩阵
3. allx是一个$N_{train}\times F$的矩阵,表示训练集的特征矩阵
#### 标签矩阵
标签矩阵的每一行表示一个节点,每一列表示一个分类。
所有标签矩阵的类型均为`numpy.ndarray`。
1. y是一个$N_s\times C$的矩阵,表示有监督节点的标签矩阵
2. ty是一个$N_{test}\times C$的矩阵,表示测试集的标签矩阵
3. ally是一个$N_{train}\times C$的矩阵,表示训练集的标签矩阵
#### 邻接矩阵
邻接矩阵的$(i, j)$号元素表示节点$i$与节点$j$之间的边权。
邻接矩阵的类型为字典。
graph是一个$N\times N$的矩阵,表示整个图的邻接矩阵。
#### 索引集合
test.index是一个包含$N_{test}$个元素的集合,表示测试集中所有节点的索引值。
### 存放方式
所有的输入文件按照上述命名,存放在gcn/data目录下。
其中特征矩阵、标签矩阵、邻接矩阵用pickle存放,test.index直接将数据用换行符分隔存放。<file_sep>/code/test.py
import numpy as np
import pickle as pkl
import networkx as nx
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
import sys
def load_data(dataset_str):
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = []
for i in range(len(names)):
with open("data/ind.{}.{}".format(dataset_str, names[i]), 'rb') as f:
if sys.version_info > (3, 0):
objects.append(pkl.load(f, encoding='latin1'))
else:
objects.append(pkl.load(f))
x, y, tx, ty, allx, ally, graph = tuple(objects)
return x, y, tx, ty, allx, ally, graph
x, y, tx, ty, allx, ally, graph = load_data('citeseer')
print(ally)
for i in ally:
print(i)
| ab827cbcbfe0e27b68f29a8f9299ced516f75455 | [
"Markdown",
"Python"
]
| 2 | Markdown | SuperSomny/GNN | 75a5f44b260cf4ad65de1f4a28c04dc07b7c98a6 | 3b9a6c50855e0d2079328e8be6f8238f3a7dd6b9 |
refs/heads/V0.8 | <repo_name>premrume/speakeasy<file_sep>/mongo/Dockerfile
FROM mongo:latest
# Depends on volume (refer to ../docker-compose.yml)
LABEL \
description="Simple Mongo Madness using defaults ..."
<file_sep>/models/install_enko.sh
#!/bin/bash -e
install_enko() {
# quick check for the folder
if [ ! -d ${SPEAKEASY_HOME}/models/enko ]
then
cd ${SPEAKEASY_HOME}/models
# origin
./mc --config-dir . ls sofwerx/models/enko.tar.gz
./mc --config-dir . cp sofwerx/models/enko.tar.gz .
tar xf enko.tar.gz
rm enko.tar.gz
echo " enko download complete"
return 0
else
echo " skipping download, looks like you already have an enko folder"
return 0
fi
}
<file_sep>/README.md
# **Speakeasy**
## *What is Speakeasy*
> Investment/POC to Translate text files containing Korean Language to English.
> Walk (V1.0)
>> Focus on the data flow

## PREREQs on VM (these steps are REQUIRED):
Install tools per your operating system instructions. (Installation steps are outside the scope of Speakeasy.)
> docker, EG:
```
$ docker --version
Docker version 17.09.1-ce, build 19e2cf6
```
> docker-compose supporting version "3", EG:
```
$ docker-compose version
docker-py version: 3.5.0
CPython version: 3.6.6
OpenSSL version: OpenSSL 1.1.0f 25 May 2017
```
## Dev Steps
1. Clone
```
# Assumption is that you setup your token to clone from BAH...
cd
git clone https://github.boozallencsn.com/tampaml/speakeasy.git --branch V0.7
OR
git clone https://github.com/premrume/speakeasy/tree/V0.8 --branch V0.8
```
2. Configuration
> If your .env does not have the right values ... THIS WILL FAIL!!! Having the correct .env is REQUIRED.
```
# GO ASK PEGGY
# ./models/config.json needs YOUR access keys!
# ./.env needs values ..
SPEAKEASY_SHARED=/var/speakeasy
SPEAKEASY_VERSION=1.08
SPEAKEASY_MINIO_URL= GO ASK PEGGY
SPEAKEASY_MINIO_ACCESS_KEY= GO ASK PEGGY
SPEAKEASY_MINIO_SECRET_KEY= GO ASK PEGGY
```
3. Build
```
cd speakeasy
make
```
4. UI
* http://localhost:5000
<file_sep>/enko_service/api/enko/logic/enko_translate.py
import tensorflow as tf
import numpy as np
import json
import logging
import pickle
# env variables
import settings
import utils
# Usurped only the needful from other files ...
# i think json is faster than pickle
# i can convert these to json l8r ...
# added to work thru tensorflow issue command line issue:
from tensorflow.contrib.seq2seq.python.ops import beam_search_ops
log = logging.getLogger(__name__)
def load_preprocess():
folder = utils.get_env_var_setting('ENKO_MODEL', settings.ENKO_MODEL)
fname = utils.get_env_var_setting('ENKO_PICKLE_PREPROCESS', settings.ENKO_PICKLE_PREPROCESS)
preprocess_file = folder + '/' + fname
return pickle.load(open(preprocess_file, mode='rb'))
def load_params():
folder = utils.get_env_var_setting('ENKO_MODEL', settings.ENKO_MODEL)
fname = utils.get_env_var_setting('ENKO_PICKLE_PREPROCESS', settings.ENKO_PARAMS)
params = folder + '/' + fname
return params
def sentence_to_seq(sentence, vocab_to_int):
"""
Convert a sentence to a sequence of ids
:param sentence: String
:param vocab_to_int: Dictionary to go from the words to an id
:return: List of word ids
"""
lower_case_words = [word.lower() for word in sentence.split()]
word_id = [vocab_to_int.get(word, vocab_to_int['<unk>']) for word in lower_case_words]
return word_id
def enko_translate(translate_text):
log.debug('input:')
log.debug(translate_text)
# init
_, (source_vocab_to_int, target_vocab_to_int), (source_int_to_vocab, target_int_to_vocab) = load_preprocess()
load_path = load_params()
# do deeds
translate_sentence = sentence_to_seq(translate_text, source_vocab_to_int)
loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
# Load saved model
loader = tf.train.import_meta_graph(load_path + '.meta')
loader.restore(sess, load_path)
encoder_inputs = loaded_graph.get_tensor_by_name('encoder_inputs:0')
encoder_inputs_length = loaded_graph.get_tensor_by_name('encoder_inputs_length:0')
decoder_pred_decode = loaded_graph.get_tensor_by_name('decoder_pred_decode:0')
predicted_ids = sess.run(decoder_pred_decode, {encoder_inputs: [translate_sentence],
encoder_inputs_length: [np.shape(translate_sentence)[0]]})[0]
translation = ''
log.debug('translate')
log.debug(translate_text)
for word_i in predicted_ids:
translation += target_int_to_vocab[word_i[0]] + ' '
log.debug(translation)
answer = {'input_text' : translate_text, 'output_text': translation}
return answer
<file_sep>/ui/app/nifi/views.py
import os
from flask import Blueprint, Flask, redirect, render_template, request, session, url_for, flash, send_file
from flask_paginate import Pagination, get_page_args
from werkzeug.utils import secure_filename
from app.nifi.forms import AddNifiForm
from app.nifi.models import *
from app.extensions import ende, kor, enko
from flask import current_app
from flask_login import login_required
import logging
logging.basicConfig(level=logging.DEBUG)
### OMG
from bson.objectid import ObjectId
from flask import Flask
################
#### config ####
################
nifi_blueprint = Blueprint('nifi', __name__)
##########################
#### helper functions ####
##########################
def flash_errors(form):
for field, errors in form.errors.items():
for error in errors:
flash(u"Error in the %s field - %s" % (
getattr(form, field).label.text,
error
), 'info')
################
#### routes ####
################
@nifi_blueprint.route('/upload/', methods=['GET','POST'])
@login_required
def go_nifi_upload():
form = AddNifiForm()
if request.method == 'POST':
try:
if form.validate_on_submit() and 'upload' in request.files:
total = len(request.files.getlist('upload'))
if total > 5:
raise Exception('upload max exceeded', '{} files exceeds 5 file limit'.format(total))
model = form.model.data
for f in request.files.getlist('upload'):
filename = secure_filename(f.filename)
if model == 'ende':
saved = ende.save(f, name=filename)
elif model == 'kor':
saved = kor.save(f, name=filename)
else:
saved = enko.save(f, name=filename)
flash('SUCCESS: Model [{}] File(s) [{}] posted'.format(model, filename), 'success')
return redirect(url_for('nifi.go_nifi_upload'))
else:
flash('ERROR: try entering filename again [{}]'.format(filename), 'error')
except Exception as e:
msg = 'UPLOAD ERROR: ' + getattr(e, 'message', repr(e))
flash(msg, 'error')
return render_template('nifi_upload.html', form=form)
@nifi_blueprint.route('/list/', methods=['GET'])
@login_required
def go_nifi_list():
page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page')
nifi = Nifi.objects.order_by('-input.start').paginate(page=page, per_page=10)
total = Nifi.objects.count()
pagination = Pagination(alignment='right', page=page, per_page=per_page, total=total, css_framework='bootstrap4')
return render_template('nifi_list.html', nifi=nifi, page=page, per_page=per_page, pagination=pagination)
@nifi_blueprint.route('/details/<nifi_uuid>', methods=['GET'])
def go_nifi_details(nifi_uuid):
patchmain = PatchMain.objects.get(uuid=nifi_uuid)
if patchmain.input_data:
patchmain.input_data.payload=ObjectId(patchmain.input_data.grid)
if patchmain.clean_data:
patchmain.clean_data.payload=ObjectId(patchmain.clean_data.grid)
if patchmain.ocr_data:
patchmain.ocr_data.payload=ObjectId(patchmain.ocr_data.grid)
if patchmain.translate_data:
patchmain.translate_data.payload=ObjectId(patchmain.translate_data.grid)
if patchmain.docx_data:
patchmain.docx_data.payload=ObjectId(patchmain.docx_data.grid)
if patchmain.pdf_data:
patchmain.pdf_data.payload=ObjectId(patchmain.pdf_data.grid)
patchmain.save()
nifi = Nifi.objects.get(uuid=nifi_uuid)
return render_template('nifi_detail.html',
nifi=nifi)
@nifi_blueprint.route('/info/', methods=['GET'])
@login_required
def go_nifi_info():
return render_template('info.html',
MONGO_EXPRESS=current_app.config['MONGO_EXPRESS'],
TF_CLIENT=current_app.config['TF_CLIENT'],
OCR_CLIENT=current_app.config['OCR_CLIENT'],
NIFI_CLIENT=current_app.config['NIFI_CLIENT'],
ENKO_CLIENT=current_app.config['ENKO_CLIENT'])
########################################
# It is what it is...
########################################
@nifi_blueprint.route('/input/<uuid>', methods=['GET'])
@login_required
def go_nifi_input(uuid):
nifi = Nifi.objects.get(uuid=uuid)
return send_file(nifi.input_data.payload, mimetype=nifi.input_data.context_type)
@nifi_blueprint.route('/input/other/<uuid>', methods=['GET'])
@login_required
def go_nifi_input_other(uuid):
nifi = Nifi.objects.get(uuid=uuid)
file_name, file_extension = os.path.splitext(nifi.source)
if file_extension == '.txt':
input_file = nifi.input_data.payload.read()
elif file_extension == '.jpg':
input_file = nifi.ocr_data.payload.read()
elif file_extension == '.png':
input_file = nifi.ocr_data.payload.read()
elif file_extension == '.docx':
input_file = nifi.docx_data.payload.read()
elif file_extension == '.pdf':
input_file = nifi.pdf_data.payload.read()
else:
input_file = 'mongodb.datab.is.bad'
input_display = str(input_file, 'UTF-8')
output_file = nifi.translate_data.payload.read()
output_display = str(output_file, 'UTF-8')
return render_template('nifi_textfiles.html', nifi=nifi, input_display=input_display, output_display=output_display)
@nifi_blueprint.route('/translate/<uuid>', methods=['GET'])
@login_required
def go_nifi_translate(uuid):
nifi = Nifi.objects.get(uuid=uuid)
return send_file(nifi.translate_data.payload, mimetype=nifi.translate_data.context_type)
@nifi_blueprint.route('/clean/<uuid>', methods=['GET'])
@login_required
def go_nifi_clean(uuid):
nifi = Nifi.objects.get(uuid=uuid)
return send_file(nifi.clean_data.payload, mimetype=nifi.clean_data.context_type)
@nifi_blueprint.route('/ocr/<uuid>', methods=['GET'])
@login_required
def go_nifi_ocr(uuid):
nifi = Nifi.objects.get(uuid=uuid)
return send_file(nifi.ocr_data.payload, mimetype=nifi.ocr_data.context_type)
@nifi_blueprint.route('/docx/<uuid>', methods=['GET'])
@login_required
def go_nifi_docx(uuid):
nifi = Nifi.objects.get(uuid=uuid)
return send_file(nifi.docx_data.payload, mimetype=nifi.docx_data.context_type)
@nifi_blueprint.route('/pdf/<uuid>', methods=['GET'])
@login_required
def go_nifi_pdf(uuid):
nifi = Nifi.objects.get(uuid=uuid)
return send_file(nifi.pdf_data.payload, mimetype=nifi.pdf_data.context_type)
# Redirect : forced it, nothing fancy here
@nifi_blueprint.route('/redirectdash/')
@login_required
def go_dash():
go_there = '/dashboard/'
logging.debug(go_there)
return redirect(go_there)
<file_sep>/ocr_service/api/ocr/logic/ocr_client.py
from __future__ import print_function
import logging
import cv2
import pytesseract
from PIL import Image
from summa import summarizer, keywords
import json
import PyPDF2
import docxpy
log = logging.getLogger(__name__)
# TODO: make these string and not files ... durh
def make_clean_image(path):
image=cv2.imread(path)
gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
# peggy hack
gray = cv2.bitwise_not(gray)
ret2,th2 = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
dst = cv2.fastNlMeansDenoising(th2,10,10,7)
tmpname = path + '.clean.jpg'
log.debug('bbbbbbbbbbbbbbb write file'+tmpname)
cv2.imwrite(tmpname,dst)
answer = {'cvt' : tmpname }
return answer
def make_ocr_file(path, lang='eng'):
img = Image.open(path)
log.debug('ccccccccccccccc read file'+path)
log.debug('ccccccccccccccc lang '+lang)
data = pytesseract.image_to_string(img, lang=lang)
log.debug('ccccccccccccccc data'+data)
# omg really? text, binary, files, images good god
tmpname = path + '.ocr.txt'
try:
log.debug('ddddddddddddddddd write file'+tmpname)
outfile = open(tmpname,'w')
outfile.write(data)
outfile.close()
answer = {'tesseract' : tmpname }
except:
# todo
answer = {'tesseract' : tmpname }
return answer
def keyword_json(list):
lst = []
for pn in list:
d = {}
d['keyword']=pn
lst.append(d)
return json.dumps(lst)
def make_keywords(path,language):
try:
with open(path) as f:
input_txt = f.read()
#keyword_list=keywords.keywords(input_txt, split=True, language=language, ratio=0.2)
keyword_list=keywords.keywords(input_txt, split=False, language=language, ratio=0.2)
except Exception as e:
raise
# for the time being (because Nifi sucs), lets make this a string
#answer = {'keywords' : keyword_json(keyword_list) }
answer = {'keywords' : keyword_list.replace('\n', ', ') }
return answer
def make_summary(path,language):
try:
with open(path) as f:
input_txt = f.read()
summary=summarizer.summarize(input_txt,ratio=0.2, language=language)
except Exception as e:
raise
answer = {'summary' : summary.replace('\n',' ') }
return answer
# very very simple get the idea in place
def make_pdf(path,language):
try:
pdfFileObj = open(path,'rb') #'rb' for read binary mode
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
num_pages=pdfReader.numPages
#loop to extract all text
text_list=[]
for page in range(num_pages):
pageObj = pdfReader.getPage(page)
text=pageObj.extractText()
text_list.append(text.replace('\n', ' ' ))
tmpname = path + '.txt'
outfile = open(tmpname, 'w')
outfile.write('\n'.join(text_list))
except Exception as e:
raise
answer = {'cvt' : tmpname }
return answer
# very very simple get the idea in place
def make_docx(path,language):
try:
log.debug('ddddddddddddddd docx ')
text = docxpy.process(path)
log.debug('ddddd')
tmpname = path + '.txt'
outfile = open(tmpname, 'w')
outfile.write(text.replace('\n',' '))
except Exception as e:
raise
answer = {'cvt' : tmpname }
return answer
<file_sep>/ui/requirements.txt
Flask
gunicorn
dash
dash-core-components
dash-html-components
dash-table-experiments
pandas-datareader
matplotlib
flask-sqlalchemy
flask-migrate
flask-login
flask-wtf
flask-mongoengine
flask-uploads
flask-paginate
<file_sep>/tfs_service/Dockerfile
FROM tensorflow/serving
# Info
LABEL \
description="Tensorflow Serving depends on models volume and models.conf"
# Depends on volume (refer to ../docker-compose.yml) /models
# Speakeasy User and Group:
RUN \
groupadd -g 1000 magpie && \
useradd -m -g magpie -u 1000 -s /bin/bash magpie
USER magpie
# Force the entry point with the config file on the mounted drive, does not work as of 11.0
#ENV MODEL_CONFIG_FILE=/models/models.conf
ENTRYPOINT [ "/usr/bin/tensorflow_model_server", "--model_config_file=/models/models.conf"]
<file_sep>/ocr_service/api/ocr/endpoints/client.py
import io
#import json
from flask import request, Response, json
from flask_restplus import Resource, fields
from api.restplus import api
from api.ocr.logic.ocr_client import *
# create dedicated namespace for OCR client
ns = api.namespace('ocr_client', description='Simple OCR client')
# Flask-RestPlus specific parser for file uploading
# Let's go hacking my friends
nifi_clean = ns.model("clean", {
"currentfile": fields.String("absolute path to file to clean")
})
nifi_ocr = ns.model("ocr", {
"currentfile": fields.String("absolute path to file to mangle"),
"lang": fields.String("kor, eng")
})
nifi_keyword = ns.model("keyword", {
"currentfile": fields.String("absolute path to file to find keywords"),
"lang": fields.String("german, english")
})
nifi_summary = ns.model("summary", {
"currentfile": fields.String("absolute path to file to find summary"),
"lang": fields.String("german, english")
})
nifi_pdf = ns.model("pdf", {
"currentfile": fields.String("absolute path to file to find pdf"),
"lang": fields.String("german, english")
})
nifi_docx = ns.model("docx", {
"currentfile": fields.String("absolute path to file to find docx"),
"lang": fields.String("german, english")
})
@ns.route('/clean')
class Clean(Resource):
@ns.doc(description='input via json, output flat string',
responses={
200: "Success",
400: "Bad request",
500: "Internal server error"
})
#@ns.marshal_with(nifi_clean, envelope='payload')
@ns.expect(nifi_clean)
def post(self):
try:
input_json = api.payload
input_filename = input_json['currentfile']
except Exception as inst:
return {'message': 'something wrong with incoming request. ' +
'Original message: {}'.format(inst)}, 400
try:
# this is a MESS! Do what you gotta do to get it done...
results = make_clean_image(input_filename)
json_string = json.dumps(results,ensure_ascii = False)
response = Response(json_string,content_type="application/json; charset=utf-8" )
return response
except Exception as inst:
return {'message': 'internal error: {}'.format(inst)}, 500
@ns.route('/ocr')
class Ocr(Resource):
@ns.doc(description='input via json, output flat string',
responses={
200: "Success",
400: "Bad request",
500: "Internal server error"
})
#@ns.marshal_with(nifi_ocr, envelope='payload')
@ns.expect(nifi_ocr)
def post(self):
try:
input_json = api.payload
input_filename = input_json['currentfile']
input_lang = input_json['lang']
except Exception as inst:
return {'message': 'something wrong with incoming request. ' +
'Original message: {}'.format(inst)}, 400
try:
# this is a MESS! Do what you gotta do to get it done...
results = make_ocr_file(input_filename, input_lang)
json_string = json.dumps(results,ensure_ascii = False)
response = Response(json_string,content_type="application/json; charset=utf-8" )
return response
except Exception as inst:
return {'message': 'internal error: {}'.format(inst)}, 500
@ns.route('/keyword')
class Keywords(Resource):
@ns.doc(description='input via json, output flat string',
responses={
200: "Success",
400: "Bad request",
500: "Internal server error"
})
#@ns.marshal_with(nifi_keyword, envelope='payload')
@ns.expect(nifi_keyword)
def post(self):
try:
input_json = api.payload
input_filename = input_json['currentfile']
input_lang = input_json['lang']
except Exception as inst:
return {'message': 'something wrong with incoming request. ' +
'Original message: {}'.format(inst)}, 400
try:
# this is a MESS! Do what you gotta do to get it done...
results = make_keywords(input_filename, input_lang)
json_string = json.dumps(results,ensure_ascii = False)
response = Response(json_string,content_type="application/json; charset=utf-8" )
return response
except Exception as inst:
return {'message': 'internal error: {}'.format(inst)}, 500
@ns.route('/summary')
class Keywords(Resource):
@ns.doc(description='input via json, output flat string',
responses={
200: "Success",
400: "Bad request",
500: "Internal server error"
})
<EMAIL>(nifi_summary, envelope='payload')
@ns.expect(nifi_summary)
def post(self):
try:
input_json = api.payload
input_filename = input_json['currentfile']
input_lang = input_json['lang']
except Exception as inst:
return {'message': 'something wrong with incoming request. ' +
'Original message: {}'.format(inst)}, 400
try:
# this is a MESS! Do what you gotta do to get it done...
results = make_summary(input_filename,input_lang)
json_string = json.dumps(results,ensure_ascii = False)
response = Response(json_string,content_type="application/json; charset=utf-8" )
return response
except Exception as inst:
return {'message': 'internal error: {}'.format(inst)}, 500
@ns.route('/pdf')
class Pdf(Resource):
@ns.doc(description='input via json, output flat string',
responses={
200: "Success",
400: "Bad request",
500: "Internal server error"
})
#<EMAIL>(nifi_pdf, envelope='payload')
@ns.expect(nifi_pdf)
def post(self):
try:
input_json = api.payload
input_filename = input_json['currentfile']
input_lang = input_json['lang']
except Exception as inst:
return {'message': 'something wrong with incoming request. ' +
'Original message: {}'.format(inst)}, 400
try:
# this is a MESS! Do what you gotta do to get it done...
results = make_pdf(input_filename,input_lang)
json_string = json.dumps(results,ensure_ascii = False)
response = Response(json_string,content_type="application/json; charset=utf-8" )
return response
except Exception as inst:
return {'message': 'internal error: {}'.format(inst)}, 500
@ns.route('/docx')
class Pdf(Resource):
@ns.doc(description='input via json, output flat string',
responses={
200: "Success",
400: "Bad request",
500: "Internal server error"
})
#@ns.marshal_with(nifi_docx, envelope='payload')
@ns.expect(nifi_docx)
def post(self):
try:
input_json = api.payload
input_filename = input_json['currentfile']
input_lang = input_json['lang']
except Exception as inst:
return {'message': 'something wrong with incoming request. ' +
'Original message: {}'.format(inst)}, 400
try:
# this is a MESS! Do what you gotta do to get it done...
results = make_docx(input_filename,input_lang)
json_string = json.dumps(results,ensure_ascii = False)
response = Response(json_string,content_type="application/json; charset=utf-8" )
return response
except Exception as inst:
return {'message': 'internal error: {}'.format(inst)}, 500
<file_sep>/enko_service/requirements.txt
numpy
Flask
flask-restplus
grpcio
tensorflow
<file_sep>/install/quickstart.sh
#!/bin/bash -e
###########################################
# Create sub-folders
mkdir -p /var/speakeasy/mongodb
mkdir -p /var/speakeasy/output
mkdir -p /var/speakeasy/input
mkdir -p /var/speakeasy/input/ende
mkdir -p /var/speakeasy/input/kor
mkdir -p /var/speakeasy/input/enko
mkdir -p /var/speakeasy/models
###########################################
# Install models
cp -r /models /var/speakeasy/
cd /var/speakeasy/models
if [ -n "${SPEAKEASY_MINIO_URL}" ]; then
cat <<EOF > config.json
{
"version": "9",
"hosts": {
"sofwerx": {
"url": "${SPEAKEASY_MINIO_URL}",
"accessKey": "${SPEAKEASY_MINIO_ACCESS_KEY}",
"secretKey": "${SPEAKEASY_MINIO_SECRET_KEY}",
"api": "S3v2",
"lookup": "auto"
}
}
}
EOF
fi
./install_models.sh
<file_sep>/tfc_service/Dockerfile
FROM python:3.6
RUN \
apt-get update \
&& apt-get install -y --no-install-recommends apt-utils
# Depends on volume (refer to ../docker-compose.yml) /models
LABEL \
description="Tensorflow Client depends on models volume"
# Speakeasy User and Group:
RUN \
groupadd -g 1000 flaskgroup \
&& useradd -m -g flaskgroup -u 1000 -s /bin/bash flask \
&& mkdir -p /var/tfc_server \
&& chown -R flask:flaskgroup /var/tfc_server \
&& pip install --upgrade pip
USER flask
# And then...
RUN \
pip3 install --user nltk \
&& python3 -m nltk.downloader popular
# Takes a long time, separated from requirements.txt
WORKDIR /var/tfc_server
COPY . /var/tfc_server
ENV PATH "$PATH:/home/flask/.local/bin"
RUN pip3 install --user --no-cache-dir -r requirements.txt
ENTRYPOINT ["python"]
CMD ["app.py"]
<file_sep>/tfc_service/api/ende/endpoints/client.py
import io
#import json
from flask import request, Response, json
from flask_restplus import Resource, fields
from api.restplus import api
from api.ende.logic.tf_client import make_prediction
from werkzeug.datastructures import FileStorage
from nltk import sent_tokenize
# create dedicated namespace for ENDE client
ns = api.namespace('ende_client', description='Operations for Translating the ende model using the sentence piece model')
# Flask-RestPlus specific parser for file uploading
UPLOAD_KEY = 'file'
UPLOAD_LOCATION = 'files'
upload_parser = api.parser()
upload_parser.add_argument(UPLOAD_KEY,
location=UPLOAD_LOCATION,
type=FileStorage,
required=True)
text_parser = api.parser()
text_parser.add_argument('text', required=True, help='enter sentences')
@ns.route('/prediction/file')
class EndePredictionFile(Resource):
@ns.doc(description='input is text file, output json',
responses={
200: "Success",
400: "Bad request",
500: "Internal server error"
})
@ns.expect(upload_parser)
def post(self):
try:
input_file = request.files[UPLOAD_KEY]
input = io.BytesIO(input_file.read())
# Do what you gotta do to get it done...
bfe = input.read()
bfe1 = str(bfe, 'utf-8')
input_list = sent_tokenize(bfe1)
except Exception as inst:
return {'message': 'something wrong with incoming request file. ' +
'Original message: {}'.format(inst)}, 400
try:
results = make_prediction(input_list)
return results, 200
except Exception as inst:
return {'message': 'internal error with processing input text from file: {}'.format(inst)}, 500
@ns.route('/prediction/text')
class EndePredictionText(Resource):
@ns.doc(description='input is text param, output is json',
responses={
200: "Success",
400: "Bad request",
500: "Internal server error"
})
@ns.expect(text_parser)
def post(self):
try:
input_text = request.args['text']
input_list = sent_tokenize(input_text)
except Exception as inst:
return {'message': 'something wrong with incoming request. ' +
'Original message: {}'.format(inst)}, 400
try:
# this is a MESS! Do what you gotta do to get it done...
results = make_prediction(input_list)
return results, 200
except Exception as inst:
return {'message': 'internal error: {}'.format(inst)}, 500
# Let's go hacking my friends
nifi_model = ns.model("ende", {
"content": fields.String("text string"),
})
@ns.route('/prediction/nifi')
class EndeNifi(Resource):
@ns.doc(description='input via json, output flat string',
responses={
200: "Success",
400: "Bad request",
500: "Internal server error"
})
#@ns.marshal_with(nifi_model, envelope='payload')
@ns.expect(nifi_model)
def post(self):
try:
input_json = api.payload
input_text = input_json['content']
input_list = sent_tokenize(input_text)
# BOM: windows notepad is nothing less than annoying
input_text.replace(u'\ufeff','')
except Exception as inst:
return {'message': 'something wrong with incoming request. ' +
'Original message: {}'.format(inst)}, 400
try:
# this is a MESS! Do what you gotta do to get it done...
# BOM: don't bother with a blank line
results = make_prediction(input_list)
json_string = json.dumps(results,ensure_ascii = False)
response = Response(json_string,content_type="application/json; charset=utf-8" )
return response
except Exception as inst:
return {'message': 'internal error: {}'.format(inst)}, 500
<file_sep>/enko_service/README.md
# **English to Korean Translation**
## *What*
> This is a "wrapped" version of the translate only from the koen project
> Crawl
>> Focus on serving the enko_translate.py
<file_sep>/enko_service/settings.py
# Flask settings
DEFAULT_FLASK_SERVER_NAME = '0.0.0.0'
DEFAULT_FLASK_SERVER_PORT = '5001'
DEFAULT_FLASK_DEBUG = '1' # Do not use debug mode in production
# Flask-Restplus settings
RESTPLUS_SWAGGER_UI_DOC_EXPANSION = 'list'
RESTPLUS_VALIDATE = True
RESTPLUS_MASK_SWAGGER = False
RESTPLUS_ERROR_404_HELP = False
# TRAN client settings
DEFAULT_TF_SERVER_NAME = '0.0.0.0'
DEFAULT_TF_SERVER_PORT = 8500
# PICKLES
# TODO: I am copying code from notebook, using the PICKLED files as-is, needs to be json...
ENKO_MODEL='/var/speakeasy/models/enko/checkpoints'
ENKO_PICKLE_PREPROCESS='preprocess.p'
ENKO_PARAMS='dev'
<file_sep>/nifi_service/run.sh
#!/bin/bash -e
gunzip /opt/nifi/nifi-current/conf/flow.xml.gz
sed -i -e "s%mongodb://speakeasy:Speakeasy123@mongo:27017%${MONGO_CONNECT}%" /opt/nifi/nifi-current/conf/flow.xml
gzip /opt/nifi/nifi-current/conf/flow.xml
. ../scripts/start.sh
<file_sep>/enko_service/api/enko/endpoints/client.py
import io
#import json
from flask import request, Response, json
from flask_restplus import Resource, fields
from api.restplus import api
from api.enko.logic.enko_translate import enko_translate
# create dedicated namespace for ENDE client
ns = api.namespace('enko_client', description='Operations for Translating the enko model')
text_parser = api.parser()
text_parser.add_argument('text', required=True, help='enter a sentence')
@ns.route('/prediction/text')
class KoenPredictionText(Resource):
@ns.doc(description='input is text param, output is json',
responses={
200: "Success",
400: "Bad request",
500: "Internal server error"
})
@ns.expect(text_parser)
def post(self):
try:
input_text = request.args['text']
except Exception as inst:
return {'message': 'something wrong with incoming request. ' +
'Original message: {}'.format(inst)}, 400
try:
# Do what you gotta do to get it done...
results = enko_translate(input_text)
return results, 200
except Exception as inst:
return {'message': 'internal error: {}'.format(inst)}, 500
# Let's go hacking my friends
nifi_model = ns.model("enko", {
"content": fields.String("text string"),
})
@ns.route('/prediction/nifi')
class EndeNifi(Resource):
@ns.doc(description='input via json, output flat string',
responses={
200: "Success",
400: "Bad request",
500: "Internal server error"
})
#@ns.marshal_with(nifi_model, envelope='payload')
@ns.expect(nifi_model)
def post(self):
try:
input_json = api.payload
input_text = input_json['content']
except Exception as inst:
return {'message': 'something wrong with incoming request. ' +
'Original message: {}'.format(inst)}, 400
try:
# Do what you gotta do to get it done...
results = enko_translate(input_text)
json_string = json.dumps(results,ensure_ascii = False)
return Response(json_string,content_type="application/json; charset=utf-8" )
except Exception as inst:
return {'message': 'internal error: {}'.format(inst)}, 500
<file_sep>/ui/app/nifi/models.py
# nifi stuff
from app.extensions import dbm
class Input(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
msg = dbm.StringField()
start = dbm.StringField()
filename = dbm.StringField()
trigger = dbm.StringField()
path = dbm.StringField()
fileSize = dbm.StringField()
class Input_data(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
grid = dbm.StringField()
payload = dbm.FileField()
context_type = dbm.StringField()
class Translate_data(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
grid = dbm.StringField()
payload = dbm.FileField()
context_type = dbm.StringField()
class Translate(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
msg = dbm.StringField()
start = dbm.StringField()
class Ocr(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
msg = dbm.StringField()
start = dbm.StringField()
lang = dbm.StringField()
class Ocr_data(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
grid = dbm.StringField()
payload = dbm.FileField()
context_type = dbm.StringField()
class Clean_data(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
grid = dbm.StringField()
payload = dbm.FileField()
context_type = dbm.StringField()
class Docx(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
msg = dbm.StringField()
start = dbm.StringField()
lang = dbm.StringField()
class Docx_data(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
grid = dbm.StringField()
payload = dbm.FileField()
context_type = dbm.StringField()
class Pdf(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
msg = dbm.StringField()
start = dbm.StringField()
lang = dbm.StringField()
class Pdf_data(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
grid = dbm.StringField()
payload = dbm.FileField()
context_type = dbm.StringField()
class Complete(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
msg = dbm.StringField()
start = dbm.StringField()
class Route(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
msg = dbm.StringField()
start = dbm.StringField()
class Metadata(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
msg = dbm.StringField()
start = dbm.StringField()
summary = dbm.StringField()
keywords = dbm.StringField()
class Nifi(dbm.Document):
meta = {
'strict' : False
}
uuid = dbm.StringField()
source = dbm.StringField()
model = dbm.StringField()
sourceLanguage = dbm.StringField()
targetLanguage = dbm.StringField()
state = dbm.StringField()
result = dbm.StringField()
input = dbm.EmbeddedDocumentField(Input)
input_data = dbm.EmbeddedDocumentField(Input_data)
translate = dbm.EmbeddedDocumentField(Translate)
translate_data = dbm.EmbeddedDocumentField(Translate_data)
ocr = dbm.EmbeddedDocumentField(Ocr)
ocr_data = dbm.EmbeddedDocumentField(Ocr_data)
clean_data = dbm.EmbeddedDocumentField(Clean_data)
docx = dbm.EmbeddedDocumentField(Docx)
docx_data = dbm.EmbeddedDocumentField(Docx_data)
pdf = dbm.EmbeddedDocumentField(Pdf)
pdf_data = dbm.EmbeddedDocumentField(Pdf_data)
complete = dbm.EmbeddedDocumentField(Complete)
route = dbm.EmbeddedDocumentField(Route)
metadata = dbm.EmbeddedDocumentField(Metadata)
####################################3
# NIFI does NOT ROCK.
# Nifi cannot save as ObjectId()
# Patch the ObjectId() ... ugh
# read the fsgrid
# store as a objectId()
####################################3
class PatchSub(dbm.EmbeddedDocument):
meta = {
'strict' : False
}
grid = dbm.StringField()
payload = dbm.ObjectIdField()
context_type = dbm.StringField()
class PatchMain(dbm.Document):
meta = {
'strict' : False,
'collection': 'nifi'
}
uuid = dbm.StringField()
input_data = dbm.EmbeddedDocumentField(PatchSub)
translate_data = dbm.EmbeddedDocumentField(PatchSub)
ocr_data = dbm.EmbeddedDocumentField(PatchSub)
clean_data = dbm.EmbeddedDocumentField(PatchSub)
docx_data = dbm.EmbeddedDocumentField(PatchSub)
pdf_data = dbm.EmbeddedDocumentField(PatchSub)
<file_sep>/tfc_service/settings.py
# Flask settings
DEFAULT_FLASK_SERVER_NAME = '0.0.0.0'
DEFAULT_FLASK_SERVER_PORT = '5001'
DEFAULT_FLASK_DEBUG = '1' # Do not use debug mode in production
# Flask-Restplus settings
RESTPLUS_SWAGGER_UI_DOC_EXPANSION = 'list'
RESTPLUS_VALIDATE = True
RESTPLUS_MASK_SWAGGER = False
RESTPLUS_ERROR_404_HELP = False
# TRAN client settings
DEFAULT_TF_SERVER_NAME = '0.0.0.0'
DEFAULT_TF_SERVER_PORT = 8500
# Things that make you go hmm...
DEFAULT_ENDE_MODEL_NAME = 'ende'
DEFAULT_ENDE_MODEL_SIGNATURE_NAME = 'serving_default'
DEFAULT_ENDE_MODEL_SENTENCE_PIECE = '/var/speakeasy/models/ende/1539080952/assets.extra/wmtende.model'
DEFAULT_KOR_MODEL_NAME = 'kor'
DEFAULT_KOR_MODEL_SIGNATURE_NAME = 'serving_default'
<file_sep>/docker-compose.yml
version: '3.1'
##########################################################################
# PRE-REQ:
# SPEAKEASY_SHARED is defined in .env (eg: /var/speakeasy)
# SEE quickstart.sh for volume requirements!
# Network is "speakeasy"
# This will need some tweeking with non-vm install
# mongo is using default host:port
##########################################################################
services:
install:
container_name: install
image: speakeasy/install
build: .
volumes:
- file_share:/var/speakeasy
- models:/var/speakeasy/models
environment:
SPEAKEASY_MINIO_URL: ${SPEAKEASY_MINIO_URL}
SPEAKEASY_MINIO_ACCESS_KEY: ${SPEAKEASY_MINIO_ACCESS_KEY}
SPEAKEASY_MINIO_SECRET_KEY: ${SPEAKEASY_MINIO_SECRET_KEY}
SPEAKEASY_SHARED: ${SPEAKEASY_SHARED}
SPEAKEASY_VERSION: ${SPEAKEASY_VERSION}
ui:
container_name: ui
image: speakeasy/ui:v${SPEAKEASY_VERSION}
depends_on:
- mongo
- install
build: ./ui
restart: always
environment:
- PYTHONUNBUFFERED=0
- FLASK_SERVER_NAME=0.0.0.0
- FLASK_SERVER_PORT=5000
- FLASK_DEBUG=0
- FLASK_ENV=production
- MONGO_EXPRESS=http://0.0.0.0:8071/
- MONGO_CONNECT=mongodb://speakeasy:Speakeasy123@mongo/speakeasy?authSource=admin
- OCR_SERVICE=http://0.0.0.0:5010/poc_api/
- TFC_SERVICE=http://0.0.0.0:5020/poc_api/
- ENKO_SERVICE=http://0.0.0.0:5030/poc_api/
- NIFI_SERVICE=http://0.0.0.0:8080/nifi/
ports:
- "5000:5000"
volumes:
- file_share:/var/speakeasy
networks:
- speakeasy
mongo:
container_name: mongo
image: speakeasy/mongo:v${SPEAKEASY_VERSION}
restart: always
build: ./mongo
depends_on:
- install
networks:
- speakeasy
environment:
- MONGO_INITDB_ROOT_USERNAME=speakeasy
- MONGO_INITDB_ROOT_PASSWORD=<PASSWORD>
- MONGO_INITDB_DATABASE=speakeasy
ports:
- 27017:27017
volumes:
- mongodb:/data/db
mongo_express:
container_name: mongo_express
image: speakeasy/mongo_express:v${SPEAKEASY_VERSION}
restart: always
depends_on:
- mongo
build: ./mongo_express
networks:
- speakeasy
ports:
- "8070-8071:8080-8081"
environment:
- ME_CONFIG_MONGODB_ADMINUSERNAME=speakeasy
- ME_CONFIG_MONGODB_ADMINPASSWORD=<PASSWORD>
tfs_service:
container_name: tfs_service
image: speakeasy/tfs_service:v${SPEAKEASY_VERSION}
depends_on:
- install
networks:
- speakeasy
ports:
- "8500:8500"
build: ./tfs_service
restart: always
volumes:
- models:/models
environment:
- MODEL_CONFIG_FILE=/models/models.conf
tfc_service:
container_name: tfc_service
image: speakeasy/tfc_service:v${SPEAKEASY_VERSION}
depends_on:
- tfs_service
networks:
- speakeasy
ports:
- "5020:5020"
build: ./tfc_service
restart: always
volumes:
- models:/models
environment:
- FLASK_SERVER_NAME=0.0.0.0
- FLASK_SERVER_PORT=5020
- FLASK_DEBUG=0
- FLASK_ENV=production
- TF_SERVER_NAME=tfs_service
- TF_SERVER_PORT=8500
- ENDE_MODEL_SENTENCE_PIECE=/models/ende/1539080952/assets.extra/wmtende.model
- ENDE_MODEL_NAME=ende
- ENDE_MODEL_SIGNATURE_NAME=serving_default
nifi_service:
container_name: nifi_service
image: speakeasy/nifi_service:v${SPEAKEASY_VERSION}
build: ./nifi_service
depends_on:
- install
environment:
- MONGO_CONNECT=mongodb://speakeasy:Speakeasy123@mongo/speakeasy?authSource=admin
- TFC_SERVICE=http://tfc_service:5020/poc_api
- ENKO_SERVICE=http://enko_service:5030/poc_api
- OCR_SERVICE_DOCX=http://ocr_service:5010/poc_api/ocr_client/docx
- OCR_SERVICE_PDF=http://ocr_service:5010/poc_api/ocr_client/pdf
- OCR_SERVICE_CLEAN=http://ocr_service:5010/poc_api/ocr_client/clean
- OCR_SERVICE_KEYWORD=http://ocr_service:5010/poc_api/ocr_client/keyword
- OCR_SERVICE_SUMMARY=http://ocr_service:5010/poc_api/ocr_client/summary
- OCR_SERVICE_OCR=http://ocr_service:5010/poc_api/ocr_client/ocr
ports:
- "8080-8081:8080-8081"
- "7001-7002:7001-7002"
volumes:
- nifi_datafiles:/opt/datafiles
- nifi_scriptfiles:/opt/scriptfiles
- nifi_certfiles:/opt/certfiles
- nifi_data:/opt/nifi
- file_share:/var/speakeasy
- models:/var/speakeasy/models
networks:
- speakeasy
ocr_service:
container_name: ocr_service
image: speakeasy/ocr_service:v${SPEAKEASY_VERSION}
depends_on:
- install
networks:
- speakeasy
ports:
- "5010:5010"
build: ./ocr_service
restart: always
volumes:
- file_share:/var/speakeasy
- models:/var/speakeasy/models
environment:
- FLASK_SERVER_NAME=0.0.0.0
- FLASK_SERVER_PORT=5010
- FLASK_DEBUG=0
- FLASK_ENV=production
enko_service:
container_name: enko_service
image: speakeasy/enko_service:v${SPEAKEASY_VERSION}
depends_on:
- install
networks:
- speakeasy
ports:
- "5030:5030"
build: ./enko_service
restart: always
volumes:
- models:/var/speakeasy/models
environment:
- FLASK_SERVER_NAME=0.0.0.0
- FLASK_SERVER_PORT=5030
- FLASK_DEBUG=0
- FLASK_ENV=production
volumes:
nifi_datafiles:
nifi_scriptfiles:
nifi_certfiles:
nifi_data:
mongodb:
driver: local
models:
driver: local
file_share:
driver: local
networks:
speakeasy:
driver: bridge
<file_sep>/nifi_service/Dockerfile
FROM apache/nifi:latest
# Depends on volume (refer to ../docker-compose.yml) /models
LABEL \
description="Simple NIFI flow"
COPY --chown=nifi:nifi flow.xml.gz /opt/nifi/nifi-current/conf/
COPY --chown=nifi:nifi ./nar/* /opt/nifi/nifi-current/lib/
COPY --chown=nifi:nifi ./nifi-env.sh /opt/nifi/nifi-current/bin/
COPY --chown=nifi:nifi ./bootstrap.conf /opt/nifi/nifi-current/conf/
ADD run.sh /run.sh
ENTRYPOINT /run.sh
<file_sep>/ocr_service/settings.py
# Flask settings
DEFAULT_FLASK_SERVER_NAME = '0.0.0.0'
DEFAULT_FLASK_SERVER_PORT = '5001'
DEFAULT_FLASK_DEBUG = '1' # Do not use debug mode in production
# Flask-Restplus settings
RESTPLUS_SWAGGER_UI_DOC_EXPANSION = 'list'
RESTPLUS_VALIDATE = True
RESTPLUS_MASK_SWAGGER = False
RESTPLUS_ERROR_404_HELP = False
<file_sep>/enko_service/app.py
import logging.config
import settings
import utils
from flask import Flask, Blueprint
from flask_restplus import Resource, Api
from api.restplus import api
from api.enko.endpoints.client import ns as enko_client_namespace
# create Flask application
application = Flask(__name__)
# load logging confoguration and create log object
logging.config.fileConfig('logging.conf')
log = logging.getLogger(__name__)
def __get_flask_server_params__():
'''
Returns connection parameters of the Flask application
:return: Tripple of server name, server port and debug settings
'''
server_name = utils.get_env_var_setting('FLASK_SERVER_NAME', settings.DEFAULT_FLASK_SERVER_NAME)
server_port = int(utils.get_env_var_setting('FLASK_SERVER_PORT', settings.DEFAULT_FLASK_SERVER_PORT))
flask_debug = utils.get_env_var_setting('FLASK_DEBUG', settings.DEFAULT_FLASK_DEBUG)
flask_debug = True if flask_debug == '1' else False
return server_name, server_port, flask_debug
def configure_app(flask_app):
'''
Configure Flask application
:param flask_app: instance of Flask() class
'''
flask_app.config['SWAGGER_UI_DOC_EXPANSION'] = settings.RESTPLUS_SWAGGER_UI_DOC_EXPANSION
flask_app.config['RESTPLUS_VALIDATE'] = settings.RESTPLUS_VALIDATE
flask_app.config['RESTPLUS_MASK_SWAGGER'] = settings.RESTPLUS_MASK_SWAGGER
flask_app.config['ERROR_404_HELP'] = settings.RESTPLUS_ERROR_404_HELP
def initialize_app(flask_app):
'''
Initialize Flask application with Flask-RestPlus
:param flask_app: instance of Flask() class
'''
blueprint = Blueprint('poc_api', __name__, url_prefix='/poc_api')
configure_app(flask_app)
api.init_app(blueprint)
api.add_namespace(enko_client_namespace)
flask_app.register_blueprint(blueprint)
if __name__ == '__main__':
server_name, server_port, flask_debug = __get_flask_server_params__()
initialize_app(application)
application.run(debug=flask_debug, host=server_name, port=server_port)
<file_sep>/tfc_service/requirements.txt
Flask==1.0.2
flask-restplus==0.11.0
grpcio==1.7.0
tensorflow==1.4.0
pyonmttok==1.10.1
<file_sep>/models/install_kor.sh
#!/bin/bash -e
install_kor() {
# quick check for the folder
if [ ! -d ${SPEAKEASY_HOME}/models/kor ]
then
cd ${SPEAKEASY_HOME}/models
./mc --config-dir . ls sofwerx/models/kor.tar.gz
./mc --config-dir . cp sofwerx/models/kor.tar.gz .
tar xf kor.tar.gz
rm kor.tar.gz
echo " kor download complete"
return 0
else
echo " skipping download, looks like you already have an kor folder"
return 0
fi
}
<file_sep>/mongo_express/Dockerfile
FROM mongo-express:latest
# Depends on volume (refer to ../docker-compose.yml) /models
LABEL \
description="Manage Mongo Madness"
<file_sep>/models/install_models.sh
#!/bin/bash -e
echo "...Get the ende model from mc and rename it"
echo "...mc depends on ./config.json which has passwords ... "
SPEAKEASY_HOME=/var/speakeasy
# Either put this here or i Docker ....
if [ ! -f mc ]; then
wget https://dl.minio.io/client/mc/release/linux-amd64/mc
fi
if [ ! -x mc ] ; then
chmod +x mc
fi
./mc version
./mc --help
. ./install_ende.sh
. ./install_kor.sh
. ./install_enko.sh
install_ende
if [ ${?} -ne 0 ]
then
echo "FAILURE on ende install"
exit 99
fi
install_kor
if [ ${?} -ne 0 ]
then
echo "FAILURE on kor install"
exit 99
fi
install_enko
if [ ${?} -ne 0 ]
then
echo "FAILURE on enko install"
exit 99
fi
<file_sep>/ocr_service/Dockerfile
FROM python:3.7-slim
ENV PYTHONUNBUFFERED=1
ENV LC_ALL=C.UTF-8
ENV LANG=C.UTF-8
RUN apt-get update \
&& apt install -y tesseract-ocr \
&& apt install libtesseract-dev \
&& apt-get install tesseract-ocr-kor \
&& apt-get install libsm6 libxrender1 libfontconfig1 \
&& rm -rf /var/lib/apt/lists/* \
&& pip install --upgrade pip
# Depends on ...
LABEL \
description="Very limited OCR"
# Speakeasy User and Group:
RUN \
groupadd -g 1000 flaskgroup && \
useradd -m -g flaskgroup -u 1000 -s /bin/bash flask
USER flask
WORKDIR /var/ocr
COPY . /var/ocr
ENV PATH "$PATH:/home/flask/.local/bin"
RUN pip install --user -r requirements.txt
ENTRYPOINT ["python"]
CMD ["app.py"]
<file_sep>/ui/app/extensions.py
################
# main login stuff
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
migrate = Migrate()
login = LoginManager()
################
# nifi stuff
#from flask_uploads import UploadSet, IMAGES, TEXT, DOCUMENTS
from flask_uploads import UploadSet, IMAGES, TEXT
from flask_mongoengine import MongoEngine
dbm = MongoEngine()
DOCUMENTS = tuple('docx pdf'.split())
################
#### flask-uploads pain ####
################
ende = UploadSet('ende', IMAGES + TEXT + DOCUMENTS)
kor = UploadSet('kor', IMAGES + TEXT + DOCUMENTS)
enko = UploadSet('enko', IMAGES + TEXT + DOCUMENTS)
<file_sep>/ui/app/nifi/forms.py
# project/nifi/forms.py
from flask_wtf import FlaskForm
from wtforms import SelectField, SubmitField
from flask_wtf.file import FileField, FileAllowed, FileRequired
class AddNifiForm(FlaskForm):
upload = FileField(
u'Choose 1 to 5 Files (jpg, png, txt, docx, pdf)',
validators=[
FileRequired(),
FileAllowed(['jpg', 'png', 'txt', 'docx', 'pdf'], 'File Types')
]
)
model = SelectField(
u'Select Translation Model',
choices=[
('kor', 'kor - Korean to English'),
('enko', 'enko - English to Korean'),
('ende', 'ende - English to German')
]
)
submit = SubmitField(u'Submit')
<file_sep>/ui/app/templates/nifi_list.html
{% extends "layout.html" %}
{% from "_form_macros.html" import render_field %}
{% block content %}
<hr>
<!--.card container -->
<div class="container-fluid" id="equal-card-decks">
<!--.card deck -->
<div class="card-deck">
<!--.card -->
<div class="card border-dark mb-3">
<div class="card-header">
<h5 class="card-title">Home</h5>
</div>
<!--.card body-->
<div class="card-body text-dark">
<!--.table -->
<div class="table-responsive">
<table id="nifilist" class="table table-striped table-bordered table-sm table-hover" cellspacing="0" width="100%">
<thead class="thead-dark">
<tr>
<th>#</th>
<th><a title="Model">Model</a></th>
<th><a title="SourceLanguage">Source Language</a></th>
<th><a title="TargetLanguage">Target Language</a></th>
<th><a title="File Name">Source File</a></th>
<th><a title="Start Time Stamp">Start Time</a></th>
<th><a title="End Time Stamp">End Time</a></th>
<th><a title="State">Current State</a></th>
<th><a title="Process Detail">Detail Link</a></th>
<tr>
</thead>
<tbody>
{% for nifi in nifi.items %}
<tr>
<td>{{ loop.index + (page - 1) * per_page }}</td>
<td><a title="Model"> {{ nifi.model }} </a></td>
<td><a title="SourceLanguage"> {{ nifi.sourceLanguage }} </a></td>
<td><a title="TargetLanguage"> {{ nifi.targetLanguage }} </a></td>
<td><a title="{{ nifi.uuid}}"> {{ nifi.source }} </a></td>
<td><a title="Input"> {{ nifi.input.start }} </a></td>
<td><a title="Complete"> {{ nifi.complete.start }} </a></td>
<td><a title="State"> {{ nifi.state }} </a></td>
<td><a title="Click for Status" href="{{ url_for('nifi.go_nifi_details', nifi_uuid=nifi.uuid) }}">{{ nifi.result}} </a></td>
</tr>
{% endfor %}
</tbody>
</table>
<a href="{{ url_for('nifi.go_nifi_list') }}" class="btn btn-sm btn-primary">Refresh</a>
<!--.table -->
</div>
{{ pagination.info }}
{{ pagination.links }}
<!--.card body-->
</div>
<!--.card -->
</div>
<!--.card deck -->
</div>
<!--.card container -->
</div>
</hr>
{% endblock %}
<file_sep>/ui/app.py
import utils
from app import create_app
import logging.config
logging.config.fileConfig('logging.conf')
log = logging.getLogger(__name__)
import pymongo
from pymongo import MongoClient
import dash
# dash libs
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dt
import plotly.graph_objs as go
import pandas as pd
from bson import json_util, ObjectId
from pandas.io.json import json_normalize
import json
def mongo_to_dictionary(mongo_data):
sanitized = json.loads(json_util.dumps(mongo_data))
normalized = json_normalize(sanitized, sep='_')
records = normalized.to_dict('records')
return records
def mongo_to_dataframe(mongo_data):
sanitized = json.loads(json_util.dumps(mongo_data))
normalized = json_normalize(sanitized)
df = pd.DataFrame(normalized)
return df
# I dislike mongodb in yet another way.
def get_match_results():
cursor = nifi_collection.find(
{}, { '_id': 0, 'model': 1, 'result': 1, 'state': 1, 'input.filename': 1 }
)
return mongo_to_dictionary(cursor)
def create_dash(server):
# I have this commented out of the html, it is failing
dashapp = dash.Dash(__name__, server=server, url_base_pathname='/dashboard/')
# todo bring this into the project - cannot run with http in demo.
# found no easy-peasy way to do this in dash
dashapp.css.append_css({
"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"
})
dashapp.layout = html.Div(
html.Div([
html.H1('Speakeasy'),
html.H2('Dashboard'),
html.H3('** Live Feed every 30 milliseconds **'),
dt.DataTable(
rows=[{}], # initialise the rows
filterable=True,
sortable=True,
id='table-results'
),
dcc.Graph(id='graph1'),
dcc.Interval(
id='interval-component',
interval=30*1000, # in milliseconds
n_intervals=0
)
])
)
@dashapp.callback(
Output('table-results', 'rows'),
[
Input('interval-component', 'n_intervals')
]
)
def load_match_results(ignoreme):
results = get_match_results()
return results
@dashapp.callback(
Output('graph1', 'figure'),
[
Input('interval-component', 'n_intervals')
]
)
def load_graph1_results(ignoreme):
dashapp.logger.info('aaaaaaaaaaaaaaaaaaa');
filtered_results = nifi_collection.find(
{'metadata.keywords': {'$nin': [ None, '']}},
{'source': 1, 'metadata.keywords': 1 }
)
print(filtered_results)
print('bbbbbbbbbbbbbbbbb')
filtered_dict = mongo_to_dictionary(filtered_results)
print(filtered_dict)
print('ccccccccccccccccc')
word_file = pd.DataFrame()
for record in filtered_dict:
print('xxxxxxxxxxxx')
print(record)
for kw in record['metadata_keywords'].split(','):
print('yyyyyyyyyyyy')
print(kw)
row = {'watch': kw, 'filename': record['source'], 'id': record['_0']}
word_file = word_file.append(row, ignore_index=True)
counts=word_file.groupby(['watch']).size().reset_index(name='count')
top_10=counts.nlargest(10, 'count')
watch_list = []
count_list = []
file_list = []
for index, row in top_10.iterrows():
watch_list.insert(index, row['watch'])
count_list.insert(index, row['count'])
matches = []
for i, r in word_file.iterrows():
if (row['watch'] == r['watch']):
matches.append( '('+ r['id']+') '+r['filename'] )
file_list.insert(index, matches)
barSet = go.Bar(
x=watch_list,
y=count_list,
text=file_list,
marker=dict(
color='#17BECF',
),
opacity=0.6
)
figure={
'data': [barSet],
'layout': go.Layout(
title='10 Most Popular Keywords (All Time)'
)
}
return figure
return dashapp
if __name__ == "__main__":
server = create_app()
MONGO_CONNECT = utils.get_env_var_setting('MONGO_CONNECT', 'youloose')
db = MongoClient(MONGO_CONNECT).get_database()
nifi_collection = db.nifi
dashapp = create_dash(server)
server_name, server_port, flask_debug = utils.get_flask_server_params()
server.run(debug=flask_debug, host=server_name, port=server_port)
<file_sep>/models/install_ende.sh
#!/bin/bash -e
install_ende() {
# quick check for the folder
if [ ! -d ${SPEAKEASY_HOME}/models/ende ]
then
cd ${SPEAKEASY_HOME}/models
# origin
# wget -q https://s3.amazonaws.com/opennmt-models/averaged-ende-export500k.tar.gz
# this requires mc to be installed and the config
./mc --config-dir . ls sofwerx/models/averaged-ende-export500k.tar.gz
./mc --config-dir . cp sofwerx/models/averaged-ende-export500k.tar.gz .
tar xf averaged-ende-export500k.tar.gz
mv averaged-ende-export500k ende
rm averaged-ende-export500k.tar.gz
echo " ende download complete"
return 0
else
echo " skipping download, looks like you already have an ende folder"
return 0
fi
}
<file_sep>/tfc_service/api/ende/logic/tf_client.py
from __future__ import print_function
import os
import operator
import logging
import settings
import utils
import tensorflow as tf
import pyonmttok
import json
# Communication to TensorFlow server via gRPC
from grpc.beta import implementations
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2
log = logging.getLogger(__name__)
def __get_tf_server_connection_params__():
'''
Returns connection parameters to TensorFlow Server
:return: Tuple of TF server name and server port
'''
server_name = utils.get_env_var_setting('TF_SERVER_NAME', settings.DEFAULT_TF_SERVER_NAME)
server_port = utils.get_env_var_setting('TF_SERVER_PORT', settings.DEFAULT_TF_SERVER_PORT)
return server_name, server_port
def __create_prediction_request__(tokenizer, input_data):
'''
Creates prediction request to TensorFlow server for ENDE model
:param: Byte array, input_data for prediction
:return: PredictRequest object
'''
# create predict request
request = predict_pb2.PredictRequest()
log.debug('create prediction request: tokenize, length and tokens MADNESS')
# Tensorflow magic
MODEL_NAME = utils.get_env_var_setting('ENDE_MODEL_NAME', settings.DEFAULT_ENDE_MODEL_NAME)
log.debug('using model:'+MODEL_NAME)
request.model_spec.name = MODEL_NAME
# TODO: using signature_def as signature_name - is that correct? IDK
# hint: python yada/lib/python3.5/site-packages/tensorflow/python/tools/saved_model_cli.py show --dir yada/ende/1539080952/ --all
SIGNATURE_NAME = utils.get_env_var_setting('ENDE_MODEL_SIGNATURE_NAME', settings.DEFAULT_ENDE_MODEL_SIGNATURE_NAME)
log.debug('using signature:'+SIGNATURE_NAME)
request.model_spec.signature_name = SIGNATURE_NAME
log.debug('building tokens')
input_tokens = [tokenizer.tokenize(text)[0] for text in input_data]
log.debug(type(input_tokens))
log.debug(input_tokens)
batch_tokens, lengths, max_length = pad_batch(input_tokens)
batch_size = len(lengths)
request.inputs['tokens'].CopyFrom(
tf.contrib.util.make_tensor_proto(batch_tokens, shape=(batch_size,max_length)))
log.debug('building length')
request.inputs['length'].CopyFrom(
tf.contrib.util.make_tensor_proto(lengths, shape=(batch_size,)))
log.debug('throw request to the grpc - here is the request:')
log.debug(request)
return request
def __open_tf_server_channel__(server_name, server_port):
'''
Opens channel to TensorFlow server for requests
:param server_name: String, server name (localhost, IP address)
:param server_port: String, server port
:return: Channel stub
'''
log.debug('create channel and stub - beware no error checking ')
channel = implementations.insecure_channel(
server_name,
int(server_port))
stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
return stub
def pad_batch(batch_tokens):
"""Pads a batch of tokens."""
log.debug('this is copied from ende_client.py - MAGIC that I did not write')
lengths = [len(tokens) for tokens in batch_tokens]
max_length = max(lengths)
for tokens, length in zip(batch_tokens, lengths):
if max_length > length:
tokens += [""] * (max_length - length)
return batch_tokens, lengths, max_length
def extract_prediction(result):
"""Parses a translation result.
Args:
result: A `PredictResponse` proto.
Returns:
A generator over the hypotheses.
"""
log.debug('this is copied from ende_client.py - MAGIC that I did not write')
batch_lengths = tf.make_ndarray(result.outputs["length"])
batch_predictions = tf.make_ndarray(result.outputs["tokens"])
log.debug(batch_predictions)
for hypotheses, lengths in zip(batch_predictions, batch_lengths):
# Only consider the first hypothesis (the best one).
best_hypothesis = hypotheses[0]
best_length = lengths[0] - 1 # Ignore </s>
yield best_hypothesis[:best_length]
def __make_prediction_and_prepare_results__(stub, tokenizer, request):
'''
Sends Predict request over a channel stub to TensorFlow server
:param stub: Channel stub
:param request: God only knows PredictRequest object
:return: And his translator might know too
'''
log.debug('predict the future here')
#result = stub.Predict(request, 60.0) # 60 secs timeout
future = stub.Predict.future(request, 60.0) # 60 secs timeout
log.debug('got a future')
result = future.result()
log.debug('make batch_output from future.result')
batch_output = [tokenizer.detokenize(prediction) for prediction in extract_prediction(result)]
log.debug(batch_output)
return batch_output
def __setup_tokenizer():
# ende/1539080952/assets.extra/wmtende.model
# tokenizer = pyonmttok.Tokenizer("none", sp_model_path=args.sentencepiece_model)
SP_MODEL = utils.get_env_var_setting('ENDE_MODEL_SENTENCE_PIECE', settings.DEFAULT_ENDE_MODEL_SENTENCE_PIECE)
log.debug('setup tokenizer:'+SP_MODEL)
tokenizer = pyonmttok.Tokenizer("none", sp_model_path=SP_MODEL)
return tokenizer
def make_prediction(input_data):
'''
Predict the translation
:param input_data: list inputs for prediction
:return: List of tuples ugh.
'''
# bail if this is an empty string
if len(input_data) < 1:
empty = {'input_text' : input_data, 'output_text': input_data }
return empty
tokenizer = __setup_tokenizer()
# get TensorFlow server connection parameters
server_name, server_port = __get_tf_server_connection_params__()
log.debug('Connecting to TensorFlow server %s:%s', server_name, server_port)
# open channel to tensorflow server
stub = __open_tf_server_channel__(server_name, server_port)
# create predict request
# input_data = [ 'Hello.', 'Hello world.' ]
request = __create_prediction_request__(tokenizer, input_data)
# make prediction
output_data = __make_prediction_and_prepare_results__(stub, tokenizer, request)
answer = []
i = ''
o = u''
for input_text, output_text in zip(input_data, output_data):
# print("{} ||| {}".format(input_text, output_text))
item = {"input_text": input_text, "output_text": output_text}
answer.append(item)
o += output_text + ' '
i += input_text + ' '
log.debug(answer)
answer2 = {'input_text' : i.rstrip(), 'output_text': o.rstrip()}
return answer2
<file_sep>/tfc_service/api/restplus.py
import logging
import traceback
from flask_restplus import Api
import settings
log = logging.getLogger(__name__)
# create Flask-RestPlus API
api = Api(
version='0.1',
title='SpeakEasy',
description='Client to TF Serving using gRPC'
)
# define default error handler
@api.errorhandler
def default_error_handler(error):
'''
Default error handler, if something unexpected occured
:param error: Contains specific error information
:return: Tuple of JSON object with error information and 500 status code
'''
message = 'Error: {}'.format(error.specific)
log.exception(message)
if not settings.DEFAULT_FLASK_DEBUG:
return {'message': message}, 500
<file_sep>/Makefile
all:
docker-compose build install
docker-compose up --force-recreate install
docker-compose build
docker-compose up -d
docker-compose ps
clean:
docker stop $$(docker ps -aq) || true
docker rm $$(docker ps -aq) || true
mrproper:
docker volume rm $$(docker volume ls -q | grep speakeasy)
devk:
@echo Killing all containers, images and volumes in this compose-file
docker-compose down --rmi all --volumes
@echo Killing any leftovers ... really killing them!!!
docker volume prune
docker rmi $$(docker images -q --filter "dangling=true")
devd:
@echo Stop and remove the container for ${foo}
docker-compose rm --force --stop ${foo}
devu:
@echo Build and Run in the forground the container for ${foo}
docker-compose build ${foo}
docker-compose up ${foo}
devi:
@echo Stop and remove the container for ${foo}
docker-compose rm --force --stop ${foo}
@echo Build and Run in the forground the container for ${foo}
docker-compose build ${foo}
docker-compose up ${foo}
<file_sep>/ui/app/__init__.py
from flask import Flask
def create_app():
server = Flask(__name__, instance_relative_config=True)
config(server)
register_extensions_main(server)
register_blueprints_main(server)
register_extensions_nifi(server)
register_blueprints_nifi(server)
seattle(server)
return server
def config(server):
server.config.from_pyfile('flask.cfg')
def register_extensions_main(server):
from app.extensions import db
from app.extensions import login
from app.extensions import migrate
db.init_app(server)
login.init_app(server)
login.login_view = 'main.login'
migrate.init_app(server, db)
def register_blueprints_main(server):
from app.main.webapp import server_bp
server.register_blueprint(server_bp)
def register_extensions_nifi(server):
from app.extensions import dbm, ende, kor, enko
from flask_uploads import configure_uploads
dbm.init_app(server)
configure_uploads(server, ende)
configure_uploads(server, kor)
configure_uploads(server, enko)
def register_blueprints_nifi(server):
from app.nifi.views import nifi_blueprint
server.register_blueprint(nifi_blueprint)
def seattle(server):
############################
#### custom error pages ####
############################
from flask import render_template
@server.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@server.errorhandler(403)
def page_not_found(e):
return render_template('403.html'), 403
@server.errorhandler(410)
def page_not_found(e):
return render_template('410.html'), 410
<file_sep>/ui/Dockerfile
FROM python:3.7-slim
# OS
RUN \
apt-get update \
&& apt-get install -y --no-install-recommends apt-utils
# Depends on volume (refer to ../docker-compose.yml) /models
LABEL \
description="UI UI"
# As ROOT
RUN \
groupadd flaskgroup \
&& useradd -m -g flaskgroup -s /bin/bash flask \
&& mkdir -p /var/ui \
&& chown -R flask:flaskgroup /var/ui \
&& pip install --upgrade pip
# Install the app as user
# see .dockerignore
USER flask
WORKDIR /var/ui
COPY . /var/ui
ENV PATH "$PATH:/home/flask/.local/bin"
RUN \
pip install --user --no-cache-dir -r requirements.txt \
&& flask db init \
&& flask db migrate -m "init" \
&& flask db upgrade
#ENTRYPOINT ["python"]
CMD ["python","-u","app.py"]
<file_sep>/Dockerfile
FROM ubuntu:xenial
RUN apt-get update
RUN apt-get install -y wget
VOLUME /var/speakeasy
ADD ./models/ ./models/
ADD ./install/ .
CMD ./quickstart.sh
<file_sep>/nifi_service/nifi-env.sh
#!/bin/sh
export JAVA_TOOL_OPTIONS=-Dfile.encoding=utf8
export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
<file_sep>/ui/utils.py
import os
def get_env_var_setting(env_var_name, default_value):
'''
Returns specified environment variable value. If it does not exist,
returns a default value
:param env_var_name: environment variable name
:param default_value: default value to be returned if a variable does not exist
:return: environment variable value
'''
try:
env_var_value = os.environ[env_var_name]
except:
env_var_value = default_value
return env_var_value
def get_flask_server_params():
'''
Returns connection parameters of the Flask application
:return: Tripple of server name, server port and debug settings
'''
server_name = get_env_var_setting('FLASK_SERVER_NAME', '0.0.0.0')
server_port = int(get_env_var_setting('FLASK_SERVER_PORT', '5000'))
flask_debug = get_env_var_setting('FLASK_DEBUG', '0')
flask_debug = True if flask_debug == '1' else False
return server_name, server_port, flask_debug
<file_sep>/ocr_service/requirements.txt
Click==7.0
Flask==1.0.2
flask-restplus==0.11.0
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.0
opencv-python==3.4.4.19
Pillow==5.3.0
Werkzeug==0.14.1
pytesseract==0.2.5
summa
PyPDF2
docxpy
| 5cc389daabd4ab21c88f847504fa52699e9b7644 | [
"YAML",
"HTML",
"Markdown",
"Makefile",
"Python",
"Text",
"Dockerfile",
"Shell"
]
| 42 | Dockerfile | premrume/speakeasy | cba45e2ea9069cdb5b7e82039e45d9d4d88bd284 | b1adcb255ef0eb1e31c624ee899db24fd09d7c08 |
refs/heads/master | <repo_name>abadalamenti1/COMPBIO<file_sep>/Functionality Test.R
### <NAME>
### May 6 2016
### CompBio group 1 Code Functionality
############################ Constants set up and Library Loading #######################################################################################
##Set directory
dir <- '/home/comp383-group1/PredixcanData/'
setwd(dir)
expName = 'GIH_p3'
k =10
alpha = 0.5
Q = 21
"%&%" = function(a,b) paste(a,b,sep="")
library(glmnet)
library(data.table)
############################ File Reading, and Formating ################################################################################################
##Load up the expression table
##IF YOU ARE RUNNING ON WINDOWS YOU MAY NEED TO CHANGE '/' to '\' for getting directory
expNametxt = 'expression Data/' %&% expName %&% '_expression.txt'
chrName = 'chr'%&% Q
chb = data.frame(fread(input = expNametxt))
##Fix the data
rownames(chb) <- chb$Normalization.REF
chb1 <- chb[-1,-1]
chb1 <-t(chb1)
##pull out the ids
ids <- data.frame( colnames(chb1) )
colnames(ids) <- c('x')
t.expdata = chb1
g = read.csv('output.csv')
g$id = gsub('\\+AF8-','_',g$id)
genecode = data.frame(g$chromosome,g$X.3,g$start,g$stop,g$ensembl,g$id)
rownames(genecode) <- genecode[,6]
genecode <- genecode[genecode[,1]==chrName,] ##pull genes on chr of interest
t.expdata <- t.expdata[,intersect(colnames(t.expdata),rownames(genecode))] ###pull gene expression data w/gene info
gencode = genecode
colnames(gencode) = c('V1','V2','V3','V4','V5','V6')
expsamplelist <- rownames(t.expdata) ###samples with exp data###
bvm <- data.frame(fread('hapmap3_r2_b36_fwd.consensus.qc.poly.bim'))
rownames(bvm) <- bvm$V2
bim <- bvm[bvm[,1]==Q,]
fvm <- data.frame(fread('hapmap3_r2_b36_fwd.consensus.qc.poly.fam',header = FALSE))
fam = fvm$V2
samplelist <- intersect(fam,expsamplelist)
###get expression of samples with genotypes###
exp.w.geno <- t.expdata[samplelist,]
explist <- colnames(exp.w.geno)
##Read in Chromosome Snp file
gtxfile = 'Chr' %&% Q %&% '.raw'
GT = data.frame(fread(gtxfile))
gtx = GT[,-(1:6)]
rownames(gtx) <- fam
X <- gtx[samplelist,]
######################################## Imputation, and file set up ####################################################################
##Impute the data with the mean of the col.
na.change <- function(COLX){
COLX[is.na(COLX)] <- mean(COLX,na.rm = TRUE)
COLX
}
X <- apply(X,2,na.change)
X<- data.frame(X)
TEST<-gsub(pattern = '.*_r',replacement = 'r',x = colnames(X),perl = TRUE)
TEST<-gsub(pattern = '_.*',replacement = '',x = TEST,perl = TRUE)
(head(TEST))
colnames(X) = TEST
##Set up files for writing
resultsarray <- array(0,c(length(explist),8))
dimnames(resultsarray)[[1]] <- explist
resultscol <- c("gene","alpha","cvm","lambda.iteration","lambda.min","n.snps","R2","pval")
dimnames(resultsarray)[[2]] <- resultscol
workingbest <- 'Results/working_' %&% expName %&% "_exp_" %&% 10 %&% "-foldCV_elasticNet_alpha" %&% 0.5 %&% "_" %&% 'hapmap' %&% chrName %&% ".txt"
write(resultscol,file=workingbest,ncolumns=8,sep="\t")
weightcol = c("gene","SNP","refAllele","effectAllele","beta")
workingweight <- 'Results/working_' %&% expName %&% "_elasticNet_alpha" %&% '0.5' %&% "_" %&% 'hapmap' %&% '_' %&% chrName %&% ".txt"
write(weightcol,file=workingweight,ncol=5,sep="\t")
################################################### Elastic Net ##########################################################################################
set.seed(312)
i = 27
for(i in 1:length(explist)){
cat(i,"/",length(explist),"\n")
gene <- explist[i]
geneinfo <- gencode[gene,]
chr <- geneinfo[1]
c <- substr(chr$V1,4,5)
start <- geneinfo$V3 - 1e6 ### 1Mb lower bound for cis-eQTLS
end <- geneinfo$V4 + 1e6 ### 1Mb upper bound for cis-eQTLs
chrsnps <- subset(bim,bim[,1]==c) ### pull snps on same chr
cissnps <- subset(chrsnps,chrsnps[,4]>=start & chrsnps[,4]<=end) ### pull cis-SNP info
cisgenos <- X[,intersect(colnames(X),cissnps[,2])] ### pull cis-SNP genotypes
if(is.null(dim(cisgenos))){
bestbetas <- data.frame() ###effectively skips genes with <2 cis-SNPs
}else{
minorsnps <- subset(Matrix::colMeans(cisgenos), Matrix::colMeans(cisgenos,na.rm=TRUE) > 0) ###pull snps with at least 1 minor allele###
minorsnps <- names(minorsnps)
cisgenos <- cisgenos[,minorsnps]
if(is.null(dim(cisgenos)) | dim(cisgenos)[2] == 0){###effectively skips genes with <2 cis-SNPs
bestbetas <- data.frame() ###effectively skips genes with <2 cis-SNPs
}else{
exppheno <- exp.w.geno[,gene] ### pull expression data for gene
exppheno <- scale(as.numeric(exppheno), center=T, scale=T) ###need to scale for fastLmPure to work properly
#exppheno <- scale(exppheno, center=T, scale=T) ###need to scale for fastLmPure to work properly
exppheno[is.na(exppheno)] <- 0
rownames(exppheno) <- rownames(exp.w.geno)
##run Cross-Validation over alphalist
fit <- cv.glmnet(as.matrix(cisgenos),as.matrix(exppheno),nfolds=k,alpha=alpha,keep=T,parallel=F) ##parallel=T is slower on tarbell, not sure why
fit.df <- data.frame(fit$cvm,fit$lambda,1:length(fit$cvm)) ##pull info to find best lambda
best.lam <- fit.df[which.min(fit.df[,1]),] # needs to be min or max depending on cv measure (MSE min, AUC max, ...)
cvm.best = best.lam[,1]
lambda.best = best.lam[,2]
nrow.best = best.lam[,3] ##position of best lambda in cv.glmnet output
ret <- as.data.frame(fit$glmnet.fit$beta[,nrow.best]) # get betas from best lambda
ret[ret == 0.0] <- NA
bestbetas = as.vector(ret[which(!is.na(ret)),]) # vector of non-zero betas
names(bestbetas) = rownames(ret)[which(!is.na(ret))]
pred.mat <- fit$fit.preval[,nrow.best] # pull out predictions at best lambda
}
}
if(length(bestbetas) > 0){
res <- summary(lm(exppheno~pred.mat))
genename <- as.character(gencode[gene,6])
rsq <- res$r.squared
pval <- res$coef[2,4]
resultsarray[gene,] <- c(genename, alpha, cvm.best, nrow.best, lambda.best, length(bestbetas), rsq, pval)
### output best shrunken betas for PrediXcan
bestbetalist <- names(bestbetas)
bestbetainfo <- bim[bestbetalist,]
betatable<-as.matrix(cbind(bestbetainfo,bestbetas))
betafile<-cbind(genename,betatable[,2],betatable[,5],betatable[,6],betatable[,7]) ##output "gene","SNP","refAllele","effectAllele","beta"
write(t(betafile),file=workingweight,ncolumns=5,append=T,sep="\t") # t() necessary for correct output from write() function
}else{
genename <- as.character(gencode[gene,6])
resultsarray[gene,1] <- genename
resultsarray[gene,2:8] <- c(NA,NA,NA,NA,0,NA,NA)
}
write(resultsarray[gene,],file=workingbest,ncolumns=8,append=T,sep="\t")
}
write.table(resultsarray,file= 'Results/' %&%expName %&% k %&% "-foldCV_elasticNet_alpha" %&% alpha %&% "_" %&% 'hapmap' %&% chrName %&% '.txt',quote=F,row.names=F,sep="\t")
<file_sep>/Plots/Interactive-Plots-from-Final-Presentation/CompBio Presentation-copy.Rmd
---
title: "Presentation COMPBIO Visualization"
author: "<NAME>"
date: "May 6, 2016"
output: ioslides_presentation
---
```{r setup, include=FALSE}
#2 Functions to extract our results, it takes in the results as they were printed by out elastic net code
modtable <- function(z){
tab <- read.table(z,stringsAsFactors=FALSE)
tab <- tab[-1,]
z1 = gsub('^.*?chr','',z)
chrNum = gsub('.txt','',z1)
tab <- cbind(tab,as.numeric(chrNum))
}
load_data <- function(expr) {
dir = '/home/shyam/Documents/CompBio/Results/'
setwd(dir)
files <- dir('/home/shyam/Documents/CompBio/Results/',pattern = expr)
tables <- lapply(files, modtable)
tables <- do.call(rbind, tables)
tables <- cbind(tables,expr)
colnames(tables) = c('gene','alpha', 'cvm', 'lambda.iteration', 'lambda.min', 'n.snps', 'R2', 'pval','ChromosomeNumber','Population')
tables
}
#List of populations
expList = c('CHB_p310-fold','GIH_p310-fold','JPT_p310-fold','LWK_p310-fold','MEX_p310-fold','MKK_p310-fold','YRI_p310-fold')
#Using function
k = lapply(expList, load_data)
k1 = do.call(rbind,k)
#Making r2 numeric
k1$R2 <- as.numeric(k1$R2)
library(dplyr)
library(plotly)
library(reshape2)
library(GGally)
#Wide Format
w <- dcast(k1,gene+ChromosomeNumber~Population,value.var = 'R2')
#Long Format
l <- k1
l$n.snps = as.numeric(l$n.snps)
##A experiment
# ind = which(l$R2 >= 0.1)
# Y <- l[ind,]
# YY <- dcast(Y,gene+ChromosomeNumber~Population,value.var = 'R2')
#
# v = w
# rownames(v) = v[,1]
# X <- v[YY$gene,]
#
# X1 = group_by(l,Population)
# X2 = summarise(X1,
# su = sum(n.snps)
# )
# X1 = group_by(l, gene)
# X3 = summarise(X1,
# su = sum(n.snps)
# )
# X1 = group_by(l, gene,Population)
# X4 = summarise(X1,
# su = sum(n.snps)
# )
#Replacing NA's with 0
w[is.na(w)] <- 0
Y1 = w
#Compute the R2 differences
Y1$CHBvJPT = Y1$`CHB_p310-fold` - Y1$`JPT_p310-fold`
Y1$CHBvGIH = Y1$`CHB_p310-fold` - Y1$`GIH_p310-fold`
Y1$CHBvJPT = Y1$`CHB_p310-fold` - Y1$`JPT_p310-fold`
Y1$CHBvLWK = Y1$`CHB_p310-fold` - Y1$`LWK_p310-fold`
Y1$CHBvMex = Y1$`CHB_p310-fold` - Y1$`MEX_p310-fold`
Y1$CHBvMKK = Y1$`CHB_p310-fold` - Y1$`MKK_p310-fold`
Y1$CHBvYRI = Y1$`CHB_p310-fold` - Y1$`YRI_p310-fold`
Y1$GIHvJPT = w$`GIH_p310-fold` - w$`JPT_p310-fold`
Y1$GIHvLWK = w$`GIH_p310-fold` - w$`LWK_p310-fold`
Y1$GIHvMex = w$`GIH_p310-fold` - w$`MEX_p310-fold`
Y1$GIHvMKK = w$`GIH_p310-fold` - w$`MKK_p310-fold`
Y1$GIHvYRI = w$`GIH_p310-fold` - w$`YRI_p310-fold`
Y1$JPTvLWK = w$`JPT_p310-fold` - w$`LWK_p310-fold`
Y1$JPTvMex = w$`JPT_p310-fold` - w$`MEX_p310-fold`
Y1$JPTvMKK = w$`JPT_p310-fold` - w$`MKK_p310-fold`
Y1$JPTvYRI = w$`JPT_p310-fold` - w$`YRI_p310-fold`
Y1$LWKvMex = w$`LWK_p310-fold` - w$`MEX_p310-fold`
Y1$LWKvMKK = w$`LWK_p310-fold` - w$`MKK_p310-fold`
Y1$LWKvYRI = w$`LWK_p310-fold` - w$`YRI_p310-fold`
Y1$MexvMKK = w$`MEX_p310-fold` - w$`MKK_p310-fold`
Y1$MexvYRI = w$`MEX_p310-fold` - w$`YRI_p310-fold`
Y1$MKKvYRI = w$`MKK_p310-fold` - w$`YRI_p310-fold`
##Pull out all genes which have atleast one Population with a greater than .5 R2
Z1 = filter(Y1,Y1$`CHB_p310-fold`>=.5|Y1$`GIH_p310-fold`>=.5|Y1$`JPT_p310-fold`>=.5|Y1$`LWK_p310-fold`>=.5|Y1$`MEX_p310-fold`>=.5|Y1$`MKK_p310-fold`>=.5|Y1$`YRI_p310-fold`>=.5)
#Quality Control
YX = Z1[,-3:-9]
YX = melt(YX, id = c('gene','ChromosomeNumber'))
x = YX[1,]
#Unefficently determining winning populations
YX$WIN <- 'tie'
dim(YX)
for (i in 1:dim(YX)[1]) {
if (!is.na(YX$value[i])){
if (YX$value[i] > 0){
YX$WIN[i] = gsub('v.*','',YX$variable[i])
}
if (YX$value[i] < 0){
YX$WIN[i] = gsub('.*v','',YX$variable[i])
}
}
}
#extracting R2-R2 that are significant
XZ = filter(YX,abs(value) > .2)
```
## Looking at the Population Expression Levels by Chromosome
```{r virginiasplot, echo = FALSE,warning=FALSE}
library(dplyr)
#Get 3 populations
l1 = filter(l,Population == 'CHB_p310-fold'| Population == 'GIH_p310-fold' | Population == 'JPT_p310-fold')
qplot(ChromosomeNumber,R2,data = l1,facets = .~Population ,color = ChromosomeNumber)
```
## Looking at the Population Expression Levels by Chromosome
```{r prevplotcont , echo = FALSE,warning=FALSE}
library(dplyr)
#Get 4 populations
l1 = filter(l,Population == 'LWK_p310-fold'| Population == 'MEX_p310-fold' | Population == 'MKK_p310-fold' | Population == 'YRI_p310-fold')
qplot(ChromosomeNumber,R2,data = l1,facets = .~Population ,color = ChromosomeNumber)
```
## Comparison of the filtered R-Sq values
```{r, echo = FALSE}
XZ = filter(YX,abs(value) > .2)
plot_ly(XZ, x = variable,y = value,
#y=ChromosomeNumber,type = "scatter3d",
mode = "markers", color = XZ$WIN ,marker = list(
size = 4), text = gene)
```
## Rsq specific plots
```{r individual Scatter Plots,include=FALSE}
library(ggplot2)
library(GGally)
trace1 <- plot_ly(w,
x = w$`CHB_p310-fold`,
y = w$`GIH_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace2 <- plot_ly(w,
x = w$`CHB_p310-fold`,
y = w$`JPT_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo= "text",
text = c('Gene: ',w$gene)
)
trace3 <- plot_ly(w,
x = w$`CHB_p310-fold`,
y = w$`LWK_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace4 <- plot_ly(w,
x = w$`CHB_p310-fold`,
y = w$`MEX_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace5 <- plot_ly(w,
x = w$`CHB_p310-fold`,
y = w$`MKK_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace6 <- plot_ly(w,
x = w$`CHB_p310-fold`,
y = w$`YRI_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace7 <- plot_ly(w,
x = w$`GIH_p310-fold`,
y = w$`JPT_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace8 <- plot_ly(w,
x = w$`GIH_p310-fold`,
y = w$`LWK_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace9 <- plot_ly(w,
x = w$`GIH_p310-fold`,
y = w$`MEX_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace10 <- plot_ly(w,
x = w$`GIH_p310-fold`,
y = w$`MKK_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace11 <- plot_ly(w,
x = w$`GIH_p310-fold`,
y = w$`YRI_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace12 <- plot_ly(w,
x = w$`JPT_p310-fold`,
y = w$`LWK_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace13 <- plot_ly(w,
x = w$`JPT_p310-fold`,
y = w$`MEX_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace14 <- plot_ly(w,
x = w$`JPT_p310-fold`,
y = w$`MKK_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace15 <- plot_ly(w,
x = w$`JPT_p310-fold`,
y = w$`YRI_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace16 <- plot_ly(w,
x = w$`LWK_p310-fold`,
y = w$`MEX_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace17 <- plot_ly(w,
x = w$`LWK_p310-fold`,
y = w$`MKK_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace18 <- plot_ly(w,
x = w$`LWK_p310-fold`,
y = w$`YRI_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace19 <- plot_ly(w,
x = w$`MEX_p310-fold`,
y = w$`MKK_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace20 <- plot_ly(w,
x = w$`MEX_p310-fold`,
y = w$`YRI_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
trace21 <- plot_ly(w,
x = w$`MKK_p310-fold`,
y = w$`YRI_p310-fold`,
marker = list(
color = "rgb(255,0,28)",
size = 10
),
mode = "markers",
type = "scatter",
hoverinfo = "text",
text = c('Gene: ',w$gene)
)
```
```{r ScatterMatrix,echo=FALSE,warning=FALSE}
ggscatmat(w,columns = 3:9)
```
##CHB vs. JPT
```{r,echo=FALSE}
trace2
```
##MEX vs. YRI
```{r,echo=FALSE}
trace20
```
##YRI vs. MKK
```{r,echo=FALSE}
trace12
```
<file_sep>/Full run code.R
##Edited by <NAME>, 2016
##########Setting up outer wrapper############################################################################################################################
dir <- '/home/comp383-group1/PredixcanData/'
setwd(dir)
expList = c('GIH_p3','JPT_p3','LWK_p3','MEX_p3','MKK_p3','YRI_p3')
#chr 9 excluded
chrNum = c(1:8,10:22)
outerBool = TRUE
innerBool = TRUE
save(list=c('expList','chrNum','outerBool','innerBool'),file="myobjects")
rm(list=ls())
load(file="myobjects")
#############Loop to run all code##############################################################################################################################
while (outerBool) {
while (innerBool) {
expName = expList[1]
k =10
alpha = 0.5
Q = chrNum[1]
"%&%" = function(a,b) paste(a,b,sep="")
library(glmnet)
library(data.table)
##Load up the expression table
##IF YOU ARE RUNNING ON WINDOWS YOU MAY NEED TO CHANGE '/' to '\' for getting directory
expNametxt = 'expression Data/' %&% expName %&% '_expression.txt'
chrName = 'chr'%&% Q
chb = data.frame(fread(input = expNametxt))
##Fix the data
rownames(chb) <- chb$Normalization.REF
chb1 <- chb[-1,-1]
chb1 <-t(chb1)
##pull out the ids
ids <- data.frame( colnames(chb1) )
colnames(ids) <- c('x')
t.expdata = chb1
g = read.csv('output.csv')
g$id = gsub('\\+AF8-','_',g$id)
genecode = data.frame(g$chromosome,g$X.3,g$start,g$stop,g$ensembl,g$id)
rownames(genecode) <- genecode[,6]
genecode <- genecode[genecode[,1]==chrName,] ##pull genes on chr of interest
t.expdata <- t.expdata[,intersect(colnames(t.expdata),rownames(genecode))] ###pull gene expression data w/gene info
gencode = genecode
colnames(gencode) = c('V1','V2','V3','V4','V5','V6')
expsamplelist <- rownames(t.expdata) ###samples with exp data###
bvm <- data.frame(fread('hapmap3_r2_b36_fwd.consensus.qc.poly.bim'))
rownames(bvm) <- bvm$V2
bim <- bvm[bvm[,1]==Q,]
fvm <- data.frame(fread('hapmap3_r2_b36_fwd.consensus.qc.poly.fam',header = FALSE))
fam = fvm$V2
samplelist <- intersect(fam,expsamplelist)
exp.w.geno <- t.expdata[samplelist,] ###get expression of samples with genotypes###
explist <- colnames(exp.w.geno)
gtxfile = 'Chromosomes/Chr' %&% Q %&% '.raw'
GT = data.frame(fread(gtxfile))
gtx = GT[,-(1:6)]
rownames(gtx) <- fam
X <- gtx[samplelist,]
na.change <- function(COLX){
COLX[is.na(COLX)] <- mean(COLX,na.rm = TRUE)
COLX
}
X <- apply(X,2,na.change)
X<- data.frame(X)
TEST<-gsub(pattern = '.*_r',replacement = 'r',x = colnames(X),perl = TRUE)
TEST<-gsub(pattern = '_.*',replacement = '',x = TEST,perl = TRUE)
(head(TEST))
colnames(X) = TEST
resultsarray <- array(0,c(length(explist),8))
dimnames(resultsarray)[[1]] <- explist
resultscol <- c("gene","alpha","cvm","lambda.iteration","lambda.min","n.snps","R2","pval")
dimnames(resultsarray)[[2]] <- resultscol
workingbest <- 'Results/working_' %&% expName %&% "_exp_" %&% 10 %&% "-foldCV_elasticNet_alpha" %&% 0.5 %&% "_" %&% 'hapmap' %&% chrName %&% ".txt"
write(resultscol,file=workingbest,ncolumns=8,sep="\t")
weightcol = c("gene","SNP","refAllele","effectAllele","beta")
workingweight <- 'Results/working_' %&% expName %&% "_elasticNet_alpha" %&% '0.5' %&% "_" %&% 'hapmap' %&% '_' %&% chrName %&% ".txt"
write(weightcol,file=workingweight,ncol=5,sep="\t")
set.seed(312)
i = 27
for(i in 1:length(explist)){
cat(i,"/",length(explist),"\n")
gene <- explist[i]
geneinfo <- gencode[gene,]
chr <- geneinfo[1]
c <- substr(chr$V1,4,5)
start <- geneinfo$V3 - 1e6 ### 1Mb lower bound for cis-eQTLS
end <- geneinfo$V4 + 1e6 ### 1Mb upper bound for cis-eQTLs
chrsnps <- subset(bim,bim[,1]==c) ### pull snps on same chr
cissnps <- subset(chrsnps,chrsnps[,4]>=start & chrsnps[,4]<=end) ### pull cis-SNP info
cisgenos <- X[,intersect(colnames(X),cissnps[,2])] ### pull cis-SNP genotypes
if(is.null(dim(cisgenos))){
bestbetas <- data.frame() ###effectively skips genes with <2 cis-SNPs
}else{
minorsnps <- subset(Matrix::colMeans(cisgenos), Matrix::colMeans(cisgenos,na.rm=TRUE) > 0) ###pull snps with at least 1 minor allele###
minorsnps <- names(minorsnps)
cisgenos <- cisgenos[,minorsnps]
if(is.null(dim(cisgenos)) | dim(cisgenos)[2] == 0){###effectively skips genes with <2 cis-SNPs
bestbetas <- data.frame() ###effectively skips genes with <2 cis-SNPs
}else{
exppheno <- exp.w.geno[,gene] ### pull expression data for gene
exppheno <- scale(as.numeric(exppheno), center=T, scale=T) ###need to scale for fastLmPure to work properly
#exppheno <- scale(exppheno, center=T, scale=T) ###need to scale for fastLmPure to work properly
exppheno[is.na(exppheno)] <- 0
rownames(exppheno) <- rownames(exp.w.geno)
##run Cross-Validation over alphalist
fit <- cv.glmnet(as.matrix(cisgenos),as.matrix(exppheno),nfolds=k,alpha=alpha,keep=T,parallel=F) ##parallel=T is slower on tarbell, not sure why
fit.df <- data.frame(fit$cvm,fit$lambda,1:length(fit$cvm)) ##pull info to find best lambda
best.lam <- fit.df[which.min(fit.df[,1]),] # needs to be min or max depending on cv measure (MSE min, AUC max, ...)
cvm.best = best.lam[,1]
lambda.best = best.lam[,2]
nrow.best = best.lam[,3] ##position of best lambda in cv.glmnet output
ret <- as.data.frame(fit$glmnet.fit$beta[,nrow.best]) # get betas from best lambda
ret[ret == 0.0] <- NA
bestbetas = as.vector(ret[which(!is.na(ret)),]) # vector of non-zero betas
names(bestbetas) = rownames(ret)[which(!is.na(ret))]
pred.mat <- fit$fit.preval[,nrow.best] # pull out predictions at best lambda
}
}
if(length(bestbetas) > 0){
res <- summary(lm(exppheno~pred.mat))
genename <- as.character(gencode[gene,6])
rsq <- res$r.squared
pval <- res$coef[2,4]
resultsarray[gene,] <- c(genename, alpha, cvm.best, nrow.best, lambda.best, length(bestbetas), rsq, pval)
### output best shrunken betas for PrediXcan
bestbetalist <- names(bestbetas)
bestbetainfo <- bim[bestbetalist,]
betatable<-as.matrix(cbind(bestbetainfo,bestbetas))
betafile<-cbind(genename,betatable[,2],betatable[,5],betatable[,6],betatable[,7]) ##output "gene","SNP","refAllele","effectAllele","beta"
write(t(betafile),file=workingweight,ncolumns=5,append=T,sep="\t") # t() necessary for correct output from write() function
}else{
genename <- as.character(gencode[gene,6])
resultsarray[gene,1] <- genename
resultsarray[gene,2:8] <- c(NA,NA,NA,NA,0,NA,NA)
}
write(resultsarray[gene,],file=workingbest,ncolumns=8,append=T,sep="\t")
}
##Saving information
write.table(resultsarray,file= 'Results/' %&%expName %&% k %&% "-foldCV_elasticNet_alpha" %&% alpha %&% "_" %&% 'hapmap' %&% chrName %&% '.txt',quote=F,row.names=F,sep="\t")
##Wiping global environ. to save memory
rm(list=ls())
##Loading initial vars, and moving to next chromosme
load(file="myobjects")
chrNum = chrNum[-1]
##when there are no chromosomes left, change indicator, and switch to outer loop
if (length(chrNum) == 0) {
innerBool = FALSE
}
save(list=c('expList','chrNum','outerBool','innerBool'),file="myobjects")
}
##Movement to next population
rm(list=ls())
load(file="myobjects")
chrNum = c(1:8,10:22)
expList = expList[-1]
innerBool = TRUE
if (length(expList) == 0) {
outerBool = FALSE
}
save(list=c('expList','chrNum','outerBool','innerBool'),file="myobjects")
load(file="myobjects")
}
<file_sep>/README.md
#Predicting Gene Regulation in Diverse Global Populations
######By <NAME>, <NAME>, <NAME>, <NAME>, and Dr. <NAME>
**Introduction**
Most studies focus on populations of European ancestry. While genomic research has broadened knowledge on human genetics, work is needed to expand this knowledge to more diverse groups, otherwise an entire breadth of useful information is missing.
**Objective**
We are working to expand genetic predictors of gene expression in additional world populations using SNP data alongside gene expression levels from the third phase of the International [*HapMap*](http://hapmap.ncbi.nlm.nih.gov/index.html.en) Project.
- Populations include East African, West African, East Asian, and Mexican ancestry.
- Elastic net modeling is used to select genotypes and weights to best predict expression of each gene using the [glmnet](https://cran.r-project.org/web/packages/glmnet/index.html) package for R.
**Methods**
A large portion of phenotypic variability in disease risk is due to regulatory variants which regulate gene expression levels. [*PrediXcan*](http://www.nature.com/ng/journal/v47/n9/full/ng.3367.html) is a gene-based association method, testing the mediating effects of gene expression levels by quantifying association between genetically regulated expression levels (GReX) and the phenotypic trait of interest. Gene expression can be decomposed into three basic components: what is genetically determined (GReX), what is altered by the phenotypic trait of interest, and remaining factors (including environment)
**Future Applications**
We hope to interpret results to answer:
- Are predictors similar among diverse populations, or unique?
- Can we better predict gene expression when samples from diverse populations are combined rather than modeled singly?
- When testing predicted expression for associated traits, are new genes implicated, or were the genes previously found in European cohorts?
The hope is to advance biological knowledge of the underlying mechanisms of disease risk not assessed in GWAS studies alone. PrediXcan provides direction of effect, which may yield opportunities for therapeutic development and drug targets.
###***Instructions***
To run our updated version of the PrediXcan pipeline for these diverse populations, you will need
Software Requirements:
- Linux or Mac OS
- R
- Specific R packages:
- glmnet
- data.table
- plotly
- dply
- ggplot2
- GGally
- RMarkdown
Plus all dependencies of aforementioned packages.
Input Files:
- Expression data matrix in the form of:
- Columns are the SNP Illumina IDs
- Each row is the illumina/gene id
- With our data we also had an extra row at the beginning
In our functionality/example code, we used the file:
*Expression Data/GIH_p3_expression.txt* (Please use this as a reference)
- Gene annotation file with the following columns:
```
id entrez ensembl ref chromosome start stop
```
In our code we used the file:
*output.csv* (Please use this as a reference)
- The .bvm and .fam files, please use the following files as guides:
*hapmap3_r2_b36_fwd.consensus.qc.poly.bim*
*hapmap3_r2_b36_fwd.consensus.qc.poly.fam*
- The SNP files in raw format, please use the following file as a guide:
*Chromosomes/Chr21.raw*
- Since the snp files we used were not properly annotated, we had to impute missing values which may not be necessary for fully fitted data.
- Remember to change the directory, with the dir variable at the top.
Example Run:
- You can do an example run using the Functionality Test.R code
- The files needed will be in the example run code file
Output Files & Analysis:
- We have included the full results of our code on our github, under the results folder
- The visualization code is done in rmarkdown, and is the rmd file in the Results/Graphs (HTML included)
- Some of the plots in our powerpoint/paper were done in the Plotly browser due to some glitches with R
| e28b75349e8c22517ea0da2b4f85fd6a8a6c5995 | [
"Markdown",
"R",
"RMarkdown"
]
| 4 | R | abadalamenti1/COMPBIO | 003fc86d14a819efa70cc869afd00599bd5aed9d | dd725827ba52e60020668dd1e3b431d122084a4f |
refs/heads/master | <repo_name>Ilya-Sorokin/My-project-wich-Entity-Framework-<file_sep>/Hotel/DB/Rooms.cs
namespace Hotel.DB
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class Rooms
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID_Room { get; set; }
[Key]
[Column(Order = 1)]
[StringLength(50)]
public string Room_Type { get; set; }
[Key]
[Column(Order = 2)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID_Client { get; set; }
[Key]
[Column(Order = 3, TypeName = "date")]
public DateTime Date_Arrive { get; set; }
[Key]
[Column(Order = 4, TypeName = "date")]
public DateTime Date_Departure { get; set; }
[Key]
[Column(Order = 5)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Cost_Per_Day { get; set; }
public virtual Clients Clients { get; set; }
public virtual Free_Rooms Free_Rooms { get; set; }
}
}
<file_sep>/Hotel/DB/HotelDB.cs
namespace Hotel.DB
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class HotelDB : DbContext
{
public HotelDB()
: base("name=HotelDB")
{
}
public virtual DbSet<Clients> Clients { get; set; }
public virtual DbSet<Contract_> Contract_ { get; set; }
public virtual DbSet<Free_Rooms> Free_Rooms { get; set; }
public virtual DbSet<Service_> Service_ { get; set; }
public virtual DbSet<Staff> Staff { get; set; }
public virtual DbSet<sysdiagrams> sysdiagrams { get; set; }
public virtual DbSet<Rooms> Rooms { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Clients>()
.HasMany(e => e.Contract_)
.WithRequired(e => e.Clients)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Clients>()
.HasMany(e => e.Rooms)
.WithRequired(e => e.Clients)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Clients>()
.HasMany(e => e.Service_)
.WithMany(e => e.Clients)
.Map(m => m.ToTable("Service_Clients").MapLeftKey("ID_Client").MapRightKey("ID_Service"));
modelBuilder.Entity<Free_Rooms>()
.HasMany(e => e.Rooms)
.WithRequired(e => e.Free_Rooms)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Service_>()
.HasMany(e => e.Staff)
.WithMany(e => e.Service_)
.Map(m => m.ToTable("Service_Staff").MapLeftKey("ID_Service").MapRightKey("ID_Staff"));
}
}
}
<file_sep>/Hotel/DB/Staff.cs
namespace Hotel.DB
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Staff")]
public partial class Staff
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Staff()
{
Service_ = new HashSet<Service_>();
}
[Key]
public int ID_Staff { get; set; }
[Required]
[StringLength(50)]
public string Full_Name { get; set; }
[Required]
[StringLength(50)]
public string Position { get; set; }
public int Salary { get; set; }
[Required]
[StringLength(50)]
public string Telephone { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Service_> Service_ { get; set; }
}
}
<file_sep>/Hotel/DB/Clients.cs
namespace Hotel.DB
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class Clients
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Clients()
{
Contract_ = new HashSet<Contract_>();
Rooms = new HashSet<Rooms>();
Service_ = new HashSet<Service_>();
}
[Key]
public int ID_Client { get; set; }
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string Surname { get; set; }
[Column(TypeName = "date")]
public DateTime? BirthDate { get; set; }
[StringLength(50)]
public string Telephone { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Contract_> Contract_ { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Rooms> Rooms { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Service_> Service_ { get; set; }
}
}
<file_sep>/Hotel/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Hotel.DB;
namespace Hotel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
HotelDB db = new HotelDB();
private void Added(string str, string id) => dataGridView2.Rows.Add($"Добавлено в таблицу {str} значение с ID = {id}");
private void Deleted(string str, string id) => dataGridView2.Rows.Add($"Удалено из таблицы {str} значение с ID = {id}");
private void Changed(string str, string id) => dataGridView2.Rows.Add($"Изменено в таблице {str} значение с ID = {id}");
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Clear();
var item = comboBox1.Text;
if (item == "Clients")
{
dataGridView1.Columns[0].HeaderText = "ID_Client";
dataGridView1.Columns[1].HeaderText = "FirstName";
dataGridView1.Columns[2].HeaderText = "Surname";
dataGridView1.Columns[3].HeaderText = "BirthDate";
dataGridView1.Columns[4].HeaderText = "Telephone";
dataGridView1.Columns[5].HeaderText = "";
var query = from x in db.Clients select x;
var l = query.ToList();
for (int i = 0; i < l.Count; i++)
dataGridView1.Rows.Add(l[i].ID_Client, l[i].FirstName, l[i].Surname, l[i].BirthDate, l[i].Telephone);
}
if (item == "Free_Rooms")
{
dataGridView1.Columns[0].HeaderText = "ID_Room";
dataGridView1.Columns[1].HeaderText = "Room_Type";
dataGridView1.Columns[2].HeaderText = "Cost";
dataGridView1.Columns[3].HeaderText = "";
dataGridView1.Columns[4].HeaderText = "";
dataGridView1.Columns[5].HeaderText = "";
var query = from x in db.Free_Rooms select x;
var l = query.ToList();
for (int i = 0; i < l.Count; i++)
dataGridView1.Rows.Add(l[i].ID_Room, l[i].Room_Type, l[i].Cost);
}
if (item == "Rooms")
{
dataGridView1.Columns[0].HeaderText = "ID_Room";
dataGridView1.Columns[1].HeaderText = "Room_Type";
dataGridView1.Columns[2].HeaderText = "ID_Client";
dataGridView1.Columns[3].HeaderText = "Date_Arrive";
dataGridView1.Columns[4].HeaderText = "Date_Departure";
dataGridView1.Columns[5].HeaderText = "Cost_Per_Day";
var query = from x in db.Rooms select x;
var l = query.ToList();
for (int i = 0; i < l.Count; i++)
dataGridView1.Rows.Add(l[i].ID_Room, l[i].Room_Type, l[i].ID_Client, l[i].Date_Arrive, l[i].Date_Departure, l[i].Cost_Per_Day);
}
if (item == "Staff")
{
dataGridView1.Columns[0].HeaderText = "ID_Staff";
dataGridView1.Columns[1].HeaderText = "Full_Name";
dataGridView1.Columns[2].HeaderText = "Position";
dataGridView1.Columns[3].HeaderText = "Salary";
dataGridView1.Columns[4].HeaderText = "Telephone";
dataGridView1.Columns[5].HeaderText = "";
var query = from x in db.Staff select x;
var l = query.ToList();
for (int i = 0; i < l.Count; i++)
dataGridView1.Rows.Add(l[i].ID_Staff, l[i].Full_Name, l[i].Position, l[i].Salary, l[i].Telephone);
}
if (item == "Service_")
{
dataGridView1.Columns[0].HeaderText = "ID_Service";
dataGridView1.Columns[1].HeaderText = "Name_of_service";
dataGridView1.Columns[2].HeaderText = "Cost";
dataGridView1.Columns[3].HeaderText = "";
dataGridView1.Columns[4].HeaderText = "";
dataGridView1.Columns[5].HeaderText = "";
var query = from x in db.Service_ select x;
var l = query.ToList();
for (int i = 0; i < l.Count; i++)
dataGridView1.Rows.Add(l[i].ID_Service, l[i].Name_of_service, l[i].Cost);
}
//service-clients & service-staff не отобразились в студии, хотя на серваке есть
if (item == "Contract_")
{
dataGridView1.Columns[0].HeaderText = "ID_Room";
dataGridView1.Columns[1].HeaderText = "Room_Type";
dataGridView1.Columns[2].HeaderText = "ID_Client";
dataGridView1.Columns[3].HeaderText = "Date_Arrive";
dataGridView1.Columns[4].HeaderText = "";
dataGridView1.Columns[5].HeaderText = "";
var query = from x in db.Contract_ select x;
var l = query.ToList();
for (int i = 0; i < l.Count; i++)
dataGridView1.Rows.Add(l[i].ID_Contract, l[i].ID_Client, l[i].Type_of_contact, l[i].Cost);
}
}
private void button2_Click(object sender, EventArgs e)
{
var item = comboBox1.Text;
if (item == "Clients")
{
var length = 5;
var query = from x in db.Clients select x;
var l = query.ToList();//список с выборки (текущий)
var l2 = new List<List<string>>();//список с таблицы (с чем сверять)
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
l2.Add(new List<string>());
for (int i = 0; i < l2.Count; i++)
for (int j = 0; j < length; j++)
l2[i].Add(dataGridView1[j, i].Value.ToString());//Заливка данных в список
for (int j = 0; j < l.Count; j++)
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
try
{
if (l2[i].Contains(l[j].ID_Client.ToString()) && l2[i].Contains(l[j].FirstName) && l2[i].Contains(l[j].Surname) && l2[i].Contains(l[j].BirthDate.ToString()) && l2[i].Contains(l[j].Telephone))//на добавление новых/удаление через фильтрацию списков
{
l2.Remove(l2[i]);//при равенстве взаимоуничтожение с откатом по индексу. Исключение обработано пустотой для продолжения итерации
l.Remove(l[j]);
i--;
}
if (l2[i].Contains(l[j].ID_Client.ToString()) && (!l2[i].Contains(l[j].FirstName) || !l2[i].Contains(l[j].Surname) || !l2[i].Contains(l[j].BirthDate.ToString()) ||
!l2[i].Contains(l[j].Telephone)))//на изменение имеющихся
{
l[j].FirstName = l2[i][1];//изменение и взаимоуничтожение
l[j].Surname = l2[i][2];
l[j].BirthDate = DateTime.Parse(l2[i][3]);
l[j].Telephone = l2[i][4];
Changed(item, l2[i][0]);//триггер на обновление
l2.Remove(l2[i]);
l.Remove(l[j]);
i--;
}
}
catch (ArgumentOutOfRangeException) { }
}
if (l2.Count > 0)//добавление новых, если есть
for (int i = 0; i < l2.Count; i++)
{
db.Clients.Add(new Clients { ID_Client = Convert.ToInt32(l2[i][0]), FirstName = l2[i][1], Surname = l2[i][2], BirthDate = DateTime.Parse(l2[i][3]), Telephone = l2[i][4] });
Added(item, l2[i][0]);//триггер на добавление
}
if (l.Count > 0)//удаление, если есть
for (int i = 0; i < l.Count; i++)
{
db.Clients.Remove(l[i]);
Deleted(item, l[i].ID_Client.ToString());//триггер на удаление
}
db.SaveChanges();//сохранение
}
if (item == "Free_Rooms")
{
var length = 3;
var query = from x in db.Free_Rooms select x;
var l = query.ToList();//список с выборки (текущий)
var l2 = new List<List<string>>();//список с таблицы (с чем сверять)
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
l2.Add(new List<string>());
for (int i = 0; i < l2.Count; i++)
for (int j = 0; j < length; j++)
l2[i].Add(dataGridView1[j, i].Value.ToString());//Заливка данных в список
for (int j = 0; j < l.Count; j++)
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
try
{
if (l2[i].Contains(l[j].ID_Room.ToString()) && l2[i].Contains(l[j].Room_Type) && l2[i].Contains(l[j].Cost.ToString()))//на добавление новых/удаление через фильтрацию списков
{
l2.Remove(l2[i]);//при равенстве взаимоуничтожение с откатом по индексу. Исключение обработано пустотой для продолжения итерации
l.Remove(l[j]);
i--;
}
if (l2[i].Contains(l[j].ID_Room.ToString()) && (!l2[i].Contains(l[j].Room_Type) || !l2[i].Contains(l[j].Cost.ToString())))//на изменение имеющихся
{
l[j].Room_Type = l2[i][1];//изменение и взаимоуничтожение
l[j].Cost = Convert.ToInt32(l2[i][2]);
Changed(item, l2[i][0]);//триггер на обновление
l2.Remove(l2[i]);
l.Remove(l[j]);
i--;
}
}
catch (ArgumentOutOfRangeException) { }
}
if (l2.Count > 0)//добавление новых, если есть
for (int i = 0; i < l2.Count; i++)
{
db.Free_Rooms.Add(new Free_Rooms { ID_Room = Convert.ToInt32(l2[i][0]), Room_Type = l2[i][1], Cost = Convert.ToInt32(l2[i][2]) });
Added(item, l2[i][0]);//триггер на добавление
}
if (l.Count > 0)//удаление, если есть
for (int i = 0; i < l.Count; i++)
{
db.Free_Rooms.Remove(l[i]);
Deleted(item, l[i].ID_Room.ToString());//триггер на удаление
}
db.SaveChanges();//сохранение
}
if (item == "Rooms")
{
var length = 6;
var query = from x in db.Rooms select x;
var l = query.ToList();//список с выборки (текущий)
var l2 = new List<List<string>>();//список с таблицы (с чем сверять)
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
l2.Add(new List<string>());
for (int i = 0; i < l2.Count; i++)
for (int j = 0; j < length; j++)
l2[i].Add(dataGridView1[j, i].Value.ToString());//Заливка данных в список
for (int j = 0; j < l.Count; j++)
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
try
{
if (l2[i].Contains(l[j].ID_Room.ToString()) && l2[i].Contains(l[j].Room_Type) && l2[i].Contains(l[j].ID_Client.ToString()) &&
l2[i].Contains(l[j].Date_Arrive.ToString()) && l2[i].Contains(l[j].Date_Departure.ToString()) && l2[i].Contains(l[j].Cost_Per_Day.ToString()))//на добавление новых/удаление через фильтрацию списков
{
l2.Remove(l2[i]);//при равенстве взаимоуничтожение с откатом по индексу. Исключение обработано пустотой для продолжения итерации
l.Remove(l[j]);
i--;
}
if (l2[i].Contains(l[j].ID_Room.ToString()) && l2[i].Contains(l[j].ID_Client.ToString()) && !l2[i].Contains(l[j].Room_Type) ||
!l2[i].Contains(l[j].Date_Arrive.ToString()) || !l2[i].Contains(l[j].Date_Departure.ToString()) || !l2[i].Contains(l[j].Cost_Per_Day.ToString()))//на изменение имеющихся
{//изменение и взаимоуничтожение
l[j].Room_Type = l2[i][1];
l[j].Date_Arrive = DateTime.Parse(l2[i][3]);
l[j].Date_Departure = DateTime.Parse(l2[i][4]);
l[j].Cost_Per_Day = Convert.ToInt32(l2[i][5]);
Changed(item, (l2[i][0] + " и " + l2[i][2]));//триггер на обновление
l2.Remove(l2[i]);
l.Remove(l[j]);
i--;
}
}
catch (ArgumentOutOfRangeException) { }
}
if (l2.Count > 0)//добавление новых, если есть
for (int i = 0; i < l2.Count; i++)
{
db.Rooms.Add(new Rooms { ID_Room = Convert.ToInt32(l2[i][0]), Room_Type = l2[i][1], ID_Client = Convert.ToInt32(l2[i][2]),
Date_Arrive = DateTime.Parse(l2[i][3]), Date_Departure = DateTime.Parse(l2[i][4]), Cost_Per_Day = Convert.ToInt32(l2[i][5]) });
Added(item, $"{l2[i][0]} и {l2[i][2]}");//триггер на добавление
}
if (l.Count > 0)//удаление, если есть
for (int i = 0; i < l.Count; i++)
{
db.Rooms.Remove(l[i]);
Deleted(item, $"{l[i].ID_Room} и {l[i].ID_Client}");//триггер на удаление
}
db.SaveChanges();//сохранение
//Примечание - надо было добавить datetime для комфорта и избежаний конфликта
}
if (item == "Staff")
{
var length = 5;
var query = from x in db.Staff select x;
var l = query.ToList();//список с выборки (текущий)
var l2 = new List<List<string>>();//список с таблицы (с чем сверять)
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
l2.Add(new List<string>());
for (int i = 0; i < l2.Count; i++)
for (int j = 0; j < length; j++)
l2[i].Add(dataGridView1[j, i].Value.ToString());//Заливка данных в список
for (int j = 0; j < l.Count; j++)
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
try
{
if (l2[i].Contains(l[j].ID_Staff.ToString()) && l2[i].Contains(l[j].Full_Name) && l2[i].Contains(l[j].Position) && l2[i].Contains(l[j].Salary.ToString()) && l2[i].Contains(l[j].Telephone))//на добавление новых/удаление через фильтрацию списков
{
l2.Remove(l2[i]);//при равенстве взаимоуничтожение с откатом по индексу. Исключение обработано пустотой для продолжения итерации
l.Remove(l[j]);
i--;
}
if (l2[i].Contains(l[j].ID_Staff.ToString()) && (!l2[i].Contains(l[j].Full_Name) || !l2[i].Contains(l[j].Position) || !l2[i].Contains(l[j].Salary.ToString()) ||
!l2[i].Contains(l[j].Telephone)))//на изменение имеющихся
{
l[j].Full_Name = l2[i][1];//изменение и взаимоуничтожение
l[j].Position = l2[i][2];
l[j].Salary = Convert.ToInt32(l2[i][3]);
l[j].Telephone = l2[i][4];
Changed(item, l2[i][0]);//триггер на обновление
l2.Remove(l2[i]);
l.Remove(l[j]);
i--;
}
}
catch (ArgumentOutOfRangeException) { }
}
if (l2.Count > 0)//добавление новых, если есть
for (int i = 0; i < l2.Count; i++)
{
db.Staff.Add(new Staff { ID_Staff = Convert.ToInt32(l2[i][0]), Full_Name = l2[i][1], Salary = Convert.ToInt32(l2[i][2]), Telephone = l2[i][3] });
Added(item, l2[i][0]);//триггер на добавление
}
if (l.Count > 0)//удаление, если есть
for (int i = 0; i < l.Count; i++)
{
db.Staff.Remove(l[i]);
Deleted(item, l[i].ID_Staff.ToString());//триггер на удаление
}
db.SaveChanges();//сохранение
}
if (item == "Service_")
{
var length = 3;
var query = from x in db.Service_ select x;
var l = query.ToList();//список с выборки (текущий)
var l2 = new List<List<string>>();//список с таблицы (с чем сверять)
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
l2.Add(new List<string>());
for (int i = 0; i < l2.Count; i++)
for (int j = 0; j < length; j++)
l2[i].Add(dataGridView1[j, i].Value.ToString());//Заливка данных в список
for (int j = 0; j < l.Count; j++)
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
try
{
if (l2[i].Contains(l[j].ID_Service.ToString()) && l2[i].Contains(l[j].Name_of_service) && l2[i].Contains(l[j].Cost.ToString()))//на добавление новых/удаление через фильтрацию списков
{
l2.Remove(l2[i]);//при равенстве взаимоуничтожение с откатом по индексу. Исключение обработано пустотой для продолжения итерации
l.Remove(l[j]);
i--;
}
if (l2[i].Contains(l[j].ID_Service.ToString()) && (!l2[i].Contains(l[j].Name_of_service) || !l2[i].Contains(l[j].Cost.ToString())))//на изменение имеющихся
{
l[j].Name_of_service = l2[i][1];//изменение и взаимоуничтожение
l[j].Cost = Convert.ToInt32(l2[i][2]);
Changed(item, l2[i][0]);//триггер на обновление
l2.Remove(l2[i]);
l.Remove(l[j]);
i--;
}
}
catch (ArgumentOutOfRangeException) { }
}
if (l2.Count > 0)//добавление новых, если есть
for (int i = 0; i < l2.Count; i++)
{
db.Service_.Add(new Service_ { ID_Service = Convert.ToInt32(l2[i][0]), Name_of_service = l2[i][2], Cost = Convert.ToInt32(l2[i][2]) });
Added(item, l2[i][0]);//триггер на добавление
}
if (l.Count > 0)//удаление, если есть
for (int i = 0; i < l.Count; i++)
{
db.Service_.Remove(l[i]);
Deleted(item, l[i].ID_Service.ToString());//триггер на удаление
}
db.SaveChanges();//сохранение
}
if (item == "Contract_")
{
var length = 4;
var query = from x in db.Contract_ select x;
var l = query.ToList();//список с выборки (текущий)
var l2 = new List<List<string>>();//список с таблицы (с чем сверять)
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
l2.Add(new List<string>());
for (int i = 0; i < l2.Count; i++)
for (int j = 0; j < length; j++)
l2[i].Add(dataGridView1[j, i].Value.ToString());//Заливка данных в список
for (int j = 0; j < l.Count; j++)
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
try
{
if (l2[i].Contains(l[j].ID_Contract.ToString()) && l2[i].Contains(l[j].ID_Contract.ToString()) && l2[i].Contains(l[j].Type_of_contact) && l2[i].Contains(l[j].Cost.ToString()))//на добавление новых/удаление через фильтрацию списков
{
l2.Remove(l2[i]);//при равенстве взаимоуничтожение с откатом по индексу. Исключение обработано пустотой для продолжения итерации
l.Remove(l[j]);
i--;
}
if (l2[i].Contains(l[j].ID_Contract.ToString()) && (!l2[i].Contains(l[j].ID_Contract.ToString()) || !l2[i].Contains(l[j].Type_of_contact) || !l2[i].Contains(l[j].Cost.ToString())))//на изменение имеющихся
{
l[j].ID_Client = Convert.ToInt32(l2[i][1]);//изменение и взаимоуничтожение
l[j].Type_of_contact = l2[i][2];
l[j].Cost = Convert.ToInt32(l2[i][3]);
Changed(item, l2[i][0]);//триггер на обновление
l2.Remove(l2[i]);
l.Remove(l[j]);
i--;
}
}
catch (ArgumentOutOfRangeException) { }
}
if (l2.Count > 0)//добавление новых, если есть
for (int i = 0; i < l2.Count; i++)
{
db.Contract_.Add(new Contract_ { ID_Contract = Convert.ToInt32(l2[i][0]), ID_Client = Convert.ToInt32(l2[i][2]), Type_of_contact = l2[i][3], Cost = Convert.ToInt32(l2[i][4]) });
Added(item, l2[i][0]);//триггер на добавление
}
if (l.Count > 0)//удаление, если есть
for (int i = 0; i < l.Count; i++)
{
db.Contract_.Remove(l[i]);
Deleted(item, l[i].ID_Contract.ToString());//триггер на удаление
}
db.SaveChanges();//сохранение
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>/Hotel/DB/Contract_.cs
namespace Hotel.DB
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class Contract_
{
[Key]
public int ID_Contract { get; set; }
public int ID_Client { get; set; }
[StringLength(50)]
public string Type_of_contact { get; set; }
public int? Cost { get; set; }
public virtual Clients Clients { get; set; }
}
}
| c5afe7d91f71f70d5d01082a5b16fa9f14b9dc83 | [
"C#"
]
| 6 | C# | Ilya-Sorokin/My-project-wich-Entity-Framework- | 682d4e33e2529eea09e3fae684e3920d93aa6e57 | fcba9ec600865813572099fbcbbe80c38bb9bc6c |
refs/heads/master | <file_sep>const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload');
require('dotenv').config();
const app = express();
const port = 4000
const MongoClient = require('mongodb').MongoClient;
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_USER_PASS}@cluster<EMAIL>.mongodb.net/creativeDB?retryWrites=true&w=majority`;
//middleware
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('services'));
app.use(fileUpload());
app.get('/', (req, res) => {
res.send('Creative-Agency-Heroku Server v2')
})
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
const orderList = client.db("creativeDB").collection("order");
const reviewList = client.db("creativeDB").collection("review");
const adminList = client.db("creativeDB").collection("admin");
const serviceList = client.db("creativeDB").collection("services");
//place order
app.post('/placeorder', (req, res) => {
const order = req.body;
orderList.insertOne(order)
.then(response => {
if (response.insertedCount > 0) {
res.status(200).send(response.insertedCount > 0)
}
})
})
//read orderList
app.get('/allorders', (req, res) => {
const user = req.query.email;
orderList.find({email:user})
.toArray((err,docs) => {
res.send(docs);
})
})
//admin service List
app.get('/allordersadmin', (req, res) => {
orderList.find({})
.toArray((err,docs) => {
res.send(docs);
})
})
//make admin
app.post('/addadmin', (req, res) => {
const admin = req.body;
adminList.insertOne(admin)
.then(response => {
if (response.insertedCount > 0) {
res.status(200).send(response.insertedCount > 0)
}
})
});
//is admin
app.post('/isAdmin', (req, res) => {
const email= req.body.email;
adminList.find({ adminemail: email})
.toArray((err,docs) => {
res.send(docs.length > 0);
})
})
//post service
app.post('/addservice', (req, res) => {
const info = req.body;
const icon = req.files.icon;
const service = {
...info,
icon:icon.name
}
serviceList.insertOne(service)
.then(response => {
console.log(response);
if (response.insertedCount > 0) {
res.status(200).send(true)
}
})
icon.mv(`${__dirname}/services/${icon.name}`)
});
//get service
app.get('/services', (req, res) => {
serviceList.find({})
.toArray((err,docs) => {
res.send(docs);
})
})
//post review
app.post('/submitreview', (req, res) => {
const review = req.body;
reviewList.insertOne(review)
.then(response => {
if (response.insertedCount > 0) {
res.status(200).send(response.insertedCount > 0)
}
})
})
//get review
app.get('/allreview', (req, res) => {
reviewList.find({})
.toArray((err,docs) => {
res.send(docs);
})
})
});
app.listen(process.env.PORT || port);<file_sep># Creative Agency Server
## NodeJs ExpressJs MongoDB
| 1f908d9103cfd4c14c7c28b6d4797f1afbe79f68 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | jobayer-h/creative-agency-server | 65ed8bb848d133a34cba5bce3ef8efd2fbf3d9bb | ae4f76afc63b061e22ee48535dd322e689d34de7 |
refs/heads/master | <repo_name>LorisGitHub/Steganography<file_sep>/README.md
# Steganographer
## Usage
Just run the main with the corrects arguments
```
positional arguments:
file
optional arguments:
-h, --help show this help message and exit
-w, --write programs run in writting mode
-f, --filename use filename as text
-t TEXT, --text TEXT specify your own text as an argument
```
## Structure
Two directories, the pypng library used to read and get info from the image and src containing the Steganographer class.<file_sep>/main.py
import argparse
from src.steganographer import *
def set_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("file")
parser.add_argument("-w", "--write", help="programs run in writting mode", action="store_true")
group = parser.add_mutually_exclusive_group()
group.add_argument("-f", "--filename", help="use filename as text", action="store_true")
group.add_argument("-t", "--text", help="specify your own text as an argument", type=str)
args = parser.parse_args()
myFile = args.file
text = ""
writeMode = False
if args.write:
writeMode = True
if args.filename:
text = myFile[2:myFile.find('.png')]
elif args.text:
text = args.text
else:
text = input("Enter your text: ")
steganographer = Steganographer(myFile, text)
if writeMode:
steganographer.write()
else:
steganographer.read()
if __name__ == "__main__":
set_arguments()
<file_sep>/src/steganographer.py
import pypng.code.png as png
import subprocess
import sys
class Steganographer:
def __init__(self, myFile, message):
'''Constructor method'''
self.file = myFile
self.message = message
self.loadPicture()
def loadPicture(self):
'''Load all data from the picture into the object'''
try:
f = open(self.file, 'rb')
r = png.Reader(file = f)
except IOError:
sys.exit('Image not accessible')
self.width, self.height, rows, self.info = r.read()
self.data = list(rows).copy()
f.close()
if (self.width*self.height*self.info["planes"])/8 < len(self.message)*8:
sys.exit('Message is too long for the selected picture')
def write(self):
'''Write the specified message into a copy of the file'''
messageAsBytes = str.encode(self.message)
messageCounter = 0
byteWritted = 0
newData = []
for row in range(self.height):
pixelRow = []
for col in range(self.width):
for i in range(self.info["planes"]):
if messageCounter < len(messageAsBytes):
pixel = bin(self.data[row][col*self.info["planes"]+i])[2:].zfill(8)
pixel = pixel[:-1]
pixel += (bin(messageAsBytes[writeCounterMessage])[2:].zfill(8))[byteWritted]
byteWritted += 1
if byteWritted > 7:
byteWritted = 0
messageCounter += 1
pixelRow.append(int(pixel, 2))
newData.append(tuple(pixelRow))
newName = self.file[:self.file.find('.png')] + "Copy" + self.file[self.file.find('.png'):]
f = open(newName, 'wb')
if 'palette' in self.info.keys():
w = png.Writer(width = self.width, height = self.height, greyscale = self.info["greyscale"], alpha = self.info["alpha"], bitdepth = self.info["bitdepth"], palette = self.info["palette"])
else:
w = png.Writer(width = self.width, height = self.height, greyscale = self.info["greyscale"], alpha = self.info["alpha"], bitdepth = self.info["bitdepth"])
w.write(f, newData)
f.close()
def read(self):
'''Read the specified file as bytes and '''
tmpBinary = ""
message = ""
for row in range(self.height):
for col in range(self.width):
for i in range(self.info["planes"]):
pixel = bin(self.data[row][col*self.info["planes"]+i])[2:].zfill(8)
tmpBinary += pixel[7]
if len(tmpBinary) > 7:
message += chr(int(tmpBinary, 2))
tmpBinary = ""
file = open("msg.txt", "w", encoding="utf-8")
file.write(message)
file.close()
strings = subprocess.Popen(['strings', 'msg.txt']) | d4450ce33247e0626740633400b968bd5801d704 | [
"Markdown",
"Python"
]
| 3 | Markdown | LorisGitHub/Steganography | 9021df3672e9e5767ee0ccba4adf0b6ec41b589f | 747f3bb628d2fd47e652bb8fbafd709417b7ff0f |
refs/heads/master | <file_sep># DriveLatencyTest
Simple Latency test for SSDs/HDDs.
Build with CMake and then run the executable with --help to see the options.
Can quickly figure out IOPS and Latency for the selected drive!
<file_sep>/*
This file is part of DriveLatencytest (DLT).
DLT is released via an MIT License.
Author(s): <NAME>
This is the implementation for config keeping things
*/
#include "Config.h"
std::string _CONFIG::toString() const
{
std::string retStr = "";
retStr += " Duration (Seconds) : " + std::to_string(Seconds) + "\n";
retStr += " Number Of Threads : " + std::to_string(ThreadCount) + "\n";
retStr += " IO Size (Bytes) : " + std::to_string(IOSizeInBytes) + "\n";
retStr += " Starting Offset (Bytes) : " + std::to_string(StartingOffsetInBytes) + "\n";
retStr += " Ending Offset (Bytes) : " + std::to_string(EndingOffsetInBytes) + "\n";
retStr += " Max IOs Per Second : " + std::to_string(MaxIOsPerSecond) + "\n";
retStr += " Workload Type : " + ::toString(WorkloadType) + "\n";
retStr += " Path : " + Path + "\n";
return retStr;
}
std::vector<CONFIG> _CONFIG::splitForThreads(const uint32_t numThreads) const
{
std::vector<CONFIG> configs;
CONFIG config = *this;
auto remaining = config.MaxIOsPerSecond % numThreads;
config.MaxIOsPerSecond = static_cast<uint64_t>(static_cast<double>(config.MaxIOsPerSecond) / numThreads);
for (uint32_t i = 0; i < numThreads; i++)
{
configs.push_back(config);
}
// first one will handle the leftover iops
configs[0].MaxIOsPerSecond += remaining;
return configs;
}
<file_sep>/*
This file is part of DriveLatencytest (DLT).
DLT is released via an MIT License.
Author(s): <NAME>
This is the implementation for stat keeping things
*/
#include <algorithm>
#include <cstring>
#include <string>
#include "Stats.h"
_WORKLOAD_RESULT::_WORKLOAD_RESULT(const std::list<_WORKLOAD_RESULT>& workloadResults) : _WORKLOAD_RESULT()
{
for (auto& result : workloadResults)
{
// min/max
maxLatencyMicroseconds = std::max(result.maxLatencyMicroseconds, maxLatencyMicroseconds);
minLatencyMicroseconds = std::min(result.minLatencyMicroseconds, minLatencyMicroseconds);
// things to divide later
averageLatencyMicroseconds += result.averageLatencyMicroseconds;
microsecondsDoingIo += result.microsecondsDoingIo;
expectedWorkloadMicroseconds += result.expectedWorkloadMicroseconds;
efficiencyPercentage += result.efficiencyPercentage;
//things just to add
numIosCompleted += result.numIosCompleted;
iops += result.iops;
totalBytesRead += result.totalBytesRead;
}
// divide to get average
averageLatencyMicroseconds /= workloadResults.size();
microsecondsDoingIo /= workloadResults.size();
expectedWorkloadMicroseconds /= workloadResults.size();
efficiencyPercentage /= workloadResults.size();
}
_WORKLOAD_RESULT::_WORKLOAD_RESULT()
{
memset(this, 0, sizeof(_WORKLOAD_RESULT));
this->minLatencyMicroseconds = -1; // preset high
}
std::string _WORKLOAD_RESULT::toString() const
{
std::string retStr = "";
retStr += " Max Latency (microseconds) : " + std::to_string(maxLatencyMicroseconds) + "\n";
retStr += " Min Latency (microseconds) : " + std::to_string(minLatencyMicroseconds) + "\n";
retStr += " Avg Latency (microseconds) : " + std::to_string(averageLatencyMicroseconds) + "\n";
retStr += " Number of Completed IOs : " + std::to_string(numIosCompleted) + "\n";
retStr += " Total Bytes Read : " + std::to_string(totalBytesRead) + "\n";
retStr += " IO Per Second (IOPS) : " + std::to_string(iops) + "\n";
retStr += " Microseconds Doing IO : " + std::to_string(microsecondsDoingIo) + "\n";
retStr += " Microseconds Expected For Workload : " + std::to_string(expectedWorkloadMicroseconds) + "\n";
retStr += " Workload Efficiency : " + std::to_string(efficiencyPercentage * 100) + "%\n";
return retStr;
}<file_sep>/*
This file is part of DriveLatencytest (DLT).
DLT is released via an MIT License.
Author(s): <NAME>
This is the header for assert-related functionality for when things go really wrong.
*/
#pragma once
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <string>
#ifndef NDEBUG
namespace details
{
//! Internal assert function, will assert if expressionValue calls for it.
void _assert(int expressionValue, const std::string& expression, const std::string& file, const std::string& function, const size_t lineNumber, const std::string &message);
}
#define ASSERT_NO_MSG(expression) \
details::_assert(expression, #expression, __FILE__, __func__, __LINE__, "")
#define ASSERT(expression, message) \
details::_assert(expression, #expression, __FILE__, __func__, __LINE__, message)
#else // ^NDEBUG not defined
#define ASSERT_NO_MSG(expression) expression
#define ASSERT(expression, message) expression
#endif // ^NDEBUG defined
<file_sep>/*
This file is part of DriveLatencytest (DLT).
DLT is released via an MIT License.
Author(s): <NAME>
This is the header for the workload
*/
#pragma once
#include <random>
#include "Config.h"
#include "Stats.h"
//! Workload class. Does the workload/test.
class Workload
{
public:
/*! Constructor that will take a config
*/
Workload(const CONFIG& config);
WORKLOAD_RESULT runWorkload();
private:
// Gets the offset for the next IO
uint64_t getNextByteOffset();
// Gets the size for the next IO
inline uint64_t getNextIoSize()
{
// will allow us to change this dynamically one day
return nextIoSize;
}
//! Private copy of the config
CONFIG config;
//! Things to maintain a current state
uint64_t nextByteOffset;
uint64_t nextIoSize;
//! Random number generation in case we need it
std::mt19937_64 randomNumberGenerator;
std::uniform_int_distribution<uint64_t> randomNumberDistribution;
// disable some things
Workload& operator=(const Workload&) = delete;
Workload(const Workload&) = delete;
Workload() = default;
};<file_sep>/*
This file is part of DriveLatencytest (DLT).
DLT is released via an MIT License.
Author(s): <NAME>
This is the implementation for the FDFile class
*/
#include <chrono>
#include <limits>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
#include "Assert.h"
#include "FDFile.h"
#ifdef DLT_OS_WINDOWS
// Windows
#include <io.h>
#define lseek64 _lseeki64
#define O_DIRECT 0
#define O_SYNC 0
typedef unsigned IO_SIZE_TYPE; // funny enough on Windows the numBytes for IO is an unsigned int. On POSIX it's a size_t.
// Aligned allocations
void* aligned_alloc(size_t alignment, size_t size)
{
return _aligned_malloc(size, alignment);
}
#define aligned_free _aligned_free
#else
// Not Windows
#include <unistd.h>
#define O_BINARY 0
typedef size_t IO_SIZE_TYPE;
// Aligned allocations
#define aligned_free free
#endif
#include <fcntl.h>
/*! Funny enough the offset is a signed int since you may want to seek backward
(in a file... not really in our case).
*/
typedef int64_t IO_OFFSET_TYPE;
const uint64_t MAX_IO_OFFSET = static_cast<uint64_t>(std::numeric_limits<IO_OFFSET_TYPE>::max());
#define MAX_IO_SIZE ((IO_SIZE_TYPE)-1)
FDFile::FDFile(const CONFIG& config)
{
lastIoInfo = { 0 };
handle = open(config.Path.c_str(), O_BINARY | O_RDWR | O_DIRECT | O_SYNC);
ASSERT(handle != -1, config.Path + " did not open!... errno was: " + std::to_string(errno) + ": " + strerror(errno));
// POSIX based systems tend to require aligned buffers for O_DIRECT.
buffer = aligned_alloc(config.IOSizeInBytes, config.IOSizeInBytes);
ASSERT(buffer != NULL, "Could not allocate " + std::to_string(config.IOSizeInBytes) + " bytes");
}
FDFile::~FDFile()
{
close(handle);
handle = -1;
aligned_free(buffer);
buffer = NULL;
}
bool FDFile::read(uint64_t offsetBytes, uint64_t numBytes)
{
ASSERT((uint64_t)MAX_IO_SIZE > numBytes, "IO was requested to be larger than max allowed. Too large: " + std::to_string(numBytes));
ASSERT(offsetBytes < MAX_IO_OFFSET, "The given byte offset was larger than the platform natively supports: " + std::to_string(offsetBytes));
ASSERT(lseek64(handle, offsetBytes, SEEK_SET) == offsetBytes, "Could not seek to offset: " + std::to_string(offsetBytes));
IO_SIZE_TYPE numBytesRead;
auto start = std::chrono::high_resolution_clock::now();
// START FAST PATH
numBytesRead = static_cast<IO_SIZE_TYPE>(::read(handle, buffer, static_cast<IO_SIZE_TYPE>(numBytes)));
// END FAST PATH
auto end = std::chrono::high_resolution_clock::now();
// Save last IO info
lastIoInfo.numBytes = numBytes;
lastIoInfo.offsetBytes = offsetBytes;
lastIoInfo.elapsedMicroseconds = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
return numBytesRead == numBytes;
}
<file_sep>/*
This file is part of DriveLatencytest (DLT).
DLT is released via an MIT License.
Author(s): <NAME>
This is the header for config keeping things
*/
#pragma once
#include "Assert.h"
#include <algorithm>
#include <cstdint>
#include <string>
#include <vector>
enum class WorkloadTypeEnum
{
Unknown,
Sequential,
Random
};
inline WorkloadTypeEnum toWorkloadTypeEnum(std::string s)
{
// convert string to upper case
std::for_each(s.begin(), s.end(), [](char& c) {
c = ::toupper(c);
});
if (s == "SEQUENTIAL")
{
return WorkloadTypeEnum::Sequential;
}
else if (s == "RANDOM")
{
return WorkloadTypeEnum::Random;
}
ASSERT(0, s + " is not a valid WorkloadTypeEnum");
return WorkloadTypeEnum::Unknown;
}
inline std::string toString(WorkloadTypeEnum w)
{
if (w == WorkloadTypeEnum::Unknown)
{
return "Unknown";
}
else if (w == WorkloadTypeEnum::Sequential)
{
return "Sequential";
}
else if (w == WorkloadTypeEnum::Random)
{
return "Random";
}
ASSERT(0, std::to_string((int)w) + " is not a valid workload type");
return "Unknown";
}
//! Contains info related to the workload configuration
typedef struct _CONFIG
{
uint32_t Seconds;
uint32_t ThreadCount;
uint64_t IOSizeInBytes;
uint64_t StartingOffsetInBytes;
uint64_t EndingOffsetInBytes;
uint64_t MaxIOsPerSecond;
WorkloadTypeEnum WorkloadType;
std::string Path;
std::string toString() const;
//! Splits this config into a vector of configs for the given number of threads.
std::vector<_CONFIG> splitForThreads(const uint32_t numThreads) const;
}CONFIG;<file_sep>/*
This file is part of DriveLatencytest (DLT).
DLT is released via an MIT License.
Author(s): <NAME>
This is the implementation for assert-related functionality for when things go really wrong.
*/
#ifndef NDEBUG
#include "Assert.h"
#include <stdlib.h>
#ifndef DLT_OS_WINDOWS
#include <libgen.h>
#else
// Give Windows an implementation for basename()
std::string basename(const std::string& path)
{
char dir[4096] = { 0 };
char ext[4096] = { 0 };
_splitpath_s(path.c_str(),
NULL, 0,
NULL, 0,
dir, sizeof(dir),
ext, sizeof(ext));
return std::string(dir) + ext;
}
#endif
namespace details
{
void _assert(int expressionValue, const std::string& expression, const std::string& file, const std::string& function, const size_t lineNumber, const std::string& message)
{
if (!expressionValue)
[[unlikely]]
{
std::string fileName = basename((char*)file.c_str());
std::cerr << "ASSERT: (" << fileName << ":" << function << ":" << lineNumber << "): " << "EXPR: " << expression << ". " << message << std::endl;
abort();
}
}
}
#endif // #ifndef NDEBUG<file_sep>/*
This file is part of DriveLatencytest (DLT).
DLT is released via an MIT License.
Author(s): <NAME>
This is the implementation for the workload
*/
#include "FDFile.h"
#include "Workload.h"
#include <algorithm>
#include <chrono>
#include <thread>
#define NOW std::chrono::high_resolution_clock::now()
Workload::Workload(const CONFIG& config)
{
this->config = config;
// setup random number generation
this->randomNumberGenerator = std::mt19937_64(std::random_device()());
this->randomNumberDistribution = std::uniform_int_distribution<uint64_t>(this->config.StartingOffsetInBytes, this->config.EndingOffsetInBytes - this->config.IOSizeInBytes);
}
WORKLOAD_RESULT Workload::runWorkload()
{
WORKLOAD_RESULT workloadResult;
workloadResult.expectedWorkloadMicroseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::seconds(config.Seconds)).count();
workloadResult.minLatencyMicroseconds = -1; // preset high
nextByteOffset = config.StartingOffsetInBytes;
nextIoSize = config.IOSizeInBytes;
FDFile drive(config);
auto end = NOW + std::chrono::seconds(config.Seconds);
uint64_t iosThisSecond = 0;
auto thisSecondStart = NOW;
auto thisSecondEnd = NOW + std::chrono::seconds(1);
while (NOW < end)
{
// loop-ty loop
ASSERT(drive.read(getNextByteOffset(), getNextIoSize()), "Failed to read");
auto& lastIoInfo = drive.getLastIoInfo();
workloadResult.maxLatencyMicroseconds = std::max(lastIoInfo.elapsedMicroseconds, workloadResult.maxLatencyMicroseconds);
workloadResult.minLatencyMicroseconds = std::min(lastIoInfo.elapsedMicroseconds, workloadResult.minLatencyMicroseconds);
workloadResult.microsecondsDoingIo += lastIoInfo.elapsedMicroseconds;
workloadResult.numIosCompleted += 1;
workloadResult.totalBytesRead += drive.getLastIoInfo().numBytes;
// start io per second handling ////
iosThisSecond += 1;
if (iosThisSecond >= config.MaxIOsPerSecond)
{
// will exit this loop when thisSecond is over
while (NOW < thisSecondEnd)
{
std::this_thread::sleep_until(thisSecondEnd);
}
}
// if we're onto the next second reset our markers
if (NOW > thisSecondEnd)
{
iosThisSecond = 0;
thisSecondStart = NOW;
thisSecondEnd = NOW + std::chrono::seconds(1);
}
// end io per second handling ////
}
workloadResult.efficiencyPercentage = std::min(static_cast<double>(100), static_cast<double>(workloadResult.microsecondsDoingIo) / workloadResult.expectedWorkloadMicroseconds);
workloadResult.iops = static_cast<uint64_t>(workloadResult.numIosCompleted / config.Seconds);
workloadResult.averageLatencyMicroseconds = static_cast<uint64_t>(static_cast<double>(workloadResult.microsecondsDoingIo) / workloadResult.numIosCompleted);
return workloadResult;
}
uint64_t Workload::getNextByteOffset()
{
auto ret = nextByteOffset;
if (config.WorkloadType == WorkloadTypeEnum::Sequential)
{
// handle if we wrap around
nextByteOffset += getNextIoSize();
if (nextByteOffset > config.EndingOffsetInBytes)
[[unlikely]]
{
nextByteOffset = config.StartingOffsetInBytes;
}
return ret;
}
else if (config.WorkloadType == WorkloadTypeEnum::Random)
{
// the number must be divisible by the io size. (technically it should be by the sector size but we don't know that).
return (randomNumberDistribution(randomNumberGenerator) / config.IOSizeInBytes) * config.IOSizeInBytes;
}
ASSERT(0, std::to_string((int)config.WorkloadType) + " is not a valid workload type");
return -1;
}
<file_sep>/*
This file is part of DriveLatencytest (DLT).
DLT is released via an MIT License.
Author(s): <NAME>
This is the main entry point for DLT.
*/
#include <thread>
#include <mutex>
#include "Assert.h"
#include "Config.h"
#include "FDFile.h"
#include "Workload.h"
#include "local/CLI11.hpp"
void printLicenseInfo()
{
std::cout << "License Information:" << std::endl << std::endl;
std::cout << R"(
CLI11 1.8 Copyright(c) 2017 - 2019 University of Cincinnati, developed by <NAME> under NSF AWARD 1414736. All rights reserved.
Redistribution and use in source and binary forms of CLI11, with or without
modification, are permitted provided that the following conditions are met :
1. Redistributions of source code must retain the above copyright notice, this
list of conditionsand the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditionsand the following disclaimer in the documentation
and /or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.)" << std::endl << std::endl;
std::cout << "DriveLatencyTest (DLT) is licensed via the MIT License" << std::endl;
std::cout << R"(
Copyright 2020 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.)" << std::endl << std::endl;
}
int main(int argc, char** argv) {
CLI::App app{ "Drive Latency Test (DLT) is a quick/dirty test to get an idea of drive latency in various conditions." };
constexpr uint16_t bitness = sizeof(void*) == 8 ? 64 : 86;
std::cout << R"(
___ _ _____
| \| ||_ _|
| |) | |__| |
|___/|____|_|
Drive Latency Test... Version 1.0.0 - )" << DLT_BUILD_TYPE << " x" << bitness << std::endl;
// flag arguments
bool license = false;
app.add_flag("--license", license, "If passed, present all license information.");
// string arguments
std::string path = "";
std::string workloadType = "SEQUENTIAL";
app.add_option("-w,--workload_type", workloadType, "The type of workload to do. Possible values: SEQUENTIAL");
app.add_option("-p,--path", path, "The path to the path we want to test with.");
// numeric arguments
uint32_t duration = 30;
uint64_t ioSize = 512;
uint64_t startingOffset = 0;
uint64_t endingOffset = 2097152; // 1 GB in 512 byte offsets
uint32_t numThreads = 1;
uint64_t maxIops = std::numeric_limits<uint64_t>::max();
app.add_option("-d,--duration", duration, "The duration for the test in seconds.");
app.add_option("-i,--io_size", ioSize, "Size of each IO in bytes.");
app.add_option("-s,--start_offset", startingOffset, "Starting offset in bytes.");
app.add_option("-e,--end_offset", endingOffset, "Ending offset in bytes.");
app.add_option("-t,--thread_count", numThreads, "Number of threads to run the workload.")->check(CLI::Range(static_cast<uint32_t>(1), std::numeric_limits<uint32_t>::max()));
app.add_option("-m,--max_iops", maxIops, "Limit the number of IOPs to this number.");
CLI11_PARSE(app, argc, argv);
if (license)
{
printLicenseInfo();
}
// technically you can give --license without a path, though i don't know how to natively allow that.
if (!path.size())
{
std::cerr << "No path was given. It is required to do a latency test." << std::endl;
exit(app.exit(CLI::RequiredError("--path/-p")));
}
CONFIG config
{
.Seconds = duration,
.ThreadCount = numThreads,
.IOSizeInBytes = ioSize,
.StartingOffsetInBytes = startingOffset,
.EndingOffsetInBytes = endingOffset,
.MaxIOsPerSecond = maxIops,
.WorkloadType = toWorkloadTypeEnum(workloadType),
.Path = path
};
std::cout << "Configuration:" << std::endl << config.toString() << std::endl;
std::list<std::thread> threads;
std::list<WORKLOAD_RESULT> workloadResults;
std::mutex mutex;
auto configs = config.splitForThreads(numThreads);
for (uint32_t i = 0; i < numThreads; i++)
{
auto& thisConfig = configs[i];
threads.push_back(std::thread([&thisConfig, &mutex, &workloadResults]() {
Workload w(thisConfig);
auto result = w.runWorkload();
mutex.lock();
workloadResults.push_back(result);
//std::cout << "Result:" << std::endl << result.toString() << std::endl;
mutex.unlock();
}));
}
for (auto& thread : threads)
{
thread.join();
}
std::cout << "Final Result:" << std::endl << WORKLOAD_RESULT(workloadResults).toString() << std::endl;
return EXIT_SUCCESS;
}<file_sep>/*
This file is part of DriveLatencytest (DLT).
DLT is released via an MIT License.
Author(s): <NAME>
This is the header for the FDFile class
*/
#pragma once
#include <list>
#include <string>
#include "Config.h"
#include "Stats.h"
//! File-descriptor based file class
class FDFile
{
public:
/*! Constructor that takes in the current config
*/
FDFile(const CONFIG &config);
//! Destructor. Will close the file.
~FDFile();
/*! Does a read for the given numBytes at the given offset. Returns true on success, false on failure.
Will place read data in the buffer on success
*/
bool read(uint64_t offsetBytes, uint64_t numBytes);
//! gets the previous IO information
const inline IO_INFO& getLastIoInfo() const
{
return lastIoInfo;
}
//! The buffer we read into. Should be sufficiently large enough for any IO
void* buffer;
private:
//! the handle to the drive
int handle;
//! info on the previous IO
IO_INFO lastIoInfo;
// disable some things
FDFile& operator=(const FDFile&) = delete;
FDFile(const FDFile&) = delete;
FDFile() = default;
};<file_sep>/*
This file is part of DriveLatencytest (DLT).
DLT is released via an MIT License.
Author(s): <NAME>
This is the header for stat keeping things
*/
#pragma once
#include <cstdint>
#include <list>
//! Contains info related to a single IO
typedef struct _IO_INFO
{
uint64_t offsetBytes;
uint64_t numBytes;
uint64_t elapsedMicroseconds;
}IO_INFO;
//! Contains results for a workload
typedef struct _WORKLOAD_RESULT
{
//! Special constructor to make a new workload result from some others.
_WORKLOAD_RESULT(const std::list<_WORKLOAD_RESULT>& workloadResults);
//! Default constructor inits all to 0
_WORKLOAD_RESULT();
uint64_t maxLatencyMicroseconds;
uint64_t minLatencyMicroseconds;
uint64_t averageLatencyMicroseconds;
uint64_t numIosCompleted;
uint64_t totalBytesRead;
uint64_t iops;
uint64_t microsecondsDoingIo;
uint64_t expectedWorkloadMicroseconds;
double efficiencyPercentage;
std::string toString() const;
}WORKLOAD_RESULT;
<file_sep># CMakeList.txt : CMake project for DriveLatencyTest, include source and define
# project specific logic here.
#
cmake_minimum_required (VERSION 3.8)
project ("DriveLatencyTest")
# Add source to this project's executable.
file(GLOB DST_SOURCES "*.cpp")
add_executable (DriveLatencyTest ${DST_SOURCES})
# Add Threads (pthread on Linux)
find_package(Threads)
target_link_libraries(DriveLatencyTest ${CMAKE_THREAD_LIBS_INIT})
# Enable latest C++ Standard
set_property(TARGET DriveLatencyTest PROPERTY CXX_STANDARD 20)
# Constants
set(EXTERNAL_INCLUDE_FOLDER "${CMAKE_CURRENT_SOURCE_DIR}/local/")
set(CLI11_PATH "${EXTERNAL_INCLUDE_FOLDER}/CLI11.hpp")
# External Downloads
if (NOT EXISTS CLI11_PATH)
file(DOWNLOAD "https://github.com/CLIUtils/CLI11/releases/download/v1.9.0/CLI11.hpp" ${CLI11_PATH})
endif()
# Preprocessor defines
# Full OS name
add_compile_definitions(DLT_OPERATING_SYSTEM="${CMAKE_SYSTEM_NAME}")
# DLT_OS_WINDOWS/LINUX
string(TOUPPER DLT_OS_${CMAKE_SYSTEM_NAME} DLT_OS_NAME)
add_compile_definitions(${DLT_OS_NAME})
# For VC++ disable Windows-specific deprecations/warnings
add_compile_definitions("_CRT_SECURE_NO_WARNINGS")
add_compile_definitions("_CRT_NONSTDC_NO_DEPRECATE")
# Add Build Type
add_compile_definitions(DLT_BUILD_TYPE="${CMAKE_BUILD_TYPE}")
| 57150ab67066945c7163c56eb445718b647083ef | [
"Markdown",
"CMake",
"C++"
]
| 13 | Markdown | csm10495/DriveLatencyTest | bac783d8d40a075fedb9010e50d2854f2a43a45b | d3c6b3c3b64f2c0bc881306a4bfbc08d94ff4695 |
refs/heads/master | <repo_name>drosseas/ProgrammingAssignment2<file_sep>/cachematrix.R
## Functions that cache the inverse of a matrix
## Create a matrix object that can cache its inverse
makeCacheMatrix <- function( m = matrix() ) {
## Initialize
i <- NULL
## Set the matrix
set <- function( matrix ) {
m <<- matrix
i <<- NULL
}
## Get a matrix
get <- function() {m}
## Set the inverse of the matrix
setInverse <- function(inverse) {
i <<- inverse
}
## Method to get the inverse of the matrix
getInverse <- function() {i}
## Return a list of the methods
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
}
## Compute the inverse of the matrix from "makeCacheMatrix" above.
##If the inverse has already been calculated & is unchanged, this function
##should retrieve the cached inverse.
cacheSolve <- function(x, ...) {
## Return the inverse matrix of x
m <- x$getInverse()
## REturn the cached inverse
if( !is.null(m) ) {
message("getting cached data")
return(m)
}
## Retrieve the matrix from our object
data <- x$get()
## Calculate the inverse
m <- solve(data) %*% data
## Set the inverse to m
x$setInverse(m)
## Return the inverse matrix
m
}
| 6f4d168ca6159aa466f36e21452d3022195128bf | [
"R"
]
| 1 | R | drosseas/ProgrammingAssignment2 | a96391f8bcf972c3f45742154530842afe010963 | 459bf614123d330788afde2683de4dfecaab08e9 |
refs/heads/master | <repo_name>sebastianbertoli/cs231n<file_sep>/README.md
# CS231n Convolutional Neural Network for Image Understanding
Course website: [http://cs231n.github.io/](http://cs231n.github.io/)
WIP These are my solutions
## Requirements
- Tested on OS X 10.12
- Processor: Intel i3 or better.
- Memory: At least 4 GB of available RAM.
- Disk space: At least 10 GB of available disk space.
## Setup
## Acknowledgments
- The authors of CS231n that have developed this amazing course and made it available to everyone.
- [<NAME>](https://github.com/kratzert) for this incredibly helpful
[blogpost](https://kratzert.github.io/2016/02/12/understanding-the-gradient-flow-through-the-batch-normalization-layer.html)
on the backpropagation step for the batch normalisation layer.
- TODO: add others.
## Author
**<NAME>**
<file_sep>/assignment1/cs231n/classifiers/linear_svm.py
import numpy as np
from random import shuffle
from copy import deepcopy
def svm_loss_naive(W, X, y, reg):
"""
Structured SVM loss function, naive implementation (with loops).
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
dW = np.zeros(W.shape) # initialize the gradient as zero
# compute the loss and the gradient
num_classes = W.shape[1]
num_train = X.shape[0]
loss = 0.0
for i in range(num_train): # Loop through training examples
scores = X[i].dot(W) # The class score is a dot product between X and W
correct_class_score = scores[y[i]] # Score assigned to the correct class
for j in range(
num_classes): # Compute hinge loss by looping though classes
if j == y[i]: # no need to compute loss for correct class
continue
margin = scores[j] - correct_class_score + 1 # note delta = 1
if margin > 0: # we only add to the loss if margin exceed 0
loss += margin
dW[:, j] += X[i]
dW[:, y[i]] -= X[i]
# Right now the loss is a sum over all training examples, but we want it
# to be an average instead so we divide by num_train.
loss /= num_train
dW /= num_train
# Add regularization to the loss.
loss += 0.5 * reg * np.sum(W * W)
dW += reg * W
return loss, dW
def svm_loss_vectorized(W, X, targets, reg):
"""
Structured SVM loss function, vectorized implementation.
Inputs and outputs are the same as svm_loss_naive.
"""
# Initialise
delta = 1
total_loss = 0.0
dW = np.zeros(W.shape) # initialize the gradient as zero
N = X.shape[0]
# Compute scores, margins and loss
score_mat = X.dot(W)
correct_class_scores = score_mat[range(N), targets].reshape(N, 1)
margins = score_mat - correct_class_scores + delta
margins[range(N), targets] = 0
margins = np.clip(margins, 0, None)
data_loss = np.mean(np.sum(margins, axis=1))
regularization_loss = 0.5 * reg * np.sum(W * W)
total_loss = data_loss + regularization_loss
# Compute dL/dW
mask = deepcopy(margins)
mask[mask > 0] = 1
row_sum = np.sum(mask, axis=1)
mask[range(N), targets] -= row_sum.T
dW = np.dot(X.T, mask) / N
dW += reg * W
return total_loss, dW
| bb207dbbd122c195fd4369ad958de8df22ec4c73 | [
"Markdown",
"Python"
]
| 2 | Markdown | sebastianbertoli/cs231n | 54c71ff2b71adb97cca7df118d931d555afcf314 | f9e5e5f3578d1ceb7a400a4f78ea82b3cb737455 |
refs/heads/master | <repo_name>Thiago250801/ProjetosEmPyhton<file_sep>/contas/migrations/0005_remove_pedido_tags_produto_tags.py
# Generated by Django 4.0 on 2021-12-23 16:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contas', '0004_tag_pedido_tags'),
]
operations = [
migrations.RemoveField(
model_name='pedido',
name='tags',
),
migrations.AddField(
model_name='produto',
name='tags',
field=models.ManyToManyField(to='contas.Tag'),
),
]
<file_sep>/contas/views.py
from django.shortcuts import render, redirect
from .forms import PedidoForm,ClienteForm
# Create your views here.
from .models import *
from .filters import PedidoFilter
def home(request):
pedido = Pedido.objects.all()
clientes = Cliente.objects.all()
total_clientes = clientes.count()
total_pedidos = pedido.count()
entregue = pedido.filter(status ='Entregue').count()
pendente = pedido.filter(status = 'Pendente').count()
context = {'pedido':pedido,'clientes':clientes,
'total_pedidos':total_pedidos,'entregue':entregue,
'pendente':pendente}
return render(request, 'contas/dashboard.html', context)
def produtos(request):
produtos = Produto.objects.all()
return render(request, 'contas/produtos.html', {'produtos':produtos})
def cliente(request, pk_test):
cliente = Cliente.objects.get(id=pk_test)
pedido = cliente.pedido_set.all()
pedido_count = pedido.count()
meuFilter = PedidoFilter(request.GET, queryset=pedido)
pedido = meuFilter.qs
context = {'cliente':cliente, 'pedido':pedido, 'pedido_count':pedido_count, 'meuFilter':meuFilter}
return render(request, 'contas/cliente.html', context)
def gerarPedido(request):
form = PedidoForm()
if request.method == 'POST':
form = PedidoForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {'form':form}
return render(request, 'contas/pedido_form.html', context)
def cadastrarCliente(request):
form = ClienteForm()
if request.method == 'POST':
form = ClienteForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {'form': form}
return render(request, 'contas/cadastrar_form.html', context)
def atualizarPedido(request, pk):
pedido = Pedido.objects.get(id=pk)
form = PedidoForm(instance = pedido)
if request.method == 'POST':
form = PedidoForm(request.POST, instance = pedido)
if form.is_valid():
form.save()
return redirect('/')
context = {'form':form}
return render(request, 'contas/pedido_form.html', context)
def removerPedido(request, pk):
pedido = Pedido.objects.get(id=pk)
if request.method == "POST":
pedido.delete()
return redirect('/')
context = {'item':pedido}
return render(request, 'contas/remover.html', context)<file_sep>/contas/admin.py
from django.contrib import admin
# Register your models here.
from .models import *
admin.site.register(Cliente)
admin.site.register(Produto)
admin.site.register(Tag)
admin.site.register(Pedido)
<file_sep>/contas/querryDemos.py
clientes = Cliente.objects.all()
primeiroCliente = CLiente.objects.first()
ultimoCLiente = Cliente.objects.last()
clientePorNome = Cliente.objects.get(name='Paulo')
clientePorId = Cliente.objects.get(id=4)
primeiroCliente.pedido_set.all()
pedido = Pedido.objects.first()
parentNome = pedido.cliente.nome
produtos = Produto.objects.filter(category="Out Door")
leastToGreatest = Produto.objects.all().order_by('id')
greatestToLeast = Produto.objects.all().order_by('-id')
produtosFiltered = Produto.objects.filter(tags__name="Sports")
ballOrders = primeiroCliente.order_set.filter(produto__nome="Ball").count()
allPedidos = {}
for pedido in primeiroCliente.pedido_set.all():
if pedido.product.name in allPedidos:
allPedidos[pedido.produto.nome] += 1
else:
allPedidos[pedido.produto.nome] = 1
class ParentModel(models.Model):
nome = models.CharField(max_length=200, null=True)
class ChildModel(models.Model):
parent = models.ForeignKey(Cliente)
nome = models.CharField(max_length=200, null=True)
parent = ParentModel.objects.first()
parent.childmodel_set.all()
<file_sep>/contas/forms.py
from django.forms import ModelForm
from .models import Pedido,Cliente
class PedidoForm(ModelForm):
class Meta:
model = Pedido
fields = '__all__'
class ClienteForm(ModelForm):
class Meta:
model = Cliente
fields = '__all__'
<file_sep>/contas/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name = "home"),
path('produtos/', views.produtos, name = "produtos"),
path('cliente/<str:pk_test>/', views.cliente, name= "cliente"),
path('gerar_pedido/', views.gerarPedido, name= "gerar_pedido"),
path('cadastrar_cliente/', views.cadastrarCliente, name= "cadastrar_cliente"),
path('atualizar_pedido/<str:pk>/', views.atualizarPedido, name= "atualizar_pedido"),
path('remover_pedido/<str:pk>/', views.removerPedido, name="remover_pedido"),
]
<file_sep>/contas/migrations/0002_pedido_produto.py
# Generated by Django 4.0 on 2021-12-23 16:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contas', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Pedido',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('data_publicacao', models.DateTimeField(auto_now_add=True, null=True)),
('status', models.CharField(choices=[('Pendente', 'Pendente'), ('Saiu pra entrega', 'Saiu pra entrega'), ('Entregue', 'Entregue')], max_length=200, null=True)),
],
),
migrations.CreateModel(
name='Produto',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(max_length=200, null=True)),
('preco', models.FloatField(null=True)),
('categoria', models.CharField(choices=[('Indoor', 'Indoor'), ('Outdoor', 'Outdoor')], max_length=200, null=True)),
('descricao', models.CharField(max_length=200, null=True)),
('data_publicacao', models.DateTimeField(auto_now_add=True, null=True)),
],
),
]
<file_sep>/README.md
# DjangoProject
Projeto pra gerenciamento de inventários.
<file_sep>/contas/migrations/0003_pedido_cliente_pedido_produto.py
# Generated by Django 4.0 on 2021-12-23 16:20
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contas', '0002_pedido_produto'),
]
operations = [
migrations.AddField(
model_name='pedido',
name='cliente',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='contas.cliente'),
),
migrations.AddField(
model_name='pedido',
name='produto',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='contas.produto'),
),
]
<file_sep>/contas/models.py
from django.db import models
# Create your models here.
class Cliente(models.Model):
nome = models.CharField(max_length=200, null=True)
telefone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
data_pubicacao = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.nome
class Tag(models.Model):
nome = models.CharField(max_length=200, null=True)
def __str__(self):
return self.nome
class Produto(models.Model):
CATEGORIA = (
('Indoor','Indoor'),
('Outdoor','Outdoor')
)
nome = models.CharField(max_length=200, null=True)
preco = models.FloatField(null=True)
categoria = models.CharField(max_length=200, null=True, choices=CATEGORIA)
descricao = models.CharField(max_length=200, null=True, blank=True)
data_publicacao = models.DateTimeField(auto_now_add=True, null=True)
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.nome
class Pedido(models.Model):
STATUS = (
('Pendente','Pendente'),
('Saiu pra entrega','Saiu pra entrega'),
('Entregue','Entregue'),
)
cliente = models.ForeignKey(Cliente, null=True, on_delete=models.SET_NULL)
produto = models.ForeignKey(Produto, null=True, on_delete=models.SET_NULL)
data_publicacao = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, choices=STATUS)
def __str__(self):
return self.produto.nome
<file_sep>/contas/migrations/0007_pedido_nome.py
# Generated by Django 4.0 on 2021-12-29 22:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contas', '0006_alter_produto_descricao'),
]
operations = [
migrations.AddField(
model_name='pedido',
name='nome',
field=models.CharField(max_length=200, null=True),
),
]
<file_sep>/contas/migrations/0004_tag_pedido_tags.py
# Generated by Django 4.0 on 2021-12-23 16:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contas', '0003_pedido_cliente_pedido_produto'),
]
operations = [
migrations.CreateModel(
name='Tag',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(max_length=200, null=True)),
],
),
migrations.AddField(
model_name='pedido',
name='tags',
field=models.ManyToManyField(to='contas.Tag'),
),
]
| d6ed64798c87e5e8bfa41874fe59fd9656691c50 | [
"Markdown",
"Python"
]
| 12 | Python | Thiago250801/ProjetosEmPyhton | aec2bcd8a4be6a0720fc6e6c35980ca3eeb1e39f | b7ffe35303560b0f7a7d0559f3f9ba371c188251 |
refs/heads/master | <file_sep>package com.hblg.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableEurekaClient//Eureka客户端
@EnableFeignClients(basePackages = {"com.hblg.springcloud"})
//@ComponentScan("com.hblg.springcloud")
public class DeptConsumer80_Feign_App {
/***
* Feign通过接口的方法调用Rest服务 之前是Ribbon+RestTemplate
* 该请求发送给Eureka服务器
* 通过Feign直接找到服务接口 由于在进行服务调用的时候融合了Ribbon技术 所以也支持负载均衡作用
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(DeptConsumer80_Feign_App.class, args);
}
}<file_sep>package com.hblg.springcloud.service;
import com.hblg.entity.Dept;
import com.hblg.springcloud.dao.DeptDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author i
* @create 2020/2/18 15:49
* @Description
*/
@Service
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptDao deptDao;
@Override
public boolean add(Dept dept) {
return deptDao.addDept(dept);
}
@Override
public Dept get(long id) {
return deptDao.findById(id);
}
@Override
public List<Dept> list() {
return deptDao.findAll();
}
}
<file_sep># SpringCloud
## SpringCloud学习笔记
## 1.微服务概述
### 1.是什么
> 但通常而言, 微服务架构是一种**架构模式**或者说是一种**架构风格**,**它提倡将单一应用程序划分成一组小的服务**,每个服务运行在其独立的自己的进程中,服务之间互相协调、互相配合,为用户提供最终价值。服务之间采用轻量级的通信机制互相沟通(通常是基于HTTP的RESTful API)。每个服务都围绕着具体业务进行构建,并且能够被独立地部署到生产环境、类生产环境等。另外,应尽量避免统一的、集中式的服务管理机制,对具体的一个服务而言,应根据业务上下文,选择合适的语言、工具对其进行构建,可以有一个非常轻量级的集中式管理来协调这些服务,可以使用不同的语言来编写服务,也可以使用不同的数据存储。
### 2.微服务和微服务架构的区别
> **微服务**
>
> 强调的是服务的大小,它关注的是某一个点,是具体解决某一个问题/提供落地对应服务的一个服务应用, 狭意的看,可以看作Eclipse里面的一个个微服务工程/或者Module
> **微服务架构**
>
> 微服务架构是⼀种架构模式,它提倡将单⼀应⽤程序划分成⼀组⼩的服务,服务之间互相协调、互相配合,为⽤户提供最终价值。每个服务运⾏在其独⽴的进程中,服务与服务间采⽤轻量级的通信机制互相协作(通常是基于HTTP协议的RESTful API)。每个服务都围绕着具体业务进⾏构建,并且能够被独⽴的部署到⽣产环境、类⽣产环境等。另外,应当尽量避免统⼀的、集中式的服务管理机制,对具体的⼀个服务⽽⾔,应根据业务上下⽂,选择合适的语⾔、⼯具对其进⾏构建。
## 2.Rest微服务构建案例工程模块
## 3.Eureka服务注册与发现
Eureka是Netflix的一个子模块,也是核心模块之一。Eureka是一个**基于REST**的服务,用于定位服务,以实现云端**中间层服务发现和故障转移**。服务注册与发现对于微服务架构来说是非常重要的,有了服务发现与注册,只需要使用服务的标识符,就可以访问到服务,而不需要修改服务调用的配置文件了。**功能类似于dubbo的注册中心**,比如Zookeeper。
## 4.Ribbon负载均衡
Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端 负载均衡的工具。
简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法,将Netflix的中间层服务连接在一起。Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说,就是在配置文件中列出Load Balancer(简称LB)后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器。我们也很容易使用Ribbon实现自定义的负载均衡算法。
## 5.Feign负载均衡
Feign是一个声明式WebService客户端。使用Feign能让编写Web Service客户端更加简单, 它的使用方法是定义一个接口,然后在上面添加注解,同时也支持JAX-RS标准的注解。Feign也支持可拔插式的编码器和解码器。Spring Cloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。
## 6.Hystrix断路器
Hystrix是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多依赖不可避免的会调用失败,比如超时、异常等,Hystrix能够保证在一个依赖出问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性。
## 7.zuul路由网关
Zuul包含了对请求的路由和过滤两个最主要的功能:
其中路由功能负责将外部请求转发到具体的微服务实例上,是实现外部访问统一入口的基础而过滤器功能则负责对请求的处理过程进行干预,是实现请求校验、服务聚合等功能的基础.Zuul和Eureka进行整合,将Zuul自身注册为Eureka服务治理下的应用,同时从Eureka中获得其他微服务的消息,也即以后的访问微服务都是通过Zuul跳转后获得。
注意:Zuul服务最终还是会注册进Eureka
## 8.SpringCloud Config分布式配置中心
SpringCloud Config分为服务端和客户端两部分。
服务端也称为分布式配置中心,它是一个独立的微服务应用,用来连接配置服务器并为客户端提供获取配置信息,加密/解密信息等访问接口
<file_sep>package com.hblg.springcloud.service;
import com.hblg.entity.Dept;
import java.util.List;
/**
* @author i
* @create 2020/2/18 15:46
* @Description
*/
public interface DeptService {
//添加
public boolean add(Dept dept);
//查询
public Dept get(long id);
//
public List<Dept> list();
}
| 127f420001a2385ea0b16b7ff8b73d906f7c855f | [
"Markdown",
"Java"
]
| 4 | Java | qxlx/SpringCloud | 272a4b8ee655ce0750bb298b3cdd666f37cdb1d6 | 655af4074c52956a1f19e5b6f30192405933da60 |
refs/heads/master | <file_sep>'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var minify = require('gulp-cssnano');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var babel = require('gulp-babel');
var minifyJs = require('gulp-minify');
gulp.task('sass', function() {
return gulp.src('./stylesheets/master.scss')
.pipe(sass().on('error', sass.logError))
.pipe(sourcemaps.init())
.pipe(autoprefixer({
browsers: ['Safari > 6']
}))
.pipe(minify())
.pipe(sourcemaps.write())
.pipe(gulp.dest('dist'))
.pipe(reload({ stream: true }));
});
gulp.task('babel', function() {
return gulp.src('src/**/*.js')
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['es2015']
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'))
.pipe(reload({ stream: true }));
});
gulp.task('minify', function() {
return gulp.src('dist/*.js')
.pipe(minifyJs())
.pipe(gulp.dest('dist'));
});
gulp.task('build', ['sass', 'babel']);
gulp.task('serve', ['build'], function() {
browserSync({
server: {
baseDir: '.'
}
});
gulp.watch(['*.html'], reload);
gulp.watch('./stylesheets/**/*.scss', ['sass']);
gulp.watch('./src/**/*.js', ['babel']);
});
gulp.task('default', ['build']);
<file_sep># Onboarding flow for Lookback for Mac
- This is a static HTML page with a simple wizard with figures for the onboarding flow.
- Can be server locally.
- Using Babel.
## Develop
Potentially over engineered, but dammit, this is a robust dev setup. In order to have a *nice* and lean dev experience while prototyping, this is set up with live injections of CSS and reload on JS saves. Hence the gulp setup.
**Run server**
```
gulp serve
```
JS and SCSS changes will reload or live inject site, respectively.
**Build**
```
gulp build
open index.html
```
Produces JS and CSS in `dist`.
***
Made by Johan.
| baf0cf4c94a7ae7bb3f794d1b1f62d695d0d76b2 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | mhaslett/Lookback | 4c27f917292d253244eefe946ac240ec1b40bd3a | 17d3fd770c4b06e4f83c0d30bc3adea24a53a618 |
refs/heads/master | <repo_name>Lex-z/bakedgoods<file_sep>/app/controllers/orders_controller.rb
class OrdersController < ApplicationController
before_action :current_user_is_owner, :only => [:edit, :update]
before_action :current_user_is_owner_or_seller, :only => [:destroy]
def current_user_is_owner
@order = Order.find(params[:id])
if current_user.id != @order.user_id
redirect_to "/orders", :alert => "Access denied. You do not have permission to perform this action."
else
end
end
def current_user_is_owner_or_seller
@order = Order.find(params[:id])
if current_user.id = @order.user_id || current_user.id = @order.food.user_id
else
redirect_to "/orders", :alert => "Access denied. You do not have permission to perform this action."
end
end
def index
@orders = Order.all
end
def myorders
@orders = current_user.orders
end
def mysales
@orders = Order.all
end
def new
@food = Food.find(params[:id])
@order = Order.new
end
def create
@order = Order.new
@order.user_id = params[:user_id]
@order.food_id = params[:food_id]
@order.quantity = params[:quantity]
@order.pickuptime = DateTime.strptime(params[:pickuptime], '%m/%d/%Y %H:%M')
@order.note = params[:note]
if @order.quantity > @order.food.servings_avail
redirect_to :back, :notice => "Order greater than quantity available! Order not placed. Please change your quantity."
else
@order.food.servings_avail = @order.food.servings_avail - @order.quantity
@order.food.servings_purch = @order.food.servings_purch + @order.quantity
if @order.save
@order.food.save
#issues with figaro hiding api key, but mailgun id works.
RestClient.post "https://api:key-xxxx"\
"@api.mailgun.net/v3/#{ENV["mailgun_id"]}/messages",
:from => "Heartbaked <mailgun@#{ENV["mailgun_id"]}>",
:to => current_user.email,
:subject => "Order number #{@order.id} created successfully!",
:text => "Thank you for placing your order for #{@order.quantity} servings of #{@order.food.foodname} at $#{@order.food.price} each. The pickup time is #{@order.pickuptime}. Your seller #{@order.food.user.username} will be in contact with you shortly. Please email #{@order.food.user.username} at #{@order.food.user.email} if you encounter any issues."
RestClient.post "https://api:key-xxxx"\
"@api.mailgun.net/v3/#{ENV["mailgun_id"]}/messages",
:from => "Heartbaked <mailgun@#{ENV["mailgun_id"]}>",
:to => @order.food.user.email,
:subject => "You have a sale! Order number #{@order.id} created successfully!",
:text => "#{current_user.username} has placed an order for #{@order.quantity} servings of #{@order.food.foodname} at $#{@order.food.price} each. The pickup time is #{@order.pickuptime}. Please email #{current_user.username} at #{current_user.email} to confirm the pickup."
redirect_to "/myorders", :notice => "Order created successfully! Your seller will email you directly with confirmation and pickup details."
else
render 'new'
end
end
end
def edit
@order = Order.find(params[:id])
end
def update
@order = Order.find(params[:id])
@order.user_id = params[:user_id]
@order.food_id = params[:food_id]
@order.quantity = params[:quantity]
@order.pickuptime = DateTime.strptime(params[:pickuptime], '%m/%d/%Y %H:%M')
@order.note = params[:note]
@startquantity = params[:startquantity].to_i
@changequantity = @order.quantity - @startquantity
if @changequantity > @order.food.servings_avail
redirect_to :back, :notice => "Order greater than quantity available! Order not placed. Please change your quantity."
else
@order.food.servings_avail = @order.food.servings_avail - @changequantity
@order.food.servings_purch = @order.food.servings_purch + @changequantity
if @order.save
@order.food.save
RestClient.post "https://api:key-xxxx"\
"@api.mailgun.net/v3/#{ENV["mailgun_id"]}/messages",
:from => "Heartbaked <mailgun@#{ENV["mailgun_id"]}>",
:to => "#{current_user.email}, #{@order.food.user.email}",
:subject => "Order number #{@order.id} #{@order.food.foodname} has been modified!",
:text => "Please log on to check the changes to Order number #{@order.id} and contact your buyer/seller with any issues."
redirect_to "/myorders", :notice => "Order updated successfully."
else
render 'edit'
end
end
end
def destroy
@order = Order.find(params[:id])
@order.food.servings_avail = @order.food.servings_avail + @order.quantity
@order.food.servings_purch = @order.food.servings_purch - @order.quantity
@order.food.save
if @order.destroy
RestClient.post "https://api:key-xxxx"\
"@api.mailgun.net/v3/#{ENV["mailgun_id"]}/messages",
:from => "Heartbaked <mailgun@#{ENV["mailgun_id"]}>",
:to => "#{current_user.email}, #{@order.food.user.email}",
:subject => "Order number #{@order.id} #{@order.food.foodname} has been canceled!",
:text => "Please contact your buyer/seller with any issues."
redirect_to "/myorders", :notice => "Order deleted."
else
end
end
end
<file_sep>/db/migrate/20151209214033_add_price_noteto_food_order.rb
class AddPriceNotetoFoodOrder < ActiveRecord::Migration
def change
add_column :foods, :price, :decimal
add_column :orders, :note, :text
end
end
<file_sep>/db/migrate/20151129025443_create_foods.rb
class CreateFoods < ActiveRecord::Migration
def change
create_table :foods do |t|
t.string :food
t.text :description
t.integer :user_id
t.integer :servings_avail
t.integer :servings_purch
t.string :image
t.time :pickuptime_start
t.time :pickuptime_end
t.integer :taste_rate
t.integer :portion_rate
t.integer :value_rate
t.timestamps
end
end
end
<file_sep>/db/migrate/20151210022128_change_time_columns.rb
class ChangeTimeColumns < ActiveRecord::Migration
def change
change_column :foods, :pickuptime_start, :datetime
change_column :foods, :pickuptime_end, :datetime
change_column :orders, :pickuptime, :datetime
end
end
<file_sep>/app/models/food.rb
class Food < ActiveRecord::Base
has_many :orders, dependent: :destroy
belongs_to :user
validates :foodname, presence: true
validates :description, presence: true
validates :servings_avail, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0}
validates :servings_purch, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0}
validates :price, :format => { :with => /\A\d+(?:\.\d{0,2})?\z/ }, :numericality => {:greater_than => 0, :less_than => 10}
validates :pickuptime_start, :presence => true
validates :pickuptime_end, :presence => true
validates :taste_rate, numericality: { only_integer: true}
validates :portion_rate, numericality: { only_integer: true}
validates :value_rate, numericality: { only_integer: true}
validate :pickuptime_start_cannot_be_in_the_past, :start_cannot_be_after_end
def pickuptime_start_cannot_be_in_the_past
errors.add(:pickuptime_start, "can't be in the past") if
!pickuptime_start.blank? and pickuptime_start < DateTime.now
end
def start_cannot_be_after_end
errors.add(:pickuptime_start, "can't be after pickuptime end") if
pickuptime_start > pickuptime_end
end
end
<file_sep>/app/models/order.rb
class Order < ActiveRecord::Base
belongs_to :food
belongs_to :user
validates :user, presence: true
validates :food, presence: true
validates :pickuptime, :presence => true
validates :quantity, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 1}
end
<file_sep>/app/controllers/foods_controller.rb
class FoodsController < ApplicationController
before_action :current_user_is_owner, :only => [:edit, :update, :destroy]
def current_user_is_owner
@food = Food.find(params[:id])
if current_user.id != @food.user_id
redirect_to "/foods", :alert => "Access denied. You do not have permission to perform this action."
end
end
def index
@foods = Food.all
end
def myinventory
@foods = Food.where(:user_id => current_user.id)
end
def new
@food = Food.new
end
def create
@food = Food.new
@food.foodname = params[:foodname]
@food.description = params[:description]
@food.user_id = params[:user_id]
@food.servings_avail = params[:servings_avail]
@food.servings_purch = params[:servings_purch]
@food.price = params[:price]
@food.image = params[:image]
@food.pickuptime_start = DateTime.strptime(params[:pickuptime_start], '%m/%d/%Y %H:%M')
@food.pickuptime_end = DateTime.strptime(params[:pickuptime_end], '%m/%d/%Y %H:%M')
@food.taste_rate = params[:taste_rate]
@food.portion_rate = params[:portion_rate]
@food.value_rate = params[:value_rate]
if @food.save
redirect_to "/foods", :notice => "Food created successfully."
else
render 'new'
end
end
def edit
@food = Food.find(params[:id])
end
def update
@food = Food.find(params[:id])
@food.foodname = params[:foodname]
@food.description = params[:description]
@food.user_id = params[:user_id]
@food.servings_avail = params[:servings_avail]
@food.servings_purch = params[:servings_purch]
@food.price = params[:price]
@food.image = params[:image]
@food.pickuptime_start = DateTime.strptime(params[:pickuptime_start], '%m/%d/%Y %H:%M')
@food.pickuptime_end = DateTime.strptime(params[:pickuptime_end], '%m/%d/%Y %H:%M')
@food.taste_rate = params[:taste_rate]
@food.portion_rate = params[:portion_rate]
@food.value_rate = params[:value_rate]
if @food.save
redirect_to "/foods", :notice => "Food updated successfully."
else
render 'edit'
end
end
def destroy
@food = Food.find(params[:id])
@food.destroy
redirect_to "/foods", :notice => "Food deleted."
end
end
<file_sep>/db/migrate/20151129034343_change_food_to_food_name.rb
class ChangeFoodToFoodName < ActiveRecord::Migration
def change
add_column :foods, :foodname, :string
remove_column :foods, :food
end
end
| 9c0e4ed6246d0ae2708cf05967ad655a1dd9019d | [
"Ruby"
]
| 8 | Ruby | Lex-z/bakedgoods | aca58a89cdeed7d229ffe4e4a525b0350408747a | 1011b0696682a372c408db296244d7378077faea |
refs/heads/master | <file_sep>Test data
==========
Aim
-----
Provide a test dataset that has a diurnal cycle plus a little noise. These data are used for testing the visualisation and 24 hour predictions.
Summary
--------
The Flask API handles the creation of these data when running app.py. Make sure to drop and recreate, or truncate all rows from the home_sensor_data table. If the table is empty then 300 records are added to the database with historical datestamps at 1 hour intervals starting from the current date and time.
.. note:: The following code blocks are in separate files. The method for creating data is in predictions.py which lives next to app.py.
Creating data
---------------
.. code-block:: python
def createData(startDate, nHourInterval, nRecords):
"""
Creates a list of dictionaries containing timeseries data points.
This function walks backwards from the startDate providing values
at each interval (nHourInterval) for as many records (nRecords)
as required.
"""
output = []
for n in range(nRecords):
# vars
dt = startDate - timedelta(hours=(n * nHourInterval))
ds = dt.isoformat()
hr = dt.hour
rn = random.random()
if (hr < 12):
val = round((10 + (hr % 12)) + rn, 3)
else:
val = round((10 - (hr % 12)) + 12 + rn, 3)
d = {"name": "TestData", "location": "Home", "category": "actual",
"measurementType": "temp", "value": val, "dsCollected": ds}
# use insert instead of append to put the
# record at the start of the list
output.insert(0, d)
return output
Testing
---------
.. code-block:: python
import pytz
from datetime import *
import predictions
import matplotlib.pyplot as plt
import dateutil.parser as parser
# variables
STARTDATE = datetime.today().replace(
tzinfo=pytz.timezone('Australia/Sydney'))
NHOURINTERVAL = 1
NRECORDS = 300
# create data
pcd = predictions.createData(STARTDATE, NHOURINTERVAL, NRECORDS)
# Format example
# [{
# 'name': 'TestData',
# 'location': 'Home',
# 'dsCollected': '2017-11-25T08:18:20.167450+10:05',
# 'category': 'actual',
# 'value': 18.947,
# 'measurementType': 'temp'
# }]
# reorganise data for plotting
data = {"ds":[], "val":[]}
# loop array of dictionaries
for elem in pcd:
# inspect dictionary
for key, value in elem.items():
# handle keys of interest
if key == 'dsCollected':
# Parse dates from string to datetime format
data["ds"].append(parser.parse(value))
elif key == "value":
data["val"].append(value)
else:
continue
plt.figure(figsize=(12,4))
plt.plot(data["ds"], data["val"])
plt.show()
.. image:: ../img/postgres_testdata.png
:width: 600
:align: center
Flask implementation
---------------------
.. code-block:: python
# REMINDER - deleting records
# DROP TABLE home_sensor_data;
# CREATE TABLE home_sensor_data;
sendat = HomeSensorData.query.all()
createFakeData = True
if createFakeData and len(sendat) == 0:
STARTDATE = datetime.today().replace(tzinfo=pytz.timezone('Australia/Sydney'))
NRECORDS = 300
NHOURINTERVAL = 1
td = predictions.createData(STARTDATE, NHOURINTERVAL, NRECORDS)
for record in td:
sendat = HomeSensorData(
name = record['name'],
location = record['location'],
category = record['category'],
measurementType = record['measurementType'],
value = record['value'],
dsCollected = record['dsCollected']
)
db.session.add(sendat)
db.session.commit()
<file_sep>import React, { Component } from 'react';
import './App.css';
import {Button, ButtonToolbar, DropdownButton, MenuItem} from 'react-bootstrap/lib';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import {
Charts,
ChartContainer,
ChartRow,
YAxis,
LineChart } from 'react-timeseries-charts';
import { TimeSeries, TimeRange } from 'pondjs';
const style = {
val: {
stroke: "#000000",
opacity: 0.5,
width: 2,
}
}
class App extends Component {
constructor(props){
super(props);
this.measurementsFilter.bind(this);
this.dropdownSelectionHandle.bind(this);
this.state={
flaskApiError: false,
data: [],
pageLoadDate: "",
sensorNames: [],
sensorLocations: [],
sensorMeasurementType: [],
temperature: "loading",
days: 7,
button7: "success",
button28: "primary",
button365: "primary",
focusName: "",
timeRange: this.createTimeRange(7),
chartXAxisFormat: "day"
}
}
componentDidMount() {
this.setState({
pageLoadDate: new Date()
})
};
componentWillMount() {
this.getDataFromApi()
};
getDataFromApi() {
return fetch('/homesensors/api/v1.0/sensor_data', {credentials: 'same-origin'})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: responseJson.data
}, () => this.measurementsFilterHandle(this.state.data, this.state.days))
})
.catch((error) => {
console.error(error);
this.setState({
flaskApiError: "Failed to fetch data from API. Make sure that the flask API is running in the background and its available on the same network."
})
});
}
measurementsFilterHandle(arrObjects, days) {
/*
This method is put in place to setup the default number of days to display.
I want to show data over 7 days as default, but if thats not the case and a
sensor has turned off for some reason then the default needs to change to
28 days and then 365 after that.
*/
try {
// filter actual data only
var filteredArray = arrObjects.filter(el=> {
return el.category === "actual"
});
// slice last object
if (filteredArray.slice(-1)[0] != null) {
var lastObject = filteredArray.slice(-1)[0]
}
// convert date
lastObject.dsCollected = new Date(lastObject.dsCollected)
// get current date
var currentDate = new Date()
// length of one day
var oneDay = 1000*60*60*24;
// convert dates to miliseconds
var lastObjectDateMs = lastObject.dsCollected.getTime();
var currentDateMs = currentDate.getTime();
// calc diff
var diffMs = currentDateMs - lastObjectDateMs
// convert to days
var daysSinceLatestRecord = Math.round(diffMs/oneDay);
console.log(daysSinceLatestRecord)
// set days to 7, 28 or 365 depending on last line of code
// this ifelse statement provides an opportunity to override the default
// 7 day timeline.
if (daysSinceLatestRecord <= 7) {
days = 7
this.setState({
days: days,
button7: "success",
button28: "primary",
button365: "primary",
timeRange: this.createTimeRange(7),
chartXAxisFormat: "day",
}, () => this.measurementsFilter(arrObjects, days))
} else if (daysSinceLatestRecord <= 28) {
days = 28
this.setState({
days: days,
button7: "primary",
button28: "success",
button365: "primary",
timeRange: this.createTimeRange(28),
chartXAxisFormat: "month",
}, () => this.measurementsFilter(arrObjects, days))
} else {
days = 365
this.setState({
days: days,
button7: "primary",
button28: "primary",
button365: "success",
timeRange: this.createTimeRange(365),
chartXAxisFormat: "year",
}, () => this.measurementsFilter(arrObjects, days))
}
} catch(err) {
console.log(err)
}
}
measurementsFilter(arrObjects, days) {
try {
// copy
var data = arrObjects.slice();
// get sensor attributes (this provides user selections)
var names = this.sensorAttrList(data, "name")
var locs = this.sensorAttrList(data, "location")
var mtype = this.sensorAttrList(data, "measurementType")
// convert date
for (var j=0; j<data.length; j++){
data[j].dsCollected = new Date(data[j].dsCollected)
}
// set start date using n days to filter date range
var d = new Date(new Date().setDate(new Date().getDate()-days))
// filter date interval (using prev line)
var filteredArray = data.filter(el=> {
return el.dsCollected >= d
});
// filter "actuals" data
var actualsData = filteredArray.filter(el=> {
return el.category === "actual"
});
// filter temp data
var tempArray = actualsData.filter(el=> {
return el.measurementType === "temp"
});
// focus data on user selections
var fName = this.focusSensorName(data, this.state.focusName, names)
var fAttr = this.focusSensorValue(tempArray, fName)
var fValue = fAttr[0]
var fDate = fAttr[1]
// create timeseries
var timeSeries = this.convertFocusDataToTimeseries(tempArray, fName)
// filter "prediction" data
var predsData = filteredArray.filter(el=> {
return el.category === "pred"
});
// filter prediction temp data
var predTempArray = predsData.filter(el=> {
return el.measurementType === "temp"
});
// create timeseries
var predTimeSeries = this.convertFocusDataToTimeseries(predTempArray, fName)
// save state
this.setState({
sensorNames: names,
sensorLocations: locs,
sensorMeasurementType: mtype,
focusName: fName,
focusValue: fValue,
focusDate: fDate,
temperature: tempArray,
timeSeries: timeSeries,
predTimeSeries: predTimeSeries,
days: days
})
} catch (err) {
console.log(err)
}
}
createTimeRange(days) {
var datePrev = new Date(new Date().setDate(new Date().getDate()-days)).getTime()
var dateNow = new Date().getTime()
if (days === 7){
dateNow = new Date(new Date().setDate(new Date().getDate()+1)).getTime()
} else if (days === 28) {
dateNow = new Date(new Date().setDate(new Date().getDate()+7)).getTime()
} else if (days === 365) {
dateNow = new Date(new Date().setDate(new Date().getDate()+28)).getTime()
} else {
// ignore
}
return new TimeRange([datePrev, dateNow])
}
convertFocusDataToTimeseries(focusData, sensorName) {
// create dictionary
var data = {
name: sensorName,
columns: ["time", "val"],
points: []
}
// filter tempArray by fName
var focusArray = focusData.filter(el=> {
return el.name === sensorName
})
// loop through data and add to points in the dictionary above
for (var i=0; i<focusArray.length; i++){
var date = focusArray[i].dsCollected
var dataPoint = [date.getTime(), focusArray[i].value]
data["points"].push(dataPoint)
}
// return
return new TimeSeries(data)
}
convertPredictionsToTimeseries(predictions, sensorName){
return "nothing done so far"
}
sensorAttrList(fArray, key) {
var sensorAttributes = [];
for (var i=0; i<fArray.length; i++){
if (sensorAttributes.includes(fArray[i][key])){
continue
} else {
sensorAttributes.push(fArray[i][key])
}
}
return sensorAttributes
}
focusSensorName(fArray, sensorName, namesList) {
//console.log("fArray", fArray.slice(-1)[0])
// name of sensor with most recent record
var startName = fArray.slice(-1)[0]["name"]
// set sensor name to focus on
var fName = (sensorName === "" & namesList.length >= 1)
? startName
: sensorName
return fName
}
focusSensorValue(fArray, sensorName) {
// filter data by sensor name
// then, take the most recent record (last record)
var fValue = fArray.filter(el=> {
return el.name === sensorName
});
var res = []
var dateNow = new Date()
//console.log(dateNow.toString())
// treat undefined variable (occurs when filter returns no data)
if (fValue.slice(-1)[0] == null) {
res.push("No data")
res.push("")
} else {
//console.log(fValue.slice(-1)[0]["dsCollected"].toString())
res.push(fValue.slice(-1)[0]["value"] + "°C")
// 36e5 = 60*60*1000
var hours = Math.floor(Math.abs(dateNow - fValue.slice(-1)[0]["dsCollected"])/36e5)
var mins = Math.floor((Math.abs(dateNow - fValue.slice(-1)[0]["dsCollected"])/(60*1000))%60)
res.push(hours + " hours " + mins + " mins ago")
}
//console.log(res)
return res
}
buttonHandle(days){
this.measurementsFilter(this.state.data, days)
this.setState({
timeRange: this.createTimeRange(days)
})
if (days === 7) {
this.setState({
button7: "success", //change color of button7 to green
button28: "primary",
button365: "primary",
chartXAxisFormat: "day"
})
} else if (days === 28) {
this.setState({
button7: "primary",
button28: "success",
button365: "primary",
chartXAxisFormat: "month"
})
} else {
this.setState({
button7: "primary",
button28: "primary",
button365: "success",
chartXAxisFormat: "year"
})
}
}
dropdownSelectionHandle(sn, n){
var fAttr = this.focusSensorValue(this.state.temperature, sn[n])
var timeSeries = this.convertFocusDataToTimeseries(this.state.temperature, sn[n])
this.setState({
focusName: sn[n],
focusValue: fAttr[0],
focusDate: fAttr[1],
timeSeries: timeSeries
})
}
render() {
let button7col = this.state.button7;
let button28col = this.state.button28;
let button365col = this.state.button365;
let sn = this.state.sensorNames
let menuItems = []
for (var i=0; i < this.state.sensorNames.length; i++){
var key = i.toString()
menuItems.push(<MenuItem key={key} eventKey={key}>
{this.state.sensorNames[i]}
</MenuItem>)
}
const buttonsInstance = (
<div className="wrapper">
<ButtonToolbar>
<DropdownButton bsStyle="info"
id="1"
title={this.state.focusName}
onSelect = {this.dropdownSelectionHandle.bind(this, sn)}
>
{menuItems}
</DropdownButton>
<Button
bsStyle={button7col}
onClick={this.buttonHandle.bind(this, 7)}>
7 days
</Button>
<Button
bsStyle={button28col}
onClick={this.buttonHandle.bind(this, 28)}>
28 days
</Button>
<Button
bsStyle={button365col}
onClick={this.buttonHandle.bind(this, 365)}>
1 year
</Button>
</ButtonToolbar>
</div>
);
if (this.state.timeSeries){
console.log(this.state.timeRange.toString())
console.log(this.state.timeSeries.toString())
console.log(this.state.timeSeries.size())
var chart = (
<div className="wrapper">
<ChartContainer
format={this.state.chartXAxisFormat}
timeRange={this.state.timeRange}
width={300}
showGrid={false}>
<ChartRow height="220">
<YAxis id="axis1" label="MType" min={0} max={50} width="20" type="linear" format=".0f"/>
<Charts>
<LineChart
axis="axis1"
series={this.state.timeSeries}
columns={["val"]}/>
<LineChart
axis="axis1"
series={this.state.predTimeSeries}
columns={["val"]}
/>
</Charts>
</ChartRow>
</ChartContainer>
</div>
)
}
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Garden Monitor</h1>
<p> {String(this.state.pageLoadDate)} </p>
</header>
{buttonsInstance}
{this.state.flaskApiError}
<div className="TempContainer">
<h1 className="TempValue">{this.state.focusValue}</h1>
<p>{this.state.focusDate}</p>
</div>
{chart}
</div>
);
}
}
export default App;
<file_sep>Sphinx documentation
=====================
Aim
----
Reminder for creating and editing documentation.
Summary
--------
Build documentation using Sphinx Documentation Generator. A little restructured text is shown as a reminder and the process of moving docs to gh-pages is detailed.
Install
--------
.. code-block:: bash
sudo pip3 install sphinx
sudo pip3 install sphinx_rtd_theme
sphinx-build -h
Core framework
-------------------
.. code-block:: bash
# /repos/GardenMonitor
mkdir docs
cd docs
Build documentation
.. code-block:: bash
# /repos/GardenMonitor/docs
sphinx-quickstart
# Follow the prompts
# I choose all default options except to have build and source in separate folders
Update theme by editing conf.py (in /repos/GardenMonitor/docs/source/conf.py)
.. code-block:: python
html_theme = "sphinx_rtd_theme"
Restructured Text
------------------
Update index.rst (/repos/GardenMonitor/docs/source)
.. code-block:: rst
.. toctree::
:maxdepth: 2
:caption: Contents:
/pages/summary
/pages/setup
/pages/docs
/pages/database
/pages/api
/pages/xbee
/pages/webserver
Add pages
.. code-block:: bash
# /repos/GardenMonitor/docs/source
mkdir pages
touch summary.rst setup.rst docs.rst database.rst api.rst xbee.rst webserver.rst
Add titles
.. code-block:: bash
Chapter 1 Title
================
Add seealso box
.. code-block:: rst
.. seealso:: seealso text
Add note box
.. code-block:: rst
.. note:: note text
Add a warning box
.. code-block:: rst
.. warning:: warning text
Add images
.. code-block:: rst
.. image:: img/rpi.jpg
:width: 600
:align: center
:alt: alternate text
This is a caption
Make documentation
.. code-block:: bash
#/repos/GardenMonitor/docs
make html
Git
----
Add changes to github (assumes repo has been created)
.. code-block:: bash
git add .
git commit -m "added docs"
git push origin master
If gh-pages already exists then remove it and start again (mainly because I stuffed it up the first time)
.. code-block:: bash
# remove from remote
git push origin --delete gh-pages
# remove from local
git branch -D gh-pages
gh-pages
---------
Host pages on github (you have to do this on every update to the docs)
.. code-block:: bash
# First time
git checkout -b gh-pages
touch .nojekyll
git checkout master docs/build/html
mv ./docs/build/html/* ./
rm -rf ./docs
git add --all
git commit -m "publishing docs"
git push origin gh-pages
# Updating
git checkout gh-pages
rm -rf *
git checkout master docs/build/html
mv ./docs/build/html/* ./
rm -rf ./docs
git add --all
git commit -m "publishing docs"
git push origin gh-pages
<file_sep>React App: Connection with API
===============================
Aim
----
Set up webserver to fetch data from the postgres db using the flask api.
Summary
--------
By the end of this page you should have a react web page running on your local network that fetches data. We wont be doing anything with the data once we have it, more on that next.
.. image:: ../img/reactapp_connection_mobile.png
:width: 300
:align: center
Requirements
--------------
- Flask api
- Postgres DB
- React app
Note on datetime stamps
-------------------------
All records have a datestamp which are used for processing and data visualisation. Postgres saves the datestamp as a string (dsCollected column) in ISO 8601 format along with timezone information. For example, "2017-10-18T10:30:00+10:00" is 10:30 am in Sydney on the 18th of October 2017. These strings get converted to a Date data type after they are collected by the react app.
Drop existing data
--------------------
.. code-block:: bash
psql homesensors ray
.. code-block:: psql
drop table home_sensor_data;
.. warning: If you drop the table called home_sensor_data then you will also need to restart the Flask API. You need to do this because the home_sensor_data table is created by Flask if it doesn't already exist.
Add test data
--------------
.. code-block:: bash
#/repos/homesensors/flask/bin
source activate
#(flask)/repos/homesensors/flask/bin
app.py
# open another terminal
# => ctrl-shft-t
# add records
# 1
curl -i -H "Content-Type: application/json"
-X post
-d '{"name": "tomatoes",
"location":"garden",
"category":"actual",
"measurementType":"temp",
"value": 16,
"dsCollected": "2017-11-18T10:30:00+11:00
"}'
http://localhost:5000/homesensors/api/v1.0/sensor_data
# 2
curl -i -H "Content-Type: application/json"
-X post
-d '{"name": "tomatoes",
"location":"garden",
"category":"actual",
"measurementType":"temp",
"value": 17,
"dsCollected": "2017-11-18T11:30:00+11:00
"}'
http://localhost:5000/homesensors/api/v1.0/sensor_data
# 3
curl -i -H "Content-Type: application/json"
-X post
-d '{"name": "tomatoes",
"location":"garden",
"category":"actual",
"measurementType":"temp",
"value": 18,
"dsCollected": "2017-11-18T12:30:00+11:00
"}'
http://localhost:5000/homesensors/api/v1.0/sensor_data
# 4
curl -i -H "Content-Type: application/json"
-X post
-d '{"name": "tomatoes",
"location":"garden",
"category":"actual",
"measurementType":"temp",
"value": 19,
"dsCollected": "2017-11-18T13:30:00+11:00
"}'
http://localhost:5000/homesensors/api/v1.0/sensor_data
# 5
curl -i -H "Content-Type: application/json"
-X post
-d '{"name": "tomatoes",
"location":"garden",
"category":"actual",
"measurementType":"temp",
"value": 17,
"dsCollected": "2017-11-18T14:30:00+11:00
"}'
http://localhost:5000/homesensors/api/v1.0/sensor_data
Add a proxy to webserver
-------------------------
Security restrictions block the transfer of data on localhost. To connect the react webserver (localhost port 3000) to the flask api (localhost post 5000) add a proxy setting to package.json.
.. code-block:: bash
nano /repos/homesensors/reactapp/package.json
.. code-block:: json
{
"name": "reactapp",
"version": "0.1.0",
"private": true,
// add proxy setting here...
"proxy": "http://localhost:5000/",
"dependencies": {
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-http-request": "^1.0.3",
"react-scripts": "1.0.14"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
Edit App.js (react webapp)
-------------------------------
.. code-block:: bash
nano /repos/homesensors/reactapp/src/app.py
.. code-block:: python
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props){
super(props);
this.state={
data: "Fetching data"
}
}
componentWillMount() {
this.getDataFromApi()
};
getDataFromApi() {
return fetch('/homesensors/api/v1.0/sensor_data', {credentials: 'same-origin'})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: responseJson.data
}, () => console.log("Success"))})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Garden Monitor</h1>
</header>
<p> {String(this.state.data)} </p>
</div>
);
}
}
export default App;
Test
-------
.. code-block:: bash
# Run flask api
cd /repos/homesensors/flask/bin
source activate
app.py
# Run react webapp
cd /repos/homesensors/reactapp
npm start
<file_sep>React App: Chart
=================
Aim
----
Add chart to display data.
Summary
--------
.. image:: ../img/reactdraft.png
:width: 300
:align: center
Install packages
-------------------------
.. code-block:: bash
npm install d3 --save
npm install react-timeseries-charts pondjs --save
Code listing
-------------
.. code-block:: javascript
import React, { Component } from 'react'
import './App.css'
import {Button, ButtonToolbar, DropdownButton, MenuItem} from 'react-bootstrap/lib'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/css/bootstrap-theme.css'
import {
Charts,
ChartContainer,
ChartRow,
YAxis,
LineChart } from 'react-timeseries-charts'
import { TimeSeries, TimeRange } from 'pondjs'
class App extends Component {
constructor(props){
super(props)
this.measurementsFilter.bind(this)
this.dropdownSelectionHandle.bind(this)
this.state={
data: [],
pageLoadDate: "",
sensorNames: [],
sensorLocations: [],
sensorMeasurementType: [],
temperature: "loading",
days: 7,
button7: "success",
button28: "primary",
button365: "primary",
focusName: "",
timeRange: this.createTimeRange(7),
chartXAxisFormat: "day",
}
}
componentDidMount() {
this.setState({
pageLoadDate: new Date()
})
}
componentWillMount() {
this.getDataFromApi()
}
getDataFromApi() {
return fetch('/homesensors/api/v1.0/sensor_data', {credentials: 'same-origin'})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: responseJson.data
}, () => this.measurementsFilter(this.state.data, this.state.days))
})
.catch((error) => {
console.error(error)
})
}
measurementsFilter(arrObjects, days) {
// copy
var data = arrObjects.slice()
// convert date
for (var j=0; j<data.length; j++){
data[j].dsCollected = new Date(data[j].dsCollected)
}
// set n days to filter
var d = new Date(new Date().setDate(new Date().getDate()-days))
// filter time interval
var filteredArray = data.filter(el=> {
return el.dsCollected >= d
})
// get sensor attributes (this provides user selections)
var names = this.sensorAttrList(filteredArray, "name")
var locs = this.sensorAttrList(filteredArray, "location")
var mtype = this.sensorAttrList(filteredArray, "measurementType")
// filter temp data (hardcode for now)
var tempArray = filteredArray.filter(el=> {
return el.measurementType === "temp"
})
// focus data on user selections
var fName = this.focusSensorName(tempArray, this.state.focusName, names)
var fAttr = this.focusSensorValue(tempArray, fName)
var fValue = fAttr[0]
var fDate = fAttr[1]
// create timeseries
var timeSeries = this.convertFocusDataToTimeseries(tempArray, fName)
// save state
this.setState({
sensorNames: names,
sensorLocations: locs,
sensorMeasurementType: mtype,
focusName: fName,
focusValue: fValue,
focusDate: fDate,
temperature: tempArray,
timeSeries: timeSeries,
days: days
})
}
createTimeRange(days) {
var dateNow = new Date().getTime()
var datePrev = new Date(new Date().setDate(new Date().getDate()-days)).getTime()
return new TimeRange([datePrev, dateNow])
}
convertFocusDataToTimeseries(focusData, sensorName) {
// create dictionary
var data = {
name: sensorName,
columns: ["time", "val"],
points: []
}
// filter tempArray by fName
var focusArray = focusData.filter(el=> {
return el.name === sensorName
})
// loop through data and add to points in the dictionary above
for (var i=0; i<focusArray.length; i++){
var date = focusArray[i].dsCollected
var dataPoint = [date.getTime(), focusArray[i].value]
data["points"].push(dataPoint)
}
// return
return new TimeSeries(data)
}
sensorAttrList(fArray, key) {
var sensorAttributes = []
for (var i=0; i<fArray.length; i++){
if (sensorAttributes.includes(fArray[i][key])){
continue
} else {
sensorAttributes.push(fArray[i][key])
}
}
return sensorAttributes
}
focusSensorValue(fArray, sensorName) {
// filter data by sensor name
// then, take the most recent record (last record)
var fValue = fArray.filter(el=> {
return el.name === sensorName
})
var res = []
var dateNow = new Date()
//console.log(dateNow.toString())
// treat undefined variable (occurs when filter returns no data)
if (fValue.slice(-1)[0] == null) {
res.push("No data")
res.push("")
} else {
//console.log(fValue.slice(-1)[0]["dsCollected"].toString())
res.push(fValue.slice(-1)[0]["value"] + "°C")
// 36e5 = 60*60*1000
var hours = Math.floor(Math.abs(dateNow - fValue.slice(-1)[0]["dsCollected"])/36e5)
var mins = Math.floor((Math.abs(dateNow - fValue.slice(-1)[0]["dsCollected"])/(60*1000))%60)
res.push(hours + " hours " + mins + " mins")
}
//console.log(res)
return res
}
focusSensorName(fArray, sensorName, namesList) {
// name of sensor with most recent record
var startName = fArray.slice(-1)[0]["name"]
// set sensor name to focus on
var fName = (sensorName === "" & namesList.length >= 1)
? startName
: sensorName
// treat undefined variable (occurs when filter returns no data)
if (fName == null) {
fName = "Select"
}
return fName
}
sevenDayHandle(){
this.measurementsFilter(this.state.data, 7)
this.setState({
button7: "success", //change color of button7 to green
button28: "primary",
button365: "primary",
timeRange: this.createTimeRange(7),
chartXAxisFormat: "day",
})
}
twentyEightDayHandle(){
this.measurementsFilter(this.state.data, 28)
this.setState({
button7: "primary",
button28: "success", //change color of button28 to green
button365: "primary",
timeRange: this.createTimeRange(28),
chartXAxisFormat: "month"
})
}
oneYearHandle(){
this.measurementsFilter(this.state.data, 365)
this.setState({
button7: "primary",
button28: "primary",
button365: "success", //change color of button365 to green
timeRange: this.createTimeRange(365),
chartXAxisFormat: "year",
})
}
dropdownSelectionHandle(sn, n){
var fAttr = this.focusSensorValue(this.state.temperature, sn[n])
var timeSeries = this.convertFocusDataToTimeseries(this.state.temperature, sn[n])
this.setState({
focusName: sn[n],
focusValue: fAttr[0],
focusDate: fAttr[1],
timeSeries: timeSeries
})
}
render() {
let button7col = this.state.button7
let button28col = this.state.button28
let button365col = this.state.button365
let sn = this.state.sensorNames
let menuItems = []
for (var i=0; i < this.state.sensorNames.length; i++){
var key = i.toString()
menuItems.push(<MenuItem key={key} eventKey={key}>
{this.state.sensorNames[i]}
</MenuItem>)
}
const buttonsInstance = (
<div className="wrapper">
<ButtonToolbar>
<DropdownButton bsStyle="info"
id="1"
title={this.state.focusName}
onSelect = {this.dropdownSelectionHandle.bind(this, sn)}
>
{menuItems}
</DropdownButton>
<Button
bsStyle={button7col}
onClick={this.sevenDayHandle.bind(this)}>
7 days
</Button>
<Button
bsStyle={button28col}
onClick={this.twentyEightDayHandle.bind(this)}>
28 days
</Button>
<Button
bsStyle={button365col}
onClick={this.oneYearHandle.bind(this)}>
1 year
</Button>
</ButtonToolbar>
</div>
)
if (this.state.timeSeries){
console.log(this.state.timeRange.toString())
console.log(this.state.timeSeries.toString())
console.log(this.state.timeSeries.size())
var chart = (
<div className="wrapper">
<ChartContainer
format={this.state.chartXAxisFormat}
timeRange={this.state.timeRange}
width={300}
showGrid={false}>
<ChartRow height="220">
<YAxis id="axis1" label="MType" min={0} max={50} width="20" type="linear" format=".0f"/>
<Charts>
<LineChart
axis="axis1"
series={this.state.timeSeries}
columns={["val"]}/>
</Charts>
</ChartRow>
</ChartContainer>
</div>
)
}
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Garden Monitor</h1>
<p> {String(this.state.pageLoadDate)} </p>
</header>
{buttonsInstance}
<div className="TempContainer">
<h1 className="TempValue">{this.state.focusValue}</h1>
<p>{this.state.focusDate}</p>
</div>
{chart}
</div>
)
}
}
export default App;
<file_sep>Setup
=====
Aim
----
Setup the project.
Summary
--------
Set up a Raspberry Pi which will be a central component of this project. The main requirement here is to update, upgrade and install python 3. I have included my setup for github.
.. image:: ../img/rpi.jpg
:width: 600
.. note:: I am not using the wifi dongle shown in this image. I used a lan cable for development and the builtin wifi capability once the project was completed.
Gear
----
- Raspberry Pi v3
- 16GB microsd card
- Keyboard and mouse
- Monitor and HDMI cable
- 5v power supply
- Lan cable
.. warning:: I ran out of space using an 8GB card. I tried cloning the RPi image to the 16GB card but this failed because the OS was NOOBS and the built in card expansion method (via raspi-config) didnt work. I tried several methods to expand the root partition using gparted and by modifying cylinder boundary markers using parted. I found that it was easier to start from scratch. On the upside this meant I had an updated desktop for the RPi.
Raspberry Pi OS
-----------------
- Download and extract Raspbian https://www.raspberrypi.org/downloads/raspbian/
- Download and install Win32 Disk Imager 1.0 (I used Windows for this, you could also use dd on Linux)
- Format 16GB microsd card to fat32
- Write image to microsd card
- Insert microsd card and boot
Preferences
------------
- Set keyboard preferences (for me English (US))
Raspberry Pi password
----------------------
.. code-block:: bash
passwd
# Enter default password => raspberry
password
password
Raspberry Pi name
------------------
.. code-block:: bash
# step 1
sudo nano /etc/hostname
#delete raspberrypi
gardenmonitor
# exit => ctrl-x > y > enter
# step 2
sudo nano /etc/hosts
127.0.0.1 raspberrypi # find this line and change it to...
127.0.0.1 gardenmonitor
192.168.1.50 gardenmonitor # static IP to be set up below
# exit => ctrl-x > y > enter
# check host name and IP
hostname
hostname -I
Set timezone
---------------
.. code-block:: bash
sudo dpkg-reconfigure tzdata
Expand file system and enable ssh
----------------------------------
.. code-block:: bash
df -h # check space on root
sudo raspi-config
# SELECT => 7 Advance Options > A1 Expand Filesystem > Select
# SELECT => 5 Interfacing Options > P2 SSH > Enable
sudo reboot now
Update and upgrade
-------------------
.. code-block:: bash
sudo apt-get update
sudo apt-get upgrade
Create static IP address
--------------------------
.. code-block:: bash
sudo nano /etc/dhcpcd.conf
# add to bottom of file...
interface eth0
static ip_address=192.168.1.50/24 # I made this up
static routers=192.168.1.1 # My router address
static domain_name_servers=192.168.1.1
# exit => ctrl-x > y > enter
sudo reboot now
Install
---------
.. code-block:: bash
sudo apt-get install python3
sudo apt-get install git
sudo apt-get install iceweasel #Dev using Firefox
Folder
------
.. code-block:: bash
# repos/
mkdir GardenMonitor
cd GardenMonitor
Git
----
.. code-block:: bash
# set global config
git config --global user.email <EMAIL>
git config --global user.name "rayblick"
# repos/GardenMonitor
git init
# setup github repo, then...
git remote add origin https://github.com/rayblick/GardenMonitor.git
Testing
--------
- Install an app on your mobile phone to ping the IP address (I used one called "Ping")
- Ensure your phone is connected to the same network as the RPi
- Test that the static IP address is found by pinging "192.168.1.50"
.. image:: ../img/network_ping_mobile.png
:width: 300
:align: center<file_sep>Postgres Database
==================
Aim
----
Setup data storage location.
Summary
--------
Setup a postgres database running on your local network. Add a user and allow the new user to have full privileges.
Install and open
-------------------
.. code-block:: bash
# search for postgres
sudo apt-cache search postgres
# install
sudo apt-get install postgresql-9.6
# open
sudo -u postgres psql postgres
Change password for user called "postgres"
---------------------------------------------
.. code-block:: psql
\password postgres
\q
Allow local connections
------------------------
.. code-block:: bash
# step 1
nano /etc/postgresql/9.4/main/pg_hba.conf
# update the following section...
# Database administrative login by Unix domain socket
local all postgres peer
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all md5
# IPv4 local connections:
host all all 127.0.0.1/32 md5
# IPv6 local connections:
host all all ::1/128 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local replication postgres peer
#host replication postgres 127.0.0.1/32 md5
#host replication postgres ::1/128 md5
host all all 0.0.0.0/0 md5
host all all ::/0 md5
# exit => ctrl-x > y > enter
# step 2
nano /etc/postgresql/9.4/main/postgresql.conf
# locate the following line...
# listen_addresses = "127.0.0.1"
# Change to this...
listen_addresses = "*" #WARNING: Make sure you uncomment this line by removing the # symbol
# exit => ctrl-x > y > enter
Create database
----------------
Start database using user "postgres" (first code block above)
.. code-block:: psql
-- list databases
\l+
-- create db
CREATE DATABASE homesensors
-- connect
\c homesensors
.. WARNING:: A database called homesensors is required in the next step. The model we create in the Flask API will be called HomeSensorsData and it will live in the homesensors database.
Create user
-----------
.. code-block:: psql
-- create
CREATE USER ray WITH PASSWORD '<PASSWORD>'
-- list users
\dg+
-- add roles
ALTER USER ray WITH CREATEROLE
ALTER USER ray WITH createdb;
ALTER USER ray WITH Superuser;
-- add privileges
GRANT ALL PRIVILEGES ON homesensors To ray
.. WARNING:: The Flask API requires that the user name "ray" is available to access the database in following steps. If you change this name, and you most likely will, make the appropriate changes to the Flask API. The location for making changes will be highlighted in the next step.
Restart postgres
-----------------
.. code-block:: bash
sudo service postgresql restart
Signing in
-----------
.. code-block:: bash
# sign in with new user
psql homesensors ray
#Password for user ray:
password
Testing
---------
Install SQL client and connect.
.. image:: ../img/remodb_mobile1.png
:width: 300
:align: center
.. image:: ../img/remodb_mobile2.png
:width: 300
:align: center
.. image:: ../img/remodb_mobile3.png
:width: 300
:align: center
<file_sep># My Garden Monitor
---
## The Garden
+++
## Floor plan
+++
## Seed propagator
---
## References
* [Github Documentation](https://github.com/rayblick/GardenMonitor)
* [Building Wireless Sensor Networks Using Arduino (Community Experience Distilled)](https://www.amazon.com.au/d/Building-Wireless-Community-Experience-Distilled-ebook/B012O8S296/ref=sr_1_1?ie=UTF8&qid=1507496006&sr=8-1&keywords=building+wireless+network)
* [Arduino docs](https://www.arduino.cc/)
* [Arduino Cheatsheet](http://makitpro.com/index.php/2016/04/14/arduino-cheat-sheet/)
* [Arduino Wireless Shield documentation](https://www.arduino.cc/en/Guide/ArduinoWirelessShield)
---
## Components
+++
## Hardware
* [Raspberry Pi](https://www.raspberrypi.org)
* [Arduino Uno](https://store.arduino.cc/usa/arduino-uno-rev3)
* [XBee Explorer USB](https://www.sparkfun.com/products/11812)
* [XBee Modules](https://core-electronics.com.au/xbee-module-zb-series-2-2mw-with-wire-antenna-xb24-z7wit-004.html)
* [Solar kit](https://core-electronics.com.au/wireless-sensor-node-solar-kit-seeed-studio.html)
* [Arduino XBee shield](https://www.pakronics.com.au/products/xbee-shield-v2-0-ss103030004)
* [Grove Temp & Humidity sensors](https://www.pakronics.com.au/products/grove-temp-humi-barometer-sensor-bme280-ss101020193)
* Waterproof enclosure
+++
## Software
* [Arduino IDE](https://www.arduino.cc/en/Main/Software)
* [Digi XBee software XTCU](https://www.digi.com/products/xbee-rf-solutions/xctu-software/xctu)
* [Postgresql](https://www.postgresql.org/)
---
## Database
+++
## Setup
```shell
# install and open Postgresql
pi@home~$ sudo apt-get install postgresql-9.4
pi@home~$ sudo -u postgres psql postgres
```
```psql
-- change password for user "postgres"
postgres=# \password postgres
-- quit
postgres=# \q
```
```bash
# modify the following file to allow local connections
pi@home~$ nano /etc/postgresql/9.4/main/pg_hba.conf
pi@home~$ sudo service postgresql restart
```
+++
## Create Database
```psql
-- create database
postgres=# CREATE DATABASE homesensors;
-- list all dbs
postgres=# \l+
-- switch to database
postgres=# \c homesensors
homesensors=# \c postgres
```
+++
## Add User and Privileges
```psql
-- create user
postgres=# CREATE USER ray WITH PASSWORD '<PASSWORD>' CREATEDB CREATEUSER;
-- list users
postgres=# \dg+
-- upgrade user to add roles
postgres=# ALTER USER ray WITH CREATEROLE;
-- add user 'ray' to database 'homesensors'
postgres=# GRANT ALL PRIVILEGES ON homesensors To ray;
-- quit
postgres=# \q
```
```shell
pi@home~$ psql homesensors ray
pi@home~$ Password for user ray: password
```
+++
## Data example
```json
{
"name": "<NAME>",
"location": "Garden",
"category": "Climate",
"measurementType": "temp",
"value": 24,
"dsCollected": 20171018T1000,
"dsAdded": (auto)
}
```
+++
## Other operations
```bash
# Sign in and show tables (if exist)
pi@home~$ psql homesensors ray
```
```psql
homesensors=# \dt
-- drop table (if required)
homesensors=# DROP TABLE sensor_data;
```
---
## Flask API
+++
## Setup
```bash
# install virtualenv
sudo apt-get install virtualenv
# create project directory
mkdir repos/homesensors
```
+++
## Virtualenv
```shell
# base install
sudo apt-get install virtualenv python-psycopg2 libpq-dev
# location: repos/homesensors - create virtual environment
virtualenv -p python3 flask
# activate and install python packages
cd flask/bin && source activate
pip install flask flask_sqlalchemy psycopg2
```
+++
## Create app.py
```shell
# create file
nano app.py
# make executable
chmod a+x app.py
```
+++
## Flask app (app.py)
```
#!python
from flask import Flask, jsonify, request, abort
from flask_sqlalchemy import SQLAlchemy
import json
app = Flask(__name__)
POSTGRES = {
'user': 'ray',
'pw': '<PASSWORD>',
'db': 'homesensors',
'host': 'localhost',
'port': '5432'
}
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://%(user)s:%(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
db = SQLAlchemy(app)
class HomeSensorData(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
location = db.Column(db.String(50))
category = db.Column(db.String(50))
measurementType = db.Column(db.String(50))
value = db.Column(db.Integer)
dsCollected = db.Column(db.String(13))
db.create_all()
@app.route('/homesensors/api/v1.0/sensor_data', methods=['POST'])
def add_sensor_data():
if not request.json or not 'value' in request.json:
abort(400)
#handle data obj
sendat = HomeSensorData(
name = request.json['name'],
location = request.json['location'],
category = request.json['category'],
measurementType = request.json['measurementType'],
value = request.json['value'],
dsCollected = request.json['dsCollected']
)
db.session.add(sendat)
db.session.commit()
@app.route('/homesensors/api/v1.0/sensor_data', methods=['GET'])
def get_sensor_data():
sendat = HomeSensorData.query.all()
mylist = []
for u in sendat:
mydict = {}
for key, value in u.__dict__.items():
if key != "_sa_instance_state":
mydict[key] = value
mylist.append(mydict)
data = json.dumps(mylist)
return data, 201
if __name__ == '__main__':
app.run(debug=True)
```
+++
## GET data
```shell
curl -i
http://localhost:5000/homesensors/api/v1.0/sensor_data
```
+++
## POST data
```shell
curl -i -H "Content-Type: application/json"
-X post -d '{
"name": "dummyA",
"location":"garden",
"category":"dummyA",
"measurementType":"temp",
"value": 1500,
"dsCollected": "20171018T1000"}' http://localhost:5000/homesensors/api/v1.0/sensor_data
```
---
## XBee Modules
+++
## XBee setup
+++
## Test run sending messages
---
## Solar kit
+++
## Grove Temp and Humidity sensor
+++
## Setup
+++
---
## Webserver & Viz
+++
## Environment setup
+++
## Run webserver
+++
## UI
+++
## Data
+++
## Filters
+++
## Figures
----
<file_sep>React App: Functionality
=============================
Summary
--------
Add functionality to the reactapp.
.. image:: ../img/reactdraft.png
:width: 200
<file_sep>Sensors
=======
TBA<file_sep>React App: Bootstrap
======================
Aim
----
Add styles to the reactapp.
Summary
--------
Add several buttons to filter data and show the most recent temperature. Note I have focussed on temperature only.
.. image:: ../img/reactapp_bootstrap_mobile.png
:width: 300
:align: center
Install
---------
.. code-block:: bash
cd homesensors/reactapp
npm install --save react-bootstrap
npm install --save bootstrap
Code listing
-------------
.. code-block:: psql
import React, { Component } from 'react'
import './App.css'
import {Button, ButtonToolbar, DropdownButton, MenuItem} from 'react-bootstrap/lib'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/css/bootstrap-theme.css'
class App extends Component {
constructor(props){
super(props)
this.measurementsFilter.bind(this)
this.dropdownSelectionHandle.bind(this)
this.state={
data: [],
pageLoadDate: "",
sensorNames: [],
sensorLocations: [],
sensorMeasurementType: [],
temperature: "loading",
days: 28,
button7: "primary",
button28: "success",
button365: "primary",
focusName: ""
}
}
componentDidMount() {
this.setState({
pageLoadDate: new Date()
})
}
componentWillMount() {
this.getDataFromApi()
}
getDataFromApi() {
return fetch('/homesensors/api/v1.0/sensor_data', {credentials: 'same-origin'})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: responseJson.data
}, () => this.measurementsFilter(this.state.data, this.state.days))
})
.catch((error) => {
console.error(error)
})
}
measurementsFilter(arrObjects, days) {
// copy
var data = arrObjects.slice()
// convert date
for (var j=0; j<data.length; j++){
data[j].dsCollected = new Date(data[j].dsCollected)
}
// set n days to filter
var d = new Date(new Date().setDate(new Date().getDate()-days))
// filter time interval
var filteredArray = data.filter(el=> {
return el.dsCollected >= d
})
// get sensor attributes
var names = this.sensorAttrList(filteredArray, "name")
var locs = this.sensorAttrList(filteredArray, "location")
var mtype = this.sensorAttrList(filteredArray, "measurementType")
// filter temp data
var tempArray = filteredArray.filter(el=> {
return el.measurementType === "temp"
})
var fName = this.focusSensorName(tempArray, this.state.focusName, names)
var fValue = this.focusSensorValue(tempArray, fName)
// save state
this.setState({
sensorNames: names,
sensorLocations: locs,
sensorMeasurementType: mtype,
focusName: fName,
focusValue: fValue,
temperature: tempArray,
days: days
})
}
sensorAttrList(fArray, key) {
var sensorAttributes = []
for (var i=0; i<fArray.length; i++){
if (sensorAttributes.includes(fArray[i][key])){
continue
} else {
sensorAttributes.push(fArray[i][key])
}
}
return sensorAttributes
}
focusSensorValue(fArray, sensorName) {
// filter data by sensor name
// then, take the most recent record (last record)
var fValue = fArray.filter(el=> {
return el.name === sensorName
})
// treat undefined variable (occurs when filter returns no data)
if (fValue.slice(-1)[0] == null) {
fValue = "No data"
} else {
fValue = fValue.slice(-1)[0]["value"] + "°C"
}
return fValue
}
focusSensorName(fArray, sensorName, namesList) {
// name of sensor with most recent record
var startName = fArray.slice(-1)[0]["name"]
// set sensor name to focus on
var fName = (sensorName === "" & namesList.length > 1)
? startName
: sensorName
// treat undefined variable (occurs when filter returns no data)
if (fName == null) {
fName = "Select"
}
return fName
}
sevenDayHandle(){
this.measurementsFilter(this.state.data, 7)
this.setState({
button7: "success", //change color of button7 to green
button28: "primary",
button365: "primary"
})
}
twentyEightDayHandle(){
this.measurementsFilter(this.state.data, 28)
this.setState({
button7: "primary",
button28: "success", //change color of button28 to green
button365: "primary"
})
}
oneYearHandle(){
this.measurementsFilter(this.state.data, 365)
this.setState({
button7: "primary",
button28: "primary",
button365: "success" //change color of button365 to green
})
}
dropdownSelectionHandle(sn, n){
this.setState({
focusName: sn[n],
focusValue: this.focusSensorValue(this.state.temperature, sn[n])
})
}
render() {
let button7col = this.state.button7
let button28col = this.state.button28
let button365col = this.state.button365
let sn = this.state.sensorNames
let menuItems = []
for (var i=0; i < this.state.sensorNames.length; i++){
var key = i.toString()
menuItems.push(<MenuItem key={key} eventKey={key}>
{this.state.sensorNames[i]}
</MenuItem>)
}
const buttonsInstance = (
<div className="wrapper">
<ButtonToolbar>
<DropdownButton bsStyle="info" id="1" title={this.state.focusName}
onSelect = {this.dropdownSelectionHandle.bind(this, sn)}
>
{menuItems}
</DropdownButton>
<Button bsStyle={button7col}
onClick={this.sevenDayHandle.bind(this)}>
7 days
</Button>
<Button bsStyle={button28col}
onClick={this.twentyEightDayHandle.bind(this)}>
28 days
</Button>
<Button bsStyle={button365col}
onClick={this.oneYearHandle.bind(this)}>
1 year
</Button>
</ButtonToolbar>
</div>
)
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Garden Monitor</h1>
<p> {String(this.state.pageLoadDate)} </p>
</header>
{buttonsInstance}
<div className="TempContainer">
<h3 className="TempValue">{this.state.focusValue}</h3>
</div>
</div>
)
}
}
export default App
Edit App.css
-------------
.. code-block:: css
.App {
text-align: center;
}
.App-header {
background-color: #222;
height: 90px;
padding-top: 5px;
padding-bottom: 20px;
color: white;
}
.App-title {
font-size: 2em;
}
.form-actions {
margin:0;
background-color: transparent;
text-align: center;
}
.wrapper {
width: 100%;
padding-top: 10px;
display: flex;
justify-content: center;
}
.TempValue {
margin: 0;
}
.TempContainer {
width: 200px;
//height: 50px;
//border-radius: 15px;
//border-width: 3px;
//border-style: solid;
//border-color: black;
margin: 0 auto;
margin-top: 10px;
}
<file_sep># My Garden Monitor
I like gardening and I like data... this project is is going to record data in my garden.
### What I want...
What I want is a modular and extensible framework to monitor plants in my garden. I want to be able to continuously add new sensors that will transmit data to a cloud service and provide real time information. All sensors must be solar powered.
### Initial project scope and direction
One coordinator (head) node will consume data from router (slave) nodes positioned in my garden. The slaves will be solar powered arduino compatible boards that collect and transmit data captured from Grove sensors (e.g. Temp and Humidity). Each slave can have two sensors that will vary depending on location and application. Importantly slaves are configured in a mesh network so that other slaves can pass on data to the head node if distance/comms is a problem. Once the data has reached the head node a runshell command will be executed to send a data packet to a Flask API. All data will be transmitted and stored on the local network. Finally these data will be accessible using an API request to provide data for visualisation.
### More information
**DOCS:** https://rayblick.github.io/GardenMonitor/
**PITCH:** https://gitpitch.com/rayblick/GardenMonitor/master
<file_sep>Garden Monitor
==============
:Authors:
<NAME>
:Version: 0.1
:Last update: 2017/11/25
Overview
----------
A Raspberry Pi hosts 1) a postgres database, 2) a flask API and 3) a basic react web application. The measurements are taken using grove sensors attached to Arduino compatible carrier boards. These data are sent to the postgres database using an API POST request. The flask API is responsible for commiting data to the database. The react web application uses an API GET request to access these data and generate a D3 timeseries chart. Several buttons allow the user to filter these data.
Aim
----
Record temperature from multiple locations in my garden/home and display these data in a dashboard.
Background
------------
I have been thinking about garden monitors for a while now. The original project was called "Tweepy Pond" which started in Brisbane 2013. This was a motion activated raspberry pi enabled camera mixed with a temperature monitor to observe creatures in a home-made pond. Tweepy Pond was my first Raspberry Pi project and one of my first Python projects.
When I moved to Sydney this project turned into a balcony temperature monitor for the occasional pot plant. Now, still in Sydney and a new place to call home I have become interested in propagating vegetables. Subsequently I have reimagined tweepy pond to incorporate a variety of sensors that could communicate on the local area network.
Development timeline
----------------------
- 2017 = Garden Monitor
- 2015 = Pot plant temperature gauge
- 2013 = Tweepy pond (Raspberry Pi pond monitor)
Scope
------
- Everything on the local network
- Raspberry Pi
- Raspbian OS
- Arduino Uno
- XBee modules
- Grove sensors
- Zigbee mesh network
- Python 3
- Flask (API)
- React
- D3
Out of scope
-------------
- The cloud.
Follow along
--------------
You can skip the pages titled setup and docs. This project was developed using a raspberry pi, Raspbian stretch and python 3.4.
.. warning:: You will need to make changes to the Flask API if you are using python 2.x. I haven't tried so the errors that might come up are not covered in this documentation.
.. image:: ../img/visitor.JPG
:width: 600
:align: center
<file_sep>Flask API
=========
Aim
----
Setup data transmission.
Summary
--------
By the end of this page you should have a method of adding and receiving data from the postgres db.
Base install
--------------
.. code-block:: bash
sudo apt-get install virtualenv
sudo apt-get install python-psycopg2
sudo apt-get install libpq-dev
# scipy dependancies
sudo apt-get install libblas-dev
sudo apt-get install liblapack-dev
sudo apt-get install libatlas-base-dev
sudo apt-get install gfortran
sudo apt-get install python-setuptools
Folder structure
-----------------
I have decided to build this section in its own repo. The following steps setup the virtual environment.
.. code-block:: bash
# folders
cd repos
mkdir homesensors
cd homesensors
# virtualenv
virtualenv -p python3 flask
cd flask/bin && source activate
# check python 3 is default
python
Pip install
------------
.. code-block:: bash
# venv activated
pip install flask
pip install flask_sqlalchemy
pip install psycopg2
pip install numpy
pip install pandas
pip install scipy
pip install scikit-learn
app.py
-------
.. code-block:: bash
# create app.py
nano app.py
# Exit >> ctrl x
# make app.py executable
chmod a+x app.py
Example app
------------
.. code-block:: python
#!python
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Hello world"
if __name__ == '__main__':
app.run(debug=True)
Run app.py
-----------
.. code-block:: bash
./app.py
# Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
# Restarting with stat
# Debugger is active!
# Debugger PIN: 144-156-571
API code listing
-----------------
.. code-block:: python
#!python
from flask import Flask, jsonify, request, abort
from flask_sqlalchemy import SQLAlchemy
import json
app = Flask(__name__)
POSTGRES = {
'user': 'ray',
'pw': 'password',
'db': 'homesensors',
'host': 'localhost',
'port': '5432'
}
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://%(user)s:%(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
db = SQLAlchemy(app)
class HomeSensorData(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
location = db.Column(db.String(50))
category = db.Column(db.String(50))
measurementType = db.Column(db.String(50))
value = db.Column(db.Integer)
dsCollected = db.Column(db.String(30))
db.create_all()
@app.route('/homesensors/api/v1.0/sensor_data', methods=['POST'])
def add_sensor_data():
if not request.json or not 'value' in request.json:
abort(400)
#handle data obj
sendat = HomeSensorData(
name = request.json['name'],
location = request.json['location'],
category = request.json['category'],
measurementType = request.json['measurementType'],
value = request.json['value'],
dsCollected = request.json['dsCollected']
)
db.session.add(sendat)
db.session.commit()
return "Record added successfully\n"
@app.route('/homesensors/api/v1.0/sensor_data', methods=['GET'])
def get_sensor_data():
sendat = HomeSensorData.query.all()
mylist = []
for u in sendat:
mydict = {}
for key, value in u.__dict__.items():
if key != "_sa_instance_state":
mydict[key] = value
mylist.append(mydict)
data = json.dumps(mylist)
return data, 201
if __name__ == '__main__':
app.run(debug=True)
.. note:: The following commands are executed in a terminal on the same computer. Further work is required to fetch data in the react app.
GET request
------------
.. code-block:: bash
curl -i http://localhost:5000/homesensors/api/v1.0/sensor_data
POST request
------------
.. code-block:: bash
curl -i -H "Content-Type: application/json"
-X post -d '{"name": "dummyA",
"location": "garden",
"category": "dummyA",
"measurementType": "temp",
"value": 1500,
"dsCollected": "20171018T1000"}'
http://localhost:5000/homesensors/api/v1.0/sensor_data
<file_sep>React App: Building blocks
===========================
Aim
----
Create react app.
Summary
--------
By the end of this page you should have a bare bones react app ready for modification.
Uninstall node
---------------
.. note:: This step was required with an old OS I was using. I have included it here for my reference because I botched an install of node and npm that required sudo permissions. The fresh install did not come with node. Also note that update and upgrade is only required if you haven't started from the beginning of these docs.
.. code-block:: bash
# node
sudo apt-get remove node
# Drop node and npm from the following locations
# 1. /usr/local/lib/
# 2. /usr/local/include/
# 3. /opt/nodejs/lib/
# 4. /usr/local/bin
# update and upgrade
sudo apt-get update
sudo apt-get upgrade
sudo reboot
Install node and npm
-----------------------
.. code-block:: bash
# Node Version Manager (nvm)
git clone https://github.com/creationix/nvm.git ~/.nvm && cd ~/.nvm && git checkout v0.33.5
# edit files (add... source ~/.nvm/nvm.sh to the end of each file)
sudo nano ~/.bashrc
sudo nano ~/.profile
# Check NVM version
nvm --version
# check pi cpu etc
lscpu
# find appropriate version of node from nodejs.org/dist
nvm install 8.0.0
# Another step from botched install of node
nvm use --delete-prefix v8.0.0
# update
npm update -g npm
Install create-react-app
-------------------------
.. code-block:: bash
npm install -g create-react-app
Build app and run
------------------
.. code-block:: bash
# repos/homesensors
create-react-app reactapp
# Run
cd reactapp
npm start
<file_sep>#!python
from flask import Flask, jsonify, request, abort
from flask_sqlalchemy import SQLAlchemy
import json
app = Flask(__name__)
POSTGRES = {
'user': 'ray',
'pw': '<PASSWORD>',
'db': 'homesensors',
'host': 'localhost',
'port': '5432'
}
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://%(user)s:%(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
db = SQLAlchemy(app)
class HomeSensorData(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
location = db.Column(db.String(50))
category = db.Column(db.String(50))
measurementType = db.Column(db.String(50))
value = db.Column(db.Integer)
dsCollected = db.Column(db.String(30))
db.create_all()
def predictions(name, location, measurementType):
predictions = []
@app.route('/homesensors/api/v1.0/sensor_data', methods=['POST'])
def add_sensor_data():
"""
Adds data to postgres database.
Two core functions
--------------------
1) add the new data
2) update prediction model
Prediction model
-----------------
Hybrid model:
Create dataframe so that every record looks back n hours.
Create a target column by shifting the data forward,
so that the predictions are n hours into the future
"""
if not request.json or not 'value' in request.json:
abort(400)
#handle data obj
sendat = HomeSensorData(
name = request.json['name'],
location = request.json['location'],
category = request.json['category'], # actual or prediction
measurementType = request.json['measurementType'],
value = request.json['value'],
dsCollected = request.json['dsCollected']
)
# add new record
db.session.add(sendat)
# conditional checks for prediction updates
# 24 hours must have elapsed since last prediction
# Atleast 7 days of data (24*7=168 records)
# truncate old predictions
#HomeSensorData.query.filter(HomeSensorData.category=="pred",
# HomeSensorData.name==request.json['name']).delete()
# get "actual" data
actuals = HomeSensorData.query.filter(HomeSensorData.category=="actual",
HomeSensorData.name==request.json['name'])
# create pandas dataframe
# create rolling mean (4 hour window)
# create regular intervals (1 hour)
# create new columns and "shift" n hours (48 records for one day=48 cols)
# create a target column (shift(-24) hours)
# random forest prediction
# merge datestamp with predictions (now to 24 hours)
# create list of dictionaries with sensor data
# add all new predictions
# commit all changes include deletion and recreation of predictions
db.session.commit()
return "Record added successfully\n"
@app.route('/homesensors/api/v1.0/sensor_data', methods=['GET'])
def get_sensor_data():
sendat = HomeSensorData.query.all()
mylist = []
for u in sendat:
mydict = {}
for key, value in u.__dict__.items():
if key != "_sa_instance_state":
mydict[key] = value
mylist.append(mydict)
data = json.dumps({"data": mylist})
#print(data)
return data, 201
if __name__ == '__main__':
app.run(debug=True)
<file_sep>.. Garden Monitor documentation master file, created by
sphinx-quickstart on Tue Oct 24 05:22:39 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Garden Monitor documentation
==============================
This documentation covers the development process used to build my garden monitor. There are probably numerous projects like this already in existance and I would bet that they are more polished than this one. Even so, I like documenting my projects for fun so here it is. Enjoy.
Status
-------
Incomplete
.. toctree::
:maxdepth: 2
:caption: Contents:
/pages/summary
/pages/setup
/pages/docs
/pages/database
/pages/api
/pages/testdata
/pages/reactappBuildingBlocks
/pages/reactappConnection
/pages/reactappBootstrap
/pages/reactappChart
/pages/predictions
/pages/xbee
<file_sep>24 hour prediction
=====================
Aim
----
Summary
--------
.. image:: ../img/24hourpredictions_mobile.png
:width: 300
:align: center <file_sep>Temp files while dev'ing
| 52092381a521ee691b4ab304c7e7a322e8267bf8 | [
"JavaScript",
"Python",
"Markdown",
"reStructuredText"
]
| 19 | reStructuredText | rayblick/GardenMonitor | 38b0f785234eb89c46d3ff80e72bcae3af5d031d | 1dfb5a751f735fd31e79ca5fb9f242926ebfbde3 |
refs/heads/main | <repo_name>LilDataMonster/Blender-Lego-Dataset<file_sep>/fiftyone/Dockerfile
FROM python:3.9-slim
WORKDIR /root
RUN apt-get update -y && apt-get install -y ffmpeg libcurl4
RUN pip install fiftyone ipython torch torchvision tensorflow tensorflow-datasets
COPY fo_setup.py /root
CMD python fo_setup.py
<file_sep>/fiftyone/deploy.sh
#!/bin/bash
docker stack deploy -c fiftyone.yml fiftyone
<file_sep>/BlenderProc/parts/view_hdf5.sh
#!/bin/bash
cd /home/panda/LDraw/BlenderProc
python scripts/visHdf5Files.py ../Blender-Lego-Dataset/BlenderProc/parts/output/*.hdf5
<file_sep>/run_blender.sh
#!/bin/bash
blender --background --python multiple_model_import.py
<file_sep>/BlenderProc/MAS003_RUDY/camera_position_writer.py
import numpy as np
import pandas as pd
points = []
# list keypoints using [x, y, z, rotx, roty, rotz], num_interpolation_points
# where the the number of interpolation points are the number of points between
# the current and previous keypoints
keypoints = [
([0, -1, 3, 0.1, 0, 0], 0),
([0, -4, 3, 0.1, 0, 0], 30),
([-4, -4, 3, 0.1, 0, 0], 30),
([-4, -2, 3, 0.1, 0, 0], 30),
([-4, 3, 3, 0.1, 0, 0], 30),
([-4, 3, 3, 0.1, 0, 0], 30),
([3, 3, 3, 0.1, 0, 0], 30),
([5, 3, 3, 0.1, 0, 0], 30),
]
last_keypoint, _ = keypoints[0]
for key, interp_points in keypoints:
# handle first point (maybe just do enumerated index?)
if np.all(key == last_keypoint):
points.append(np.array(key))
last_keypoint = key
continue
# use linspace to evenly distribute between two arrays, a given number of points
# ignore the fist point as it will be a copy from the previous run
new_points = np.linspace(last_keypoint, key, interp_points)[1:]
last_keypoint = key
#print(new_points)
points.extend(new_points)
#print(points)
#print(np.shape(points))
df = pd.DataFrame(points)
df.to_csv('camera_positions1', sep=' ', index=False, header=False, float_format='%.3f')
print(df)
<file_sep>/BlenderProc/parts/run.sh
#!/bin/bash
cd /home/panda/LDraw/BlenderProc
for (( c=1; c<=10; c++ )); do
python run.py ../Blender-Lego-Dataset/BlenderProc/parts/config.yaml ../Blender-Lego-Dataset/BlenderProc/parts/camera_positions ../Blender-Lego-Dataset/BlenderProc/parts/generated_blend.blend resources/cctextures ../Blender-Lego-Dataset/BlenderProc/parts/output
done
<file_sep>/BlenderProc/MAS003_RUDY/main.py
import blenderproc as bproc
import argparse
import numpy as np
import os, re
parser = argparse.ArgumentParser()
parser.add_argument('camera', nargs='?', default="camera_positions", help="Path to the camera file")
parser.add_argument('scene', nargs='?', default="MAS003_RUDY.blend", help="Path to the scene.blend file")
parser.add_argument('cc_material_path', nargs='?', default="resources/cctextures", help="Path to CCTextures folder, see the /scripts for the download script.")
parser.add_argument('output_dir', nargs='?', default="output", help="Path to where the final files will be saved ")
args = parser.parse_args()
append_to_existing_output = True
bproc.init()
####################################
# load the objects into the scene
####################################
objs = bproc.loader.load_blend(args.scene)
# Make all spheres actively participate in the simulation
for obj in objs:
category_id = re.sub('^[0-9]+_', '', obj.get_name())
category_id = re.sub('.dat', '', category_id)
category_id = re.sub('b', '', category_id) # remove 'b'
print(f'Setting {obj.get_name()} to category {category_id}')
obj.set_cp("category_id", category_id)
obj.enable_rigidbody(active=True)
# print(dir(obj))
####################################
# Define a light
####################################
print('Setting up lighting')
light = bproc.types.Light()
light.set_type("POINT")
# Sample its location in a shell around the point [0, 0, 0]
light.set_location(bproc.sampler.shell(
center=[-3, 0, 0],
radius_min=5,
radius_max=9,
elevation_min=20,
elevation_max=89
))
light.set_energy(200)
####################################
# Define a light
####################################
print('Setting up lighting')
lightr = bproc.types.Light()
lightr.set_type("POINT")
# Sample its location in a shell around the point [0, 0, 0]
lightr.set_location(bproc.sampler.shell(
center=[3, 0, 0],
radius_min=5,
radius_max=9,
elevation_min=20,
elevation_max=89
))
lightr.set_energy(200)
####################################
# define the camera intrinsics
####################################
print('Setting up camera')
bproc.camera.set_resolution(1280, 720)
bproc.camera.set_intrinsics_from_blender_params(lens=2, lens_unit='FOV')
# read the camera positions file and convert into homogeneous camera-world transformation
with open(args.camera, "r") as f:
for line in f.readlines():
line = [float(x) for x in line.split()]
position, euler_rotation = line[:3], line[3:6]
matrix_world = bproc.math.build_transformation_mat(position, euler_rotation)
bproc.camera.add_camera_pose(matrix_world)
####################################
# load all recommended cc materials
####################################
print('Setting up materials')
cc_used_assets = ["Bricks", "Wood", "Carpet", "Tile", "Marble","Fabric",
"Ground", "Rock", "Metal", "Concrete", "Leather", "Gravel",
"Asphalt", "Plank", "Terrazzo", "Paint", "Carpet", "Plastic",
"Plaster", "Scratch", "Cardboard", "Clay", "Grass", "Moss",
"Chipboard", "Foam", "Paper", "Porcelain", "Sponge", ]
cc_textures = bproc.loader.load_ccmaterials(args.cc_material_path,
used_assets=cc_used_assets)
####################################
# create the ground
####################################
print('Setting up ground plane')
random_cc_texture = np.random.choice(cc_textures)
ground_plane = bproc.object.create_primitive('PLANE', scale=[10, 6, 1])
ground_plane.replace_materials(random_cc_texture)
# The ground should only act as an obstacle and is therefore marked passive.
# To let the spheres fall into the valleys of the ground, make the collision shape MESH instead of CONVEX_HULL.
ground_plane.enable_rigidbody(active=False, collision_shape="MESH")
####################################
# sample objects ontop of surface
####################################
print('Setting up object positioning')
# define a function that samples the initial pose of a given object above the ground
def sample_initial_pose(obj: bproc.types.MeshObject):
obj.set_location(bproc.sampler.upper_region(objects_to_sample_on=ground_plane,
min_height=1, max_height=2))#, face_sample_range=[0.4, 0.6]))
# obj.set_location(np.random.uniform([-2.5, -1.5, -0.2], [2.5, 1.5, 0.2]))
obj.set_rotation_euler(np.random.uniform([0, 0, 0], [np.pi, np.pi, np.pi]))
# sample objects on the given surface
placed_objects = bproc.object.sample_poses_on_surface(objects_to_sample=objs,
surface=ground_plane,
sample_pose_func=sample_initial_pose,
min_distance=0.8,
max_distance=5)
####################################
# physics positioning
####################################
print('Setting up simulated physics')
bproc.object.simulate_physics_and_fix_final_poses(min_simulation_time=2,
max_simulation_time=20,
check_object_interval=1,
substeps_per_frame = 20,
solver_iters=25)
####################################
# Render
####################################
print('Setting up render')
# activate distance rendering and set amount of samples for color rendering
# bproc.renderer.enable_distance_output()
# bproc.renderer.enable_normals_output()
bproc.renderer.set_samples(400)
# render the whole pipeline
data = bproc.renderer.render()
# Render segmentation masks (per class and per instance)
seg_data = bproc.renderer.render_segmap(map_by=["class", "instance"])
data.update(seg_data)
# # Convert distance to depth
# data["depth"] = bproc.postprocessing.dist2depth(data["distance"])
# del data["distance"]
####################################
# write data
####################################
print('Setting up file saves')
# # write the data to a .hdf5 container
# bproc.writer.write_hdf5(args.output_dir,
# data,
# append_to_existing_output=append_to_existing_output)
# Write data to coco file
bproc.writer.write_coco_annotations(os.path.join(args.output_dir, 'coco_data'),
instance_segmaps=seg_data["instance_segmaps"],
instance_attribute_maps=seg_data["instance_attribute_maps"],
colors=data["colors"],
color_file_format="JPEG",
append_to_existing_output=append_to_existing_output,
jpg_quality=100)
<file_sep>/BlenderProc/MAS003_RUDY/clean_import.py
import bpy, os, re
import numpy as np
ldr_file = 'MAS003_RUDY.ldr'
ldr_path = os.path.join(os.getcwd(), ldr_file)
import_ldraw_file = 'importldraw1.1.11_for_blender_281.zip'
import_ldraw_path = os.path.join(os.getcwd(), import_ldraw_file)
output_file = ldr_file.replace('.ldr', '.blend')
output_path = os.path.join(os.getcwd(), output_file)
# install LDraw Addon for importing Lego Models
bpy.ops.preferences.addon_install(filepath=import_ldraw_path, overwrite=True)
bpy.ops.preferences.addon_enable(module="io_scene_importldraw")
bpy.ops.wm.save_userpref()
# import model
bpy.ops.import_scene.importldraw(filepath=ldr_path, ldrawPath="/home/panda/LDraw/ldraw/")
# remove lego ground plane
bpy.context.collection.objects['LegoGroundPlane']
plane = bpy.context.active_object
bpy.ops.object.delete()
bpy.data.materials.remove( bpy.data.materials['Mat_LegoGroundPlane'])
# remove parent object and links
objects = bpy.data.objects
#objects.remove(objects['00000_' + ldr_file], do_unlink=True)
for obj in objects:
if not obj.name.endswith('.dat'):
print(f'Removing {obj.name}')
objects.remove(obj, do_unlink=True)
# remove custom parts
custom_parts = ['00160_m898c3b67_202136_062848.dat', '00161_m898c3b67_202136_062819.dat']
for parts in custom_parts:
print(f'Removing custom parts: {parts}')
objects.remove(objects[parts])
## select random pieces from set
#rng = np.random.default_rng()
#keep_obj = rng.choice(objects, 60, replace=False)
#for obj in objects:
# if obj not in keep_obj:
# print(f'Pruning objects, removing {obj.name}')
# objects.remove(obj, do_unlink=True)
# remove all lights
lights = bpy.data.lights
for light in lights:
lights.remove(light)
# remove all cameras
cameras = bpy.data.cameras
for camera in cameras:
cameras.remove(camera)
# create handle to all lego pieces
lego_pieces = [obj for obj in objects]
# add camera to scene
scene = bpy.context.scene
#scene.camera = cam
scene.render.image_settings.file_format='PNG'
# set render engine
scene.render.engine = 'CYCLES'
scene.cycles.device = 'GPU'
scene.cycles.use_denoising = True
#scene.cycles.denoiser = 'OPENIMAGEDENOISE'
scene.cycles.denoiser = 'OPTIX'
scene.cycles.use_preview_denoising = True
## render scene
#scene.render.filepath=f'output.png'
#bpy.ops.render.render(write_still=1)
# make single user
bpy.ops.object.make_single_user(type='ALL', object=True, obdata=True, material=False, animation=False)
# save blend file
bpy.ops.wm.save_as_mainfile(filepath=output_path)
# list classes
print('Class List')
classes = []
for obj in objects:
n0 = re.sub('^[0-9]+_', '', obj.name)
name = re.sub('.dat', '', n0)
if name not in classes:
classes.append(name)
for cl in sorted(classes, key=lambda x: int(re.sub('[A-Za-z_]', '', x))):
print(cl)
<file_sep>/BlenderProc/MAS003_RUDY/mount_s3.sh
#!/bin/bash
s3fs blender-rudy-set `pwd`/output -o passwd_file=./passwd-s3fs -o url=https://s3.wasabisys.com -o allow_other
<file_sep>/BlenderProc/MAS003_RUDY/run.sh
#!/bin/bash
CONFIG_PATH=`pwd`
#BLENDER_PROC_PATH=/home/panda/LDraw/BlenderProc
BLEND_FILE=MAS003_RUDY.blend
#cd $BLENDER_PROC_PATH
NUM_IMAGES=5000
#NUM_IMAGES=2
for (( c=0; c<$NUM_IMAGES; c++ )); do
#python run.py $CONFIG_PATH/config.yaml $CONFIG_PATH/camera_positions $CONFIG_PATH/$BLEND_FILE resources/cctextures $CONFIG_PATH/output
blender --background --python clean_import.py
blenderproc run main.py
done
<file_sep>/BlenderProc/docker/Dockerfile
FROM python:3.9-buster
ARG DEBIAN_FRONTEND noninteractive
ARG TZ America/New_York
USER root
ENV USER=root
RUN apt-get update -y && apt-get install -y ffmpeg libxi-dev libxxf86vm-dev libgl-dev &&\
pip install blenderproc numpy ffmpeg-python pandas && echo "import blenderproc; blenderproc.init()" > test.py
RUN blenderproc run test.py && rm -rf /var/lib/apt/lists/* && rm test.py
CMD ["blenderproc", "run"]
<file_sep>/BlenderProc/parts/fo_setup.py
import fiftyone as fo
# A name for the dataset
name = "lego"
# The directory containing the dataset to import
dataset_dir = "/home/panda/LDraw/Blender-Lego-Dataset/BlenderProc/lego/output/"
#dataset_dir = "/home/panda/LDraw/Blender-Lego-Dataset/BlenderProc/lego/output/coco_data/"
#labels_path = "/home/panda/LDraw/Blender-Lego-Dataset/BlenderProc/lego/output/coco_annotations.json"
labels_path = "/home/panda/LDraw/Blender-Lego-Dataset/BlenderProc/lego/output/coco_data/coco_annotations.json"
# The type of the dataset being imported
dataset_type = fo.types.COCODetectionDataset # for example
dataset = fo.Dataset.from_dir(
dataset_dir=dataset_dir,
dataset_type=dataset_type,
labels_path=labels_path,
name=name,
)
session = fo.launch_app(dataset)
session.wait()
<file_sep>/BlenderProc/parts/debug.sh
#!/bin/bash
cd /home/panda/LDraw/BlenderProc
python run.py --debug ../Blender-Lego-Dataset/BlenderProc/parts/config.yaml ../Blender-Lego-Dataset/BlenderProc/parts/camera_positions ../Blender-Lego-Dataset/BlenderProc/parts/generated_blend.blend resources/cctextures ../Blender-Lego-Dataset/BlenderProc/parts/output
<file_sep>/helloworld.py
import bpy, os
# install LDraw Addon for importing Lego Models
p = os.path.abspath("importldraw1.1.11_for_blender_281.zip")
bpy.ops.preferences.addon_install(filepath=p, overwrite=True)
bpy.ops.preferences.addon_enable(module="io_scene_importldraw")
bpy.ops.wm.save_userpref()
bpy.ops.import_scene.importldraw(filepath="/home/panda/LDraw/4x1.ldr", ldrawPath="/home/panda/LDraw/ldraw/")
bpy.context.collection.objects['LegoGroundPlane']
plane = bpy.context.active_object
bpy.ops.object.delete()
# add ground plane
bpy.ops.mesh.primitive_plane_add(size=50)
plane = bpy.context.active_object
##
# adding objects using bpy.ops library will automatically
# link it to the collection
##
# create light source
# other types of light sources:
# https://docs.blender.org/manual/en/latest/render/lights/light_object.html#light-objects
light_data = bpy.data.lights.new('light', type='POINT')
light = bpy.data.objects.new('light', light_data)
bpy.context.collection.objects.link(light)
# light location and energy
light.location = (3, 4, -5)
light.data.energy = 200.0
# we first create the camera object
cam_data = bpy.data.cameras.new('camera')
cam = bpy.data.objects.new('camera', cam_data)
bpy.context.collection.objects.link(cam)
cam.location=(0, 0, 20)
# add camera to scene
scene = bpy.context.scene
scene.camera = cam
scene.render.image_settings.file_format='PNG'
# set render engine
scene.render.engine = 'CYCLES'
scene.cycles.device = 'GPU'
scene.cycles.use_denoising = True
scene.cycles.denoiser = 'OPENIMAGEDENOISE'
# render scene
scene.render.filepath=f'output.png'
bpy.ops.render.render(write_still=1)
print("hello World")
<file_sep>/BlenderProc/MAS003_RUDY/white_bg.py
import blenderproc as bproc
import argparse
import numpy as np
import os, re
parser = argparse.ArgumentParser()
parser.add_argument('camera', nargs='?', default="camera_positions", help="Path to the camera file")
parser.add_argument('scene', nargs='?', default="MAS003_RUDY.blend", help="Path to the scene.blend file")
parser.add_argument('cc_material_path', nargs='?', default="resources/cctextures", help="Path to CCTextures folder, see the /scripts for the download script.")
parser.add_argument('--set', nargs='?', default="train", help="Sub directory to save coco annotations")
parser.add_argument('--num_repeats', nargs='?', type=int, default=1, help="Number of repeats")
parser.add_argument('output_dir', nargs='?', default="output", help="Path to where the final files will be saved")
args = parser.parse_args()
append_to_existing_output = True
bproc.init()
####################################
# load the objects into the scene
####################################
objs = bproc.loader.load_blend(args.scene)
# Make all spheres actively participate in the simulation
for obj in objs:
category_id = re.sub('^[0-9]+_', '', obj.get_name())
category_id = re.sub('.dat', '', category_id)
category_id = re.sub('b', '', category_id) # remove 'b'
print(f'Setting {obj.get_name()} to category {category_id}')
obj.set_cp("category_id", category_id)
obj.enable_rigidbody(active=True)
# print(dir(obj))
####################################
# Define a light
####################################
print('Setting up lighting')
light = bproc.types.Light()
light.set_type("POINT")
# Sample its location in a shell around the point [0, 0, 0]
light.set_location(bproc.sampler.shell(
center=[
np.random.uniform(-1,1),
np.random.uniform(-1,1),
10,
],
radius_min=0,
radius_max=10,
elevation_min=10,
elevation_max=20
))
light.set_energy(4000)
#####################################
## Define a light
#####################################
#print('Setting up lighting')
#lightr = bproc.types.Light()
#lightr.set_type("POINT")
## Sample its location in a shell around the point [0, 0, 0]
#lightr.set_location(bproc.sampler.shell(
# center=[1.5, 0, 0],
# radius_min=30,
# radius_max=50,
# elevation_min=55,
# elevation_max=89
#))
#lightr.set_energy(15000)
####################################
# define the camera intrinsics
####################################
print('Setting up camera')
bproc.camera.set_resolution(1280, 720)
bproc.camera.set_intrinsics_from_blender_params(lens=2, lens_unit='FOV')
####################################
# load all recommended cc materials
####################################
print('Setting up materials')
cc_used_assets = ["Tile", "Fabric", "Concrete",
"Paint", "Plastic",
"Plaster", "Paper", "Porcelain" ]
cc_textures = bproc.loader.load_ccmaterials(args.cc_material_path,
used_assets=cc_used_assets)
####################################
# create the ground
####################################
print('Setting up ground plane')
ground_plane = bproc.object.create_primitive('PLANE', scale=[8, 8, 1])
# The ground should only act as an obstacle and is therefore marked passive.
# To let the spheres fall into the valleys of the ground, make the collision shape MESH instead of CONVEX_HULL.
ground_plane.enable_rigidbody(active=False, collision_shape="MESH")
# define a function that samples the initial pose of a given object above the ground
def sample_initial_pose(obj: bproc.types.MeshObject):
obj.set_location(bproc.sampler.upper_region(objects_to_sample_on=ground_plane,
min_height=1, max_height=2))#, face_sample_range=[0.4, 0.6]))
# obj.set_location(np.random.uniform([-2.5, -1.5, -0.2], [2.5, 1.5, 0.2]))
obj.set_rotation_euler(np.random.uniform([0, 0, 0], [np.pi, np.pi, np.pi]))
for _ in range(args.num_repeats):
## reset
bproc.utility.reset_keyframes()
# read the camera positions file and convert into homogeneous camera-world transformation
with open(args.camera, "r") as f:
for line in f.readlines():
line = [float(x) for x in line.split()]
position, euler_rotation = line[:3], line[3:6]
matrix_world = bproc.math.build_transformation_mat(position, euler_rotation)
bproc.camera.add_camera_pose(matrix_world)
# texture ground plane
random_cc_texture = np.random.choice(cc_textures)
ground_plane.replace_materials(random_cc_texture)
####################################
# sample objects ontop of surface
####################################
print('Setting up object positioning')
# sample objects on the given surface
placed_objects = bproc.object.sample_poses_on_surface(objects_to_sample=objs,
surface=ground_plane,
sample_pose_func=sample_initial_pose,
min_distance=0.8,
max_distance=5)
####################################
# physics positioning
####################################
print('Setting up simulated physics')
bproc.object.simulate_physics_and_fix_final_poses(min_simulation_time=2,
max_simulation_time=20,
check_object_interval=1,
substeps_per_frame = 20,
solver_iters=25)
####################################
# Render
####################################
print('Setting up render')
# activate distance rendering and set amount of samples for color rendering
# bproc.renderer.enable_distance_output()
# bproc.renderer.enable_normals_output()
bproc.renderer.set_samples(400)
# render the whole pipeline
data = bproc.renderer.render()
# Render segmentation masks (per class and per instance)
seg_data = bproc.renderer.render_segmap(map_by=["class", "instance"])
data.update(seg_data)
# # Convert distance to depth
# data["depth"] = bproc.postprocessing.dist2depth(data["distance"])
# del data["distance"]
####################################
# write data
####################################
print('Setting up file saves')
# # write the data to a .hdf5 container
# bproc.writer.write_hdf5(args.output_dir,
# data,
# append_to_existing_output=append_to_existing_output)
# Write data to coco file
bproc.writer.write_coco_annotations(os.path.join(args.output_dir, args.set),
instance_segmaps=seg_data["instance_segmaps"],
instance_attribute_maps=seg_data["instance_attribute_maps"],
colors=data["colors"],
color_file_format="JPEG",
append_to_existing_output=append_to_existing_output,
jpg_quality=100)
<file_sep>/BlenderProc/MAS003_RUDY/run_white.sh
#!/bin/bash
CONFIG_PATH=`pwd`
#BLENDER_PROC_PATH=/home/panda/LDraw/BlenderProc
BLEND_FILE=MAS003_RUDY.blend
#cd $BLENDER_PROC_PATH
NUM_IMAGES=5000
#NUM_IMAGES=2
for (( c=0; c<$NUM_IMAGES; c++ )); do
blenderproc run white_bg.py
done
<file_sep>/BlenderProc/MAS003_RUDY/stitch_frames.py
import ffmpeg
(
ffmpeg
.input('output/coco_data_vid0/images/*.jpg', pattern_type='glob', framerate=10)
#.filter('deflicker', mode='pm', size=10)
#.filter('scale', size='hd1080', force_original_aspect_ratio='increase')
#.output('movie.mp4', crf=20, preset='slower', movflags='faststart', pix_fmt='yuv420p')
#.filter("minterpolate='mi_mode=mci:mc_mode=aobmc:vsbmc=1'")
.filter("minterpolate", mi_mode="mci", mc_mode="aobmc", vsbmc=1)
.output('movie.mp4', crf=20, preset='slower', pix_fmt='yuv420p', vcodec='h264')
#.overwrite_output()
#.view(filename='filter_graph')
.run()
)
<file_sep>/BlenderProc/parts/multi_run.sh.old
#!/bin/bash
cd /home/panda/LDraw/BlenderProc
python rerun.py ../Blender-Lego-Dataset/BlenderProc/parts/config.yaml ../Blender-Lego-Dataset/BlenderProc/parts/camera_positions ../Blender-Lego-Dataset/BlenderProc/parts/generated_blend.blend resources/cctextures ../Blender-Lego-Dataset/BlenderProc/parts/output
<file_sep>/fiftyone/fo_setup.py
import fiftyone as fo
import os
# A name for the dataset
name = os.environ['NAME']
# The directory containing the dataset to import
dataset_dir = os.environ['DATASET_DIR']
labels_path = os.environ['LABELS_PATH']
# The type of the dataset being imported
dataset_type = fo.types.COCODetectionDataset # for example
dataset = fo.load_dataset(name) if name in fo.list_datasets() else fo.Dataset.from_dir(dataset_dir=dataset_dir, dataset_type=dataset_type, labels_path=labels_path, name=name)
session = fo.launch_app(dataset, remote=True)
#session = fo.launch_app(remote=True)
port = os.environ['FIFTYONE_DEFAULT_APP_PORT']
print(f'Session started on port {port}')
session.wait()
| fae0f0498f4e887dc1a399140b05b29b17dad61d | [
"Python",
"Dockerfile",
"Shell"
]
| 19 | Dockerfile | LilDataMonster/Blender-Lego-Dataset | 6c0d6e7aaa9900b5bd8114244fe4dd899cbf2f83 | 224d916797d75e817a558a7bc523a6c0f76a5e36 |
refs/heads/master | <repo_name>Gregawa/durf<file_sep>/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
Index
<br>
<!--
<a href="inscription.php">S'inscrire</a>
<a href="connexion.php">Connexion</a>
-->
<a href="boutique.php">Boutique</a>
<br><br>
<form action="" method="GET">
<input id="search" name="keywords" type="text" placeholder="Nom du produit">
<input id="submit" type="submit" value="Rechercher">
</form>
<?php
//$bdd = new PDO('mysql:host=localhost;dbname=durf', 'root', '');
?>
<?php
//Connection à la bdd
$connection = mysql_connect("localhost","root","");
mysql_select_db("durf")or die(mysql_error());
//Fin de la Connection
$keywords = isset($_GET['keywords']) ? '%'.$_GET['keywords'].'%' : '';
$result = mysql_query("SELECT name FROM products where name like '$keywords'");
while ($row = mysql_fetch_assoc($result))
{
echo "<div id='link' onClick='addText(\"".$row['name']."\");'>" . $row['name'] . "</div>";
}
?>
<?php
session_start();
if (isset($_SESSION['id'])){
echo "<a href='profil.php?&id=".$_SESSION["id"]."'>Profil</a>";
echo '
<a href="deconnexion.php">Déconnexion</a>
';
}
else{
echo '
<a href="inscription.php">Inscription</a>
';
echo '
<a href="connexion.php">Connexion</a>
';
}
?>
<br><br>
</body>
</html><file_sep>/connexion.php
<!doctype html>
<html lang="fr">
<head>
<link rel="icon" type="image/gif" href="img/favicon.png">
<link rel="stylesheet" type="text/css" href="css.css">
<title>C'est Vous-Connexion</title>
<meta charset="UTF-8">
</head>
<body>
<a href="index.php">Accueil</a>
<header>
<?php
session_start(); //permet d'utiliser les "$_SESSION"
if (isset($_GET['msg'])){
echo "Compte crée";
}
/*$bdd = new PDO('mysql:host=sqletud.u-pem.fr;dbname=gcolombe_db', 'gcolombe', 'philippe');*/
$bdd = new PDO('mysql:host=localhost;dbname=durf', 'root', '');
/* Charge le fichier config en fonction de si on charge fichier en local ou pas */
/* if (file_exists('config-local.php')){
include 'config-local.php';
}
else{
include('config.php');
}*/
if (isset($_POST['formConnexion']))
{
$emailConnect = htmlspecialchars(addslashes($_POST['emailConnect']));
$mdpConnect = sha1($_POST['mdpConnect']);
$UserEtudiant=0;
if (!empty($emailConnect) AND !empty($mdpConnect))
{
// echo "<br> userExist = ".$userEtudiantExist." !";
$reqUser=$bdd->prepare("SELECT * FROM user WHERE mail = ? AND mdp=? ");
$reqUser->execute(array($emailConnect, $mdpConnect));
$userEtudiantExist=$reqUser->rowCount();
if($userEtudiantExist == 1){
$userInfo = $reqUser->fetch();
$_SESSION['id'] = $userInfo['id'];
$_SESSION['nom'] = $userInfo['nom'];
$_SESSION['mail'] = $userInfo['mail'];
/*header("Location: profil.php?id=".$_SESSION['id']);//redirige vers le profil de la personne selon l'id*/
header("Location: index.php?id=".$_SESSION['id']);
}
else
{
$erreur="Mauvais email ou mot de passe";
}
}
else
{
$erreur="Tout les champs doivent etre complétés ! ";
}
}
?>
<div class="wrapper">
<?php
echo "<a href='index.php'><img src='Images/imgNeutre.png' width='230px'></a><br><br>";
?>
</div>
</header>
<div class="zoneConnexion pageconnexion">
<form method="POST" action="">
<label>Email</label>
<input type="email" name="emailConnect" placeholder="Email" />
<label>Mot de passe</label>
<input type="<PASSWORD>" name="mdpConnect" placeholder="<PASSWORD>"/>
<input type="submit" class="button"name="formConnexion" value="Connexion"/>
<p class="message">Vous n'ètes pas enregistré. <a class="lien message" href="inscription.php">Creer un compte</a></p>
</form>
</div>
<?php
if (isset($erreur))
{
echo '<font color="red">'.$erreur.'</font>';
}
?>
</body>
</html>
<file_sep>/profil.php
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<link rel="icon" type="image/gif" href="img/favicon.png">
<link rel="stylesheet" type="text/css" href="css.css">
<title>C'est Vous-Profil</title>
</head>
<body>
<?php
session_start(); //permet d'utiliser les "$_SESSION" (la on les recupere)
$bdd = new PDO('mysql:host=localhost;dbname=durf', 'root', '');
/* Charge le fichier config en fonction de si on charge fichier en local ou pas */
/* if (file_exists('config-local.php')){
include 'config-local.php';
}
else{
include('config.php');
}*/
/*$bdd = new PDO('mysql:host=sqletud.u-pem.fr;dbname=gcolombe_db', 'gcolombe', 'philippe');*/
?>
<?php
if(isset($_SESSION['id'])){
// si etudiant afficher le profil d'un étudiant
/*echo "<a href='accueilEtudiant.php?type=".$_GET["type"]."&id=".$_SESSION["id"]."'><img src='Images/imgEtudiant.png' width='230px'></a><br><br>"; */
$getId = intval($_GET['id']); //convertit en nombre
$reqUser = $bdd->prepare('SELECT * FROM user WHERE id = ?');
$reqUser->execute(array($getId));
$userInfo = $reqUser->fetch();
if(isset($_GET['id']) AND $_GET['id'] > 0 )
{
?>
Votre nom :<br><br>
<?php echo $userInfo['nom']; ?><br><br>
Votre E-mail :<br><br>
<?php echo $userInfo['mail']; ?><br>
<?php
}
?>
<?php
if (isset($_SESSION['id']) AND $userInfo['id'] == $_SESSION['id'])
{
echo "<br><br><br>";
}
?>
<?php
?>
<?php
}
else{
header("Location: connexion.php");
}
?>
</body>
</html>
<file_sep>/boutique.php
<?php
require 'db.class.php';
$DB = new DB();
?>
<?php
//var_dump();
//$DB->query('SELECT * FROM products')
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
La boutique <br><br>
<!-- Search Box -->
<body>
<form action="" method="GET">
<input id="search" name="keywords" type="text" placeholder="Nom du produit">
<input id="submit" type="submit" value="Rechercher">
</form>
</body>
<?php
$connection = mysql_connect("localhost","root","");
mysql_select_db("durf")or die(mysql_error());
$keywords = isset($_GET['keywords']) ? '%'.$_GET['keywords'].'%' : '';
$result = mysql_query("SELECT name FROM products WHERE name like '$keywords'");
while ($row = mysql_fetch_assoc($result)) {
echo "<div id='link' onClick='addText(\"".$row['name']."\");'>" . $row['name'] . "</div><div>
<img src='img/test.jpg' alt='' height='150' width='150'></div>";
echo "ttt";
echo $row['img'];
//$resultImg = mysql_query("SELECT img FROM products ");
//while ($row = mysql_fetch_assoc($resultImg)) {
// echo '<img src="img/'.$resultImg.'" alt="" >';
//$img=mysql_query("SELECT img FROM products where name like '$keywords'");
//var_dump(img);
}
?>
<!-- Fin de la Search Box -->
<?php
//Ajout au panier
//Fin Ajout au panier
?>
</body>
</html><file_sep>/inscription.php
<!doctype html>
<html lang="fr">
<head>
<link rel="icon" type="image/gif" href="img/favicon.png" >
<link rel="stylesheet" type="text/css" href="css.css">
<style>
@import url('https://fonts.googleapis.com/css?family=Roboto');
</style>
<title>Inscription</title>
<meta charset="UTF-8">
</head>
<body>
<?php
/*$bdd = new PDO('mysql:host=localhost;dbname=cv', '', '');*/
/* Charge le fichier config en fonction de si on charge fichier en local ou pas */
/*if (file_exists('config-local.php')){
include 'config-local.php';
}
else{
include('config.php');
}*/
//Ancienne BDD
/*
$bdd = new PDO('mysql:host=localhost;dbname=durf', 'root', '');
*/
$bdd = new PDO('mysql:host=localhost;dbname=durf', 'root', '');
if(isset($_POST['submit']))
{
/*
$fichier = basename($_FILES['image']['name']);
$taille_maxi = 5900000;
$taille = filesize($_FILES['image']['tmp_name']);
$extensions = array('.png', '.gif', '.jpg', '.jpeg');
$extension = strrchr($_FILES['image']['name'], '.');
*/
$nom=htmlspecialchars(addslashes($_POST['nom']));
$prenom=htmlspecialchars(addslashes($_POST['prenom']));
$mdp=sha1($_POST['mdp']); //floutte le mdp
$mdp2=sha1($_POST['mdp2']); //floutte le mdp2
$email=htmlspecialchars(addslashes($_POST['email']));
//$image=$_FILES['image'];
/*$image = implode(', ', $_FILES['image']);*/
/*header("Location: connexion.php?msg");*/
if(
!empty($_POST['nom'])AND
!empty($_POST['prenom'])AND
!empty($_POST['mdp'])AND!empty($_POST['mdp2'])AND
!empty($_POST['email']))
{
$nomlength= strlen($nom);
if ($nomlength <= 30) //Plus de 30 caracteres ?
{
if(filter_var($email, FILTER_VALIDATE_EMAIL)) //Email validée ?
{
$reqnom=$bdd->prepare("SELECT * FROM user WHERE nom=?");
$reqnom->execute(array($nom));
$nomExist=$reqnom->rowCount();
if($nomExist == 0) //Nom deja utilisée ?
{
$reqmail=$bdd->prepare("SELECT * FROM user WHERE mail=?");
$reqmail->execute(array($email));
$emailExist=$reqmail->rowCount();
if($emailExist == 0) //Email deja utilisée ?
{
if($mdp == $mdp2) //Les mots de passe correspondent ?
{
/*
//Début des vérifications de sécurité...
if(!in_array($extension, $extensions)) //Si l'extension n'est pas dans le tableau
{
$erreur = 'Vous devez uploader un fichier de type png, gif, jpg, jpeg, txt ou doc...';
}
if($taille>$taille_maxi)
{
$erreur = 'Le fichier est trop gros...';
}
if(!isset($erreur)) //S'il n'y a pas d'erreur, on upload
{
//On formate le nom du fichier ici...
$fichier = strtr($fichier,
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$fichier = preg_replace('/([^.a-z0-9]+)/i', '-', $fichier);
if(move_uploaded_file($_FILES['image']['tmp_name'], $fichier)) //Si la fonction renvoie TRUE, c'est que ça a fonctionné...
{
/*echo 'Upload effectué avec succès !';
echo "<src img='-7A1F27D4A2F5CB1A5DB407AB1475F24BB47165BEBA48152077-pimgpsh-thumbnail-win-distr.jpg'>";
echo '<br><br><br><img src='.$fichier.'>';*/
$insertMembre=$bdd->prepare ("INSERT INTO user(nom,prenom,mdp,mail) VALUES(?,?,?,?)");
$insertMembre->execute(array($nom,$prenom,$mdp,$email));
//var_dump($image);
//header("Location: connexion.php?msg");
$pasErreur="Votre compte a bien été crée !<br> <a href=\"connexion.php\" class='retourAccueil'>Me connecter</a>";
//echo $fichier;
/*
}
else //Sinon (la fonction renvoie FALSE).
{
echo 'Echec de l\'upload !';
}
}
else
{
echo $erreur;
}
*/
}
else
{
$erreur="Les mots de passe ne correspondent pas !";
}
}
else
{
$erreur="Adresse mail déjà utilisée !";
}
}
else
{
$erreur="Ce Nom est déjà utilisée !";
}
}
else
{
$erreur="Votre adresse mail n'est pas valide !";
}
}
else
{
$erreur= "Votre Nom ne doit pas dépasser 30 caractères !";
}
}
else
{
$erreur="Tout les champs doivent etre complétés !";
}
}
?>
<header>
<div class="wrapper">
<a href=index.php><img class="image" src="Images/C'EST%20VOUS.png" alt=""></a>
</div>
</header>
<div class="inscription">
<div class="formE">
<form class="login-form" method="POST" action="" enctype="multipart/form-data" >
<!--<p class="message">Vous ètes <a>ÉTUDIANT</a></p>-->
<label>Nom</label>
<input type="text" placeholder="Votre nom" name="nom" id="nom" value="<?php if(isset($nom))
{
echo $nom; //laisser ce que l'utilisateur a ecrit
}?>" />
<label>Prénom</label>
<input type="text" placeholder="Votre prenom" name="prenom" id="prenom" value="<?php if(isset($prenom))
{
echo $prenom; //laisser ce que l'utilisateur a ecrit
}?>" />
<!--<label for="dateNaissance">Date de naissance</label>-->
<!--<input type="hidden" name="MAX_FILE_SIZE" value="90000000">-->
<label>Email</label>
<input type="Email" placeholder="Votre Email" name="email" id="email" value="<?php if(isset($email))
{
echo $email; //laisser ce que l'utilisateur a ecrit
}?>"/>
<!--<label for="image">Photo de profil</label>
<input type="file" name="image" id="image"/>-->
<label>Mot de passe</label>
<input type="<PASSWORD>" placeholder="<PASSWORD>" name="mdp" id="mdp"/>
<label>Confirmation mot de passe</label>
<input type="<PASSWORD>" placeholder="<PASSWORD> votre mot de passe" name="mdp2" id="mdp2"/>
<input class="button" type="submit" name="submit" value="Inscription">
</form>
</div>
<!-- RECRUTEURS : -->
<!-- Inscription recruteur-->
</div>
<br><br>
<div align="center">
<?php
if (isset($erreur))
{
echo '<div class="formERREUR ">
<form class="login-formERREUR ">
<p class="message"><a>ERREUR</a></p>
<p class="message1">'.$erreur.'</p>
</form>
</div>';
}
if (isset($pasErreur))
{
echo '<div class="formVALIDATION">
<form class="login-formVALIDATION">
<p class="message"><a>VALIDATION</a></p>
<p class="message1">'.$pasErreur.'</p>
</form>
</div>';
}
?>
</div>
</body>
<style>
/*
.login-formVALIDATION {
width: 100%;
padding: 8% 0 0;
margin: auto;
}
.formVALIDATION {
display: flex;
z-index: 1;
background: #FFFFFF;
max-width: 360px;
margin: 0 auto 10px;
padding: 0px;
text-align: center;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
margin-top: 155vh;
z-index: 999;
margin-bottom: 20vh;
}
.formVALIDATION button:hover,.formVALIDATION button:active,.formVALIDATION button:foscus {
background-color: dimgray;
transition-duration: 0.3s;
}
.formVALIDATION .message {
margin: 15px 0 0;
margin-top: 0%;
}
.formVALIDATION .message a {
color: green;
text-decoration: none;
font-size:2.5em;
}
.formVALIDATION .message a:hover{color: grey;
transition-duration: 0.3s;}
.formVALIDATION .message a: {transition-duration: 0.3s;}
.formVALIDATION .message::selection {
background-color: grey;
}
.formVALIDATION .message a::selection {
background-color: grey;
}
.formVALIDATION .retour a{
color: green;
text-decoration: none;
font-size:1em;
transition-duration: 0.5s;
}
.formVALIDATION .retour a:hover{
color: grey;
cursor: pointer;
transition-duration: 0.5s;
}
.formVALIDATION .message1{font-size: 1rem;
color: grey;
margin-bottom: 30px;}
.login-formERREUR {
width: 100%;
padding: 8% 0 0;
margin: auto;
}
.formERREUR {
display: flex;
z-index: 1;
background: #FFFFFF;
max-width: 360px;
margin: 0 auto 10px;
padding: 0px;
text-align: center;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
margin-top: 155vh;
z-index: 999;
margin-bottom: 20vh;
}
.formERREUR button:hover,.formERREUR button:active,.formERREUR button:foscus {
background-color: dimgray;
transition-duration: 0.3s;
}
.formERREUR .message {
margin: 15px 0 0;
margin-top: 0%;
}
.formERREUR .message a {
color: red;
text-decoration: none;
font-size:2.5em;
}
.formERREUR .message a:hover{color: grey;
transition-duration: 0.3s;}
.formERREUR .message a: {transition-duration: 0.3s;}
.formERREUR .message::selection {
background-color: red;
}
.formERREUR .message a::selection {
background-color: grey;
}
.formERREUR .retour a{
color: red;
text-decoration: none;
font-size:1em;
transition-duration: 0.5s;
}
.formERREUR .retour a:hover{
color: grey;
cursor: pointer;
transition-duration: 0.5s;
}
.formERREUR .message1{font-size: 1rem;
color: grey;
margin-bottom: 30px;}
@import url(https://fonts.googleapis.com/css?family=Roboto:300);
@import "compass/css3";
.login-form {
width: 100%;
padding: 8% 0 0;
margin: auto;
}
.formE {
display: flex;
z-index: 1;
background: white;
max-width: 360px;
margin: 0 auto 100px;
padding: 45px;
text-align: center;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
float: left;
margin-left: 15%;
margin-top: 10vh;
}
.formE input {
font-family: "Roboto", sans-serif;
outline: 0;
background: #f2f2f2;
width: 100%;
border: 0;
margin: 0 0 15px;
padding: 15px;
box-sizing: border-box;
font-size: 14px;
transition-duration: 0.3s;
}
.formE input:hover{color: #28c19b;
transition-duration: 0.3s;}
.formE input:active{color: #28c19b;
transition-duration: 0.3s;}
.formE input::selection {
background-color: grey;
color: #28c19b;
}
.formE select {
font-family: "Roboto", sans-serif;
outline: 0;
background: #f2f2f2;
width: 100%;
border: 0;
margin: 0 0 15px;
padding: 15px;
box-sizing: border-box;
font-size: 14px;
color:dimgray;
height: 6%;
}
.formE .button {
margin-top:2vh;
font-family: "Roboto", sans-serif;
text-transform: uppercase;
outline: 0;
background: #28c19b;
width: 100%;
border: 0;
padding: 15px;
color: #FFFFFF;
font-size: 14px;
-webkit-transition: all 0.3 ease;
transition: all 0.3 ease;
cursor: pointer;
transition-duration: 0.3s;
}
.formE .button:hover,.formE .button:active,.formE .button:focus {
background-color: dimgray;
transition-duration: 0.3s;
}
.formE .imput:active{border: 1px solid #2d3e50;}
.formE .message {
margin: 15px 0 0;
color: #b3b3b3;
font-size: 12px;
margin-bottom: 10%;
margin-top: 0%;
}
.formE .message a {
color: #28c19b;
text-decoration: none;
font-size:3em;
}
.formE .button a {text-decoration: none;
color: white;
}
.formE .message a:hover{color: grey;
transition-duration: 0.3s;}
.formE .message a:{transition-duration: 0.3s;}
.formE .message::selection {
background-color: grey;
color: #28c19b;
}
.formE .message a::selection {
background-color: grey;
color: #28c19b;
}
.formR {
display: flex;
z-index: 1;
background: #FFFFFF;
max-width: 360px;
margin: 0 auto 100px;
padding: 45px;
text-align: center;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
float:right;
margin-right: 15%;
margin-top: 10vh;
}
.formR input {
font-family: "Roboto", sans-serif;
outline: 0;
background: #f2f2f2;
width: 100%;
border: 0;
margin: 0 0 15px;
padding: 15px;
box-sizing: border-box;
font-size: 14px;
transition-duration: 0.3s;
}
.formR input:hover{color: #f59782;
transition-duration: 0.3s;}
.formR input:active{color: #f59782;
transition-duration: 0.3s;}
.formR input::selection {
background-color: grey;
color: #f59782;
}
.formR .button {
font-family: "Roboto", sans-serif;
text-transform: uppercase;
outline: 0;
background: #f59782;
width: 100%;
border: 0;
padding: 15px;
color: #FFFFFF;
font-size: 14px;
-webkit-transition: all 0.3 ease;
transition: all 0.3 ease;
cursor: pointer;
transition-duration: 0.3s;
}
.formR .button:hover,.formR .button:active,.formR .button:focus {
background-color: dimgray;
transition-duration: 0.3s;
}
.formR .message {
margin: 15px 0 0;
color: #b3b3b3;
font-size: 12px;
margin-bottom: 10%;
margin-top: 0%;
}
.formR .message a {
color: #f59782;
text-decoration: none;
font-size:3em;
}
.formR button a {text-decoration: none;
color: white;}
.formR .message a:hover{color: grey;
transition-duration: 0.3s;}
.formR .message a: {transition-duration: 0.3s;}
.formR .message::selection {
background-color: grey;
color: #f59782;
}
.formR .message a::selection {
background-color: grey;
color: #f59782;
}
body {
background:white;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale; font-family: "Roboto", sans-serif;
}
label{color: black;
float: left;
margin-bottom: 1vh;}
header {
left: 0px;
right: 0px;
top: 0px;
height: 20%vh;
}
.wrapper{display: flex;
margin-left: 5%;}
.wrapper h1 a{position: relative;
text-decoration: none;
color: dimgrey;
margin-top: 10vh;}
.wrapper h1 a:hover{text-decoration: none;
color: black;}
.image{width: 50%;}
.titrepage{font-size: 4em;
color: dimgray;
margin-left: 30%;
margin-top: 4vh;}
*/
</style>
</html
| c90ebdf5ca3d72d951effc7c6fb158f9d3e3b7d3 | [
"PHP"
]
| 5 | PHP | Gregawa/durf | 1bb1b28cdca8448d6fa0c26ccf83f04dccbd4e08 | 9d23b911eb972e66c90000b59b5c72bccd641d7e |
refs/heads/main | <repo_name>NAJU-Sachsen/Homepage<file_sep>/redaxo/data/addons/developer/modules/Home Karten [1]/output.php
<!-- mod_home_cards -->
<?php
$bs_cols = 12; // the number of columns in a Bootstrap grid
$n_cards = 'REX_VALUE[20]';
$col_lg_width = $bs_cols / $n_cards;
?>
<?php
if (rex::isBackend()) {
$image_names = array();
$images = array();
$image_names[] = 'REX_MEDIA[id=1 ifempty=default-card-image.jpg]';
$image_names[] = 'REX_MEDIA[id=2 ifempty=default-card-image.jpg]';
if ($n_cards >= 3) {
$image_names[] = 'REX_MEDIA[id=3 ifempty=default-card-image.jpg]';
}
if ($n_cards >= 4) {
$image_names[] = 'REX_MEDIA[id=4 ifempty=default-card-image.jpg]';
}
$ratios = array();
foreach ($image_names as $img) {
$img = new naju_image($img);
$images[] = $img;
if (!in_array($img->aspectRatio(), $ratios)) {
$ratios[] = $img->aspectRatio();
}
}
if (sizeof($ratios) > 1) {
$ratio_details = '<ul class="list-group">';
foreach ($images as $img) {
$name = $img->name();
$ratio = naju_image::aspectRatioName($img);
$ratio_details .= "<li class=\"list-group-item list-group-item-warning\" style=\"color:white;\">$name: $ratio</li>";
}
$ratio_details .= '</ul>';
echo "
<p class=\"alert alert-warning\">
Die Bilder haben verschiedene Seitenverhältnisse. Die Karten werden damit unterschiedliche Größen
aufweisen. <strong>Es wird dringend empfohlen, die Bilder entsprechend anzupassen.</strong><br>
</p><p class=\"alert alert-warning\">Folgende Seitenverhältnisse wurden gefunden:</p>$ratio_details";
}
}
?>
<div id="home-cards" class="container-fluid mb-4">
<div class="row card-grid">
<div class="card-grid-item col-lg-<?= $col_lg_width; ?> col-md-6 col-sm-12">
<article class="card intro-card">
<?php
$card1 = naju_rex_var::toArray('REX_VALUE[1]');
$img1 = new naju_image('REX_MEDIA[id=1 ifempty=default-card-image.jpg]');
?>
<div class="card-body-wrapper webp-fallback" style="background-image: url('<?= $img1->optimizedUrl(false, 800); ?>');" aria-label="<?= rex_escape($img1->altText()); ?>" data-webp-fallback="<?= $img1->url(); ?>">
<div class="card-body">
<h2 class="display-8"><?= rex_escape($card1['title']); ?></h2>
<hr class="my-4">
<p><?= rex_escape($card1['content']); ?></p>
<a class="btn btn-primary btn-lg intro-card-btn" href="REX_LINK[id=1 output=url]" role="button"><?= rex_escape($card1['link-text']) ?? ''; ?></a>
</div>
</div>
</article>
</div>
<div class="card-grid-item col-lg-<?= $col_lg_width; ?> col-md-6 col-sm-12">
<article class="card intro-card">
<?php
$card2 = naju_rex_var::toArray('REX_VALUE[2]');
$img2 = new naju_image('REX_MEDIA[id=2 ifempty=default-card-image.jpg]');
?>
<div class="card-body-wrapper webp-fallback" style="background-image: url('<?= $img2->optimizedUrl(false, 800); ?>');" aria-label="<?= rex_escape($img2->altText()); ?>" data-webp-fallback="<?= $img2->url(); ?>">
<div class="card-body">
<h2 class="display-8"><?= rex_escape($card2['title']); ?></h2>
<hr class="my-4">
<p><?= rex_escape($card2['content']); ?></p>
<a class="btn btn-primary btn-lg intro-card-btn" href="REX_LINK[id=2 output=url]" role="button"><?= rex_escape($card2['link-text']) ?? ''; ?></a>
</div>
</div>
</article>
</div>
<?php if($n_cards >= 3) : ?>
<div class="card-grid-item col-lg-<?= $col_lg_width; ?> col-md-6 col-sm-12">
<article class="card intro-card">
<?php
$card3 = naju_rex_var::toArray('REX_VALUE[3]');
$img3 = new naju_image('REX_MEDIA[id=3 ifempty=default-card-image.jpg]');
?>
<div class="card-body-wrapper webp-fallback" style="background-image: url('<?= $img3->optimizedUrl(false, 800); ?>');" aria-label="<?= rex_escape($img3->altText()); ?>" data-webp-fallback="<?= $img3->url(); ?>">
<div class="card-body">
<h2 class="display-8"><?= rex_escape($card3['title']); ?></h2>
<hr class="my-4">
<p><?= rex_escape($card3['content']); ?></p>
<a class="btn btn-primary btn-lg intro-card-btn" href="REX_LINK[id=3 output=url]" role="button"><?= rex_escape($card3['link-text']) ?? ''; ?></a>
</div>
</div>
</article>
</div>
<?php endif; ?>
<?php if($n_cards >= 4) : ?>
<div class="card-grid-item col-lg-<?= $col_lg_width; ?> col-md-6 col-sm-12">
<article class="card intro-card">
<?php
$card4 = naju_rex_var::toArray('REX_VALUE[4]');
$img4 = new naju_image('REX_MEDIA[id=4 ifempty=default-card-image.jpg]');
?>
<div class="card-body-wrapper webp-fallback" style="background-image: url('<?= $img4->optimizedUrl(false, 800); ?>');" aria-label="<?= rex_escape($img4->altText()); ?>" data-webp-fallback="<?= $img4->url(); ?>">
<div class="card-body">
<h2 class="display-8"><?= rex_escape($card4['title']); ?></h2>
<hr class="my-4">
<p><?= rex_escape($card4['content']); ?></p>
<a class="btn btn-primary btn-lg intro-card-btn" href="REX_LINK[id=4 output=url]" role="button"><?= rex_escape($card4['link-text']) ?? ''; ?></a>
</div>
</div>
</article>
</div>
<?php endif; ?>
</div>
</div>
<file_sep>/redaxo/data/addons/developer/modules/Veranstaltungskalender [12]/input.php
<?php
$mform = MForm::factory();
$mform->addAlertInfo(<<<EOTXT
Der Veranstaltungskalender zeigt standardmäßig alle Veranstaltungen des aktuellen Jahres an. Dieses Verhalten lässt
sich anpassen, sodass der Kalender nur zukünftige Veranstaltungen anzeigt und alle vergangenen Veranstaltungen
ignoriert. Außerdem kann der Kalender optional auch Veranstaltungen der nächsten Jahre in die Anzeige einbeziehen.
Wenn die Filteroptionen genutzt werden, bekommen Besucher*innen der Webseite die Möglichkeit, nur Veranstaltungen
in einem bestimmten Monat oder für eine bestimmte Ortsgruppe anzuzeigen.
EOTXT
);
$id_show_group_filter = 1;
$id_show_month_filter = 2;
$id_include_future_years = 3;
$id_group = 4;
$id_target_group = 5;
$id_event_type = 6;
$id_exlude_past = 7;
$id_event_year = 8;
$mform_tab = MForm::factory();
$mform_tab->addSelectField($id_group);
$mform_tab->setOption('-1', 'alle');
$mform_tab->setSqlOptions('SELECT group_id AS id, group_name AS name FROM naju_local_group ORDER BY group_name');
$mform_tab->setAttributes(['label' => 'Ortsgruppe auswählen']);
$mform->addTabElement('Basiseinstellungen', $mform_tab, true);
$mform_tab = MForm::factory();
$mform_tab->addInputField('number', $id_event_year, ['label' => 'Jahr auswählen']);
$mform_tab->addHiddenField($id_include_future_years, 'false');
$mform_tab->addCheckboxField($id_include_future_years, ['true' => 'Veranstaltungen der nächsten Jahre auch anzeigen'], ['label' => '']);
$mform_tab->addDescription('Falls oben ein Jahr ebenfalls ausgewählt wurde, wird dieses als "Startjahr" verwendet.');
$mform_tab->addHiddenField($id_exlude_past, 'false');
$mform_tab->addCheckboxField($id_exlude_past, ['true' => 'vergangene Veranstaltungen ausblenden'], ['label' => '']);
$mform->addTabElement('Zeitraum', $mform_tab);
$mform_tab = MForm::factory();
$target_groups = ['children' => 'Kinder', 'teens' => 'Jugendliche', 'families' => 'Familien', 'young_adults' => 'junge Erwachsene'];
$mform_tab->addSelectField($id_target_group, $target_groups, ['label' => 'Zielgruppe', 'multiple' => 'multiple', 'class' => 'selectpicker']);
$event_types = ['camp' => 'Camp', 'workshop' => 'Workshop', 'work_assignment' => 'Arbeitseinsatz',
'group_meeting' => 'Aktiventreffen', 'excursion' => 'Exkursion', 'other' => 'sonstige Veranstaltungen'];
$mform_tab->addSelectField($id_event_type, $event_types, ['label' => 'Veranstaltungsart', 'multiple' => 'multiple', 'class' => 'selectpicker']);
$mform->addTabElement('Kalender anpassen', $mform_tab);
$mform_tab = MForm::factory();
$mform_tab->addHiddenField($id_show_group_filter, 'false');
$mform_tab->addCheckboxField($id_show_group_filter, ['true' => 'Ortsgruppen-Filter anzeigen'], ['label' => '']);
$mform_tab->addHiddenField($id_show_month_filter, 'false');
$mform_tab->addCheckboxField($id_show_month_filter, ['true' => 'Monats-Filter anzeigen'], ['label' => '']);
$mform->addTabElement('Filter anzeigen', $mform_tab);
echo $mform->show();
?>
<file_sep>/redaxo/data/addons/developer/modules/Statistiken Export [13]/test.py
# test.py
# example client to consume the stats
import ssl
import requests
# disable SSL certificate validation
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
content = {
'Stats-Credential': '<KEY>'
}
url = 'https://redaxo.local/intern/statistiken/?from=2020-03-24 23:59'
resp = requests.post(url, data=content, verify=False)
print(resp.status_code)
print(resp.text)
<file_sep>/README.md
# NAJU Sachsen Homepage
That's about it: this repo gathers all source files as well as some simple
mockups for our new Homepage. Really nothing special here.
<file_sep>/redaxo/data/addons/developer/modules/[Blog] Beitragsliste [27]/input.php
<?php
$id_blog_select = 1;
$id_image_display = 2;
$mform = MForm::factory();
$mform->addSelectField($id_blog_select);
$mform->setLabel('Blog auswählen:');
$mform->setOption('all', 'Beiträge aus allen Blogs');
if (rex::getUser()->isAdmin()) {
$query = 'SELECT blog_id AS id, CONCAT(blog_title, " (", group_name, ")") AS name
FROM naju_blog JOIN naju_local_group
ON blog_group = group_id
ORDER BY name';
$mform->setSqlOptions($query);
} else {
$user_id = rex::getUser()->getId();
$query = 'SELECT b.blog_id AS id, CONCAT(b.blog_title, " (", g.group_name, ")") AS name
FROM naju_blog b JOIN naju_group_account a JOIN naju_local_group g
ON b.blog_group = a.group_id AND g.group_id = a.group_id
WHERE a.account_id = ' . $user_id .'
ORDER BY name';
$mform->setSqlOptions($query);
}
$mform->addRadioField($id_image_display, ['focus' => 'Fokus', 'column' => 'Extra Spalte']);
$mform->setLabel('Bilder anzeigen');
$mform->setDefaultValue('focus');
echo $mform->show();
<file_sep>/redaxo/data/addons/developer/modules/[Blog] Beitragsliste [27]/output.php
<!-- mod_blog_articles -->
<?php
$single_article_id = rex_request('blog_article', 'string', '');
if ($single_article_id && ctype_digit($single_article_id)) {
$single_article_id = intval($single_article_id);
}
$image_col = 'REX_VALUE[id=2 ifempty=focus]' === 'column';
$sql = rex_sql::factory();
$projection = 'article_title, article_subtitle, article_link, article_link_text, article_image, article_content, article_published, article_updated';
if ($single_article_id) {
$query = "SELECT $projection FROM naju_blog_article WHERE article_id = :id AND (article_status = 'published' OR article_status = 'archived')";
$sql->setQuery($query, ['id' => $single_article_id]);
} else {
$blog_id = 'REX_VALUE[id=1 ifempty=all]';
if ($blog_id === 'all') {
$n_articles = naju_kvs::getOrInflate('naju.blogs.all.count', "SELECT COUNT(*) AS count FROM naju_blog_article WHERE article_status = 'published'");
} else {
$n_articles = naju_kvs::getOrInflate("naju.blogs.$blog_id.count",
"SELECT COUNT(*) AS count FROM naju_blog_article WHERE article_status = 'published' AND article_blog = :blog", ['blog' => $blog_id]);
}
$offset = rex_get('offset', 'string', '0');
$offset = ctype_digit($offset) ? intval($offset) : 0;
$limit = 3;
if ($blog_id === 'all') {
$query = "SELECT $projection, blog_title, group_name
FROM naju_blog_article
JOIN naju_blog ON article_blog = blog_id
JOIN naju_local_group ON blog_group = group_id
WHERE article_status = 'published'
ORDER BY article_published DESC, article_title ASC
LIMIT $limit OFFSET $offset";
$sql->setQuery($query);
} else {
$query = "SELECT $projection
FROM naju_blog_article
WHERE article_status = 'published' AND article_blog = :blog
ORDER BY article_published DESC, article_title ASC
LIMIT $limit OFFSET $offset";
$sql->setQuery($query, ['blog' => $blog_id]);
}
}
if ($image_col) {
$img_attributes = ['img-fluid', 'rounded'];
$img_col_width = 'col-lg-4';
$content_col_width = 'col-lg-8';
} else {
$img_attributes = ['img-fluid', 'rounded', 'd-block', 'mx-auto'];
$img_col_width = 'col-lg-12';
$content_col_width = 'col-lg-12';
}
$content = '';
$articles = $sql->getArray();
$content .= '
<div class="container-fluid">
<div class="row">
<div class="col-12 list-group list-group-flush news-blog">';
if (!$articles) {
$content .= '<p class="alert alert-secondary">Hier erscheint bald der erste Eintrag!</p>';
}
foreach ($articles as $article) {
$content .= '
<article class="list-group-item news-item">
<header class="w-100 justify-content-between news-item-header">
<h3 class="mb-1 news-item-title">';
$content .= rex_escape($article['article_title']);
$subtitle = $article['article_subtitle'];
if ($subtitle) {
$content .= '<small class="news-item-subtitle d-block text-muted">' . rex_escape($subtitle) . '</small>';
}
$content .= '</h3>';
$content .= '<small class="text-muted news-item-meta">';
if ($blog_id == 'all') {
$content .= rex_escape($article['group_name']) . ': ';
$content .= rex_escape($article['blog_title']) . ', ';
}
$published = $article['article_published'];
$updated = $article['article_updated'];
if ($updated) {
$content .= 'aktualisiert ' . rex_escape(date_create_from_format('Y-m-d', $updated)->format('d.m.Y'));
} else {
$content .= 'veröffentlicht ' . rex_escape(date_create_from_format('Y-m-d', $published)->format('d.m.Y'));
}
$content .= '</small>
</header>
<div class="container-fluid mt-4 mb-1">
<div class="row align-items-center">';
$image = $article['article_image'];
if ($image) {
$image = new naju_image($image);
$content .= '<div class="col-sm-12 ' . $img_col_width . ' mb-4 news-image">';
$content .= $image->generatePictureTag($img_attributes);
$content .= '</div>';
}
$content .= '<div class="col-sm-12 ' . $content_col_width . ' news-content">';
$content .= ' <p class="mb-1 news-item-content">';
$content .= $article['article_content'];
$content .= ' </p>';
$link = $article['article_link'];
if ($link) {
$content .= '<a href="' . rex_getUrl($link) . '">' . rex_escape($article['article_link_text']) . '</a>';
}
$content .= '</div>';
$content .= '</div>
</div>
</article>';
}
$content .= '
</div>
</div>'; // closes the news list row
// show pagination if necessary
if (!$single_article_id && ($limit < $n_articles)) {
$content .= '
<div class="row">
<div class="col-12">';
$content .= '<nav><ul class="pagination justify-content-center">';
$prev_page = $offset - $limit;
if ($prev_page >= 0) {
$content .= '<li class="page-item"><a class="page-link" href="' . rex_getUrl(null, null, ['offset' => $prev_page]) . '">Zurück</a></li>';
}
$next_page = $offset + $limit;
if ($next_page <= $n_articles) {
$content .= '<li class="page-item"><a class="page-link" href="' . rex_getUrl(null, null, ['offset' => $next_page]) . '">Weiter</a></li>';
}
$content .= '</ul></nav>';
$content .= '</div>
</div>'; // closes the pagination row
}
$content .= '</div>'; // closes the final container
echo $content;
<file_sep>/redaxo/data/addons/developer/templates/head Meta-Informationen [10]/template.php
<!-- temp_head_meta -->
<!-- SEO -->
<?php
// first of, extract some general info about the requested page
$article = rex_article::getCurrent();
$title = htmlspecialchars($article->getName());
$image = $article->getValue('art_image');
$hasCustomImage = $image || false;
$image = $hasCustomImage ? new naju_image($image) : new naju_image('default-social-image.jpg');
$params = '?'; // all GET parameters in one string
// if there are any params, we need to add them after a '?' sign
// when the params are appended, they will be suffixed by a '&' sign to
// enable appending the next param
// as the last step, the final character of the url will be deleted
// this may be the redundant '&' from the last parameter
// or the '?' in case there were no parameters at all
foreach ($_GET as $param => $val) {
// if there are private parameters present, we do not save any of the parameters
// instead reset the string to default to mimic a 'no parameters' case
if ($param == 'private' && ($val == 'true' || $val == 1 )) {
$params = '?';
break;
}
$params .= rex_escape(rex_escape($param, 'url')) . '=' . rex_escape(rex_escape($val, 'url')) . '&';
}
$params = substr($params, 0, -1);
// SEO info
$seo = new rex_yrewrite_seo();
$description = $seo->getDescription();
if ($description) {
echo $seo->getDescriptionTag();
} else {
$description = naju_kvs::getOrInflate('naju.seo.description',
'select meta_value from naju_seo where meta_key = :key', ['key' => 'description']);
echo '<meta name="description" content="' . rex_escape($description) . '">';
}
echo '<!-- General -->';
echo $seo->getRobotsTag();
echo $seo->getHreflangTags();
echo $seo->getCanonicalUrlTag();
?>
<!-- Open graph info (Facebook) -->
<meta property="og:url" content="<?= rex_yrewrite::getFullUrlByArticleId($article->getId()) . $params; ?>">
<meta property="og:site_name" content="<NAME>">
<meta property="og:locale" content="de_DE">
<meta property="og:type" content="website">
<meta property="og:title" content="<?= $title; ?>">
<?php if ($description) : ?>
<meta property="og:description" content="<?= rex_escape($description); ?>">
<?php endif; ?>
<meta property="og:image" content="<?= $image->absoluteUrl(); ?>">
<meta property="og:image:secure_url" content="<?= $image->absoluteUrl(); ?>">
<meta property="og:image:width" content="<?= $image->width(); ?>">
<meta property="og:image:height" content="<?= $image->height(); ?>">
<!-- Twitter -->
<meta name="twitter:title" content="<?= $title; ?>">
<?php if ($description) : ?>
<meta name="twitter:description" content="<?= rex_escape($description); ?>">
<?php endif; ?>
<?php if ($hasCustomImage) : ?>
<meta name="twitter:image" content="<?= $image->absoluteUrl(); ?>">
<?php endif; ?>
<meta name="twitter:card" content="summary_large_image">
<file_sep>/redaxo/data/addons/developer/modules/Diashow [16]/input.php
<input type="hidden" name="REX_INPUT_VALUE[1]" value="<?= rex_escape(rex_get('slice_id')); ?>">
<div class="form-group">
<label>Maximale Höhe (px):</label>
<div class="input-group">
<input type="number" name="REX_INPUT_VALUE[2]" value="REX_VALUE[id=2 ifempty=0]" min="0" class="form-control">
<div class="input-group-addon">
<span class="input-group-text">0 zum deaktivieren</span>
</div>
</div>
</div>
<div class="form-group">
<label>Bilder auswählen:</label>
REX_MEDIALIST[id=1 widget=1 types=jpg,jpeg,png]
</div>
<file_sep>/redaxo/data/addons/developer/modules/Editor komplett [2]/output.php
<!-- mod_editor_full -->
REX_VALUE[id="1" output="html"]
<file_sep>/redaxo/data/addons/developer/templates/Header [6]/template.php
<!-- temp_header -->
<header id="top-bar">
<a href="/">
<?php
$logo = rex_escape(naju_article::getLogoForCurrentLocalGroup());
$logo_name = pathinfo($logo, PATHINFO_FILENAME);
$webp_logo = $logo_name . '.webp';
?>
<h1 class="text-hide naju-logo webp-fallback" style="background-image: url('/assets/<?= $webp_logo; ?>');" data-webp-fallback="/assets/<?= $logo; ?>"><NAME></h1>
</a>
</header>
<file_sep>/redaxo/data/addons/developer/modules/Auflistung [22]/input.php
<?php
// REX_VALUE
$display_type_id = 1;
$item_id = 2;
$image_params_id = 3;
$list_wide_img_cols = 4;
// REX_MEDIA
$item_media_id = 1;
// REX_LINK
$item_link_id = 1;
$mform = MForm::factory();
$mform_tab = MForm::factory();
$mform_tab->addRadioField($display_type_id, ['media-list' => 'als Liste', 'grid' => 'als Gitter']);
$mform_tab->setLabel('Wie sollen die Einträge angezeigt werden?');
$mform->addTabElement('Allgemeine Einstellung', $mform_tab, true);
$mform_tab = MForm::factory();
$mform_tab->addInputField('number', "$image_params_id.width");
$mform_tab->setLabel('Breite der Bilder');
$mform_tab->addInputField('number', "$image_params_id.height");
$mform_tab->setLabel('Höhe der Bilder');
$mform_tab->addCheckboxField("$image_params_id.enable_effects", ['label' => 'aktiviert']);
$mform_tab->setLabel('Tolle Bildeffekte');
$mform_tab->addSelectField("$image_params_id.effect", ['random' => 'zufällig', 'img-fancy-default' => 'Dunkelrot [Standard]',
'img-fancy-green' => 'Maigrün (Hellgrün)', 'img-fancy-green-alternate' => 'Laubgrün (Dunkelgrün)']);
$mform_tab->setLabel('Effekt auswählen');
$mform_tab->addCheckboxField("$image_params_id.no_rotate_img", ['label' => 'Rotation ausschalten']);
$mform_fieldset = MForm::factory();
$mform_fieldset->addCheckboxField($list_wide_img_cols, ['label' => 'breite Bild-Spalte verwenden']);
$mform_tab->addFieldsetArea('Für die Listendarstellung', $mform_fieldset);
$mform->addTabElement('Bilddarstellung', $mform_tab);
echo $mform->show();
$mform = MForm::factory();
$mform_fieldset = MForm::factory();
$mform_fieldset->addTextField("$item_id.0.title", ['label' => 'Titel']);
$mform_fieldset->addMediaField($item_media_id, ['label' => 'Foto', 'types' => naju_image::ALLOWED_TYPES]);
$mform_fieldset->addTextAreaField("$item_id.0.content", ['label' => 'Inhalt', 'class' => 'redactorEditor2-links-bold-italic-lists']);
$mform_fieldset->addLinkField($item_link_id, ['label' => 'Weiterführender Link']);
$mform_fieldset->addTextField("$item_id.0.link_text", ['label' => 'Link Beschriftung']);
$mform->addFieldsetArea('Eintrag', $mform_fieldset);
echo MBlock::show($item_id, $mform->show());
<file_sep>/redaxo/data/addons/developer/modules/Freianzeige [14]/output.php
<!-- mod_ad -->
<?php
$img = 'REX_MEDIA[id=1]';
if ($img) {
$img = new naju_image($img);
// 17vw roughly correspondends to 1/6 of the viewport width which is equal to the width of the glance section
echo '<a href="/media/' . $img->name() . '">' . $img->generatePictureTag(['img', 'img-fluid'], '', [], ["sizes" => "17vw"], false) . '</a>';
}
<file_sep>/redaxo/data/addons/developer/modules/Freies HTML [21]/output.php
<!-- mod_html -->
REX_VALUE[id=1 output=html]
<file_sep>/redaxo/data/addons/developer/modules/Naechste Veranstaltungen [5]/output.php
<!-- mod_upcoming_events -->
<?php
define('DATE_FMT', 'd.m.');
$limit = 3;
$local_group = 'REX_VALUE[1]';
$today = date(naju_event_calendar::$DB_DATE_FMT);
$additional_filters = '';
$filter_target_group = 'REX_VALUE[id=2]';
if ($filter_target_group) {
$event_target_group = rex_sql::factory()->escape($filter_target_group);
$additional_filters .= " and find_in_set($event_target_group, event_target_group_type) ";
}
$filter_event_type = 'REX_VALUE[id=3]';
if ($filter_event_type) {
$event_type = rex_sql::factory()->escape($filter_event_type);
$additional_filters .= " and event_type = $event_type ";
}
// local group == -1 means no group selected => show all instead
if ($local_group == -1) {
$event_query = <<<EOSQL
select
event_name,
group_name,
event_start,
event_end,
event_location,
event_type,
event_link
from
naju_event
join naju_local_group
on event_group = group_id
where
(event_end >= :date or event_start >= :date)
and event_active = true
$additional_filters
order by event_start, event_end
limit $limit
EOSQL;
$events = rex_sql::factory()->setQuery($event_query, ['date' => $today])->getArray();
} else {
$event_query = <<<EOSQL
select
event_name,
group_name,
event_start,
event_end,
event_location,
event_type,
event_link
from
naju_event
join naju_local_group
on event_group = group_id
where
group_id = :group and
(event_end >= :date or event_start >= :date)
and event_active = true
$additional_filters
order by event_start, event_end
limit $limit
EOSQL;
$events = rex_sql::factory()->setQuery($event_query, ['group' => $local_group, 'date' => $today])->getArray();
}
echo 'REX_VALUE[id=6 ifempty=true]' == 'true' ? 'REX_VALUE[4]' : ''; // intro text
$plain_list = 'REX_VALUE[id=5 ifempty=false]' == 'false'; // REX_VAL 5 is 'format as cards'
?>
<?php if ($events && $plain_list) : ?>
<dl class="events-list">
<?php foreach ($events as $event) : ?>
<dt>
<?php
$start_date = DateTime::createFromFormat(naju_event_calendar::$DB_DATE_FMT, $event['event_start']);
$event_end = $event['event_end'];
echo rex_escape($start_date->format(DATE_FMT));
if ($event_end) {
$event_end = DateTime::createFromFormat(naju_event_calendar::$DB_DATE_FMT, $event_end);
echo ' ‐ ' . rex_escape($event_end->format(DATE_FMT));
}
if ($event['event_type'] == 'work_assignment') {
echo ' Arbeitseinsatz:';
} elseif ($event['event_type'] == 'group_meeting') {
echo ' Aktiventreffen:';
}
?>
</dt>
<dd class="event-announcement">
<?php
if ($event['event_link']) {
echo '<a href="' . rex_getUrl($event['event_link']) . '" class="event-link">' . rex_escape($event['event_name']) . '</a> ';
} else {
echo rex_escape($event['event_name']);
}
if ($local_group == -1) {
echo ' (' . rex_escape($event['group_name']) . ')';
}
?>
</dd>
<?php endforeach; ?>
</dl>
<?php elseif ($events) : ?>
<div class="card-deck mt-3">
<?php foreach ($events as $event) : ?>
<div class="card">
<div class="card-body">
<h4 class="card-title">
<?php echo rex_escape($event['event_name']); ?>
</h4>
<p class="card-text">
<?php
if ($event['event_type'] == 'work_assignment') {
echo ' <span class="badge badge-pill badge-secondary mr-1">Arbeitseinsatz</span>';
} elseif ($event['event_type'] == 'group_meeting') {
echo ' <span class="badge badge-pill badge-secondary mr-1">Aktiventreffen</span>';
}
$start_date = DateTime::createFromFormat(naju_event_calendar::$DB_DATE_FMT, $event['event_start']);
$event_end = $event['event_end'];
echo rex_escape($start_date->format(DATE_FMT));
if ($event_end) {
$event_end = DateTime::createFromFormat(naju_event_calendar::$DB_DATE_FMT, $event_end);
echo ' ‐ ' . rex_escape($event_end->format(DATE_FMT));
}
if ($event['event_location']) {
echo '<br>' . rex_escape($event['event_location']);
}
?>
</p>
<p class="card-text"><small class="text-muted"><?= rex_escape($event['group_name']); ?></small></p>
<?php
if ($event['event_link']) {
echo '<a href="' . rex_getUrl($event['event_link']) . '" class="card-link">Mehr erfahren</a>';
}
?>
</div>
</div>
<?php endforeach; ?>
</div>
<?php else: ?>
<p class="ml-1 font-italic">Demnächst stehen keine Veranstaltungen an</p>
<?php endif; ?>
<file_sep>/redaxo/data/addons/developer/templates/Blogbeitrag [11]/template.php
<!doctype html>
<?php
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
$is_ios = str_contains($ua, 'iphone') || str_contains($ua, 'ipad');
?>
<html lang="de" <?= $is_ios ? 'ontouchmove' : ''; ?>>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title><?= rex_escape($this->getValue('name')); ?> | <NAME></title>
<link rel="preload" href="/fonts/SourceSansPro-Regular.ttf" as="font" type="font/ttf" crossorigin="anonymous">
<link rel="preload" href="/fonts/Amaranth-Regular.ttf" as="font" type="font/ttf" crossorigin="anonymous">
<link rel="icon" href="/assets/favicon.ico">
<link rel="stylesheet" href="/css/kernel.css">
<?= 'REX_TEMPLATE[key=template-head-meta]' ?>
</head>
<body class="container-fluid">
<div id="complete-wrapper">
<div id="top-bar-wrapper" class="row">
<?= 'REX_TEMPLATE[key=template-header]'; ?>
</div>
<div id="nav-content-wrapper" class="row">
<?php
define('ARTICLE_CTYPE', 1);
define('SIDEBAR_CTYPE', 2);
$article_id = rex_article::getCurrent()->getId();
$slices = rex_article_slice::getSlicesForArticle($article_id);
echo 'REX_TEMPLATE[key=template-nav]';
?>
<div id="content-wrapper" class="col-lg-8 offset-lg-2 col-md-12">
<!-- Main content -->
<main id="content" class="clearfix">
REX_ARTICLE[ctype=1]
</main>
</div>
<!-- Side bar -->
<?php if($this->getValue('art_has_sidebar') === '|true|') : ?>
<aside id="at-a-glance" class="col-lg-2 border border-right-0 rounded-left offset-lg-10">
<h2>Auf einen Blick</h2>
<?php
foreach ($slices as $slice) {
// only print slices for the sidebar (ctype=2)
if ($slice->getCtype() != SIDEBAR_CTYPE) {
continue;
}
// wrap the slice in a section and print its contents
echo '<section class="glance-section">';
echo $slice->getSlice();
echo '</section>';
}
?>
</aside>
<?php endif; ?>
</div>
REX_TEMPLATE[key=template-footer-copyright]
REX_TEMPLATE[key=template-footer-navigation]
</div>
<script src="/js/jquery-3.5.1.js"></script>
<script src="/js/popper.js"></script>
<script src="/js/bootstrap.js"></script>
<script src="/js/site.js"></script>
</body>
</html>
<?php naju_stats::logVisitor(); ?>
<file_sep>/redaxo/data/addons/developer/modules/[Blog] Einzelner Beitrag [28]/input.php
<?php
if (rex::getUser()->isAdmin()) {
$blogs = rex_sql::factory()->getArray('SELECT blog_title, blog_id FROM naju_blog ORDER BY blog_title');
} else {
$user_id = rex::getUser()->getId();
$query = 'SELECT blog_title, blog_id FROM naju_blog JOIN naju_group_account ON blog_group = group_id WHERE account_id = :id';
$blogs = rex_sql::factory()->getArray($query, ['id' => $user_id]);
}
?>
<fieldset style="margin-bottom: 30px;">
<legend>1. Nach Artikel suchen:</legend>
<div class="form-inline">
<div class="form-group">
<label for="blog-select">Blog auswählen:</label>
<select class="form-control" id="blog-select">
<option value="all">alle</option>
<?php foreach($blogs as $blog) : ?>
<option value="<?= rex_escape($blog['blog_id']); ?>"><?= rex_escape($blog['blog_title']); ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group" style="margin-left: 15px;">
<label for="blog-query">Beitrag suchen:</label>
<input type="search" class="form-control" autocomplete="off" placeholder="Titel" id="blog-query">
</div>
<div class="form-group">
<button type="button" class="btn btn-default" id="blog-search">
<i class="fa fa-search"></i> Suchen
</button>
</div>
</div>
</fieldset>
<fieldset>
<legend>2. Artikel aus den Resultaten auswählen:</legend>
<div class="form">
<div class="form-group">
<label for="article-select">Artikel auswählen:</label>
<select class="form-control" name="REX_INPUT_VALUE[1]" id="article-select">
<?php
$selected_article = 'REX_VALUE[1]';
if ($selected_article) {
$query = 'SELECT article_title, article_id, blog_title FROM naju_blog_article JOIN naju_blog ON article_blog = blog_id
WHERE article_id = :id';
$article = rex_sql::factory()->getArray($query, ['id' => $selected_article])[0];
echo '<option value="' . rex_escape($article['article_id']) . '" id="default-article">' . rex_escape($article['article_title']) . '</option>';
}
?>
</select>
</div>
</div>
</fieldset>
<script>
$(document).on('rex:ready', () => {
const currentArticle = $('#default-article');
const articleSelect = $('#article-select');
const blogSelect = $('#blog-select');
const blogQuery = $('#blog-query');
const searchBtn = $('#blog-search');
searchBtn.click((e) => {
const blogId = blogSelect.val();
const query = blogQuery.val();
let params = '';
if (blogId !== 'all') {
params += 'blog_id=' + encodeURIComponent(blogId) + '&';
}
params += 'query=' + encodeURIComponent(query);
$.get('', 'rex-api-call=naju_article_search&' + params, (data) => {
articleSelect.empty();
articleSelect.append(currentArticle);
$.each(data.result, (i, opt) => {
if (opt.article_id != currentArticle.val()) {
articleSelect.append($('<option>', {
value: opt.article_id,
text: opt.article_title + ' (' + opt.blog_title + ')'
}));
}
});
});
});
});
</script>
<file_sep>/js/site.js
/**
* site.js
* v0.2.0
*
*/
//
// Listing cards height
//
function adjustListingCardsHeight(container) {
const cards = container.getElementsByClassName('listing-card');
const maxHeight = Math.max(...Array.from(cards).map((card) => card.clientHeight));
for (const card of cards) {
card.style.height = '' + maxHeight + 'px';
const footers = card.getElementsByClassName('card-footer');
if (footers) {
footers[0].style.position = 'absolute';
footers[0].style.bottom = '0';
}
}
}
window.addEventListener('load', () => {
const cardContainers = document.getElementsByClassName('listing-cards-container');
for (const cardContainer of cardContainers) {
adjustListingCardsHeight(cardContainer);
}
const scrollSpyers = document.querySelectorAll('[data-spy="scroll"]');
for (const spyer of scrollSpyers) {
console.log(spyer);
spyer.dataset.offset = window.innerHeight - spyer.getBoundingClientRect().top;
console.log(spyer);
}
//$('[data-spy="scroll"]').each(() => $(this).scrollspy('refresh'));
});
//
// Iframe lazy loading
//
function lazyLoadIframe(container, src, height) {
const iframe = container.getElementsByClassName('iframe-holder')[0];
iframe.setAttribute('src', src);
iframe.style.height = height;
while (container.firstChild !== iframe) {
container.removeChild(container.firstChild);
}
while (container.lastChild !== iframe) {
container.removeChild(container.lastChild);
}
container.className = 'iframe-container loaded';
iframe.className = 'iframe-holder';
}
document.addEventListener('DOMContentLoaded', () => {
const iframeContainers = document.getElementsByClassName('iframe-container load-on-demand');
for (const iframe of iframeContainers) {
const src = iframe.dataset.iframeSrc;
const height = iframe.dataset.iframeHeight;
const loadBtn = iframe.getElementsByClassName('iframe-load-btn')[0];
loadBtn.addEventListener('click', () => lazyLoadIframe(iframe, src, height));
}
});
<file_sep>/redaxo/data/addons/developer/modules/Piktogramm [23]/output.php
<!-- mod_pictogram -->
<?php
$img = 'REX_MEDIA[1]';
if ($img) {
$img = new naju_image($img);
echo $img->generatePictureTag(['img-fluid', 'd-block', 'mx-auto'], '', ['style' => 'max-height: 200px;'], [], false);
}
<file_sep>/redaxo/data/addons/developer/modules/Veranstaltungsdetails [15]/output.php
<!-- mod_event_details -->
<?php
$event_id = 'REX_VALUE[1]';
$event_query = <<<EOSQL
select
event_start,
event_end,
event_location,
event_group, group_name,
event_target_group,
event_price, event_price_reduced,
event_registration
from naju_event
left join naju_local_group
on event_group = group_id
where event_id = :event
EOSQL;
$event = rex_sql::factory()->setQuery($event_query, ['event' => $event_id])->getArray()[0];
?>
<div class="container">
<table class="table table-sm">
<tbody>
<tr class="row">
<th class="col-lg-2">Wann?</th>
<td class="col-lg-10">
<?php
$start_date = $event['event_start'];
$end_date = $event['event_end'];
$start_time = $event['event_start_time'];
$end_time = $event['event_end_time'];
if (!$end_date) {
echo DateTime::createFromFormat(naju_event_calendar::$DB_DATE_FMT, $start_date)->format('d.m.y');
if ($start_time) {
echo ' ' . DateTime::createFromFormat('H:i:s', $start_time)->format('H:i');
if ($end_time) {
echo ' ‐ ' . DateTime::createFromFormat('H:i:s', $end_time)->format('H:i');
}
echo ' Uhr';
}
} else {
$start_date = DateTime::createFromFormat(naju_event_calendar::$DB_DATE_FMT, $start_date);
$end_date = DateTime::createFromFormat(naju_event_calendar::$DB_DATE_FMT, $end_date);
if ($start_date->format('Y') == $end_date->format('Y')) {
if ($start_date->format('m') == $end_date->format('m')) {
echo $start_date->format('d.') . ' ‐ ' . $end_date->format('d.m.y');
} else {
echo $start_date->format('d.m.') . ' ‐ ' . $end_date->format('d.m.y');
}
} else {
echo $start_date->format('d.m.y') . ' ‐ ' . $end_date->format('d.m.y');
}
}
?>
</td>
</tr>
<?php if ($event['event_location']) : ?>
<tr class="row">
<th class="col-lg-2">Wo?</th>
<td class="col-lg-10"><?= rex_escape($event['event_location']); ?></td>
</tr>
<?php endif; ?>
<?php if ($event['event_group']) : ?>
<tr class="row">
<th class="col-lg-2">Wer?</th>
<td class="col-lg-10">
<!-- TODO link to local group -->
<?= rex_escape($event['group_name']); ?>
</td>
</tr>
<?php endif; ?>
<?php if ($event['event_target_group']) : ?>
<tr class="row">
<th class="col-lg-2">Für wen?</th>
<td class="col-lg-10"><?= rex_escape($event['event_target_group']); ?></td>
</tr>
<?php endif; ?>
<?php if ($event['event_price'] || $event['event_price_reduced']) : ?>
<tr class="row">
<th class="col-lg-2">Kosten?</th>
<td class="col-lg-10">
<?php
$normal_price = $event['event_price'];
$reduced_price = $event['event_price_reduced'];
if ($normal_price) {
echo rex_escape($normal_price);
}
if ($normal_price && $reduced_price) {
echo ' bzw. ';
}
if ($reduced_price) {
echo rex_escape($reduced_price) . ' ermäßigt';
}
?>
</td>
</tr>
<?php endif; ?>
<?php if ($event['event_registration']) : ?>
<tr class="row">
<th class="col-lg-2">Anmeldung?</th>
<td class="col-lg-10"><?= naju_article::make_emails_anchors(htmlspecialchars($event['event_registration'])); ?></td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
<file_sep>/redaxo/data/addons/developer/modules/Veranstaltungskalender [12]/output.php
<!-- mod_event_calendar -->
<?php
$sql = rex_sql::factory();
$local_group = 'REX_VALUE[id=4 ifempty=-1]';
$local_group_filter = 'REX_VALUE[id=1 ifempty="false"]' === 'true';
$include_all_future_events = 'REX_VALUE[id=3 ifempty="false"]' === 'true';
$ignore_past_events = 'REX_VALUE[id=7 ifempty="false"]' === 'true';
$month_filter = 'REX_VALUE[id=2 ifempty="false"]' === 'true';
$any_user_filter = $local_group_filter || $month_filter;
$event_year = 'REX_VALUE[id=8]';
if (!$event_year) {
$event_year = date('Y');
}
if ($ignore_past_events) {
$start_date = $event_year . '-' . date('m-d');
} else {
$start_date = $event_year . '-01-01';
}
$end_date = $event_year . '-12-31';
$months = array('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni',
'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember');
$req_month = '';
if ('events' === rex_get('filter')) {
$local_group = rex_get('local_group', 'int', $local_group);
if (rex_get('month', 'int', 0)) {
$req_month = rex_get('month', 'int');
if ($req_month != -1) {
$start_date = $event_year . '-' . $req_month . '-01';
$end_date = $event_year . '-' . $req_month . '-31';
}
}
}
if ($include_all_future_events && rex_get('month', 'int', -1) === -1) {
$end_date = '9999-12-31';
}
$additional_filters = '';
$filter_target_group = rex_get('target_group');
if (!$filter_target_group) {
$filter_target_group = rex_var::toArray('REX_VALUE[id=5]');
}
if ($filter_target_group) {
$target_group_criteria = 'and (';
$target_groups = array();
foreach ($filter_target_group as $target_group) {
$target_groups[] = 'find_in_set(' . $sql->escape($target_group) . ', event_target_group_type)';
}
$target_group_criteria .= implode(' OR ', $target_groups) . ')';
$additional_filters .= $target_group_criteria;
}
$filter_event_type = rex_get('event_type');
if (!$filter_event_type) {
$filter_event_type = rex_var::toArray('REX_VALUE[id=6]');
}
if ($filter_event_type) {
$event_type_criteria = 'and (';
$event_types = array();
foreach ($filter_event_type as $event_type) {
$event_types[] = 'event_type = ' . $sql->escape($event_type);
}
$event_type_criteria .= implode(' OR ', $event_types) . ')';
$additional_filters .= $event_type_criteria;
}
if ($local_group == -1) {
$event_query = <<<EOSQL
select
event_name,
group_name,
event_start,
event_end,
event_start_time,
event_end_time,
event_description,
event_location,
event_target_group,
event_price,
event_price_reduced,
event_registration,
event_type,
event_link
from
naju_event
join naju_local_group
on event_group = group_id
where
((event_start <= :end and event_end >= :start) or
(event_end is null and event_start >= :start and event_start <= :end))
and event_active = true
$additional_filters
order by event_start, event_end
EOSQL;
$events = $sql->getArray($event_query, ['start' => $start_date, 'end' => $end_date]);
} else {
$event_query = <<<EOSQL
select
event_name,
group_name,
event_start,
event_end,
event_start_time,
event_end_time,
event_description,
event_location,
event_target_group,
event_price,
event_price_reduced,
event_registration,
event_type,
event_link
from
naju_event
join naju_local_group
on event_group = group_id
where
group_id = :group and
((event_start <= :end and event_end >= :start) or
(event_end is null and event_start >= :start and event_start <= :end))
and event_active = true
$additional_filters
order by event_start, event_end
EOSQL;
$events = $sql->getArray($event_query, ['group' => $local_group, 'start' => $start_date, 'end' => $end_date]);
}
$slice_id = 'REX_SLICE_ID';
$event_counter = 0;
?>
<div class="container-fluid">
<?php if ($any_user_filter) : ?>
<div class="row justify-content-center">
<form action="<?= rex_getUrl(); ?>" method="get" class="form-inline p-3 mb-5 bg-light rounded">
<input type="hidden" name="filter" value="events">
<!-- local group filter -->
<?php if ($local_group_filter) : ?>
<label class="my-1 mr-2" for="select-local-group">Wähle deine Ortsgruppe:</label>
<select name="local_group" id="select-local-group" class="form-control my-2 mr-sm-5">
<option value="-1" <?= $local_group == -1 ? 'selected' : '' ?>>alle</option>
<?php
$local_groups = $sql->getArray('SELECT group_id, group_name FROM naju_local_group');
foreach ($local_groups as $group) {
$selected = $local_group == $group['group_id'] ? ' selected' : '';
echo '<option value="' . rex_escape($group['group_id']) . '"' . $selected . '>' .
rex_escape($group['group_name']) .
'</option>';
}
?>
</select>
<?php endif; ?>
<!-- month filter -->
<?php if($month_filter) : ?>
<label class="my-1 mr-2" for="select-month">Wähle den Monat:</label>
<select name="month" id="select-month" class="form-control my-2 mr-sm-5">
<option value="-1" <?= $req_month == -1 ? ' selected' : '' ?>>alle</option>
<?php
foreach ($months as $midx => $month) {
/* $months is a static variable, no need to escape it */
echo '<option value="' . ($midx+1) . '"' . ($req_month == $midx+1 ? ' selected' : '') . '>' . $month . '</option>';
}
?>
</select>
<?php endif; ?>
<button type="submit" class="btn btn-primary my-2">Los</button>
</form>
</div>
<?php endif; ?>
<!-- event list -->
<div class="row">
<?php if ($events) : ?>
<div class="list-group list-group-flush event-calendar">
<?php
foreach ($events as $event) :
$event_counter++;
?>
<article class="list-group-item event">
<header class="d-flex w-100 justify-content-between event-header">
<h3 class="mb-1 text-left event-title">
<?php
if ($event['event_type'] == 'work_assignment') {
echo 'Arbeitseinsatz: ';
} elseif ($event['event_type'] == 'group_meeting') {
echo 'Aktiventreffen: ';
}
echo rex_escape($event['event_name']);
?>
<small class="text-muted">
<?php
$start_date = $event['event_start'];
$end_date = $event['event_end'];
$start_time = $event['event_start_time'];
$end_time = $event['event_end_time'];
if (!$end_date) {
echo DateTime::createFromFormat(naju_event_calendar::$DB_DATE_FMT, $start_date)->format('d.m.y');
if ($start_time) {
echo ' ' . DateTime::createFromFormat('H:i:s', $start_time)->format('H:i');
if ($end_time) {
echo ' ‐ ' . DateTime::createFromFormat('H:i:s', $end_time)->format('H:i');
}
echo ' Uhr';
}
} else {
$start_date = DateTime::createFromFormat(naju_event_calendar::$DB_DATE_FMT, $start_date);
$end_date = DateTime::createFromFormat(naju_event_calendar::$DB_DATE_FMT, $end_date);
if ($start_date->format('Y') == $end_date->format('Y')) {
if ($start_date->format('m') == $end_date->format('m')) {
echo $start_date->format('d.') . '‐' . $end_date->format('d.m.y');
} else {
echo $start_date->format('d.m.') . '‐' . $end_date->format('d.m.y');
}
} else {
echo $start_date->format('d.m.y') . '‐' . $end_date->format('d.m.y');
}
}
?>
</small>
</h3>
<!-- TODO: insert group link -->
<small class="text-muted"><?= rex_escape($event['group_name']); ?></small>
</header>
<?php if ($event['event_description']) : ?>
<?php $event_description_id = 'event-description-' . $slice_id . '-' . $event_counter; ?>
<div class="event-description-wrapper">
<p class="event-description collapse mb-1" id="<?= $event_description_id ?>" aria-expanded="false">
<?= naju_article::richFormatText(rex_escape($event['event_description'])); ?>
</p>
<a href="#<?= $event_description_id; ?>" class="float-right further-reading mr-3 mb-3"
data-toggle="collapse" role="button" aria-expanded="false" aria-controls="<?= $event_description_id; ?>">
Weiterlesen
</a>
</div>
<?php endif; ?>
<?php if (naju_event_calendar::hasExtraInfos($event)) : ?>
<div class="container mt-3">
<table class="table table-sm">
<?php if ($event['event_location']) : ?>
<tr class="row">
<th class="col-lg-2">Wo?</th>
<td class="col-lg-10"><?= rex_escape($event['event_location']); ?></td>
</tr>
<?php endif; ?>
<?php if ($event['event_target_group']) : ?>
<tr class="row">
<th class="col-lg-2">Für wen?</th>
<td class="col-lg-10"><?= rex_escape($event['event_target_group']) ?></td>
</tr>
<?php endif; ?>
<?php if ($event['event_price'] || $event['event_price_reduced']) : ?>
<tr class="row">
<th class="col-lg-2">Was kostet es?</th>
<td class="col-lg-10">
<?php
$normal_price = $event['event_price'];
$reduced_price = $event['event_price_reduced'];
if ($normal_price) {
echo rex_escape($normal_price);
}
if ($normal_price && $reduced_price) {
echo ' bzw. ';
}
if ($reduced_price) {
echo rex_escape($reduced_price) . ' ermäßigt';
}
?>
</td>
</tr>
<?php endif; ?>
<?php if ($event['event_registration']) : ?>
<tr class="row">
<th class="col-lg-2">Anmeldung?</th>
<td class="col-lg-10"><?= naju_article::richFormatText(rex_escape($event['event_registration'])); ?></td>
</tr>
<?php endif; ?>
</table>
</div>
<?php endif; ?>
<?php if ($event['event_link']) : ?>
<a href="<?= rex_getUrl($event['event_link']); ?>" class="mb-1 link">Mehr Infos</a>
<?php endif; ?>
</article>
<?php endforeach; ?>
</div>
<?php else : ?>
<div class="mx-auto"><p class="alert alert-secondary">Es wurden keine Veranstaltungen gefunden</p></div>
<?php endif; ?>
</div>
</div>
<file_sep>/redaxo/data/addons/developer/modules/Naechste Veranstaltungen [5]/input.php
<?php
$group_query = <<<EOSQL
select group_id, group_name
from naju_local_group
EOSQL;
$local_groups = rex_sql::factory()->setQuery($group_query)->getArray();
?>
<div class="form-group">
<label for="select-local-group">Ortsgruppe auswählen</label>
<select class="form-control" name="REX_INPUT_VALUE[1]">
<option value="-1">alle</option>
<?php foreach ($local_groups as $group) : ?>
<option value="<?= rex_escape($group['group_id']); ?>" <?= "REX_VALUE[id=1 ifempty='']" == $group['group_id'] ? 'selected' : '' ?>>
<?= rex_escape($group['group_name']); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="select-event-target-group">Nur Veranstaltungen mit folgender Zielgruppe anzeigen:</label>
<select class="form-control" name="REX_INPUT_VALUE[2]" id="select-event-target-group">
<option value="" <?= 'REX_VALUE[2]' == '' ? 'selected' : ''; ?>>deaktiviert</option>
<option value="children" <?= 'REX_VALUE[2]' == 'children' ? 'selected' : ''; ?>>Kinder</option>
<option value="teens" <?= 'REX_VALUE[2]' == 'teens' ? 'selected' : ''; ?>>Jugendliche</option>
<option value="families" <?= 'REX_VALUE[2]' == 'families' ? 'selected' : ''; ?>>Familien</option>
<option value="young_adults" <?= 'REX_VALUE[2]' == 'young_adults' ? 'selected' : ''; ?>>junge Erwachsene</option>
</select>
</div>
<div class="form-group">
<label for="select-event-type">Nur folgende Veranstaltungsarten einbinden:</label>
<select class="form-control" name="REX_INPUT_VALUE[3]" id="select-event-type">
<option value="" <?= 'REX_VALUE[3]' == '' ? 'selected' : ''; ?>>deaktiviert</option>
<option value="camp" <?= 'REX_VALUE[3]' == 'camp' ? 'selected' : ''; ?>>Camp</option>
<option value="workshop" <?= 'REX_VALUE[3]' == 'workshop' ? 'selected' : ''; ?>>Workshop</option>
<option value="work_assignment" <?= 'REX_VALUE[3]' == 'work_assignment' ? 'selected' : ''; ?>>Arbeitseinsatz</option>
<option value="group_meeting" <?= 'REX_VALUE[3]' == 'group_meeting' ? 'selected' : ''; ?>>Aktiventreffen</option>
<option value="excursion" <?= 'REX_VALUE[3]' == 'excursion' ? 'selected' : ''; ?>>Exkursion</option>
<option value="other" <?= 'REX_VALUE[3]' == 'other' ? 'selected' : ''; ?>>Sonstige Veranstaltungen</option>
</select>
</div>
<div class="form-group">
<label>
<input type="hidden" name="REX_INPUT_VALUE[6]" value="false">
<input type="checkbox" name="REX_INPUT_VALUE[6]"
value="true" <?= 'REX_VALUE[6]' == 'true' ? 'checked' : ''; ?>> Text über den Veranstaltungen:
</label>
<input type="text" id="custom-title" class="form-control" name="REX_INPUT_VALUE[4]"
value="REX_VALUE[id=4 ifempty='Die nächsten Camps']" autocomplete="off">
</div>
<div class="form-group">
<label>Anzeige:</label>
<div class="checkbox">
<label>
<input type="hidden" name="REX_INPUT_VALUE[5]" value="false">
<input type="checkbox" name="REX_INPUT_VALUE[5]" value="true" <?= 'REX_VALUE[5]' == 'true' ? 'checked' : ''; ?>>
als Karten formatieren
</label>
</div>
</div>
<file_sep>/redaxo/data/addons/developer/modules/Artikel Navigation [25]/input.php
<?php
$mform = new MForm();
echo $mform->show();
<file_sep>/redaxo/data/addons/developer/modules/Text [9]/output.php
<!-- mod_editor -->
<?php
$block_id = 'REX_VALUE[2]';
$start_tag = '<div %%ID%%>';
$close_tag = '</div>';
if ($block_id) {
$start_tag = str_replace('%%ID%%', 'id="' . rex_escape($block_id) . '"', $start_tag);
} else {
$start_tag = str_replace('%%ID%%', '', $start_tag);
}
echo $start_tag;
echo 'REX_VALUE[1 output=html]';
echo $close_tag;
?>
<file_sep>/redaxo/data/addons/developer/modules/Kontakt-Informationen [4]/output.php
<!-- mod_contact_info -->
<?php
$local_group = 'REX_VALUE[1]';
$show_headline = 'REX_VALUE[2]' == 'true';
$show_business_headline = 'REX_VALUE[3]' == 'true';
$contact_info = rex_sql::factory()->setQuery(
'select office_name, business_hours, street, city, email, phone from naju_contact_info where group_id = :id', ['id' => $local_group]
)->getArray()[0];
?>
<div class="mt-3">
<?php if ($show_headline) : ?>
<h3>Kontakt</h3>
<?php endif; ?>
<address>
<?php if ($contact_info['office_name']) echo rex_escape($contact_info['office_name']) . ':<br>'; ?>
<?php if ($show_business_headline)
echo '<span class="font-italic">Öffnungszeiten</span>
<p class="address business-hours">' . nl2br(rex_escape($contact_info['business_hours'])) . '</p>'
?>
<?php if ($contact_info['street']) echo rex_escape($contact_info['street']) . '<br>'; ?>
<?php if ($contact_info['city']) echo rex_escape($contact_info['city']) . '<br>'; ?>
<?php
if ($contact_info['email']) {
$email = $contact_info['email'];
echo '<a href="mailto:' . rex_escape(rex_escape($email, 'url')) . '" class="contact-link">' . rex_escape($email) . '</a><br>';
}
?>
<?php
if ($contact_info['phone']) {
$phone = $contact_info['phone'];
echo '<a href="tel:' . rex_escape(rex_escape($phone, 'url')) . '" class="contact-link">' . rex_escape($phone) . '</a><br>';
}
?>
</address>
</div>
<file_sep>/redaxo/data/addons/developer/modules/Home Titel [18]/output.php
<!-- mod_home_title -->
REX_VALUE[1]<file_sep>/redaxo/data/addons/developer/modules/Gliederung [6]/input.php
<div class="form-group">
<label for="header-level">Stufe der Überschriften, für die die Gliederung erstellt werden soll</label>
<input type="number" min="2" max="6" name="REX_INPUT_VALUE[1]" id="header-level" value="REX_VALUE[1 ifempty=3]" class="form-control">
</div>
<div class="form-group">
<div class="checkbox">
<input type="hidden" name="REX_INPUT_VALUE[2]" value="false">
<label>
<input type="checkbox" name="REX_INPUT_VALUE[2]" value="true" <?= 'REX_VALUE[2]' === 'true' ? 'checked' : '' ?>> die Gliederung nur aus dem Modul "Überschrift" erstellen
</label>
</div>
</div><file_sep>/redaxo/data/addons/developer/modules/[Blog] Archiv [30]/input.php
<?php
$id_blog = 1;
$mform = MForm::factory();
$mform->addSelectField($id_blog);
$mform->setLabel('Blog auswählen');
if (rex::getUser()->isAdmin()) {
$query = 'SELECT blog_title as name, blog_id as id FROM naju_blog ORDER BY blog_title';
} else {
$user_id = rex::getUser()->getId();
$query = 'SELECT blog_title as name, blog_id as id
FROM naju_blog JOIN naju_group_account ON blog_group = group_id
WHERE account_id = ' . $user_id;
}
$mform->setSqlOptions($query);
echo $mform->show();
<file_sep>/redaxo/data/addons/developer/modules/Trennlinie [10]/output.php
<!-- mod_separator -->
<?php
$margin_top = 'REX_VALUE[id=1 ifempty=0]';
$margin_btm = 'REX_VALUE[id=2 ifempty=0]';
$show_hr = 'REX_VALUE[3]' == 'true';
$style = '';
if ($margin_top > 0) {
$style .= ' margin-top: ' . rex_escape($margin_top) . 'px; ';
}
if ($margin_btm > 0) {
$style .= ' margin-bottom: ' . rex_escape($margin_btm) . 'px; ';
}
if ($show_hr) {
echo '<hr style="' . $style . '">';
} else {
echo '<div style="' . $style . '"></div>';
}
?>
<file_sep>/redaxo/data/addons/developer/modules/Auflistung [22]/output.php
<!-- mod_listing -->
<?php
$fancy_effect_classes = ['img-fancy-default', 'img-fancy-green', 'img-fancy-green-alternate'];
$slice_id = 'REX_SLICE_ID';
$full_width = 'col-lg-12';
$wide_list_img_cols = 'REX_VALUE[id=4 ifempty=false]' == 'true';
$reduced_width = $wide_list_img_cols ? 'col-lg-8' : 'col-lg-9';
$offset_width = $wide_list_img_cols ? 'col-log-8 offset-lg-4' : 'col-lg-9 offset-lg-3';
$list_img_col_width = $wide_list_img_cols ? 'col-lg-4' : 'col-lg-3';
$display_style = 'REX_VALUE[id=1 ifempty=grid]';
$img_params = naju_rex_var::toArray('REX_VALUE[id=3]');
$img_width = $img_params['width'];
$img_height = $img_params['height'];
// check whether some value was set in the image effects checkbox and if so, use the fancy class
$img_effects = $img_params['enable_effects'] ?? '';
$img_effects = $img_effects ? 'img-fancy' : '';
$img_effect_style = $img_params['effect'] ?? 'random';
$img_suppress_rotate = $img_params['no_rotate_img'] ?? '';
$img_suppress_rotate = $img_suppress_rotate ? '' : ' img-fancy-rotate ';
// the tokens will contain a random prefix to minimize the chance of replacing actual
// content that just happens to look like a token
$card_id_token = '%%CARD_ID%%' . rand() . '%%';
$img_token = '%%IMG%%' . rand() . '%%';
$img_tag_token = '%%IMG_TAG%%' . rand() . '%%';
$title_token = '%%TITLE%%' . rand() . '%%';
$content_token = '%%CONTENT%%' . rand() . '%%';
$content_width_token = '%%CONTENT_WIDTH%%' . rand() . '%%';
$link_token = '%%LINK%%' . rand() . '%%';
$link_url_token = '%%LINK_URL%%' . rand() . '%%';
$link_label_token = '%%LINK_LABEL%%' . rand() . '%%';
$card_id_template = 'card-%s-%s';
$list_container = '<ul class="list-unstyled">%s</ul>';
$list_template = <<<EOHTML
<li class="media mb-3 row listing">
<div class="container-fluid">
<div class="row" id="$card_id_token">
$img_token
<div class="media-body $content_width_token col-md-12 col-sm-12 mt-2 listing-content">
<h4 class="media-heading">$title_token</h4>
$content_token
$link_token
<div class="listing listing-end"></div>
</div>
</div>
</div>
</li>
EOHTML;
$list_image_template = "<div class='$list_img_col_width col-md-12 col-sm-12'>
$img_tag_token
</div>";
$list_link_template = "<a href='$link_url_token'>$link_label_token</a>";
$card_container = '<div class="container-fluid"><div class="row listing-cards-container">%s</div></div>';
$card_template = <<<EOHTML
<div class="col-lg-4 col-md-12 col-sm-12 mb-2">
<div class="card listing-card d-block" id="$card_id_token">
$img_token
<div class="card-body">
<h4 class="card-title">$title_token</h4>
<p class="card-text">$content_token</p>
</div>
$link_token
</div>
</div>
EOHTML;
$card_image_template = "$img_tag_token";
$card_link_template = "<div class='card-footer'><a href='$link_url_token' class='btn btn-primary'>$link_label_token</a></div>";
$container = '';
$item_template = '';
$image_template = '';
$link_template = '';
$img_styles = '';
if ($img_width) {
$img_styles .= ' width: ' . rex_escape($img_width) . 'px; max-width: 100%;';
}
if ($img_height) {
$img_styles .= ' max-height: ' . rex_escape($img_height) . 'px; max-width: 100%;';
}
if ($display_style === 'media-list') {
$container = $list_container;
$item_template = $list_template;
$image_template = $list_image_template;
$image_classes = ['d-block', 'mx-auto'];
$link_template = $list_link_template;
} else {
$container = $card_container;
$item_template = $card_template;
$image_template = $card_image_template;
$image_classes = ['card-img-top', 'mx-auto'];
$link_template = $card_link_template;
}
$item_counter = 0;
$items = naju_rex_var::toArray('REX_VALUE[id=2]');
$contents = '';
$list_contains_images = false;
foreach ($items as $item) {
if ($item['REX_MEDIA_1']) {
$list_contains_images = true;
break;
}
}
foreach ($items as $item) {
$item_counter++;
$title = naju::escape($item['title']);
$img_path = $item['REX_MEDIA_1'];
$content = $item['content']; // content is rich HTML
$link = $item['REX_LINK_1'];
$formatted_item = str_replace($title_token, $title, $item_template);
$formatted_item = str_replace($card_id_token, sprintf($card_id_template, $slice_id, $item_counter), $formatted_item);
$formatted_item = str_replace($content_token, $content, $formatted_item);
// if the current item contains an image, generate the corresponding tag for it
// otherwise just drop the tag altogether
if ($list_contains_images) {
if ($img_path) {
$img = new naju_image($img_path);
$item_img_effects = array();
if ($img_effects) {
$item_img_effects = [$img_effects];
if ($img_effect_style == 'random') {
$item_img_effects[] = rex_escape($fancy_effect_classes[array_rand($fancy_effect_classes)]);
} else {
$item_img_effects[] = rex_escape($img_effect_style);
}
$item_img_effects[] = rex_escape($img_suppress_rotate);
}
$item_img_effects = array_merge($image_classes, $item_img_effects);
if ($img_width) {
$src_sizes = ['sizes' => rex_escape($img_width) . 'px'];
} elseif ($img_height) {
$size_ratio = $img_height / $img->height();
$width = ceil($size_ratio * $img->width());
$src_sizes = ['sizes' => $width . 'px'];
} else {
$src_sizes = ['sizes' => '25vw'];
}
$picture_tag = $img->generatePictureTag($item_img_effects, '', ['style' => $img_styles], $src_sizes, false);
$formatted_image = str_replace($img_tag_token, $picture_tag, $image_template);
$formatted_item = str_replace($img_token, $formatted_image, $formatted_item);
$formatted_item = str_replace($content_width_token, $reduced_width, $formatted_item);
} else {
$formatted_item = str_replace($img_token, '', $formatted_item);
$formatted_item = str_replace($content_width_token, $offset_width, $formatted_item);
}
} else {
$formatted_item = str_replace($img_token, '', $formatted_item);
$formatted_item = str_replace($content_width_token, $full_width, $formatted_item);
}
// if the current item contains a 'further reading' link, generate the correspoding anchor
// otherwise just drop the link from the rendered item
if ($link) {
$link_text = rex_escape($item['link_text']);
$link_text = $link_text ? $link_text : 'Weiterlesen';
$formatted_link = str_replace($link_url_token, rex_getUrl($link), $link_template);
$formatted_link = str_replace($link_label_token, $link_text , $formatted_link);
$formatted_item = str_replace($link_token, $formatted_link, $formatted_item);
} else {
$formatted_item = str_replace($link_token, '', $formatted_item);
}
$contents .= $formatted_item;
}
printf($container, $contents);
<file_sep>/redaxo/data/addons/developer/templates/Startseite [1]/template.php
<!doctype html>
<?php
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
$is_ios = str_contains($ua, 'iphone') || str_contains($ua, 'ipad');
?>
<html lang="de" <?= $is_ios ? 'ontouchmove' : ''; ?>>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= rex_escape($this->getValue('name')); ?> | <NAME></title>
<link rel="preload" href="/fonts/SourceSansPro-Regular.ttf" as="font" type="font/ttf" crossorigin="anonymous">
<link rel="preload" href="/fonts/Amaranth-Regular.ttf" as="font" type="font/ttf" crossorigin="anonymous">
<link rel="icon" href="/assets/favicon.ico">
<link rel="preload" href="/assets/grass-pattern.png" as="image">
<link rel="preload" href="/assets/bow-symmetrical.svg" as="image">
<link rel="preload" href="/assets/naju-sachsen-logo.webp" as="image">
<?php
echo '<style>';
readfile(rex_path::base('css/kernel.css'));
echo '</style>';
?>
REX_TEMPLATE[key=template-head-meta]
</head>
<body class="container-fluid">
<div id="complete-wrapper">
<div id="top-bar-wrapper" class="row">
REX_TEMPLATE[key=template-header]
</div>
<div id="nav-content-wrapper" class="row">
<div id="content-wrapper" class="col-lg-12 col-md-12 col-sm-12">
<!-- Main content -->
<main class="clearfix">
REX_ARTICLE[ctype=1]
<div class="container-fluid">
<div class="row">
<div class="col-lg-8 offset-lg-2">
<div id="content">
<article>
<header>
<h2 class="h1 page-title">REX_ARTICLE[ctype=3]</h2>
</header>
REX_ARTICLE[ctype=2]
</article>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
REX_TEMPLATE[key=template-footer-copyright]
REX_TEMPLATE[key=template-footer-navigation]
</div>
<script src="/js/compat.js"></script>
</body>
</html>
<?php naju_stats::logVisitor(); ?>
<file_sep>/redaxo/data/addons/developer/modules/[Blog] Teaser [29]/output.php
<!-- mod_blog_teaser -->
<?php
$show_newest = 'REX_VALUE[id=3 ifempty=false]' === 'true';
$newest_count = 'REX_VALUE[id=1 ifempty=2]';
$newest_blog = 'REX_VALUE[id=4 ifempty=all]';
$manual_articles = 'REX_VALUE[id=2]';
$sql = rex_sql::factory();
if ($show_newest) {
$criteria = $newest_blog == 'all' ? '' : ' AND article_blog = ' . $newest_blog;
$query = 'SELECT article_title, article_id, article_image, article_intro, blog_page
FROM naju_blog_article JOIN naju_blog ON article_blog = blog_id
WHERE article_status = "published" ' . $criteria . '
ORDER BY article_published DESC
LIMIT ' . $newest_count;
$articles = $sql->getArray($query);
} else {
$manual_articles = rex_var::toArray($manual_articles);
$article_ids = array();
foreach ($manual_articles as $article) {
$article_ids[] = $article['article_id'];
}
$article_ids = implode(', ', $article_ids);
$query = 'SELECT article_title, article_id, article_image, article_intro, blog_page
FROM naju_blog_article JOIN naju_blog ON article_blog = blog_id
WHERE article_id IN (' . $article_ids . ') AND article_status = "published"
ORDER BY article_published DESC';
$articles = $sql->getArray($query);
}
$content = '';
$content .= '<div class="blog-teaser container-fluid"><div class="row row-cols-1 row-cols-lg-3">';
foreach ($articles as $article) {
$card = '<div class="col mb-4"><article class="card">';
if ($article['article_image']) {
$img = new naju_image($article['article_image']);
$card .= $img->generatePictureTag(['card-img-top']);
}
$card .= '<div class="card-body">';
$card .= ' <h4 class="card-title">' . naju::escape($article['article_title']) . '</h4>';
$card .= ' <p class="card-text">' . rex_escape($article['article_intro']) . '</p>';
$card .= '</div>'; // <div class=card-body>
$card .= '<footer class="card-footer">';
$card .= ' <a class="btn btn-primary" href="' . rex_getUrl($article['blog_page'], null, ['blog_article' => $article['article_id']]) . '">Weiterlesen</a>';
$card .= '</footer>';
$card .= '</article></div>';
$content .= $card;
}
$content .= '</div></div>'; // <div class=blog-teaser>
echo $content;
<file_sep>/redaxo/data/addons/developer/modules/[Blog] Einzelner Beitrag [28]/output.php
<!-- mod_blog_single -->
<?php
$single_article_template = new rex_template(rex_article::getCurrent()->getTemplateId());
$article = naju_news_manager::fetchArticle('REX_VALUE[1]');
$content = '<article class="blog-article">';
if ($article['article_subtitle']) {
$subtitle = '<small class="d-block text-muted mt-2">' . rex_escape($article['article_subtitle']) . '</small>';
} else {
$subtitle = '';
}
$content .= '
<header>
<h2 class="page-title">' . rex_escape($article['article_title']) . $subtitle . '</h2>
</header>';
if ($article['article_intro'] && naju_news_article::featuresRealIntro($article)) {
$content .= '<p class="article-intro mx-5">' . rex_escape($article['article_intro']) . '</p>';
}
if ($article['article_image']) {
$img = new naju_image($article['article_image']);
$content .= '<div class="article-img">';
$content .= $img->generatePictureTag(['d-block', 'mx-auto', 'w-75', 'mb-3']);
$content .= '</div>';
}
$content .= '<div id="article-content">' . $article['article_content'] . '</div>';
if ($article['article_link']) {
$link_text = $article['article_link_text'] ? rex_escape($article['article_link_text']) : 'Weiterlesen';
$content .= '<footer class="article-footer clearfix">';
$content .= ' <a class="btn btn-primary float-right mr-2" href="' . rex_getUrl($article['article_link']) . '">' . $link_text . '</a>';
$content .= '</footer>';
}
$content .= '</article>';
echo $content;
<file_sep>/redaxo/data/addons/developer/modules/Foto [11]/output.php
<!-- mod_img -->
<?php
$img_src = 'REX_MEDIA[id=1]';
$img = $img_src ? new naju_image($img_src) : '';
$img_width = 'REX_VALUE[id=1 ifempty=-1]';
$img_height = 'REX_VALUE[id=2 ifempty=-1]';
$img_integrate = 'REX_VALUE[id=3 ifempty=no-integrate]';
$fancy_effects = 'REX_VALUE[id=4 ifempty="false"]' === 'true';
$show_author = 'REX_VALUE[id=7 ifempty="true"]' === 'true';
$img_class_base = 'mt-4 mb-4 ';
$img_class = '';
if ($fancy_effects) {
$chosen_class = 'REX_VALUE[id=5 ifempty="random"]';
$rotate_effect = 'REX_VALUE[id=6 ifempty="true"]' === 'true';
if ($chosen_class == 'random') {
$fancy_effect_classes = ['img-fancy-default', 'img-fancy-green', 'img-fancy-green-alternate'];
$chosen_class = $fancy_effect_classes[array_rand($fancy_effect_classes)];
}
$img_class .= ' img-fancy ' . $chosen_class . ' ';
if ($rotate_effect) {
$img_class .= ' img-fancy-rotate ';
}
}
$img_float = "";
$floating_img = false;
switch($img_integrate) {
case 'integrate-left':
$img_float = ' float-left mr-4 ';
$floating_img = true;
break;
case 'integrate-right':
$img_float = ' float-right ml-4 ';
$floating_img = true;
break;
case 'no-integrate':
// fall through
default:
$img_float = ' d-block mx-auto ';
$floating_img = false;
break;
}
$img_dimens = array();
$src_attrs = array();
if ($img_width > 0) {
$img_dimens['width'] = $img_width;
if ($img_width > 800) {
$src_attrs['sizes'] = '75vw';
}
}
if ($img_height > 0) {
$img_dimens['height'] = $img_height;
} else {
$img_class .= 'img-fluid ';
if (!$img_width) {
$src_attrs['sizes'] = '75vw';
}
}
$img_link = 'REX_LINK[id=1]';
// preambles
if ($img_link) {
echo '<a href="' . rex_getUrl($img_link) . '" class="img-link">';
}
if ($show_author) {
$float_option = $floating_img ? $img_float : 'clearfix';
echo '<figure class="' . $float_option . ' ' . $img_class_base .'">';
if (!$floating_img) {
$img_class .= $img_class_base . $img_float;
}
} else {
$img_class .= $img_class_base . $img_float;
}
if ($img_src) {
echo $img->generatePictureTag([$img_class], '', $img_dimens, $src_attrs, false);
}
// close preambles
if ($show_author) {
$float_option = $floating_img ? '' : 'float-right';
echo '<figcaption class="' . $float_option . ' mr-2">Foto: ' . rex_escape($img->author()) . '</figcaption>';
echo '</figure>';
}
if ($img_link) {
echo '</a>';
}
<file_sep>/redaxo/data/addons/developer/modules/Trennlinie [10]/input.php
<div class="form-group">
<label for="margin-top">Abstand nach oben</label>
<div class="input-group">
<input type="number" name="REX_INPUT_VALUE[1]" id="margin-top" value="REX_VALUE[1]" class="form-control">
<span class="input-group-addon">px</span>
</div>
</div>
<div class="form-group">
<label for="margin-btm">Abstand nach unten</label>
<div class="input-group">
<input type="number" name="REX_INPUT_VALUE[2]" id="margin-top" value="REX_VALUE[2]" class="form-control">
<span class="input-group-addon">px</span>
</div>
</div>
<div class="form-group">
<input type="hidden" name="REX_INPUT_VALUE[3]" value="false">
<label>
<input type="checkbox" name="REX_INPUT_VALUE[3]" value="true" <?= 'REX_VALUE[id=3 default=false]' === 'true' ? 'checked' : ''; ?>>
Trennlinie anzeigen?
</label>
</div>
<file_sep>/redaxo/data/addons/developer/modules/[Blog] Teaser [29]/input.php
<?php
$id_newest_count = 1;
$id_manual_select = 2;
$id_show_newest = 3;
$id_blog_select = 4;
$mform = MForm::factory();
// newest selection
$mform_tab = MForm::factory();
$mform_tab->addHiddenField($id_show_newest, 'false');
$mform_tab->addCheckboxField($id_show_newest, ['true' => 'Automatisch die neuesten Artikel anzeigen'], ['label' => '']);
$mform_tab->addSelectField($id_blog_select);
$mform_tab->setLabel('Blog auswählen');
if (rex::getUser()->isAdmin()) {
$query = 'SELECT CONCAT(blog_title, " (", group_name, ")") as name, blog_id as id
FROM naju_blog JOIN naju_local_group ON blog_group = group_id ORDER BY blog_title';
} else {
$user_id = rex::getUser()->getId();
$query = 'SELECT blog_title as name, blog_id as id FROM naju_blog JOIN naju_group_account ON blog_group = group_id
WHERE account_id = ' . $user_id . ' ORDER BY blog_title';
}
$mform_tab->setOption('all', 'alle');
$mform_tab->setSqlOptions($query);
$mform_tab->addInputField('number', $id_newest_count, ['label' => 'Anzahl', 'min' => '2']);
$mform->addTabElement('Neueste Artikel anzeigen', $mform_tab, true);
// manual selection
$mform_tab = MForm::factory();
$mblock = MForm::factory();
$mblock_fieldset = MForm::factory();
$mblock_fieldset->addSelectField("$id_manual_select.0,article_id");
$mblock_fieldset->setLabel('Auswählen:');
if (rex::getUser()->isAdmin()) {
$query = 'SELECT
CONCAT("[", blog_title , "] ", article_title, " (veröffentlicht ", DATE_FORMAT(article_published, "%d.%m.%y") ,")") as name,
article_id as id
FROM naju_blog_article JOIN naju_blog ON article_blog = blog_id
WHERE article_status = "published"
ORDER BY blog_title, article_published, article_updated, article_title';
} else {
$user_id = rex::getUser()->getId();
$query = 'SELECT
CONCAT("[", blog_title , "] ", article_title, " (veröffentlicht ", DATE_FORMAT(article_published, "%d.%m.%y") ,")") as name,
article_id as id
FROM naju_blog_article JOIN naju_blog JOIN naju_group_account ON article_blog = blog_id AND blog_group = group_id
WHERE article_status = "published" AND account_id = ' . $user_id . '
ORDER BY blog_title, article_published, article_updated, article_title';
}
$mblock_fieldset->setSqlOptions($query);
$mblock_fieldset->setAttributes(['class' => 'selectpicker', 'data-live-search' => 'true']);
$mblock->addFieldsetArea('Artikel', $mblock_fieldset);
$mform_tab->addHtml(MBlock::show($id_manual_select, $mblock->show(), ['min' => '2']));
$mform->addTabElement('Manuell auswählen', $mform_tab);
echo $mform->show();
<file_sep>/redaxo/data/addons/developer/modules/Tabelle [24]/output.php
<!-- mod_table -->
<?php
// Redactor does not enable the specification of custom CSS classes on the table.
// Therefore we've got to add them by ourselves.
$table_content = 'REX_VALUE[id=1 output=html]';
$table_tag = '<table class="table">';
$table_content = preg_replace('/(\<table>).*/', $table_tag, $table_content, $count = 1);
?>
<div class="table-fluid">
<?= $table_content; ?>
</div>
<file_sep>/redaxo/data/addons/developer/modules/Statistiken Export [13]/output.php
<?php
$authentication_required = true;
if (!rex::isBackend()) {
$stats_credential = rex_post('Stats-Credential');
if ($authentication_required && !$stats_credential) {
rex_response::setStatus(401); // 401 Unauthorized means 'No authentication provided' (!!!)
$post_content = '';
foreach ($_POST as $key => $val) {
$post_content .= "$key: $val\r\n";
}
$get_content = '';
foreach ($_GET as $key => $val) {
$get_content .= "$key: $val\r\n";
}
rex_response::sendContent('You must authenticate with your stats credential token: ' . $post_content);
} elseif ($authentication_required && !naju_credentials::checkToken($stats_credential)) {
rex_response::setStatus(403); // 403 Forbidden means authorization failed
rex_response::sendContent('Invalid stats credential token');
} else {
$stats_csv = "timestamp,page,referer\r\n";
$from = rex_get('from', 'string', null);
$to = rex_get('to', 'string', null);
$log_entries = naju_stats::fetchStats($from, $to);
foreach ($log_entries as $entry) {
$stats_csv .= "{$entry['timestamp']},{$entry['page']},{$entry['referer']}\r\n";
}
rex_response::setHeader('Content-Type', 'text/csv');
rex_response::sendContent($stats_csv);
}
} else {
echo 'Hier wird die Besucherstatistik angezeigt';
}
<file_sep>/redaxo/data/addons/developer/modules/Diashow [16]/output.php
<?php
$images = explode(',', 'REX_MEDIALIST[1]');
$slice_id = 'REX_VALUE[1]';
$max_height = 'REX_VALUE[2]';
$show_id = 'diashow-' . $slice_id;
?>
<div id="<?= $show_id; ?>" class="diashow carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<?php foreach ($images as $idx => $img) : ?>
<li data-target="#<?= $show_id; ?>" data-slide-to="<?= $idx; ?>" class="<?= $idx == 0 ? 'active' : ''; ?>"></li>
<?php endforeach; ?>
</ol>
<div class="carousel-inner">
<?php foreach ($images as $idx => $img) : ?>
<div class="carousel-item <?= $idx == 0 ? 'active' : ''; ?>">
<?php
if (!$img) {
continue;
}
$img = new naju_image($img);
if ($max_height) {
$style = "height: 500px; background-image: url('" . $img->optimizedUrl() . "'); background-size: contain; ";
$style .= " background-repeat: no-repeat; background-position: center;";
echo '<div class="webp-fallback" style="' . $style . '" aria-label="' . rex_escape($img->altText()) . '" data-webp-fallback="' . $img->url() . '"></div>';
} else {
echo $img->generatePictureTag(['d-block', 'w-100']);
}
?>
</div>
<?php endforeach; ?>
</div>
<a class="carousel-control-prev" href="#<?= $show_id; ?>" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#<?= $show_id; ?>" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<file_sep>/redaxo/data/addons/developer/modules/Karten Uebersicht [7]/input.php
<div class="form-group">
<label for="cards-count">Anzahl der aktiven Karten</label>
<input type="number" name="REX_INPUT_VALUE[20]" id="cards-count" min="2" max="4" value="REX_VALUE[id=20 ifempty=3]" class="form-control" />
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
<?php $card1 = naju_rex_var::toArray('REX_VALUE[1]'); ?>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Karte 1</h3>
</div>
<div class="panel-body">
<div class="form-group">
<label for="panel-1-title">Titel</label>
<input type="text" name="REX_INPUT_VALUE[1][title]" id="panel-1-title" class="form-control" value="<?= rex_escape($card1['title']) ?? ''; ?>" />
</div>
<div class="form-group">
<label for="panel-1-content">Inhalt</label>
<textarea name="REX_INPUT_VALUE[1][content]" rows="3" id="panel-1-content" class="form-control"><?= rex_escape($card1['content']) ?? ''; ?></textarea>
</div>
<div class="form-group">
<label>Bild</label>
REX_MEDIA[id=1 widget=1 types=jpg,jpeg,png preview=1]
</div>
<div class="form-group">
<label for="panel-1-link-text">Link Text</label>
<input type="text" name="REX_INPUT_VALUE[1][link-text]" id="panel-1-link-text" class="form-control" value="<?= rex_escape($card1['link-text']) ?? ''; ?>"/>
</div>
<div class="form-group">
<label>Link Ziel</label>
REX_LINK[id=1 widget=1]
</div>
</div>
</div>
</div>
<div class="col-md-6">
<?php $card2 = naju_rex_var::toArray('REX_VALUE[2]'); ?>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Karte 2</h3>
</div>
<div class="panel-body">
<div class="form-group">
<label for="panel-2-title">Titel</label>
<input type="text" name="REX_INPUT_VALUE[2][title]" id="panel-2-title" class="form-control" value="<?= rex_escape($card2['title']) ?? ''; ?>" />
</div>
<div class="form-group">
<label for="panel-2-content">Inhalt</label>
<textarea name="REX_INPUT_VALUE[2][content]" rows="3" id="panel-2-content" class="form-control"><?= rex_escape($card2['content']) ?? ''; ?></textarea>
</div>
<div class="form-group">
<label>Bild</label>
REX_MEDIA[id=2 widget=1 types=jpg,jpeg,png preview=1]
</div>
<div class="form-group">
<label for="panel-2-link-text">Link Text</label>
<input type="text" name="REX_INPUT_VALUE[2][link-text]" id="panel-2-link-text" class="form-control" value="<?= rex_escape($card2['link-text']) ?? ''; ?>"/>
</div>
<div class="form-group">
<label>Link Ziel</label>
REX_LINK[id=2 widget=1]
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<?php $card3 = naju_rex_var::toArray('REX_VALUE[3]'); ?>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Karte 3</h3>
</div>
<div class="panel-body">
<div class="form-group">
<label for="panel-3-title">Titel</label>
<input type="text" name="REX_INPUT_VALUE[3][title]" id="panel-3-title" class="form-control" value="<?= rex_escape($card3['title']) ?? ''; ?>" />
</div>
<div class="form-group">
<label for="panel-3-content">Inhalt</label>
<textarea name="REX_INPUT_VALUE[3][content]" rows="3" id="panel-3-content" class="form-control"><?= rex_escape($card3['content']) ?? ''; ?></textarea>
</div>
<div class="form-group">
<label>Bild</label>
REX_MEDIA[id=3 widget=1 types=jpg,jpeg,png preview=1]
</div>
<div class="form-group">
<label for="panel-3-link-text">Link Text</label>
<input type="text" name="REX_INPUT_VALUE[3][link-text]" id="panel-3-link-text" class="form-control" value="<?= rex_escape($card3['link-text']) ?? ''; ?>"/>
</div>
<div class="form-group">
<label>Link Ziel</label>
REX_LINK[id=3 widget=1]
</div>
</div>
</div>
</div>
<div class="col-md-6">
<?php $card = naju_rex_var::toArray('REX_VALUE[4]'); ?>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Karte 4</h3>
</div>
<div class="panel-body">
<div class="form-group">
<label for="panel-4-title">Titel</label>
<input type="text" name="REX_INPUT_VALUE[4][title]" id="panel-4-title" class="form-control" value="<?= rex_escape($card4['title']) ?? ''; ?>" />
</div>
<div class="form-group">
<label for="panel-4-content">Inhalt</label>
<textarea name="REX_INPUT_VALUE[4][content]" rows="3" id="panel-4-content" class="form-control"><?= rex_escape($card4['content']) ?? ''; ?></textarea>
</div>
<div class="form-group">
<label>Bild</label>
REX_MEDIA[id=4 widget=1 types=jpg,jpeg,png preview=1]
</div>
<div class="form-group">
<label for="panel-4-link-text">Link Text</label>
<input type="text" name="REX_INPUT_VALUE[4][link-text]" id="panel-4-link-text" class="form-control" value="<?= rex_escape($card4['link-text']) ?? ''; ?>"/>
</div>
<div class="form-group">
<label>Link Ziel</label>
REX_LINK[id=4 widget=1]
</div>
</div>
</div>
</div>
</div>
</div>
<file_sep>/redaxo/data/addons/developer/modules/Gliederung [6]/output.php
<!-- mod_in_page_nav -->
<?php if (rex::isFrontend()) : ?>
<h3 class="mt-4">Übersicht</h3>
<nav id="page-nav-REX_SLICE_ID" class="page-nav">
<ul class="nav flex-column">
<!-- Menu content goes here -->
</ul>
<template id="page-nav-template-REX_SLICE_ID">
<li class="nav-item">
<a class="nav-link"></a>
</li>
</template>
</nav>
<script>
const sel = '#content hREX_VALUE[1]:not(.page-title)<?= 'REX_VALUE[id=2 ifempty=false]' === 'true' ? '.content-heading' : ''; ?>';
document.addEventListener('DOMContentLoaded', () => {
const headerNodes = document.querySelectorAll(sel);
if (!headerNodes) {
exit;
}
const headers = [];
// for all headers which do not have an ID we need to create one manually
for (let header of headerNodes) {
if (!header.id) {
// the ID will be based on the header's content
let generatedId = null;
for (const headerContent of header.childNodes) {
if (headerContent.nodeType === Node.TEXT_NODE) {
generatedId = headerContent.nodeValue;
break;
}
}
if (!generatedId) {
generatedId = header.innerText;
}
// but in a simplified version with all lower case
generatedId = generatedId.toLowerCase();
// without whitespace
generatedId = generatedId.replace(/ /g, '-');
// with expanded umlauts
generatedId = generatedId.replace(/ä/g, 'ae');
generatedId = generatedId.replace(/ö/g, 'oe');
generatedId = generatedId.replace(/ü/g, 'ue');
generatedId = generatedId.replace(/ß/g, 'ss');
// and only basic characters
generatedId = generatedId.replace(/[^a-z0-9_-]/g, '');
// we also need to make sure we did not create an ID that is already used by accident
while (document.getElementById(generatedId)) {
generatedId += '1';
}
header.id = generatedId;
}
headers.push(header);
}
// We will try to generate the heading based on the templating mechanism.
// If that fails we will use old-school string interpolation instead
if ('content' in document.createElement('template')) {
const template = document.getElementById('page-nav-template-REX_SLICE_ID');
const nav = document.querySelector('#page-nav-REX_SLICE_ID ul');
for (let heading of headers) {
const menuEntry = template.content.cloneNode(true);
const anchor = menuEntry.querySelector('a');
anchor.href = '#' + heading.id;
let headingText = null;
for (const headingContent of heading.childNodes) {
if (headingContent.nodeType === Node.TEXT_NODE) {
headingText = headingContent.nodeValue;
break;
}
}
if (!headingText) {
headingText = heading.innerText;
}
anchor.innerText = headingText;
nav.appendChild(menuEntry);
}
}
});
</script>
<?php else: ?>
<h3>Gliederung</h3>
<p class="alert alert-info">Die Gliederung wird nur im Frontend generiert</p>
<?php endif; ?>
<file_sep>/redaxo/data/addons/developer/modules/Veranstaltungsdetails [15]/input.php
<?php
$current_year = date('Y') . '-01-01';
$event_query = <<<EOSQL
select event_id, event_name, group_name, event_start
from naju_event
join naju_local_group on event_group = group_id
where event_start >= :date and event_active = true
order by event_start
EOSQL;
$events = rex_sql::factory()->setQuery($event_query, ['date' => $current_year])->getArray();
$current_event_year = null;
?>
<div class="form-group">
<label for="select-event">Veranstaltung auswählen</label>
<select class="form-control" name="REX_INPUT_VALUE[1]">
<?php foreach ($events as $event) :
$event_text = rex_escape($event['event_name']) . ' (' . rex_escape($event['group_name']) . ')';
$event_year = date_parse($event['event_start'])['year'];
if ($event_year > $current_event_year) {
// if the $current_event_year is set, this means that at least one group has already started. That one needs
// to be closed first
if ($current_event_year) {
echo '</optgroup>';
}
echo '<optgroup label="' . rex_escape($event_year) . '">';
$current_event_year = $event_year;
}
?>
<option value="<?= rex_escape($event['event_id']); ?>" <?= "REX_VALUE[id=1 ifempty='']" == $event['event_id'] ? 'selected' : ''; ?>>
<?= $event_text; /* $event_text has already been escaped */ ?>
</option>
<?php endforeach; ?>
</optgroup>
</select>
</div>
<file_sep>/redaxo/data/addons/developer/modules/Artikel Navigation [25]/output.php
<!-- mod_article_nav -->
<?php
$content = '<div class="row row-cols-1 row-cols-md-3">';
$articles = rex_category::getCurrent()->getArticles(true);
foreach ($articles as $article) {
if ($article->getId() == rex_article::getCurrentId()) {
continue;
}
$content .= '<div class="col mb-4-md mb-3"><div class="card card-dense"><div class="card-body">';
$content .= '<h4 class="card-title">' . rex_escape($article->getName()) . '</h4>';
$content .= '<a href="' . rex_getUrl($article->getId()) . '" class="article-link">Weiterlesen</a>';
$content .= '</div></div></div>';
}
$content .= '</div>';
echo $content;
<file_sep>/redaxo/data/addons/developer/modules/Social Media [17]/output.php
<!-- mod_social_media -->
<?php
$group_id = 'REX_VALUE[1]';
$group_query = 'select facebook, instagram from naju_contact_info where group_id = :id';
$group = rex_sql::factory()->setQuery($group_query, ['id' => $group_id])->getArray()[0];
$include_heading = 'REX_VALUE[2]' == 'true';
?>
<div class="mt-3">
<?php if ($include_heading) : ?>
<h3>Social Media</h3>
<?php endif; ?>
<?php if ($group['facebook']) : ?>
<a href="<?= $group['facebook']; ?>" target="_blank" rel="noopener noreferrer" class="link-mute mr-4">
<picture>
<source type="image/webp" srcset="/assets/facebook-logo.webp">
<img src="/assets/facebook-logo.png" alt="Logo of the Facebook social network" class="social-logo">
</picture>
</a>
<?php endif; ?>
<?php if ($group['instagram']) : ?>
<a href="https://instagram.com/<?= $group['instagram']; ?>" target="_blank" rel="noopener noreferrer" class="link-mute mr-4">
<picture>
<source type="image/webp" srcset="/assets/instagram-logo.webp">
<img src="/assets/instagram-logo.png" alt="Logo of the Instagram social network" class="social-logo">
</picture>
</a>
<?php endif; ?>
<?php if ($group['whatsapp']) : ?>
<a href="<?= $group['whatsapp']; ?>" target="_blank" rel="noopener noreferrer" class="link-mute mr-4">
<picture>
<source type="image/webp" srcset="/assets/whatsapp-logo.webp">
<img src="/assets/whatsapp-logo.png" alt="Logo of the Whatsapp messenger" class="social-logo">
</picture>
</a>
<?php endif; ?>
<?php if ($group['telegram']) : ?>
<a href="<?= $group['telegram']; ?>" target="_blank" rel="noopener noreferrer" class="link-mute mr-4">
<picture>
<source type="image/webp" srcset="/assets/telegram-logo.webp">
<img src="/assets/telegram-logo.png" alt="Logo of the Telegram messenger" class="social-logo">
</picture>
</a>
<?php endif; ?>
</div>
<file_sep>/redaxo/data/addons/developer/modules/Piktogramm [23]/input.php
REX_MEDIA[id=1 widget=1 category=13]
<file_sep>/redaxo/data/addons/developer/modules/[Blog] Archiv [30]/output.php
<!-- mod_blog_archive -->
<?php
$blog = 'REX_VALUE[1]';
$slice = 'REX_SLICE_ID';
$sql = rex_sql::factory();
$query = 'SELECT article_id, article_title, article_subtitle, article_intro, article_content, article_image, article_published
FROM naju_blog_article WHERE article_status = "archived" ORDER BY article_updated DESC';
$articles = $sql->getArray($query);
if ($articles) {
$years = array();
foreach ($articles as $article) {
$published = explode('-', $article['article_published'])[0];
$years[] = $published;
}
rsort($years);
$years = array_unique($years);
$year_nav = 'blog-archive-years-' . $slice;
$content = '<div class="container-fluid"><div class="row align-items-start">';
// year navigation
$content .= '<div class="col-sm-12 col-md-3 order-sm-1 order-md-2 sticky-top pt-3">';
$content .= ' <nav class="nav flex-column" id="' . $year_nav . '">';
foreach ($years as $year) {
$content .= ' <a class="nav-link" href="#blog-' . $slice . '-articles-' . $year . '">' . $year . '</a>';
}
$content .= ' </nav>';
$content .= '</div>'; // year navigation
// article list
$initial_year = '9999';
$article_id_base = 'blog-archive-article-';
$current_year = $initial_year;
$content .= '<div class="col-sm-12 col-md-9 order-sm-2 order-md-1 blog-archive-container" data-spy="scroll" data-target="#' . $year_nav . '" data-offset="0">';
foreach ($articles as $article) {
$published = explode('-', $article['article_published'])[0];
if ($published < $current_year) {
if ($current_year !== $initial_year) {
$content .= '</div>'; // close previously opened article accordion first
}
$content .= '<h3 id="blog-' . $slice . '-articles-' . $published . '">' . $published . '</h3>';
$content .= '<div class="accordion blog-year-archive" id="blog-archive-' . $published . '">';
$current_year = $published;
}
$article_id = $article_id_base . $article['article_id'];
$content .= '<article class="blog-archive-article-container">';
$content .= ' <h4>';
$content .= ' <button type="button" class="article-controller btn btn-mute text-left article-title" data-toggle="collapse" data-target="#' . $article_id . '" aria-controls="' . $article_id . '" aria-expanded="false">';
$content .= rex_escape($article['article_title']) . '<small class="text-muted article-subtitle">' . rex_escape($article['article_subtitle']) . '</small>';
$content .= ' </button>';
$content .= ' </h4>';
$content .= ' <div id="' . $article_id . '" class="collapse" data-parent="#blog-archive-' . $published . '">';
if ($article['article_intro'] && naju_news_article::featuresRealIntro($article)) {
$content .= '<p class="mx-5">' . rex_escape($article['article_intro']) . '</p>';
}
if ($article['article_image']) {
$img = new naju_image($article['article_image']);
$content .= $img->generatePictureTag(['d-block', 'mx-auto', 'w-75', 'mb-3'], ['sizes' => '70vw']);
}
$content .= $article['article_content'];
$content .= ' </div>';
$content .= '</article>';
}
$content .= '</div></div>'; // close final article acordion as well as entire article container
$content .= '</div></div>'; // <div class=container>
echo $content;
} else {
echo '<div class="mx-auto"><p class="alert alert-secondary">Aktuell ist das Archiv noch leer.</p></div>';
}
<file_sep>/redaxo/data/addons/developer/modules/Foto [11]/input.php
<?php
$img_id = 1; // MEDIA type --> separate media ID
$link_id = 1; // LINK type --> separate link ID
$width_id = 1; // normal type --> true IDs start here
$height_id = 2;
$integrate_id = 3;
$activate_effects_id = 4;
$effects_kind_id = 5;
$effects_rotate_id = 6;
$hide_author_id = 7;
$effects_kind_select = ['random' => 'zufällig',
'img-fancy-default' => 'Standard (Dunkelrot)',
'img-fancy-green' => 'Maigrün (Hellgrün)',
'img-fancy-green-alternate' => 'Laubgrün (Dunkelgrün)'];
$integrate_select = ['no-integrate' => 'nicht integrieren',
'integrate-left' => 'links abbilden',
'integrate-right' => 'rechts abbilden'];
$mform = MForm::factory();
$mform_tab = MForm::factory();
$mform_tab->addMediaField($img_id, ['preview' => '1', 'types' => naju_image::ALLOWED_TYPES, 'label' => 'Bild auswählen']);
$mform_tab->addLinkField($link_id, ['label' => 'Verlinkung hinzufügen?']);
$mform_tab->addCheckboxField($hide_author_id, ['false' => 'Fotograf*in ausblenden'], ['label' => 'Fotograf*in']);
$mform_tab->addDescription("Zu jedem Bild _muss_ der*die Fotograf*in angegeben werden! Wenn nicht direkt am Bild, dann im Begleittext!");
$mform->addTabElement('Bild', $mform_tab, true);
$mform_tab = MForm::factory();
$mform_tab->addHiddenField($activate_effects_id, 'false');
$mform_tab->addCheckboxField($activate_effects_id, ['true' => 'tolle Bildeffekte aktivieren'], ['label' => 'Aktivieren?']);
$mform_tab->addSelectField($effects_kind_id, $effects_kind_select, ['label' => 'Effektfarbe:']);
$mform_tab->addHiddenField($effects_rotate_id, 'true');
$mform_tab->addCheckboxField($effects_rotate_id, ['false' => 'Rotation ausschalten'], ['label' => 'Weiteres']);
$mform->addTabElement('Bildeffekte', $mform_tab);
$mform_tab = MForm::factory();
$mform_tab->addInputField('number', $width_id, ['label' => 'Breite', 'min' => -1]);
$mform_tab->addInputField('number', $height_id, ['label' => 'Höhe', 'min' => -1]);
$mform_tab->addSelectField(3, $integrate_select, ['label' => 'Bild in den Textfluss integrieren?']);
$mform->addTabElement('Optionen', $mform_tab);
echo $mform->show();
<file_sep>/redaxo/data/addons/developer/modules/Notiz [26]/output.php
<?php
if (rex::isBackend()) {
echo '<div class="alert alert-info">REX_VALUE[1]</div>';
}
<file_sep>/redaxo/data/addons/developer/modules/Ueberschrift [8]/output.php
<!-- mod_heading -->
<?php
$content = 'REX_VALUE[id=1]';
$raw_level = 'REX_VALUE[id=2 ifempty=2]';
$level = 'h' . $raw_level;
$subtitle = 'REX_VALUE[id=3]';
if ($subtitle) {
$subtitle = '<small class="d-block text-muted">' . $subtitle . '</small>';
}
$classes = ' content-heading ';
if ($this->getValue('art_custom_title') === '|true|' && $raw_level <= 2) {
$classes .= ' page-title ';
}
echo "<header><$level class='$classes'>" . $content . $subtitle . "</$level></header>";
?>
<file_sep>/redaxo/data/addons/developer/modules/Iframe [20]/output.php
<!-- mod_iframe -->
<?php
$height = 'REX_VALUE[id=3 ifempty=0]';
if ($height) {
$height = $height . 'vh';
}
?>
<div class="container-fluid">
<article class="iframe-container load-on-demand" data-iframe-src="REX_VALUE[1]" data-iframe-height="<?= $height; ?>">
<p class="iframe-load-description">
Hier soll Inhalt aus einer externen Quelle angezeigt werden.
Dabei werden Daten an den jeweiligen Anbieter übertragen.
</p>
<button type="button" class="iframe-load-btn">Jetzt laden</button>
<iframe src="" class="iframe-holder d-none"></iframe>
</article>
</div>
<file_sep>/redaxo/data/addons/developer/modules/Kontakt-Informationen [4]/input.php
<?php
$local_groups = rex_sql::factory()->setQuery('select group_id, group_name from naju_local_group')->getArray();
$rex_var_group = "REX_VALUE[id=1 ifempty='']";
$rex_var_heading = "REX_VALUE[id=2 ifempty='']";
$rex_var_business_hours = "REX_VALUE[id=3 ifempty='']";
?>
<div class="form-group">
<label for="select-local-group">Ortsgruppe auswählen</label>
<select class="form-control" name="REX_INPUT_VALUE[1]">
<?php foreach ($local_groups as $group) : ?>
<option value="<?= rex_escape($group['group_id']); ?>" <?= $rex_var_group == $group['group_id'] ? 'selected' : '' ?>>
<?= rex_escape($group['group_name']); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="hidden" name="REX_INPUT[2]" value="false">
<input type="checkbox" name="REX_INPUT_VALUE[2]" value="true" <?= $rex_var_heading == 'true' ? 'checked' : '' ?>>
Überschrift über den Kontakt-Informationen anzeigen
</label>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="hidden" name="REX_INPUT[3]" value="false">
<input type="checkbox" name="REX_INPUT_VALUE[3]" value="true" <?= $rex_var_business_hours == 'true' ? 'checked' : '' ?>>
Büro-Öffnungszeiten anzeigen
</label>
</div>
</div>
<file_sep>/redaxo/data/addons/developer/modules/Text [9]/input.php
<?php
$full_redactor_profile = 'full';
$reduced_redactor_profile = 'links-bold-italic-lists';
$editor_type = rex::getUser()->isAdmin() ? $full_redactor_profile : $reduced_redactor_profile;
?>
<fieldset class="form-horizontal">
<div class="form-group">
<textarea class="form-control redactorEditor2-<?= $editor_type; ?>" name="REX_INPUT_VALUE[1]">REX_VALUE[1]</textarea>
</div>
</fieldset>
<fieldset>
<legend>Weitere Optionen:</legend>
<div class="form-group">
<label for="text-id">Dem Text eine ID geben</label>
<input type="text" name="REX_INPUT_VALUE[2]" id="text-id" class="form-control" value="REX_VALUE[2]">
</div>
</fieldset>
<file_sep>/redaxo/data/addons/developer/templates/Navigation [5]/template.php
<!-- temp_navigation -->
<?php
$active_ids = naju_navigation::collect_active_category_ids();
?>
<nav id="main-nav" class="col-lg-2 col-md-12">
<ul class="nav nav-primary flex-column">
<?php foreach(rex_category::getRootCategories(true) as $cat) : ?>
<li class="nav-item">
<?php $is_active = in_array($cat->getId(), $active_ids) ? 'active' : ''; ?>
<a href="<?= $cat->getUrl(); ?>" class="nav-link <?= $is_active; ?>">
<?= rex_escape($cat->getValue('catname')) ?>
</a>
<?= naju_navigation::inflate_subnav($cat, $active_ids); ?>
</li>
<?php endforeach; ?>
</ul>
</nav>
<file_sep>/redaxo/data/addons/developer/modules/Karten Uebersicht [7]/output.php
<!-- mod_overview_cards -->
<?php
$bs_cols = 12; // the number of columns in a Bootstrap grid
$n_cards = 'REX_VALUE[20]';
$col_lg_width = $bs_cols / $n_cards;
$image_names = array();
$images = array();
$image_names[] = 'REX_MEDIA[id=1 ifempty=default-card-image.jpg]';
$image_names[] = 'REX_MEDIA[id=2 ifempty=default-card-image.jpg]';
if ($n_cards >= 3) {
$image_names[] = 'REX_MEDIA[id=3 ifempty=default-card-image.jpg]';
}
if ($n_cards >= 4) {
$image_names[] = 'REX_MEDIA[id=4 ifempty=default-card-image.jpg]';
}
foreach ($image_names as $img) {
$images[] = new naju_image($img);
}
?>
<?php
if (rex::isBackend()) {
$ratios = array();
foreach ($images as $img) {
if (!in_array($img->aspectRatio(), $ratios)) {
$ratios[] = $img->aspectRatio();
}
}
if (sizeof($ratios) > 1) {
$ratio_details = '<ul class="list-group">';
foreach ($images as $img) {
$name = $img->name();
$ratio = naju_image::aspectRatioName($img);
$ratio_details .= "<li class=\"list-group-item list-group-item-warning\" style=\"color:white;\">$name: $ratio</li>";
}
$ratio_details .= '</ul>';
echo "
<p class=\"alert alert-warning\">
Die Bilder haben verschiedene Seitenverhältnisse. Die Karten werden damit unterschiedliche Größen
aufweisen. <strong>Es wird dringend empfohlen, die Bilder entsprechend anzupassen.</strong><br>
</p><p class=\"alert alert-warning\">Folgende Seitenverhältnisse wurden gefunden:</p>$ratio_details";
}
}
?>
<div class="container-fluid mb-4">
<div class="row">
<div class="card-deck overview-cards">
<article class="card">
<?php
$card1 = naju_rex_var::toArray('REX_VALUE[1]');
$img1 = $images[0];
echo $img1->generatePictureTag(['card-img-top']);
?>
<div class="card-body">
<h3 class="card-title"><?= naju::escape($card1['title']); ?></h3>
<p class="card-text"><?= naju::escape($card1['content']); ?></p>
</div>
<footer class="card-footer">
<a class="btn btn-primary" href="REX_LINK[id=1 output=url]" role="button"><?= rex_escape($card1['link-text']) ?? ''; ?></a>
</footer>
</article>
<article class="card">
<?php
$card2 = naju_rex_var::toArray('REX_VALUE[2]');
$img2 = $images[1];
echo $img2->generatePictureTag(['card-img-top']);
?>
<div class="card-body">
<h3 class="card-title"><?= naju::escape($card2['title']); ?></h3>
<p class="card-text"><?= naju::escape($card2['content']); ?></p>
</div>
<footer class="card-footer">
<a class="btn btn-primary" href="REX_LINK[id=2 output=url]" role="button"><?= rex_escape($card2['link-text']) ?? ''; ?></a>
</footer>
</article>
<?php if($n_cards >= 3) : ?>
<article class="card">
<?php
$card3 = naju_rex_var::toArray('REX_VALUE[3]');
$img3 = $images[2];
echo $img3->generatePictureTag(['card-img-top']);
?>
<div class="card-body">
<h3 class="card-title"><?= naju::escape($card3['title']); ?></h3>
<p class="card-text"><?= naju::escape($card3['content']); ?></p>
</div>
<footer class="card-footer">
<a class="btn btn-primary" href="REX_LINK[id=3 output=url]" role="button"><?= rex_escape($card3['link-text']) ?? ''; ?></a>
</footer>
</article>
<?php endif; ?>
<?php if($n_cards >= 4) : ?>
<article class="card">
<?php
$card4 = naju_rex_var::toArray('REX_VALUE[4]');
$img4 = $images[3];
echo $img4->generatePictureTag(['card-img-top']);
?>
<div class="card-body">
<h3 class="card-title"><?= naju::escape($card4['title']); ?></h3>
<p class="card-text"><?= naju::escape($card4['content']); ?></p>
</div>
<footer class="card-footer">
<a class="btn btn-primary" href="REX_LINK[id=4 output=url]" role="button"><?= rex_escape($card4['link-text']) ?? ''; ?></a>
</footer>
</article>
<?php endif; ?>
</div>
</div>
</div>
<file_sep>/redaxo/data/addons/developer/modules/Test [3]/input.php
<input type="text" name="<?= 'REX_'; ?>INPUT_VALUE[1]" /> | a0d2291992e15a10150fc6c9ea510485e8913de3 | [
"Markdown",
"Python",
"JavaScript",
"PHP"
]
| 54 | PHP | NAJU-Sachsen/Homepage | 45e00d16abeb5c69077f25c683cdedf6911faf24 | 7ce91936bbc6a84b991f2e476e617a3adc7ad37f |
refs/heads/master | <file_sep><?php
namespace RakeTechTest;
class HealthController
{
public static function GetHealthStatus()
{
return true;
}
}
<file_sep><?php
namespace RakeTechTest;
class FormClientController
{
public static function ClientSubmitMessage($data)
{
return $data;
}
}
<file_sep><?php
namespace RakeTechTest;
include_once($_SERVER["DOCUMENT_ROOT"] . "/wp-content/plugins/raketech-form-test/Form-API/controllers/FormClient.controller.php");
class FormClientRoutes
{
static $namespace = "/raketech-form-test/v1";
public static function FormClientRoutes()
{
register_rest_route(self::$namespace, '/form-client/submit-message', array(
'methods' => 'POST',
'callback' => function ($request) {
return FormClientController::ClientSubmitMessage($request->get_body());
}
));
register_rest_route(self::$namespace, '/form-client/submit-message/get', array(
'methods' => 'GET',
'callback' => function ($request) {
return FormClientController::ClientSubmitMessage($request->get_body());
}
));
}
}
<file_sep><?php
namespace RakeTechTest;
class FormController
{
/**
* @param $data
* @return array
*/
public static function SetFormTitle($data)
{
$title = json_decode($data)->title;
delete_option("form-title");
add_option("form-title", $title);
return [
"status" => 'success',
"message" => "Form Title stored",
"data" => get_option("form-title")
];
}
/**
* @param $data
* @return array
*/
public static function SetAbout($data)
{
$about = json_decode($data)->about;
delete_option("form-about");
add_option("form-about", $about);
return [
"status" => 'success',
"message" => "About stored",
"data" => get_option("form-about")
];
}
/**
* @param $data
* @return array
*/
public static function SetCompanyDetails($data)
{
$details = json_decode($data)->CompanyDetails;
delete_option("company-details");
add_option("company-details", $details);
return [
"status" => 'success',
"message" => "Company Details stored",
"details" => get_option("company-details")
];
}
/**
* @param $data
* @return false|string
*/
public static function SetSubmitMessage($data)
{
$message = json_decode($data)->message;
delete_option("form-submit-message");
add_option("form-submit-message", $message);
return json_encode([
"status" => 'success',
"message" => "Submit Message stored",
"data" => get_option("form-submit-message")
]);
}
/**
* @return array
*/
public static function GetSubmitMessage()
{
return [
'submitMessage' => get_option("form-submit-message")
];
}
/**
* @return array
*/
public static function GetFormTitle()
{
return [
'title' => get_option("form-title")
];
}
/**
* @return array
*/
public static function GetAbout()
{
return [
'about' => get_option('form-about')
];
}
/**
* @return array
*/
public static function GetCompanyDetails()
{
return [
'details' => get_option('company-details')
];
}
}
<file_sep><?php
/**
* Plugin Name: Raketech Form Test
* Description:
* Version: 1.0.0
* License:
* Author: <NAME>
* Author URI:
*/
require_once($_SERVER["DOCUMENT_ROOT"] . "/wp-content/plugins/raketech-form-test/Form-API/routes/routes.php");
add_action('admin_bar_menu', 'my_admin_bar_menu', 100);
function my_admin_bar_menu($wp_admin_bar)
{
$wp_admin_bar->add_menu(array(
'id' => 'menu_id',
'title' => __('Raketech Form Test'),
'href' => admin_url('admin.php?page=taketech-form-test'),
));
}
function menuCallBack()
{
add_menu_page('Raketech Form Test',
'Raketech Form Test',
'manage_options',
'raketech_form_test',
'raketech_form_test_init',
'');
}
add_action('admin_menu', 'menuCallBack');
function raketech_form_test_init()
{
require_once __DIR__ . '/dist/index.html';
}
add_action('rest_api_init', function () {
$Router = new \RakeTechTest\Router();
$Router->InitializeRoutes();
});
/**
* Enqueueing the JS and CSS for our plugin settings page
*/
add_action('admin_enqueue_scripts', function ($page) {
$menu_slug = 'raketech_form_test';
if ($menu_slug === substr($page, -1 * strlen($menu_slug))) {
wp_register_script('raketest_form_test_handle', null);
wp_localize_script('raketest_form_test_handle', 'raketech_form_test_options',
[
'siteUrl' => get_site_url(),
'isMultiSite' => is_multisite(),
'locale' => substr(get_locale(), 0, 2)
]);
wp_enqueue_script('raketest_form_test_handle');
}
});
<file_sep># raketech-form-test
This is a wordpress headless plugin written in VueJS using wp-json
## For Development
Project setup
```
npm install
```
Compiles and hot-reloads for development
```
npm run serve
```
Host Url
```
Helpers/UrlList.js {Host} should point on the localhost
```
## For Production
Host Url
```
Helpers/UrlList.js {Host} should point on http://172.16.17.32
```
Compiles and minifies for production
```
npm run build
```
In the dist/index.html the paths of the js and css should point /wp-content/plugins/raketech-form-test/dist
<br />
This can be done manual or confugued from webpack.
<br />
Then it can be installed from the wp admin like any other normal plugin
<file_sep>import {Host} from "../Helpers/UrlList";
export default class HealthHttpService {
constructor(http) {
this.http = http;
this.host = Host;
this.namespace = 'raketech-form-test/v1';
this.UrlList = {
AppHealth: `${this.host}/wp-json/${this.namespace}/health/status`,
};
}
GetAppHealth() {
return this.http.get(this.UrlList.AppHealth).then((response) => {
return response.data;
})
}
}
<file_sep><?php
namespace RakeTechTest;
include_once($_SERVER["DOCUMENT_ROOT"] . "/wp-content/plugins/raketech-form-test/Form-API/controllers/Health.controller.php");
include_once($_SERVER["DOCUMENT_ROOT"] . "/wp-content/plugins/raketech-form-test/Form-API/controllers/Form.controller.php");
include_once($_SERVER["DOCUMENT_ROOT"] . "/wp-content/plugins/raketech-form-test/Form-API/routes/libs/FormClient.routes.php");
class Router extends \WP_REST_Controller
{
protected $namespace;
public function __construct()
{
$this->namespace = "/raketech-form-test/v1";
}
/**
* router initializer
*/
public function InitializeRoutes()
{
FormClientRoutes::FormClientRoutes();
register_rest_route($this->namespace, '/form/submit-message', array(
'methods' => 'POST',
'callback' => function ($request) {
return FormController::SetSubmitMessage($request->get_body());
}
));
register_rest_route($this->namespace, '/form/about', array(
'methods' => 'POST',
'callback' => function ($request) {
return FormController::SetAbout($request->get_body());
}
));
register_rest_route($this->namespace, '/form/title', array(
'methods' => 'POST',
'callback' => function ($request) {
return FormController::SetFormTitle($request->get_body());
}
));
register_rest_route($this->namespace, '/form/company-details', array(
'methods' => 'POST',
'callback' => function ($request) {
return FormController::SetCompanyDetails($request->get_body());
}
));
register_rest_route($this->namespace, '/form/about/get', array(
'methods' => 'GET',
'callback' => function () {
return FormController::GetAbout();
}
));
register_rest_route($this->namespace, '/form/submit-message/get', array(
'methods' => 'GET',
'callback' => function () {
return FormController::GetSubmitMessage();
}
));
register_rest_route($this->namespace, '/form/title/get', array(
'methods' => 'GET',
'callback' => function () {
return FormController::GetFormTitle();
}
));
register_rest_route($this->namespace, '/form/company-details/get', array(
'methods' => 'GET',
'callback' => function () {
return FormController::GetCompanyDetails();
}
));
register_rest_route($this->namespace, '/health/status', array(
'methods' => 'GET',
'callback' => function () {
return HealthController::GetHealthStatus();
}
));
}
}
| 00440aaed2ffb45223a333a1f8ca5fc54d33d1a0 | [
"Markdown",
"JavaScript",
"PHP"
]
| 8 | PHP | alexandrosok/raketech-form-test | db723ce41f3517eb659c412d0887e5e36aa7ebc1 | d6966bbb4264459bb7f0b47ee1a6c8bf87ebdd9a |
refs/heads/master | <file_sep>const utilities = require('../utilities/torUtilities.js');
const fs = require('fs');
const path = require('path');
exports.command = 'remove <name>'
exports.describe = 'remove instance'
exports.builder = {
'name': {
description: 'instance name'
}
}
exports.handler = async function (argv) {
var config = await utilities.getConfig(argv);
if(!config.instances[argv.name]) {
console.log("Instance '" + argv.name + "' not found.");
return;
}
delete config.instances[argv.name];
await utilities.saveConfig(argv, config);
console.log("Removed '" + argv.name + "'.");
}<file_sep>var utilities = require('../utilities/torUtilities.js');
const options = require('../utilities/options.js');
const camelcase = require('camelcase');
exports.command = 'add <name>'
exports.describe = 'add an instance'
exports.builder = options.withoutDefaults;
exports.handler = async function (argv) {
const config = await utilities.getConfig(argv);
try {
check(argv, config);
} catch(e) {
console.log("Error: " + e.message);
return;
}
let isUpdate = config.instances[argv.name] != null;
var instanceConfig = {
name: argv.name
};
for(var key in options.withoutDefaults) {
let camelKey = camelcase(key);
if(typeof(argv[camelKey]) !== 'undefined')
instanceConfig[camelKey] = argv[camelKey];
}
config.instances[argv.name] = instanceConfig;
await utilities.saveConfig(argv, config);
console.log((isUpdate ? "Updated": "Added") + " instance '" + argv.name + "'");
}
const check = function(argv, config) {
let others = Object.values(config.instances).filter(i => i.name != argv.name);
checkConflict('IP:OrPort', argv, others, i => i.ip + ":" + i.orPort);
checkConflict('IP:DirPort', argv, others, i => i.ip + ":" + i.dirPort);
}
const checkConflict = function(title, item, others, map) {
var unique = map(item);
var duplicate = others.map(map).indexOf(unique);
if(duplicate > -1) {
throw new Error(title + " conflicts with an existing instance '" + others[duplicate].name + "'. Please select a different combination.");
}
}<file_sep>const os = require('os');
const path = require('path');
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const constants = require('./constants.js');
switch(os.platform()) {
case 'linux':
module.exports = {
DEFAULT_CONFIG_DB: '~/.tor-manager.db',
DEFAULT_TOR_DIR: '/etc/tor',
DEFAULT_DATA_DIR: '/var/lib/tor',
executionCommand: async function(action, name, configs) {
await exec('systemctl ' + action + ' tor@' + name + '.service')
}
}
break;
// TODO add support for more OS types?
case 'win32':
module.exports = {
DEFAULT_CONFIG_DB: path.join(os.homedir(), 'Tor', '.tor-manager.db'),
DEFAULT_TOR_DIR: 'C:\\path\\Data\\Tor', // TODO what is default Tor directory?
DEFAULT_DATA_DIR: path.join(os.homedir(), 'Tor', 'Data'),
executionCommand: async function(action, name, configs) {
switch(action) {
case 'start':
case 'stop':
return await exec('tor --service ' + action + ' -f ' + path.join(configs.torDir, name + constants.TORRC_EXTENSION));
case 'restart':
await module.exports.executionCommand('stop', name, configs);
await module.exports.executionCommand('start', name, configs);
}
}
}
break;
default: // These very likely will not work
module.exports = {
DEFAULT_CONFIG_DB: path.join(os.homedir(), 'tor', '.tor-manager.db'),
DEFAULT_TOR_DIR: '???',
DEFAULT_DATA_DIR: path.join(os.homedir(), 'tor', 'data'),
executionCommand: async function(action, name, configs) {
await exec('systemctl ' + action + ' tor@' + name + '.service')
}
}
break;
}<file_sep>const axios = require('axios');
const fs = require('fs');
const path = require('path');
const Onionoo = require('onionoo');
const onionoo = new Onionoo({
baseUrl: 'https://onionoo.torproject.org',
endpoints: [
'summary',
'details',
'bandwidth',
'weights',
'clients',
'uptime'
],
cache: new Map()
});
const ensureParentDirectoryExists = async function(file) {
let parent = path.dirname(file);
if(!fs.existsSync(parent)) {
ensureParentDirectoryExists(parent);
fs.mkdirSync(parent);
}
}
module.exports = {
getFamily: async function (prefix) {
var query = {
search: prefix
};
var response = await onionoo.summary(query);
if(response.statusCode != 200)
throw response;
return response.body.relays.map(i => ({
name: i.n,
fingerprint: i.f,
ip: i.a[0]
}));
},
getRemoteFile: async function(url) {
const response = await axios.get(url);
return response.data;
},
getConfig: async function(argv) {
var config = fs.existsSync(argv.database) ? JSON.parse(fs.readFileSync(argv.database, 'utf8')) : {};
if(!config.instances) config.instances = {};
return config;
},
saveConfig: async function(argv, data) {
await ensureParentDirectoryExists(argv.database);
fs.writeFileSync(argv.database, JSON.stringify(data), 'utf8');
},
ensureParentDirectoryExists: ensureParentDirectoryExists
}<file_sep>const path = require('path');
const osUtilities = require('./osUtilities.js');
var options = {
'family-prefix': {
describe: 'name prefix for all your tor instances',
default: ''
},
'template': {
describe: 'template for torrc file (Mustache)',
default: path.join(__dirname, '..', 'templates', 'torrc.template'),
coerce: path.resolve
},
'contactInfo': {
describe: 'admin contact details',
default: 'Random Person <nobody AT example dot com>'
},
'data-dir': {
describe: 'tor config directory',
default: osUtilities.DEFAULT_DATA_DIR,
coerce: path.resolve
},
'tor-dir': {
describe: 'tor config directory',
default: osUtilities.DEFAULT_TOR_DIR,
coerce: path.resolve
},
'include-tor-null': {
describe: 'include tor-null block list',
default: false
},
'tor-null-url': {
describe: 'TorNull url',
default: 'https://tornull.org/tornull-bl.txt'
},
'dir-frontpage': {
describe: 'default directory frontpage',
default: path.join(osUtilities.DEFAULT_TOR_DIR, 'tor-exit-notice.html'),
coerce: path.resolve
},
'ip': {
description: 'ip to bind to',
default: '0.0.0.0'
},
'exit-policy': {
describe: 'default exit policy',
choices: ['none', 'strict','reduced','all'],
default: 'none'
},
'dir-port': {
describe: 'default DirPort to listen on',
default: 80
},
'or-port': {
describe: 'default OrPort to listen on',
default: 443
}
}
// Now lets clone and strip all "defaults"
var optionsWithoutDefaults = JSON.parse(JSON.stringify(options))
for(let key in optionsWithoutDefaults) {
if(typeof(optionsWithoutDefaults[key].default) !== 'undefined')
delete optionsWithoutDefaults[key].default;
}
module.exports = {
withDefaults: options,
withoutDefaults: optionsWithoutDefaults
}<file_sep>#!/usr/bin/env node
const path = require('path');
const osUtilities = require('./utilities/osUtilities');
require('yargs')
.option('database', {
alias: 'db',
describe: 'Database file of active bindings',
default: osUtilities.DEFAULT_CONFIG_DB,
coerce: path.resolve
})
.commandDir('commands')
.demandCommand()
.help()
.argv;<file_sep>const fs = require('fs');
const path = require('path');
const Mustache = require('mustache');
const options = require('../utilities/options.js');
const utilities = require('../utilities/torUtilities.js');
const osUtilities = require('../utilities/osUtilities.js');
const constants = require('../utilities/constants.js');
// Disable Mustache Escape
Mustache.escape = (value) => value;
exports.command = 'build'
exports.describe = 'build configuration'
exports.builder = options.withDefaults;
exports.handler = async function (argv) {
var config = await utilities.getConfig(argv);
for(let instance of Object.values(config.instances)) {
const filename = path.join(argv.torDir, instance.name + constants.TORRC_EXTENSION);
var result = await build(Object.assign({}, argv, config, instance));
await utilities.ensureParentDirectoryExists(filename);
fs.writeFileSync(filename, result, 'utf8');
}
console.log("Updated all config files.");
await cleanConfigs(argv.torDir, config);
}
async function cleanConfigs(dir, config) {
var names = Object.values(config.instances).map(i => i.name);
var files = fs.readdirSync(dir);
for(var file in files) {
if(file.endsWith(constants.TORRC_EXTENSION)) {
let name = file.substring(0, -1*constants.TORRC_EXTENSION.length)
if(names.indexOf(file.substring(0, -6)) == -1) {
console.log("Removing old configuratoin for '" + name + "'");
unlinkSync(path.join(dir, file));
}
}
}
}
async function build(configs) {
let policyFile = configs.exitPolicyFile
|| path.join(__dirname, '..', 'templates', 'policies', configs.exitPolicy + '.template')
let data = {
family: configs.familyPrefix ? await utilities.getFamily(configs.familyPrefix) : null,
nickname: configs.familyPrefix + configs.name.replace(/[^a-zA-Z0-9]/,''),
name: configs.name,
ip: configs.ip,
contactInfo: configs.contactInfo,
dirPort: configs.dirPort,
orPort: configs.orPort,
dataDir: path.join(configs.dataDir, configs.name),
dirFrontpage: configs.dirFrontpage,
exitPolicy: fs.readFileSync(policyFile, 'utf8'),
torNullPolicy: configs.includeTorNull ? await utilities.getRemoteFile(configs.torNullUrl) : ''
}
return Mustache.render(fs.readFileSync(configs.template, 'utf8'), data);
}<file_sep># What is this? #
This is a fairly simple tool to help manage and maintain multiple tor relays on one server.
It's not really meant for others to use, so use at your own risk.
# Why multiple tor nodes on the same server? #
The main motivation for this is to make full use of all the cors on each server. This makes
it easy to add/remove multiple "instances" of tor, listening on different ports or IP addresses.
It also helps with keeping the MyFamily synchronized, and automatically populates exit policy and
TorNull rules if needed. Abuses seem to run in spurts, so it's nice to have an easy mechanism to
switch the exit policy without any hassle. I simply switch to a reduced policy if complaints are
high, then a few days later, switch back to a fairly open policy.<file_sep>var utilities = require('../utilities/torUtilities.js');
exports.command = 'list [name]'
exports.describe = 'list configured instances'
exports.builder = {
'name': {
description: 'name of the instance',
default: 'all'
}
}
exports.handler = async function (argv) {
const config = await utilities.getConfig(argv);
if(argv.name == 'all') {
console.log(config.instances);
}else{
if(!config.instances[argv.name]) {
console.log("Error: Instance '" + argv.name + "' not found.");
} else {
console.log(config.instances[argv.name]);
}
}
} | b157f339ef3e04a7d0b90b58813a5a61e38b968f | [
"JavaScript",
"Markdown"
]
| 9 | JavaScript | conneryn/tor-manager | 6d2ef34f9549793eef74d23df8cb120572dd6065 | 5946b7dd9c10e608ae01d85a1b872879bbc07236 |
refs/heads/master | <file_sep>module hh{
var triangleVertexPositionBuffer;
var squareVertexPositionBuffer;
var gl;
var shaderProgram;
export function initGL(canvas) {
try {
gl = canvas.getContext("experimental-webgl");
gl.viewportWidth = canvas.width;
gl.viewportHeight = canvas.height;
} catch(e) {
}
if (!gl) {
alert("Could not initialise WebGL, sorry :-(");
}
}
export function getShader(gl, id) {
var shaderScript = document.getElementById(id);
if (!shaderScript) {
return null;
}
var str = "";
var k = shaderScript.firstChild;
while (k) {
if (k.nodeType == 3)
str += k.textContent;
k = k.nextSibling;
}
var shader;
if (shaderScript.type == "x-shader/x-fragment") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (shaderScript.type == "x-shader/x-vertex") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
return null;
}
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
export function initShaders() {
var fragmentShader = getShader(gl, "shader-fs");
var vertexShader = getShader(gl, "shader-vs");
shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
gl.useProgram(shaderProgram);
shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
}
export function initBuffers(){
triangleVertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
var vertices = [
0.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
triangleVertexPositionBuffer.itemSize = 3;
triangleVertexPositionBuffer.numItems = 3;
squareVertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer);
vertices = [
1.0, 1.0, 0.0,
-1.0, 1.0, 0.0,
1.0, -1.0, 0.0,
-1.0, -1.0, 0.0
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
squareVertexPositionBuffer.itemSize = 3;
squareVertexPositionBuffer.numItems = 4;
}
export function drawScene(){
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
mat4.identity(mvMatrix);
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, triangleVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
setMatrixUniforms();
gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems);
mat4.translate(mvMatrix, [3.0, 0.0, 0.0]);
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, squareVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
setMatrixUniforms();
gl.drawArrays(gl.TRIANGLE_STRIP, 0, squareVertexPositionBuffer.numItems);
}
export function study_gl1(){
var canvas = document.getElementById("canvas");
initGL(canvas);
initShaders();
initBuffers();
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
setInterval(drawScene, 15);
}
}<file_sep>/**
* Created by SmallAiTT on 2015/6/26.
*/
///<reference path="../hh.ts" /><file_sep>/**
* Created by Administrator on 2015/7/4.
*/
///<reference path="../ref.ts" />
///<reference path="../base/__module.ts" />
module hh{
export class Texture extends Emitter{
url:string;
data:any;
x:number;
y:number;
width:number;
height:number;
//@override
_initProp():void{
super._initProp();
var self = this;
self.x = 0;
self.y = 0;
}
setData(data){
var self = this;
self.data = data;
self.width = data.width;
self.height = data.height;
}
render(ctx:IRenderingContext2D, dstX:number, dstY:number, dstW:number, dstH:number, grid?:number[]){
var self = this, data = self.data;
var x = self.x, y = self.y, width = self.width, height = self.height;
if(!grid || grid.length == 0){
// 普通绘图模式
ctx.drawImage(data, x, y, width, height, dstX, dstY, dstW, dstH);
engine.__fpsInfo.drawCount++;
return;
}
var gridType = grid[0];
if(gridType == 1){
// 九宫格模式
var vx = grid[1], vy = grid[2], vw = grid[3], vh = grid[4];
var arrX = [0, vx, vx+vw, width];
var arrY = [0, vy, vy+vh, height];
var arrX1 = [0, vx, dstW-(width-vx-vw), dstW];
var arrY1 = [0, vy, dstH-(height-vy-vh), dstH];
for(var i = 0; i < 3; ++i){
var sx = arrX[i], sw = arrX[i+1] - sx;
var dx = arrX1[i], dw = arrX1[i+1] - dx;
for(var j = 0; j < 3; ++j){
var sy = arrY[j], sh = arrY[j+1] - sy;
var dy = arrY1[j], dh = arrY1[j+1] - dy;
ctx.drawImage(data, sx, sy, sw, sh, dx, dy, dw, dh);
}
}
engine.__fpsInfo.drawCount += 9;
}else if(gridType == 3){
// 垂直三宫格模式
// 方向
var v1 = grid[1], v2 = grid[2], v3 = height - v1 - v2;
ctx.drawImage(data, x, y, width, v1, dstX, dstY, dstW, v1);
var repeat = dstH - v1 - v3;
ctx.drawImage(data, x, v1, width, v2, dstX, v1, dstW, repeat);
//var yTemp = v1;
//while(repeat > 0){
// var d = Math.min(repeat, v2);
// ctx.drawImage(data, x, v1, width, d, dstX, yTemp, dstW, d);
// repeat -= d;
// yTemp += d;
//}
ctx.drawImage(data, x, height - v3, width, v3, dstX, dstH - v3, dstW, v3);
engine.__fpsInfo.drawCount += 3;
}else if(gridType == 4){
// 垂直三宫格模式
// 方向
var v1 = grid[1], v2 = grid[2], v3 = height - v1 - v2;
ctx.drawImage(data, x, y, v1, height, dstX, dstY, v1, dstH);
var repeat = dstW - v1 - v3;
ctx.drawImage(data, v1, y, v2, height, v1, dstY, repeat, dstH);
//var yTemp = v1;
//while(repeat > 0){
// var d = Math.min(repeat, v2);
// ctx.drawImage(data, x, v1, width, d, dstX, yTemp, dstW, d);
// repeat -= d;
// yTemp += d;
//}
ctx.drawImage(data, width - v3, y, v3, height, dstW - v3, dstY, v3, dstH);
engine.__fpsInfo.drawCount += 3;
}
}
}
}<file_sep>/**
* Created by SmallAiTT on 2015/6/29.
*/
///<reference path="../ref.ts" />
///<reference path="../base/__module.ts" />
///<reference path="Layout.ts" />
module hh{
export class NodeOpt extends Class{
_TargetClass:any;
debug:boolean;
debugRectColor:any;
name:string;
width:number;
height:number;
x:number;
y:number;
scaleX:number;
scaleY:number;
anchorX:number;
anchorY:number;
rotation:number;
skewX:number;
skewY:number;
alpha:number;
worldAlpha:number;
zIndex:number;
visible:boolean;
parent:Node;
children:Node[];
drawable:boolean;
matrix:Matrix;
layout:Layout;
clip:Function;
renderQueueRange:number[];
//@override
_initProp():void{
super._initProp();
var self = this;
self.name = self._TargetClass.__n;
self.width = 0;
self.height = 0;
self.x = 0;
self.y = 0;
self.scaleX = 1;
self.scaleY = 1;
self.anchorX = 0.5;
self.anchorY = 0.5;
self.rotation = 0;
self.skewX = 0;
self.skewY = 0;
self.alpha = 0;
self.worldAlpha = 1;
self.visible = true;
self.children = [];
self.drawable = false;
self.matrix = new Matrix();
self.renderQueueRange = [];
}
constructor(NodeClass:any){
this._TargetClass = NodeClass;
super();
}
}
}<file_sep>/**
* Created by SmallAiTT on 2015/6/30.
*/
module hh.STR {
export var NUM_EXP = /(^([\-]?[\d]+)$)|(^([\-]?[\d]+\.[\d]+)$)/;
/**
* 字符串补全。
* @param src
* @param fillStr
* @param isPre
* @returns {*}
*/
export function fill(src:any, fillStr:string, isPre:boolean = true){
src = src + "";
var sl = src.length, fl = fillStr.length;
if(sl >= fl) return src;
if(isPre){
return fillStr.substring(0, fl - sl) + src;
}else{
return src + fillStr.substring(sl);
}
}
/**
* 获取字符串长度,中文为2
* @param str
*/
export function getStringLength(str:string){
var strArr = str.split("");
var length = 0;
for (var i = 0; i < strArr.length; i++) {
var s = strArr[i];
if(isChinese(s)){
length+=2;
}else{
length+=1;
}
}
return length;
}
/**
* 判断一个字符串是否包含中文
* @param str
* @returns {boolean}
*/
export function isChinese(str:string){
var reg = /^[u4E00-u9FA5]+$/;
if(!reg.test(str)){
return true;
}
return false;
}
/**
* 根据字节长度获取文字
* @param str
* @param startNum 字数序号
* @param subLength
*/
export function sub(str:string, startNum:number, subLength:number){
var strArr = str.split("");
var length = 0;
for (var i = startNum; i < strArr.length; i++) {
var s = strArr[i];
if(isChinese(s)){
length+=2;
}else{
length+=1;
}
if(length > subLength) break;
}
return str.substring(startNum, i);
}
/**
* 字符串转为对象,注意,对象只能是最低级嵌套,也就是说只有一层 "1:2,2:3" => {"1":2,"2":3}
* @param str
* @return {Object}
*/
export function toObj(str):any{
str = (str+"").replace(/,/g, ",").replace(/:/g, ":");//为了防止策划误填,先进行转换
var tempArr0 = str.split(",");
var obj = {};
for (var i = 0; i < tempArr0.length; i++) {
var locTemp = tempArr0[i];
if(!locTemp) continue;
var tempArr1 = locTemp.split(":");
obj[tempArr1[0]] = parseInt(tempArr1[1]);
}
return obj;
}
/**
* 将字符串转换为number数组。
* @param str
* @param splitStr
* @returns {Array}
*/
export function toNums(str:string, splitStr:string = ','):number[]{
var results = [];
if(str){
var arr = str.split(splitStr);
for (var i = 0, l_i = arr.length; i < l_i; i++) {
results.push(parseFloat(arr[i]));
}
}
return results;
}
/**
* 敏感词检测
* @param word
* @param sensitiveArr
* @returns {boolean}
*/
export function checkSensitiveWord(word, sensitiveArr){
for (var i = 0; i < sensitiveArr.length; i++) {
var sen = sensitiveArr[i];
if(sen=="") continue;
if(word.indexOf(sen) !== -1){
return true;
}
}
return false;
}
/**
* 替换敏感词
* @param word
* @param sensitiveArr
* @returns {*}
*/
export function replaceSensitiveWord(word, sensitiveArr){
for (var i = 0; i < sensitiveArr.length; i++) {
var sen = sensitiveArr[i];
word = word.replace(sen, "*");
}
return word;
}
export function parseNumOrStr(value:string):any{
if(!value) return value;
if((value).search(NUM_EXP) == 0){
return value.indexOf(".") > 0 ? parseFloat(value) : parseInt(value);
}
return value;
}
}
<file_sep>/**
* Created by SmallAiTT on 2015/6/29.
*/
///<reference path="PATH.ts" />
///<reference path="STR.ts" />
///<reference path="ColorMatrix.ts" />
///<reference path="Matrix.ts" />
///<reference path="Point.ts" /><file_sep>/**
* Created by SmallAiTT on 2015/7/1.
*/
///<reference path="../node/NodeOpt.ts" />
module hh{
export class UITextOpt extends Class{
text:string;
font:string;
size:number;
//@override
_initProp():void{
super._initProp();
var self = this;
self.font = '';
self.size = 18;
}
}
}<file_sep>/**
* Created by Administrator on 2015/6/28.
*/
///<reference path="sty_init.ts" />
module sty{
unit.curModuleName = moduleName_composite;
unit.addMenuItem4Ctx('混合', function(ctx111:IRenderingContext2D){
var canvas1 = document.createElement("canvas");
var canvas2 = document.createElement("canvas");
var gco = [ 'source-over','source-in','source-out','source-atop',
'destination-over','destination-in','destination-out','destination-atop',
'lighter', 'copy','xor', 'multiply', 'screen', 'overlay', 'darken',
'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light',
'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity'
].reverse();
var gcoText = [
'This is the default setting and draws new shapes on top of the existing canvas content.',
'The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent.',
'The new shape is drawn where it doesn\'t overlap the existing canvas content.',
'The new shape is only drawn where it overlaps the existing canvas content.',
'New shapes are drawn behind the existing canvas content.',
'The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent.',
'The existing content is kept where it doesn\'t overlap the new shape.',
'The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content.',
'Where both shapes overlap the color is determined by adding color values.',
'Only the existing canvas is present.',
'Shapes are made transparent where both overlap and drawn normal everywhere else.',
'The pixels are of the top layer are multiplied with the corresponding pixel of the bottom layer. A darker picture is the result.',
'The pixels are inverted, multiplied, and inverted again. A lighter picture is the result (opposite of multiply)',
'A combination of multiply and screen. Dark parts on the base layer become darker, and light parts become lighter.',
'Retains the darkest pixels of both layers.',
'Retains the lightest pixels of both layers.',
'Divides the bottom layer by the inverted top layer.',
'Divides the inverted bottom layer by the top layer, and then inverts the result.',
'A combination of multiply and screen like overlay, but with top and bottom layer swapped.',
'A softer version of hard-light. Pure black or white does not result in pure black or white.',
'Subtracts the bottom layer from the top layer or the other way round to always get a positive value.',
'Like difference, but with lower contrast.',
'Preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer.',
'Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer.',
'Preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer.',
'Preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer.'
].reverse();
var width = 320;
var height = 340;
// HSV (1978) = H: Hue / S: Saturation / V: Value
var Color:any = {};
Color.HSV_RGB = function (o) {
var H = o.H / 360,
S = o.S / 100,
V = o.V / 100,
R, G, B;
var A, B, C, D;
if (S == 0) {
R = G = B = Math.round(V * 255);
} else {
if (H >= 1) H = 0;
H = 6 * H;
D = H - Math.floor(H);
A = Math.round(255 * V * (1 - S));
B = Math.round(255 * V * (1 - (S * D)));
C = Math.round(255 * V * (1 - (S * (1 - D))));
V = Math.round(255 * V);
switch (Math.floor(H)) {
case 0:
R = V;
G = C;
B = A;
break;
case 1:
R = B;
G = V;
B = A;
break;
case 2:
R = A;
G = V;
B = C;
break;
case 3:
R = A;
G = B;
B = V;
break;
case 4:
R = C;
G = A;
B = V;
break;
case 5:
R = V;
G = A;
B = B;
break;
}
}
return {
R: R,
G: G,
B: B
};
};
var createInterlace = function (size, color1, color2) {
var proto:any = document.createElement("canvas").getContext("2d");
proto.canvas.width = size * 2;
proto.canvas.height = size * 2;
proto.fillStyle = color1; // top-left
proto.fillRect(0, 0, size, size);
proto.fillStyle = color2; // top-right
proto.fillRect(size, 0, size, size);
proto.fillStyle = color2; // bottom-left
proto.fillRect(0, size, size, size);
proto.fillStyle = color1; // bottom-right
proto.fillRect(size, size, size, size);
var pattern = proto.createPattern(proto.canvas, "repeat");
pattern.data = proto.canvas.toDataURL();
return pattern;
};
var op_8x8 = createInterlace(8, "#FFF", "#eee");
var lightMix = function() {
var ctx:IRenderingContext2D = <any>canvas2.getContext("2d");
ctx.save();
ctx.globalCompositeOperation = "lighter";
ctx.beginPath();
ctx.fillStyle = "rgba(255,0,0,1)";
ctx.arc(100, 200, 100, Math.PI*2, 0, false);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = "rgba(0,0,255,1)";
ctx.arc(220, 200, 100, Math.PI*2, 0, false);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = "rgba(0,255,0,1)";
ctx.arc(160, 100, 100, Math.PI*2, 0, false);
ctx.fill();
ctx.restore();
ctx.beginPath();
ctx.fillStyle = "#f00";
ctx.fillRect(0,0,30,30);
ctx.fill();
};
var colorSphere = function() {
var ctx:IRenderingContext2D = <any>canvas1.getContext("2d");
var width = 360;
var halfWidth = width / 2;
var rotate = (1 / 360) * Math.PI * 2; // per degree
var offset = 0; // scrollbar offset
var oleft = -20;
var otop = -20;
for (var n = 0; n <= 359; n ++) {
var gradient = ctx.createLinearGradient(oleft + halfWidth, otop, oleft + halfWidth, otop + halfWidth);
var color = Color.HSV_RGB({ H: (n + 300) % 360, S: 100, V: 100 });
gradient.addColorStop(0, "rgba(0,0,0,0)");
gradient.addColorStop(0.7, "rgba("+color.R+","+color.G+","+color.B+",1)");
gradient.addColorStop(1, "rgba(255,255,255,1)");
ctx.beginPath();
ctx.moveTo(oleft + halfWidth, otop);
ctx.lineTo(oleft + halfWidth, otop + halfWidth);
ctx.lineTo(oleft + halfWidth + 6, otop);
ctx.fillStyle = gradient;
ctx.fill();
ctx.translate(oleft + halfWidth, otop + halfWidth);
ctx.rotate(rotate);
ctx.translate(-(oleft + halfWidth), -(otop + halfWidth));
}
ctx.beginPath();
ctx.fillStyle = "#00f";
ctx.fillRect(15,15,30,30)
ctx.fill();
return ctx.canvas;
};
function runComposite() {
var dl = document.createElement("dl");
document.body.appendChild(dl);
while(gco.length) {
var pop = gco.pop();
var dt = document.createElement("dt");
dt.textContent = pop;
dl.appendChild(dt);
var dd = document.createElement("dd");
var p = document.createElement("p");
p.textContent = gcoText.pop();
dd.appendChild(p);
var canvas = document.createElement("canvas");
canvas.style.background = "url("+op_8x8.data+")";
canvas.style.border = "1px solid #000";
canvas.style.margin = "10px";
canvas.width = width/2;
canvas.height = height/2;
// 关键性代码
var ctx:IRenderingContext2D = <any>canvas.getContext('2d');
ctx.clearRect(0, 0, width, height);
ctx.save();
ctx.drawImage(canvas1, 0, 0, width/2, height/2);
// 设置混合模式
ctx.globalCompositeOperation = pop;
ctx.drawImage(canvas2, 0, 0, width/2, height/2);
// 还原
ctx.globalCompositeOperation = "source-over";
// 描述文字
ctx.fillStyle = "rgba(0,0,0,0.8)";
ctx.fillRect(0, height/2 - 20, width/2, 20);
ctx.fillStyle = "#FFF";
ctx.font = "14px arial";
ctx.fillText(pop, 5, height/2 - 5);
ctx.restore();
dd.appendChild(canvas);
dl.appendChild(dd);
}
};
// lum in sRGB
var lum = {
r: 0.33,
g: 0.33,
b: 0.33
};
// resize canvas
canvas1.width = width;
canvas1.height = height;
canvas2.width = width;
canvas2.height = height;
lightMix();
colorSphere();
runComposite();
});
}<file_sep>/// <reference path="Class.ts" />
/// <reference path="profile.ts" />
module hh{
var _isRunning:boolean = false;
export function mainLoop(cb, ctx?:any){
if(_isRunning){
warn(logCode.w_1);
return;
}
_isRunning = true;
var requestAnimFrame:Function = window["requestAnimationFrame"] ||
window["webkitRequestAnimationFrame"] ||
window["mozRequestAnimationFrame"] ||
window["oRequestAnimationFrame"] ||
window["msRequestAnimationFrame"];
var preTime = Date.now();
var loop = function(){
var curTime = Date.now();
var frameTime = curTime - preTime;
preTime = curTime;
cb.call(ctx, frameTime);
profile(frameTime);
};
if (requestAnimFrame != null) {
var callback = function () {
loop();
requestAnimFrame(callback);
};
requestAnimFrame(callback);
} else {
setInterval(loop, (1/60) * 1000);
}
}
}<file_sep>/**
* Created by SmallAiTT on 2015/7/1.
*/
///<reference path="../base/ColorMatrix.ts" />
///<reference path="../node/Node.ts" />
///<reference path="UIImgOpt.ts" />
module hh{
export class UIImg extends Node{
static NodeOpt:any = UIImgOpt;
_imgOpt:UIImgOpt;
//@override
_initProp(){
super._initProp();
var self = this, nodeOpt = self._nodeOpt;
nodeOpt.anchorX = nodeOpt.anchorY = 0.5;
self._imgOpt = new UIImgOpt();
}
constructor(urlOrTexture?:any){
super();
}
/**
* N宫格
* @param grid
* @private
*/
_setGrid(grid:number[]){
this._imgOpt.grid = grid;
}
public set grid(grid:number[]){
this._setGrid(grid);
}
public get grid():number[]{
return this._imgOpt.grid;
}
load(urlOrTexture, cb?:Function, ctx?:any){
if(!urlOrTexture) return;
var self = this, imgOpt = self._imgOpt;
if(typeof urlOrTexture == 'string'){
// 是url
var texture = res.get(urlOrTexture);
if(!self._loadTexture(texture)){
// 如果还没加载则进行动态加载
res.load(urlOrTexture, function(){
self._loadTexture(res.get(urlOrTexture));
if(cb) cb.call(ctx, self);
});
}else{
if(cb) cb.call(ctx, self);
}
}else{
self._loadTexture(urlOrTexture);
if(cb) cb.call(ctx, self);
}
}
_loadTexture(texture):boolean{
if(texture){
var self = this, nodeOpt = self._nodeOpt, imgOpt = self._imgOpt;
// 如果已经加载了
imgOpt.texture = texture;
// 设置成可以绘制
nodeOpt.drawable = true;
var grid = imgOpt.grid;
if(!grid || grid.length == 0){
self._setWidth(texture.width);
self._setHeight(texture.height);
}else{
var type = grid[0];
if(type == 1 || type == 2){
// 九宫格,改变设定的size,而是外部定义size。
}else if(type == 3){
// 三宫格,只改变一个方向的
// 垂直的时候改变width
self._setWidth(texture.width);
}else if(type == 4){
// 三宫格,只改变一个方向的
// 水平的时候改变height
self._setHeight(texture.height);
}
}
return true;
}
return false;
}
// @override
_render(ctx:IRenderingContext2D, engine:Engine){
var self = this, nodeOpt = self._nodeOpt, imgOpt = self._imgOpt, texture = imgOpt.texture;
texture.render(ctx, 0, 0, nodeOpt.width, nodeOpt.height, imgOpt.grid);
if(imgOpt.isBCSH()){
var bcsh = imgOpt.bcsh;
var colorMatrix:ColorMatrix = new ColorMatrix();
colorMatrix.adjustColor(bcsh[0], bcsh[1], bcsh[2], bcsh[3]);
var imageData = ctx.getImageData(0,0,engine.design.width, engine.design.height);
var data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
var srcR = data[i], srcG = data[i+1], srcB = data[i+2], srcA = data[i+3];
data[i] = (colorMatrix[0] * srcR) + (colorMatrix[1] * srcG) + (colorMatrix[2] * srcB) + (colorMatrix[3] * srcA) + colorMatrix[4];
data[i+1] = (colorMatrix[5] * srcR) + (colorMatrix[6] * srcG) + (colorMatrix[7] * srcB) + (colorMatrix[8] * srcA) + colorMatrix[9];
data[i+2] = (colorMatrix[10] * srcR) + (colorMatrix[11] * srcG) + (colorMatrix[12] * srcB) + (colorMatrix[13] * srcA) + colorMatrix[14];
data[i+3] = (colorMatrix[15] * srcR) + (colorMatrix[16] * srcG) + (colorMatrix[17] * srcB) + (colorMatrix[18] * srcA) + colorMatrix[19];
}
ctx.putImageData(imageData, 0, 0);
}
}
setBCSH(brightness:number, contrast:number, saturation:number, hub:number){
var self = this, bcsh = self._imgOpt.bcsh;
bcsh[0] = brightness;
bcsh[1] = contrast;
bcsh[2] = saturation;
bcsh[3] = hub;
return self;
}
}
}<file_sep>/**
* Created by SmallAiTT on 2015/7/7.
*/
///<reference path="../node/Node.ts" />
///<reference path="UITextOpt.ts" />
module hh{
export class UIText extends Node{
_textOpt:UITextOpt;
//@override
_initProp(){
super._initProp();
var self = this;
self._nodeOpt.drawable = true;
self._textOpt = new UITextOpt();
}
/**
* 文本内容
*/
_setText(text:any){
this._textOpt.text = text;
var size = hh.engine.canvasCtx.measureText(text);
console.log(size.width);
}
public set text(text:any){
this._setText(text);
}
public get text():any{
return this._textOpt.text;
}
// @override
_render(ctx:IRenderingContext2D, engine:Engine){
ctx.fillStyle = 'red';
ctx.font = "30px serif";
ctx.fillText(this._textOpt.text, 0, 0);
}
}
}<file_sep>/**
* Created by SmallAiTT on 2015/7/7.
*/
///<reference path="../../tc_init.ts" />
module tc {
unit.curModuleName = moduleName_ui;
unit.addMenuItem('文本', function(){
var uTxt = new hh.UIText();
uTxt.text = 'Holy-High 游戏引擎 好厉害';
uTxt.x = uTxt.y = 100;
hh.engine.stage.addChild(uTxt);
});
}<file_sep>/**
* Created by SmallAiTT on 2015/6/29.
*/
///<reference path="../../hh/hh.ts" />
///<reference path="../../hh/core/__module.ts" />
///<reference path="../../unit/unit.ts" />
///<reference path="../res_helper/res_helper.ts" /><file_sep>/**
* Created by SmallAiTT on 2015/6/29.
*/
///<reference path="sty_init.ts" />
module sty{
unit.curModuleName = moduleName_aria = "ARIA";
unit.addMenuItem4Ctx('ARIA', function(ctx:IRenderingContext2D){
ctx.beginPath();
ctx.arc(70, 80, 10, 0, 2 * Math.PI, false);
ctx.fill();
console.log('目前好像还不支持');
if((<any>ctx).addHitRegion) (<any>ctx).addHitRegion({id: "circle"});
var canvas = hh.engine._canvas;
canvas.addEventListener("mousemove", function(event){
if(event.region) {
alert("hit region: " + event.region);
}
});
});
}<file_sep>///<reference path="../../src/boot.ts" />
///<reference path="../../src/core/reference-core.ts" />
hh.boot(function(){
//hh.ColorNode.debug = true;
var node1:hh.ColorNode = new hh.ColorNode();
node1.name = "node1";
node1.width = 100;
node1.height = 100;
node1.x = 10;
node1.y = 10;
hh.root.addChild(node1);
var node2:hh.ColorNode = new hh.ColorNode();
node2.name = "node2";
node2.x = 20;
node2.y = 20;
node2.width = 100;
node2.height = 100;
node2.color = "blue";
node2.rotation = 50;
hh.root.addChild(node2);
var node3:hh.ColorNode = new hh.ColorNode();
node3.x = 40;
node3.y = 40;
node3.width = 100;
node3.height = 100;
node3.color = "#444444";
node1.addChild(node3);
hh.loadImage("res/item_00001.png", function(err, texture){
var image = new hh.UIImage();
image.texture = texture;
hh.root.addChild(image);
});
});<file_sep>module hh {
export var log = console.log.bind(console);
export var info = console.info.bind(console);
export var debug = console.debug.bind(console);
export var warn = console.warn.bind(console);
export var error = console.error.bind(console);
}<file_sep>/// <reference path="../const/logCode.ts" />
/// <reference path="../const/const.ts" />
/// <reference path="logger.ts" />
/// <reference path="path.ts" />
module hh{
export class Class{
static __n:string;
static __instanceIdCount:number = 1;
static _instance:any;
public static create(...args:any[]):any{
var Class:any = this;
var obj:any = new Class();
if(obj.init) obj.init.apply(obj, arguments);
return obj;
}
public static getInstance(...args:any[]):any{
var Clazz:any = this;
if(!Clazz._instance){
var instance:any = Clazz._instance = Clazz.create.apply(Clazz, arguments);
instance._isInstance = true;
}
return Clazz._instance;
}
public static purgeInstance(...args:any[]):any{
var Clazz:any = this;
var instance:any = Clazz._instance;
if(instance){
if(instance.release) instance.release();
Clazz._instance = null;
}
}
__instanceId:number;
__c:any;
__n:string;
public constructor(){
var self = this;
self.__instanceId = Class.__instanceIdCount++;
self._initProp();
self._init();
}
_initProp():void{
var self = this;
}
_init():void{
var self = this;
}
public init(...args:any[]):void{
}
/** 释放已经释放过了 */
_hasReleased:boolean;
/** 进行释放 注意,该处子类一般不进行重写 */
public release():void{
var self = this;
if(self._hasReleased) return;//避免重复释放
self._hasReleased = true;
self._release();
}
/** 进行释放的逻辑书写处 */
_release():void{
}
}
}<file_sep>/// <reference path="../event/EventDispatcher.ts" />
module hh{
export class Node extends Class{
static debug:boolean;
public debug:boolean;
_name:string;
_setName(name:string){
this._name = name;
}
public set name(name:string){
this._setName(name);
}
public get name():string{
return this._name;
}
_visible:boolean;
_setVisible(visible:boolean){
this._visible = visible;
}
public set visible(visible:boolean){
this._setVisible(visible);
}
public get visible():boolean{
return this._visible;
}
_setValueOrPercent(value:any, valueFunc, percentFunc):boolean{
var type:string = typeof value;
var self = this;
if(type == "number"){
valueFunc.call(self, value);
}else if(type == "string"){
if(type.match(/^((\d+)|(\d+.\d*))%$/)){
percentFunc.call(self, parseFloat(type.substring(0, type.length - 1))/100);
return true;
}else if(type.match(/^((\d+)|(\d+.\d*))$/)){
valueFunc.call(self, parseFloat(type)/100);
}
}else{
error(logCode.e_2);
}
return false;
}
/**
* x坐标
*/
_x:number;
_xDirty:boolean;
_xPercent:number;//x坐标百分比。
_xPercentDirty:boolean;
_xPercentEnabled:boolean;
_setXPercent(xPercent:number){
var self = this;
if(self._xPercent != xPercent) self._xPercentDirty = true;
self._xPercent = xPercent;
}
_setX(x:number){
var self = this;
if(self._x != x) self._xDirty = true;
self._x = x;
}
_onXPercentDirty():void{}
_onXDirty():void{}
public set x(x:number){
var self = this;
var flag = self._xPercentEnabled;
self._xPercentEnabled = self._setValueOrPercent(x, self._setX, self._setXPercent);
if(self._xPercentEnabled && !flag){
self._xPercentDirty = true;
}else if(!self._xPercentDirty){
self._xPercentDirty = false;
}
}
public get x():number{
return this._x;
}
/**
* y坐标
*/
_y:number;
_yDirty:boolean;
_yPercent:number;//y坐标百分比
_yPercentDirty:boolean;//y坐标百分比dirty
_yPercentEnabled:boolean;
_setYPercent(yPercent:number){
var self = this;
if(self._yPercent != yPercent) self._yPercentDirty = true;
self._yPercent = yPercent;
}
_setY(y:number){
var self = this;
if(self._y != y) self._yDirty = true;
self._y = y;
}
_onYPercentDirty():void{}
_onYDirty():void{}
public set y(y:number){
var self = this;
var flag = self._yPercentEnabled;
self._yPercentEnabled = self._setValueOrPercent(y, self._setY, self._setYPercent);
if(self._yPercentEnabled && !flag){
self._yPercentDirty = true;
}else if(!self._yPercentEnabled){
self._yPercentDirty = false;
}
}
public get y():number{
return this._y;
}
/**
* 宽度
*/
_width:number;
_widthDirty:boolean;
_widthPercent:number;//宽度百分比
_widthPercentDirty:boolean;//宽度百分比dirty
_widthPercentEnabled:boolean;
_setWidthPercent(widthPercent:number){
var self = this;
if(self._widthPercent != widthPercent) self._widthPercentDirty = true;
self._widthPercent = widthPercent;
}
_setWidth(width:number){
var self = this;
if(self._width != width) self._widthDirty = true;
self._width = width;
}
_onWidthPercentDirty():void{}
_onWidthDirty():void{}
public set width(width:any){
var self = this;
var flag = self._widthPercentEnabled;
self._widthPercentEnabled = self._setValueOrPercent(width, self._setWidth, self._setWidthPercent);
if(self._widthPercentEnabled && !flag){
self._widthPercentDirty = true;
}else if(!self._widthPercentEnabled){
self._widthPercentDirty = false;
}
}
public get width():any{
return this._width;
}
/**
* 高度
*/
_height:number;
_heightDirty:boolean;
_heightPercent:number;//高度百分比
_heightPercentDirty:boolean;//高度百分比dirty
_heightPercentEnabled:boolean;
_setHeightPercent(heightPercent:number){
var self = this;
if(self._heightPercent != heightPercent) self._heightPercentDirty = true;
self._heightPercent = heightPercent;
}
_setHeight(height:number){
var self = this;
if(self._height != height) self._heightDirty = true;
self._height = height;
}
_onHeightPercentDirty():void{}
_onHeightDirty():void{}
public set height(height:number){
var self = this;
var flag = self._heightPercentEnabled;
self._heightPercentEnabled = self._setValueOrPercent(height, self._setHeight, self._setHeightPercent);
if(self._heightPercentEnabled && !flag){
self._heightPercentDirty = true;
}else if(!self._heightPercentEnabled){
self._heightPercentDirty = false;
}
}
public get height():number{
return this._height;
}
/**
* z轴堆叠顺序,按照html命名
*/
_zIndex:number;
_setZIndex(zIndex:number){
var self = this;
if(self._parent && self._zIndex != zIndex) {//这时候设置父亲需要重排子节点列表
self._parent._childrenDirty = true;
}
self._zIndex = zIndex;
}
public set zIndex(zIndex:number){
this._setZIndex(zIndex);
}
public get zIndex():number{
return this._zIndex;
}
/**
* x轴缩放
*/
_scaleX:number;
_setScaleX(scaleX:number){
this._scaleX = scaleX;
}
public set scaleX(scaleX:number){
this._setScaleX(scaleX);
}
public get scaleX():number{
return this._scaleX;
}
/**
* y轴缩放
*/
_scaleY:number;
_setScaleY(scaleY:number){
this._scaleY = scaleY;
}
public set scaleY(scaleY:number){
this._setScaleY(scaleY);
}
public get scaleY():number{
return this._scaleY;
}
/**
* 缩放
*/
_setScale(scale:number){
this._setScaleX(scale);
this._setScaleY(scale);
}
public set scale(scale:number){
this._setScale(scale);
}
/**
* 旋转
*/
_rotation:number;
_setRotation(rotation:number){
this._rotation = rotation;
}
public set rotation(rotation:number){
this._setRotation(rotation);
}
public get rotation():number{
return this._rotation;
}
/**
* 父亲节点
*/
_parent:Node;
_setParent(parent:Node){
this._parent = parent;
}
public set parent(parent:Node){
this._setParent(parent);
}
public get parent():Node{
return this._parent;
}
/**
* 布局类型
*/
_layoutType:number;
_layoutTypeDirty:boolean;
_setLayoutType(layoutType:number){
var self = this;
if(self._layoutType != layoutType) self._layoutTypeDirty = true;
self._layoutType = layoutType;
}
public set layoutType(layoutType:number){
this._setLayoutType(layoutType);
}
public get layoutType():number{
return this._layoutType;
}
/**
* 是否开启布局功能。
*/
_layoutEnabled:boolean;
_setLayoutEnabled(layoutEnabled:boolean){
this._layoutEnabled = layoutEnabled;
}
public set layoutEnabled(layoutEnabled:boolean){
this._setLayoutEnabled(layoutEnabled);
}
public get layoutEnabled():boolean{
return this._layoutEnabled;
}
/**
* 上内边距。
*/
_paddingTop:number;
_paddingTopDirty:boolean;
_setPaddingTop(paddingTop:number){
var self = this;
if(self._paddingTop != paddingTop) self._paddingTopDirty = true;
self._paddingTop = paddingTop;
}
public set paddingTop(paddingTop:number){
this._setPaddingTop(paddingTop);
}
public get paddingTop():number{
return this._paddingTop;
}
_onPaddingTopDirty():void{}
/**
* 右内边距。
*/
_paddingRight:number;
_paddingRightDirty:boolean;
_setPaddingRight(paddingRight:number){
var self = this;
if(self._paddingRight != paddingRight) self._paddingRightDirty = true;
self._paddingRight = paddingRight;
}
public set paddingRight(paddingRight:number){
this._setPaddingRight(paddingRight);
}
public get paddingRight():number{
return this._paddingRight;
}
_onPaddingRightDirty():void{}
/**
* 下内边距。
*/
_paddingBottom:number;
_paddingBottomDirty:boolean;
_setPaddingBottom(paddingBottom:number){
var self = this;
if(self._paddingBottom != paddingBottom) self._paddingBottomDirty = true;
self._paddingBottom = paddingBottom;
}
public set paddingBottom(paddingBottom:number){
this._setPaddingBottom(paddingBottom);
}
public get paddingBottom():number{
return this._paddingBottom;
}
_onPaddingBottomDirty():void{}
/**
* 左内边距。
*/
_paddingLeft:number;
_paddingLeftDirty:boolean;
_setPaddingLeft(paddingLeft:number){
var self = this;
if(self._paddingLeft != paddingLeft) self._paddingLeftDirty = true;
self._paddingLeft = paddingLeft;
}
public set paddingLeft(paddingLeft:number){
this._setPaddingLeft(paddingLeft);
}
public get paddingLeft():number{
return this._paddingLeft;
}
_onPaddingLeftDirty():void{}
/**
* 设置内边距,【上右下左】
* @param padding
*/
public set padding(padding){
var self = this;
if(padding instanceof Array){
self._setPaddingTop(padding[0]);
self._setPaddingRight(padding[1]);
self._setPaddingBottom(padding[2]);
self._setPaddingLeft(padding[3]);
}
}
/**
* 上外边距。
*/
_marginTop:number;
_marginTopDirty:boolean;
_setMarginTop(marginTop:number){
var self = this;
if(self._marginTop != marginTop) self._marginTopDirty = true;
self._marginTop = marginTop;
}
public set marginTop(marginTop:number){
this._setMarginTop(marginTop);
}
public get marginTop():number{
return this._marginTop;
}
_onMarginTopDirty():void{}
/**
* 右外边距。
*/
_marginRight:number;
_marginRightDirty:boolean;
_setMarginRight(marginRight:number){
var self = this;
if(self._marginRight != marginRight) self._marginRightDirty = true;
self._marginRight = marginRight;
}
public set marginRight(marginRight:number){
this._setMarginRight(marginRight);
}
public get marginRight():number{
return this._marginRight;
}
_onMarginRightDirty():void{}
/**
* 下外边距。
*/
_marginBottom:number;
_marginBottomDirty:boolean;
_setMarginBottom(marginBottom:number){
var self = this;
if(self._marginBottom != marginBottom) self._marginBottomDirty = true;
self._marginBottom = marginBottom;
}
public set marginBottom(marginBottom:number){
this._setMarginBottom(marginBottom);
}
public get marginBottom():number{
return this._marginBottom;
}
_onMarginBottomDirty():void{}
/**
* 左外边距。
*/
_marginLeft:number;
_marginLeftDirty:boolean;
_setMarginLeft(marginLeft:number){
var self = this;
if(self._marginLeft != marginLeft) self._marginLeftDirty = true;
self._marginLeft = marginLeft;
}
public set marginLeft(marginLeft:number){
this._setMarginLeft(marginLeft);
}
public get marginLeft():number{
return this._marginLeft;
}
_onMarginLeftDirty():void{}
/**
* 设置外边距,【上右下左】
* @param margin
*/
public set margin(margin){
var self = this;
if(margin instanceof Array){
self._setMarginTop(margin[0]);
self._setMarginRight(margin[1]);
self._setMarginBottom(margin[2]);
self._setMarginLeft(margin[3]);
}
}
/**
* 垂直排列类型。
*/
_verticalAlign:number;
_verticalAlignDirty:boolean;
_setVerticalAlign(verticalAlign:number){
var self = this;
if(self._verticalAlign != verticalAlign) self._verticalAlignDirty = true;
self._verticalAlign = verticalAlign;
}
public set verticalAlign(verticalAlign:number){
this._setVerticalAlign(verticalAlign);
}
public get verticalAlign():number{
return this._verticalAlign;
}
_onVerticalAlignDirty():void{}
/**
* 水平排列类型。
*/
_horizontalAlign:number;
_horizontalAlignDirty:boolean;
_setHorizontalAlign(horizontalAlign:number){
var self = this;
if(self._horizontalAlign != horizontalAlign) self._horizontalAlignDirty = true;
self._horizontalAlign = horizontalAlign;
}
public set horizontalAlign(horizontalAlign:number){
this._setHorizontalAlign(horizontalAlign);
}
public get horizontalAlign():number{
return this._horizontalAlign;
}
_onHorizontalAlignDirty():void{}
//@override
_initProp():void{
super._initProp();
var self = this;
self._visible = true;
self._x = 0;
self._y = 0;
self._width = 0;
self._height = 0;
self._zIndex = 0;
self._xPercent = 0;
self._yPercent = 0;
self._widthPercent = 0;
self._heightPercent = 0;
self._children = [];
}
_children:Node[];
_childrenDirty:boolean;
/**
* 添加子节点。
* 如果改节点已经被添加在其他的节点上,则会先进行移除操作。
* 如果子节点已经添加了,则返回false。
* @param child
* @returns {boolean}
*/
public addChild(child:Node):boolean{
var self = this;
if(child._parent && self != child._parent){//如果改节点已经被添加在其他的节点上
child._parent.removeChild(child);
}
var children = self._children;
var indexToInsert = 0;
for (var i = 0, l_i = children.length; i < l_i; i++) {
var cNode = children[i];
if(child == cNode) {//已经添加了
return false;
}else if(child._zIndex < cNode._zIndex){//算出需要插入的位置
indexToInsert = i;
break;
}else{
indexToInsert = i+1;
}
}
children.splice(indexToInsert, 0, child);
child.parent = self;
return true;
}
/**
* 移除子节点。
* 如果child确实是该节点的子节点,则返回true,否则返回false
* @param child
* @returns {boolean}
*/
public removeChild(child:Node):boolean{
var self = this;
var children = self._children;
for (var i = 0, l_i = children.length; i < l_i; i++) {
var cNode = children[i];
if(child == cNode) {
children.splice(i, 1);
return true;
}
}
return false;
}
/**
* 将自身从父亲节点移除。
* 如果不存在父亲,则返回false,否则返回true
*/
public removeFromParent():boolean{
var self = this;
if(!self._parent) return false;
return self._parent.removeChild(self);
}
/**
* 对子节点进行排序(按照zIndex进行排序,zIndex越大则排在越后面)。
*/
public sortChildren():void{
this._children.sort(function(a:Node, b:Node){
if(a._zIndex > b._zIndex) return 1;
if(a._zIndex < b._zIndex) return -1;
return 0;
});
}
/**
* 设置在父节点中的布局情况
* @param preVisibleSibling
* @param nextSibling
* @private
*/
_doLayoutInParent(preVisibleSibling:Node, nextSibling:Node):void{
var self = this, parent = self._parent;
if(!parent) return;//没有父亲则直接返回
if(!parent._layoutEnabled) return;//父节点未开启布局功能
var pLayoutType = parent._layoutType, pLayoutTypeDirty = parent._layoutTypeDirty;
if(pLayoutType == LAYOUT_ABSOLUTE){//绝对布局则不做处理
//do nothing
}else if(pLayoutType == LAYOUT_RELATIVE){//相对布局
if(pLayoutTypeDirty || self._widthDirty){//TODO 或者相对布局参数dirty
}
if(pLayoutTypeDirty || self._heightDirty){//TODO 或者相对布局参数dirty
}
}else if(pLayoutType == LAYOUT_LINEAR_H){//线性水平布局
if(pLayoutTypeDirty || self._widthDirty || preVisibleSibling._xDirty || preVisibleSibling._widthDirty){//TODO 或者线性水平布局参数dirty
}
}else if(pLayoutType == LAYOUT_LINEAR_V){//线性垂直布局
if(pLayoutTypeDirty || self._heightDirty || preVisibleSibling._yDirty || preVisibleSibling._heightDirty){//TODO 或者线性垂直布局参数dirty
}
}
}
public visit(renderCtx, preVisibleSibling?:Node, nextSibling?:Node):void{
var self = this, clazz = self.__c;
if(!self._visible) return;
var parent = self._parent;
if(self._childrenDirty) self.sortChildren();//需要重新对子节点排序
if(parent){
//百分比设置需要父节点存在
if(self._widthPercentDirty) self._onWidthPercentDirty();
if(self._heightPercentDirty) self._onHeightPercentDirty();
if(self._xPercentDirty) self._onXPercentDirty();
if(self._yPercentDirty) self._onYPercentDirty();
}
if(self._xDirty) self._onXDirty();
if(self._yDirty) self._onYDirty();
if(self._widthDirty) self._onWidthDirty();
if(self._heightDirty) self._onHeightDirty();
self._onBeforeVisit(preVisibleSibling, nextSibling);
if(parent && parent._layoutEnabled)//当存在父节点并且父节点开启布局管理的时候才进行
self._doLayoutInParent(preVisibleSibling, nextSibling);//在父节点内部进行布局
self._onVisit(preVisibleSibling, nextSibling);
self._onUpdateView();
var children:Node[] = self._children, index:number = 0, length:number = children.length;
//先遍历zIndex<0的部分
var preVisibleSiblingTemp:Node = null;//上一个可见的兄弟节点
for (; index < length; index++) {
var child = children[index];
if(child._zIndex >= 0) break;
if(child._visible){
child.visit(renderCtx, preVisibleSiblingTemp, children[index+1]);
preVisibleSiblingTemp = child;
}
}
self._transform(renderCtx);//转化
renderCtx.save();
renderCtx.translate(self._transX, self._transY);
renderCtx.rotate(self._rotation);
renderCtx.scale(self._scaleX, self._scaleY);
self._draw(renderCtx);//进行自身视图的绘制
if(clazz.debug || self.debug) self._drawDebug(renderCtx);
renderCtx.restore();
//再遍历zIndex>=0的部分
for (; index < length; index++) {
var child = children[index];
if(child._visible){
child.visit(renderCtx, preVisibleSiblingTemp, children[index+1]);
preVisibleSiblingTemp = child;
}
}
self._onAfterVisit(preVisibleSibling, nextSibling);
renderCtx["enterFromRoot"] = false;
}
_onBeforeVisit(preVisibleSibling:Node, nextSibling:Node):void{}
_onVisit(preVisibleSibling:Node, nextSibling:Node):void{}
_onAfterVisit(preVisibleSibling:Node, nextSibling:Node):void{
var self = this, parent = self._parent;
self._xDirty = false;
self._yDirty = false;
self._widthDirty = false;
self._heightDirty = false;
self._childrenDirty = false;
if(parent){
//只有当父节点存在是,才将百分比dirty重置
self._xPercentDirty = false;
self._yPercentDirty = false;
self._widthPercentDirty = false;
self._heightPercentDirty = false;
}
if(self._layoutEnabled) {//只有当开启布局管理时,才需要将布局类型dirty重置
self._layoutTypeDirty = false;
}
}
_onUpdateView():void{}
_transX:number;
_transY:number;
_transWidth:number;
_transHeight:number;
_transform(renderCtx:CanvasRenderingContext2D){
var self = this, parent = self._parent;
var transX = 0, transY = 0;
if(parent){
transX += parent._transX || 0;
transY += parent._transY || 0;
}
if(renderCtx["enterFromRoot"]){
self._transX = transX + self._x;
self._transY = transY + self._y;
}else{
self._transX = 0;
self._transY = 0;
renderCtx["enterFromRoot"] = true;
}
self._transWidth = self._width;
self._transHeight = self._height;
}
_draw(renderCtx:CanvasRenderingContext2D):void{
}
_drawDebug(renderCtx:CanvasRenderingContext2D):void{
var self = this;
var transWidth = self._transWidth, transHeight = self._transHeight;
renderCtx.beginPath();
renderCtx.moveTo(0, 0); // 设置路径起点,坐标为(20,20)
renderCtx.lineTo(transWidth, 0); // 绘制一条到(200,20)的直线
renderCtx.lineTo(transWidth, transHeight); // 绘制一条到(200,20)的直线
renderCtx.lineTo(0, transHeight); // 绘制一条到(200,20)的直线
renderCtx.closePath();
renderCtx.lineWidth = 1.0; // 设置线宽
renderCtx.strokeStyle = "#ff0000"; // 设置线的颜色
renderCtx.stroke(); // 进行线的着色,这时整条线才变得可见
}
}
}<file_sep>/// <reference path="../base/Class.ts" />
module hh{
export class Event extends Class{
}
}<file_sep>/**
* Created by SmallAiTT on 2015/7/3.
*/
///<reference path="../../tc_init.ts" />
module tc{
unit.curModuleName = moduleName_Node;
var func4RelativeType = function(relativeType){
unit.addMenuItem('Node4Layout relativeType ' + relativeType, function(){
var node1 = new hh.Node();
node1.name = 'node1';
node1.width = node1.height = 200;
node1.x = node1.y = 200;
var node2 = new hh.Node();
node2.width = node2.height = 100;
var layout = node2.layout = new hh.Layout();
layout.relativeType = relativeType;
layout.x = layout.y = 20;
var stage:hh.Node = hh.engine.stage;
stage.addChild(node1);
node1.addChild(node2);
});
};
var func4LinearType = function(linearType){
unit.addMenuItem('Node4Layout linearType ' + linearType, function(){
var node1 = new hh.Node();
node1.name = 'node1';
var layout1 = node1.layout = new hh.Layout();
layout1.linearType = linearType;
layout1.padding = [10, 10, 20, 20];
layout1.x = layout1.y = 200;
node1.width = node1.height = 100;
for(var i = 0; i < 4; ++i){
var node2 = new hh.Node();
node2.name = 'node_' + i;
node2.width = node2.height = 50;
var layout = node2.layout = new hh.Layout();
layout.x = layout.y = 20;
layout.margin = [10, 10, 20, 20];
node1.addChild(node2);
}
var stage:hh.Node = hh.engine.stage;
stage.addChild(node1);
});
};
func4RelativeType(0);
func4RelativeType(1);
func4RelativeType(2);
func4RelativeType(10);
func4RelativeType(11);
func4RelativeType(12);
func4RelativeType(20);
func4RelativeType(21);
func4RelativeType(22);
func4LinearType(0);
func4LinearType(1);
func4LinearType(-1);
func4LinearType(2);
func4LinearType(-2);
}<file_sep>/**
* Created by SmallAiTT on 2015/7/6.
*/
///<reference path="ref.ts" />
unit.htmlMenuEnabled = false;
module tc{
//解析http参数
export function parseParam():any{
var data = {};
var src = window.location.href;
var index = src.indexOf('?');
if(index > 0){
var str = src.substring(index + 1);
var arr = str.split('&');
for (var i = 0, l_i = arr.length; i < l_i; i++) {
var paramStr = arr[i];
var param = paramStr.split('=');
var pKey = param[0], pValue:any = param[1];
if(pValue.match(/(^\d+$)/)){
pValue = parseInt(pValue);
}else if(pValue.match(/(^\d+.\d+$)/)){
pValue = parseFloat(pValue);
}
data[pKey] = window['unescape'](window['decodeURI'](pValue));
}
}
return data;
}
hh.engine.once(hh.Engine.AFTER_BOOT, function(){
var param = parseParam();
console.log(param);
unit.onMenu(param.moduleName, param.itemName);
});
}<file_sep>///<reference path="const/logCode.ts" />
///<reference path="const/const.ts" />
///<reference path="base/path.ts" />
///<reference path="base/logger.ts" />
///<reference path="base/Class.ts" />
///<reference path="base/async.ts" />
///<reference path="base/profile.ts" />
///<reference path="base/mainLoop.ts" />
///<reference path="utils/utils.ts" />
///<reference path="event/Event.ts" />
///<reference path="event/EventDispatcher.ts" />
///<reference path="res/res.ts" />
///<reference path="node/Node.ts" />
///<reference path="node/Root.ts" />
///<reference path="node/Scene.ts" />
///<reference path="node/ColorNode.ts" />
///<reference path="gui/UIImage.ts" /><file_sep>/**
* Created by SmallAiTT on 2015/6/29.
*/
///<reference path="../../tc_init.ts" />
module tc{
unit.curModuleName = moduleName_Node;
unit.addMenuItem('Node遍历测试', function(param){
hh.Node.debug = true;
var node1 = new hh.Node();
node1.name = 'node1';
node1.width = node1.height = 100;
var node2 = new hh.Node();
node2.name = 'node2';
node2.width = node2.height = 100;
node2.x = 110;
var node3 = new hh.Node();
node3.name = 'node3';
node3.width = node3.height = 100;
node3.x = 220;
node3.scaleX = node3.scaleY = 0.5;
var node4 = new hh.Node();
node4.name = 'node4';
node4.width = node4.height = 100;
node4.x = node4.y = 110;
node4.scaleX = node4.scaleY = 0.5;
node4.anchorX = node4.anchorY = 0.5;
var node5 = new hh.Node();
node5.name = 'node5';
node5.width = node5.height = 100;
node5.x = 220;
node5.y = 110;
node5.scaleX = node5.scaleY = 0.5;
node5.anchorX = node5.anchorY = 0.5;
node5.rotation = Math.PI/4;
var node6 = new hh.Node();
node6.name = 'node5';
node6.width = node6.height = 100;
node6.x = 0;
node6.y = 100;
node6.scaleX = node6.scaleY = 0.5;
node6.anchorX = node6.anchorY = 0.5;
var distance = 300, speed = 10;
var rate = 1;
var mv = function(){
if(rate == 1 && (node6.x + speed > distance)) rate = -1;
else if(rate == -1 && (node6.x - speed < 0)) rate = 1;
node6.x += speed*rate;
node6.rotation += 0.1;
};
hh.tick(mv);
param.mv = mv;
hh.engine.stage
.addChild(node1)
.addChild(node2)
.addChild(node3)
.addChild(node4)
.addChild(node5)
.addChild(node6);
}, function(param){
hh.unTick(param.mv);
});
unit.addMenuItem('Node 数量测试200', function(){
hh.Node.debug = false;
var url = res_helper.getItemUrl(11001);
hh.res.load(url, function(){
var stage:hh.Node = hh.engine.stage;
var w = stage.width, h = stage.height;
for(var i = 0; i < 200; ++i){
var randX = w*(Math.random());
var randY = h*(Math.random());
var img = new hh.Node();
img.x = randX;
img.y = randY;
img.height = 200;
stage.addChild(img);
}
});
});
unit.addMenuItem('Node 数量测试400', function(){
hh.Node.debug = false;
var url = res_helper.getItemUrl(11001);
hh.res.load(url, function(){
var stage:hh.Node = hh.engine.stage;
var w = stage.width, h = stage.height;
for(var i = 0; i < 400; ++i){
var randX = w*(Math.random());
var randY = h*(Math.random());
var img = new hh.Node();
img.x = randX;
img.y = randY;
img.height = 200;
stage.addChild(img);
}
});
});
unit.addMenuItem('Node 数量测试600', function(){
hh.Node.debug = false;
var url = res_helper.getItemUrl(11001);
hh.res.load(url, function(){
var stage:hh.Node = hh.engine.stage;
var w = stage.width, h = stage.height;
for(var i = 0; i < 600; ++i){
var randX = w*(Math.random());
var randY = h*(Math.random());
var img = new hh.Node();
img.x = randX;
img.y = randY;
img.height = 200;
stage.addChild(img);
}
});
});
}<file_sep>var __extends = function (d, b) {
for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p];
function __() {
this.constructor = d;
}
__.prototype = b.prototype;
d.prototype = new __();
};
//++++++++++++++++++++++++++AsyncPool api begin+++++++++++++++++++++++++++++++
module hh {
/**
* 异步池
*/
export class AsyncPool {
private _srcObj = null;
private _limit:number = 0;
private _pool:any[] = [];
private _iterator:Function = null;
private _iteratorCtx:any = null;
private _onEnd:Function = null;
private _onEndCtx:any = null;
private _results:any = null;
private _isErr:boolean = false;
/** 总大小 */
public size:number = 0;
/** 已完成的大小 */
public finishedSize:number = 0;
/** 正在工作的大小 **/
public _workingSize:number = 0;
constructor(srcObj:any, limit:number, iterator:Function, onEnd:Function, ctx?:any) {
var self = this;
self._srcObj = srcObj;
self._iterator = iterator;
self._iteratorCtx = ctx;
self._onEnd = onEnd;
self._onEndCtx = ctx;
self._results = srcObj instanceof Array ? [] : {};
self._each(srcObj, function (value:any, index?:any) {
self._pool.push({index: index, value: value});
});
self.size = self._pool.length;//总大小
self._limit = limit || self.size;
}
_each(obj, iterator:(value:any, index?:any)=>any, context?:any) {
if (!obj) return;
if (obj instanceof Array) {
for (var i = 0, li = obj.length; i < li; i++) {
if (iterator.call(context, obj[i], i) === false) return;
}
} else {
for (var key in obj) {
if (iterator.call(context, obj[key], key) === false) return;
}
}
}
public onIterator(iterator:Function, target:any):void {
this._iterator = iterator;
this._iteratorCtx = target;
}
public onEnd(endCb:Function, endCbTarget:any):void {
this._onEnd = endCb;
this._onEndCtx = endCbTarget;
}
private _handleItem():void {
var self = this;
if (self._pool.length == 0) return;//数组长度为0直接返回不操作了
if (self._workingSize >= self._limit) return;//正在工作的数量应达到限制上限则直接返回
var item:any = self._pool.shift();
var value = item.value;
var index = item.index;
self._workingSize++;//正在工作的大小+1
self._iterator.call(self._iteratorCtx, value, index, function (err) {
if (self._isErr) return;//已经出错了,就直接返回了
self.finishedSize++;//完成数量+1
self._workingSize--;//正在工作的大小-1
if (err) {
self._isErr = true;//设置成已经出错了
if (self._onEnd) self._onEnd.call(self._onEndCtx, err);//如果出错了
return
}
var arr = Array.prototype.slice.call(arguments);
arr.splice(0, 1);//去除第一个参数
self._results[this.index] = arr[0];//保存迭代器返回结果
if (self.finishedSize == self.size) {//已经结束
if (self._onEnd) self._onEnd.call(self._onEndCtx, null, self._results);
return
}
self._handleItem();//继续执行下一个
}.bind(item), self);
}
public flow(atOnce:boolean = false):void {
var self = this;
var onFlow = function () {
if (self._pool.length == 0) {
if (self._onEnd) self._onEnd.call(self._onEndCtx, null, []);//数组长度为0,直接结束
} else {
for (var i = 0; i < self._limit; i++) {
self._handleItem();
}
}
};
if (atOnce) {
onFlow();
} else {
setTimeout(function () {
onFlow();
}, 1);
}
}
}
}
//++++++++++++++++++++++++++AsyncPool api end+++++++++++++++++++++++++++++++
module hh{
var loadNext = function(){};
export var _jsCache:any = {};
export function getXMLHttpRequest(){
return window["XMLHttpRequest"] ? new window["XMLHttpRequest"]() : new ActiveXObject("MSXML2.XMLHTTP");
}
export function loadText(url:string, cb:Function){
var xhr = getXMLHttpRequest(),
errInfo = "load " + url + " failed!";
xhr.open("GET", url, true);
if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
// IE-specific logic here
xhr.setRequestHeader("Accept-Charset", "utf-8");
xhr.onreadystatechange = function () {
xhr.readyState == 4 && xhr.status == 200 ? cb(null, xhr.responseText) : cb(errInfo);
};
} else {
if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8");
xhr.onload = function () {
xhr.readyState == 4 && xhr.status == 200 ? cb(null, xhr.responseText) : cb(errInfo);
};
}
xhr.send(null);
}
export function loadJs(jsPath:string, cb:Function, ctx?:any){
if(_jsCache[jsPath]) return cb.call(ctx);
var d = document, s = d.createElement('script');
s.async = false;
s.src = jsPath;
_jsCache[jsPath] = true;
s.addEventListener('load',function(){
this.removeEventListener('load', arguments.callee, false);
cb.call(ctx);
},false);
s.addEventListener('error',function(){
cb.call(ctx, "Load " + jsPath + " failed!");
},false);
var scriptParent = d.body || d.head;
scriptParent.appendChild(s);
}
export function onEngineReady(cb, ctx){
}
export function onGameReady(cb, ctx){}
export var project:any = {};
export function boot(cb:Function, ctx?:any){
loadText("project.json", function(err, text){
if(err) return console.error(err);
project = JSON.parse(text);
var engineOpt = project["engine"];
var engineDir = engineOpt["dir"];
var modules = engineOpt["modules"];
//TODO test
var coreName = modules[0];
var coreRoot = engineDir+"/" + coreName + "/";
loadText(coreRoot + "module.json", function(err, moduleJsonText){
if(err) return console.error(err);
var moduleJson = JSON.parse(moduleJsonText);
var jsList = moduleJson["jsList"];
var asyncPool = new AsyncPool(jsList, 0, function(jsPath, index, cb1){
loadJs(coreRoot + jsPath, cb1);
}, function(){
(<any>hh).initRoot();
cb.call(ctx);
});
asyncPool.flow(true);
});
})
}
/**
* 获取入口js。
* @private
*/
export function _getMainScriptUrl():string{
var main = null;
if(document){
var scripts = document.getElementsByTagName("script");
var curScript:HTMLElement = scripts[scripts.length - 1];
main = curScript.getAttribute("main") || "src/main.js";
}
return main;
}
export var _mainScriptUrl = _getMainScriptUrl();
loadJs(_mainScriptUrl, function(){
});
}<file_sep>/// <reference path="Event.ts" />
module hh{
export class EventDispatcher extends Class{
}
}<file_sep>/**
* Created by Administrator on 2015/6/28.
*/
///<reference path="sty_init.ts" />
module sty{
unit.curModuleName = sty.moduleName_image;
unit.addMenuItem4Ctx('绘制', function(ctx:IRenderingContext2D){
resHelper.loadImage(resHelper.getItemUrl(10001), function(err, img){
// 普通绘制
ctx.drawImage(img,0,0);
// 默认为平滑过度
//(<any>ctx).mozImageSmoothingEnabled = false;
//(<any>ctx).webkitImageSmoothingEnabled = false;
//(<any>ctx).msImageSmoothingEnabled = false;
//(<any>ctx).imageSmoothingEnabled = false;
// 简单投射绘制,image, x, y, width, height
// 图标根据绘制区域进行拉伸
ctx.drawImage(img, 300, 0, 150, 50);
var w = img.width, h = img.height;
var sx = w/4, sy = h/4, sw = w/4, sh = h/4;
var ox = 300, oy = 100;
// image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight
ctx.drawImage(img, sx, sy, sw, sh, ox, oy, 200, 200);
});
});
}<file_sep>/**
* Created by SmallAiTT on 2015/7/3.
*/
///<reference path="../../tc_init.ts" />
module tc{
unit.curModuleName = moduleName_Node;
unit.addMenuItem('点击事件测试', function(){
var TH = hh.Touch;
var func = function(handler, x, y, phase){
console.log(this.touchType, '--->', handler.target.name, x, y, phase);
};
var stage:hh.Node = hh.engine.stage;
var node1 = new hh.Node();
node1.name = 'node1';
node1.width = node1.height = 200;
node1.x = node1.y = 200;
var handler1 = node1.touch;
handler1.on(TH.BEGAN, func, {touchType:'BEGAN'});
handler1.on(TH.MOVE, func, {touchType:'MOVE'});
handler1.on(TH.END, func, {touchType:'END'});
stage.addChild(node1);
var node2 = new hh.Node();
node2.name = 'node2';
node2.width = node2.height = 200;
node2.x = node2.y = 25;
node2.scaleX = node2.scaleY = 0.5;
node2.rotation = Math.PI/4;
var handler2 = node2.touch;
handler2.on(TH.BEGAN, func, {touchType:'BEGAN'});
handler2.on(TH.MOVE, func, {touchType:'MOVE'});
handler2.on(TH.END, func, {touchType:'END'});
node1.addChild(node2);
// 裁剪的节点
var node3 = new hh.Node();
node3.name = 'node3';
node3.x = node3.y = 100;
node3.width = node3.height = 100;
// 设置矩形裁剪
node3.clip = hh.Node.CLIP_RECT;
var handler3 = node3.touch;
handler3.on(TH.BEGAN, func, {touchType:'BEGAN'});
handler3.on(TH.MOVE, func, {touchType:'MOVE'});
handler3.on(TH.END, func, {touchType:'END'});
node1.addChild(node3);
var node4 = new hh.Node();
node4.name = 'node4';
node4.x = node4.y = 100;
node4.width = node4.height = 100;
node4._nodeOpt.debugRectColor = 'blue';
var handler4 = node4.touch;
handler4.on(TH.BEGAN, func, {touchType:'BEGAN'});
handler4.on(TH.MOVE, func, {touchType:'MOVE'});
handler4.on(TH.END, func, {touchType:'END'});
node3.addChild(node4);
});
}<file_sep>/**
* Created by SmallAiTT on 2015/6/26.
*/
///<reference path="canvas.d.ts" />
var _thisGlobal:any = this;
_thisGlobal.__extends = _thisGlobal.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() {
this.constructor = d;
}
__.prototype = b.prototype;
d.prototype = new __();
};
module logger{
var _map = {};
/**
* 初始化模块日志
* @param m
* @param mName
*/
export function initLogger(m:any, mName){
_map[mName] = m;
m.log = console.log.bind(console);
m.debug = console.debug.bind(console);
m.info = console.info.bind(console);
m.warn = console.warn.bind(console);
m.error = console.error.bind(console);
}
/**
* 设置日志等级
* @param mName
* @param lvl
*/
export function setLvl(mName, lvl){
if(mName == 'default'){
for (var key in _map) {
if(key == 'default') continue;
var m = _map[key];
if(!m) continue;
initLogger(m, key);
if(lvl > 1){
m.log = function(){};
m.debug = function(){};
}
if(lvl > 2) m.info = function(){};
if(lvl > 3) m.warn = function(){};
if(lvl > 4) m.error = function(){};
}
}else{
var m = _map[mName];
if(!m) return;//该日志还没初始化过,没法设置等级
initLogger(m, mName);
if(lvl > 1){
m.log = function(){};
m.debug = function(){};
}
if(lvl > 2) m.info = function(){};
if(lvl > 3) m.warn = function(){};
if(lvl > 4) m.error = function(){};
}
}
/**
* 根据配置文件信息初始化日志。
* @param config
*/
export function initByConfig(config){
var logLvl = config.logLvl;
if(typeof logLvl == 'number'){
logger.setLvl('default', logLvl);
}else{
var logLvlDefault = logLvl['default'];
if(logLvlDefault != null) logger.setLvl('default', logLvlDefault);
for (var mName in logLvl) {
if(mName == 'all') continue;
logger.setLvl(mName, logLvl[mName]);
}
}
}
export var log:Function;
export var debug:Function;
export var info:Function;
export var warn:Function;
export var error:Function;
initLogger(logger, 'logger');
}
module hh.net {
export var log:Function;
export var debug:Function;
export var info:Function;
export var warn:Function;
export var error:Function;
logger.initLogger(hh.net, 'net');
export function getXHR(){
return window['XMLHttpRequest'] ? new window['XMLHttpRequest']() : new ActiveXObject('MSXML2.XMLHTTP');
}
export function loadTxt(url:string, cb:Function){
var xhr = hh.net.getXHR(),
errInfo = 'load ' + url + ' failed!';
xhr.open('GET', url, true);
if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
// IE-specific logic here
xhr.setRequestHeader('Accept-Charset', 'utf-8');
xhr.onreadystatechange = function () {
if(xhr.readyState === 4)
xhr.status === 200 ? cb(null, xhr.responseText) : cb(errInfo);
};
} else {
if (xhr.overrideMimeType) xhr.overrideMimeType('text\/plain; charset=utf-8');
xhr.onload = function () {
if(xhr.readyState === 4)
xhr.status === 200 ? cb(null, xhr.responseText) : cb(errInfo);
};
}
xhr.send(null);
}
export function loadJson(url:string, cb:Function){
hh.net.loadTxt(url, function (err, txt) {
if (err) {
cb(err);
}
else {
try {
cb(null, JSON.parse(txt));
}
catch (e) {
err = 'parse json [' + url + '] failed : ' + e;
error(err);
cb(err);
}
}
});
}
var _getArgs4Js = function (args) {
var a0 = args[0], a1 = args[1], a2 = args[2], results = ['', null, null];
if (args.length === 1) {
results[1] = a0 instanceof Array ? a0 : [a0];
} else if (args.length === 2) {
if (typeof a1 === 'function') {
results[1] = a0 instanceof Array ? a0 : [a0];
results[2] = a1;
} else {
results[0] = a0 || '';
results[1] = a1 instanceof Array ? a1 : [a1];
}
} else if (args.length === 3) {
results[0] = a0 || '';
results[1] = a1 instanceof Array ? a1 : [a1];
results[2] = a2;
} else throw 'arguments error to load js!';
if(results[0] != '' && results[0].substring(results[0].length - 1) != '/') results[0] += '/';
return results;
};
var _jsCache = {};
var _loadScript4H5 = function(jsPath, cb){
var d = document, s = d.createElement('script');
s.async = false;
s.src = jsPath;
_jsCache[jsPath] = true;
var _onLoad = function(){
this.removeEventListener('load', _onLoad, false);
this.removeEventListener('error', _onError, false);
cb();
};
var _onError = function(){
this.removeEventListener('load', _onLoad, false);
this.removeEventListener('error', _onError, false);
cb('Load ' + jsPath + ' failed!');
};
s.addEventListener('load', _onLoad,false);
s.addEventListener('error', _onError,false);
d.body.appendChild(s);
};
export function loadJs(baseDir?:any, jsList?:any, cb?:any) {
var args = _getArgs4Js(arguments);
var preDir = args[0], list = args[1], callback:any = args[2];
if(!(<any>hh).isNative){
var asyncPool = new AsyncPool(list, 0, function(item, index, cb1){
var jsPath = preDir + item;
if(_jsCache[jsPath]) return cb1();
_loadScript4H5(jsPath, cb1);
}, callback);
asyncPool.flow();
}else{
for (var i = 0, l_i = list.length; i < l_i; i++) {
var jsPath = preDir + list[i];
if(_jsCache[jsPath]) continue;
_jsCache[jsPath] = true;
_thisGlobal.require(jsPath);
}
callback();
}
}
}
module hh.project {
var _handlerArr = [];
/**
* 注册project值处理函数。
* @param handler
*/
export function registerValueHandler(handler){
_handlerArr.push(handler);
}
/**
* 设置project值。
* @param data
* @param key
* @param isBool
*/
export function setValue(data, key, isBool?){
var defaultValue = project[key];
var dv = data[key];
if(dv == null) project[key] = defaultValue;
else{
dv = isBool ? !!dv : dv;
project[key] = dv;
}
}
/**
* 解析project内容
* @param data
*/
export function parse(data){
for (var i = 0, l_i = _handlerArr.length; i < l_i; i++) {
var handler = _handlerArr[i];
handler(data);
}
}
//解析http参数
export function parseParam(){
var data = {};
var src = window.location.href;
var index = src.indexOf('?');
if(index > 0){
var str = src.substring(index + 1);
var arr = str.split('&');
for (var i = 0, l_i = arr.length; i < l_i; i++) {
var paramStr = arr[i];
var param = paramStr.split('=');
var pKey = param[0], pValue:any = param[1];
if(pValue.match(/(^\d+$)/)){
pValue = parseInt(pValue);
}else if(pValue.match(/(^\d+.\d+$)/)){
pValue = parseFloat(pValue);
}
data[pKey] = pValue;
}
}
project.parse(data);
}
//加载project配置
export function load(cb){
//加载配置文件
hh.net.loadJson('project.json', function(err, data){
if(err){
logger.error('缺失project.json文件,请检查!');
}else{
project.parse(data);
}
if((<any>hh).isNative){//不是h5就没有myProject.json和浏览器参数模式
return cb();
}
hh.net.loadJson('myProject.json', function(err, data){
if(err){
project.parseParam();
cb();
}else{
project.parse(data);
project.parseParam();
cb();
}
});
});
}
/** 版本号 */
export var version:string = '0.0.1';
/** 程序包名,实际上会再加上projName作为真正的包名 */
export var pkg:string = 'net.holyhigh';
/** 项目名称 */
export var projName:string = 'hh';
/** app名称 */
export var appName:string = 'HolyHigh精品游戏';
/** 日志等级 */
export var logLvl:any = {};
/** 渲染模式,1为webgl,否则为canvas */
export var renderMode:number = 1;
export var canvas:string;
/** 是否显示FPS */
export var showFPS:boolean = false;
/** 帧率 */
export var frameRate:number = 60;
/** 设计分辨率 */
export var design:any = {width:960, height:640};//size
/** 适配,目前没用 */
export var resolution:any = {width:0, height:0};//size
/** 自由选项 */
export var option:any = {};
export var scaleMode:string;
registerValueHandler(function(data){
setValue(data, 'version');
setValue(data, 'pkg');
setValue(data, 'projName');
setValue(data, 'appName');
setValue(data, 'logLvl');
setValue(data, 'renderMode');
setValue(data, 'showFPS', true);
setValue(data, 'frameRate');
setValue(data, 'design');
setValue(data, 'resolution');
setValue(data, 'option');
setValue(data, 'scaleMode');
setValue(data, 'canvas');
});
}
module hh.STR{
/**
* 格式化参数成String。
* 参数和h5的console.log保持一致。
* @returns {*}
*/
export function format(...args:any[]):string{
var l = args.length;
if(l < 1){
return '';
}
var str = args[0];
var needToFormat = true;
if(typeof str == 'object'){
str = JSON.stringify(str);
needToFormat = false;
}
if(str == null) str = 'null';
str += '';
var count = 1;
if(needToFormat){
var content = str.replace(/(%d)|(%i)|(%s)|(%f)|(%o)/g, function(world){
if(args.length <= count) return world;
var value = args[count++];
if(world == '%d' || world == '%i'){
return parseInt(value);
}else{
return value;
}
});
for (var l_i = args.length; count < l_i; count++) {
content += ' ' + args[count];
}
return content;
}else{
for(var i = 1; i < l; ++i){
var arg = args[i];
arg = typeof arg == 'object' ? JSON.stringify(arg) : arg;
str += ' ' + arg;
}
return str;
}
}
var _tempStrRegExp = /\$\{[^\s\{\}]*\}/g;
/**
* 占位符模式替换。
* @param tempStr
* @param map
* @returns {string}
*/
export function placeholder(tempStr:string, map:any):string{
function change(word){
var key = word.substring(2, word.length - 1)
var value = map[key];
if(value == null) {
console.error("formatTempStr时,map中缺少变量【%s】的设置,请检查!", key);
return word;
}
return value;
}
return tempStr.replace(_tempStrRegExp, change);
}
}
module hh {
export class Class{
/** 类名 */
static __n:string;
static __recycler:any[] = [];
static push(obj:any){
this.__recycler.push(obj);
}
static pop(...args):any{
var clazz = this;
var obj = clazz.__recycler.pop();
if(obj) return obj;
else clazz.create.apply(clazz, args);
}
/** 创建 */
static create(...args:any[]):any {
var Class:any = this;
var obj:any = new Class();
if (obj.init) obj.init.apply(obj, arguments);
return obj;
}
/** 获取单例 */
static getInstance(...args:any[]) {
var Class:any = this;
if (!Class._instance) {
var instance:any = Class._instance = Class.create.apply(Class, arguments);
instance._isInstance = true;
}
return Class._instance;
}
/** 释放单例 */
static release() {
var Class:any = this;
var instance:any = Class._instance;
if (instance) {
if (instance.doDtor) instance.doDtor();
Class._instance = null;
}
}
/** 类名 */
__n:string;
/** 实例对应的类 */
__c:any;
/** 是否是单例 */
_isInstance:boolean;
/** 储藏室 */
_store:Store;
/** 是否已经释放了 */
_hasDtored:boolean;
_initProp():void {
var self = this;
self._store = new Store();
}
constructor() {
var self = this;
self._initProp();
}
public init(...args:any[]) {
}
public dtor() {
var self = this;
if (self._hasDtored) return;
self._hasDtored = true;
self._dtor();
}
_dtor() {
}
}
/**
* 异步池
*/
export class AsyncPool {
private _srcObj = null;
private _limit:number = 0;
private _pool:any[] = [];
private _iterator:Function = null;
private _iteratorCtx:any = null;
private _onEnd:Function = null;
private _onEndCtx:any = null;
private _results:any = null;
private _isErr:boolean = false;
/** 总大小 */
public size:number = 0;
/** 已完成的大小 */
public finishedSize:number = 0;
/** 正在工作的大小 **/
public _workingSize:number = 0;
constructor(srcObj:any, limit:number, iterator:Function, onEnd:Function, ctx?:any) {
var self = this;
self._srcObj = srcObj;
self._iterator = iterator;
self._iteratorCtx = ctx;
self._onEnd = onEnd;
self._onEndCtx = ctx;
self._results = srcObj instanceof Array ? [] : {};
self._each(srcObj, function (value:any, index?:any) {
self._pool.push({index: index, value: value});
});
self.size = self._pool.length;//总大小
self._limit = limit || self.size;
}
_each(obj, iterator:(value:any, index?:any)=>any, context?:any) {
if (!obj) return;
if (obj instanceof Array) {
for (var i = 0, li = obj.length; i < li; i++) {
if (iterator.call(context, obj[i], i) === false) return;
}
} else {
for (var key in obj) {
if (iterator.call(context, obj[key], key) === false) return;
}
}
}
public onIterator(iterator:Function, target:any):AsyncPool {
this._iterator = iterator;
this._iteratorCtx = target;
return this;
}
public onEnd(endCb:Function, endCbTarget:any):AsyncPool {
this._onEnd = endCb;
this._onEndCtx = endCbTarget;
return this;
}
private _handleItem():void {
var self = this;
if (self._pool.length == 0) return;//数组长度为0直接返回不操作了
if (self._workingSize >= self._limit) return;//正在工作的数量应达到限制上限则直接返回
var item:any = self._pool.shift();
var value = item.value;
var index = item.index;
self._workingSize++;//正在工作的大小+1
self._iterator.call(self._iteratorCtx, value, index, function (err) {
if (self._isErr) return;//已经出错了,就直接返回了
self.finishedSize++;//完成数量+1
self._workingSize--;//正在工作的大小-1
if (err) {
self._isErr = true;//设置成已经出错了
if (self._onEnd) self._onEnd.call(self._onEndCtx, err);//如果出错了
return
}
var arr = Array.prototype.slice.call(arguments);
arr.splice(0, 1);//去除第一个参数
self._results[this.index] = arr[0];//保存迭代器返回结果
if (self.finishedSize == self.size) {//已经结束
if (self._onEnd) self._onEnd.call(self._onEndCtx, null, self._results);
return
}
if (engine._isMainLooping) {// 如果主循环已经开始执行了,就延迟到下一帧执行
hh.nextTick(self._handleItem, self);
} else {
//实在没有就用自带的(浏览器环境下才会进)
_thisGlobal.setTimeout(function () {
self._handleItem();
}, 1);
}
//self._handleItem();//继续执行下一个
}.bind(item), self);
}
public flow():void {
var self = this;
var onFlow = function () {
if (self._pool.length == 0) {
if (self._onEnd) self._onEnd.call(self._onEndCtx, null, []);//数组长度为0,直接结束
} else {
for (var i = 0; i < self._limit; i++) {
self._handleItem();
}
}
};
if (engine._isMainLooping) {
hh.nextTick(onFlow);
} else {
//实在没有就用自带的(浏览器环境下才会进)
_thisGlobal.setTimeout(function () {
onFlow();
}, 1);
}
}
}
/**
* 储藏室
*/
export class Store {
pool:any = {};
tempPool:any = {};
pool4Single:any = {};
tempArgsMap:any = {};
valuePool:any = {};
register(owner:string, type:string, listener:Function, ctx:any, priority:number) {
var pool = this.pool;
var map = pool[owner];
if (!map) {
pool[owner] = map = {};
}
var arr = map[type];
if (!arr) {
arr = map[type] = [];
}
for (var i = 0, l_i = arr.length; i < l_i; i++) {
var obj = arr[i];
if (!obj) continue;
if (obj.listener == listener && obj.ctx == ctx) return;//避免重复注册
}
var info = {listener: listener, ctx: ctx, priority: priority};
if (priority == null) {
arr.push(info);
} else {
var index = 0;
for (var i = 0, l_i = arr.length; i < l_i; i++) {
var obj = arr[i];
if (obj.priority == null || obj.priority <= priority) {//往后追加
index = i + 1;
} else if (obj.priority > priority) {
index = i;
break;
}
}
arr.splice(index, 0, info);
}
}
unRegister(owner:string, type:string, listener:Function, ctx:any) {
var pool = this.pool;
var map = pool[owner];
if (!map) return;
var arr = map[type];
if (!arr) return;
for (var i = 0, l_i = arr.length; i < l_i; i++) {
var obj = arr[i];
if (obj.listener == listener && obj.ctx == ctx) {
arr.splice(i, 1);
return;
}
}
}
clear(owner:string, type:string) {
var pool = this.pool;
var map = pool[owner];
if (!map) return;
var arr = map[type];
if (!arr) return;
arr.length = 0;
}
registerSingle(owner:string, type:string, listener:Function, ctx:any) {
var self = this, pool4Single = self.pool4Single, map = pool4Single[owner];
if (!map) {
map = pool4Single[owner] = {};
}
map[type] = {listener: listener, ctx: ctx};
}
unRegisterSingle(owner:string, type:string) {
var self = this, pool4Single = self.pool4Single, map = pool4Single[owner];
if (!map) return;
delete map[type];
}
unRegisterAll(owner:string, type?:string) {
var pool = this.pool, pool4Single = this.pool4Single;
var map = pool[owner], map4Single = pool4Single[owner];
if (arguments.length == 1) {//删除所有
if (map) {
for (var key in map) {
delete map[key];
}
}
if (map4Single) {
for (var key in map4Single) {
delete map4Single[key];
}
}
} else {//删除指定的type。
if (map) {
var arr = map[type];
if (arr) arr.length = 0;
}
if (map4Single) {
delete map4Single[type];
}
}
}
getTempArr(owner:string, type:string) {
var pool = this.pool, tempPool = this.tempPool;
var map = pool[owner];
if (!map) return null;
var arr = map[type];
if (!arr) return null;
var tempMap = tempPool[owner];
if (!tempMap) {
tempMap = tempPool[owner] = {};
}
var tempArr = tempMap[type];
if (!tempArr) {
tempArr = tempMap[type] = [];
}
tempArr.length = 0;
for (var i = 0, l_i = arr.length; i < l_i; i++) {
tempArr.push(arr[i]);
}
return tempArr;
}
getSingle(owner:string, type:string):any {
var self = this, pool4Single = self.pool4Single, map = pool4Single[owner];
if (!map) return null;
return map[type];
}
getTempArgs(owner:string, type:string, args):any[] {
var tempArgsMap = this.tempArgsMap;
var map = tempArgsMap[owner];
if (!map) {
map = tempArgsMap[owner] = {};
}
var arr = map[type];
if (!arr) {
arr = map[type] = [];
}
if (arr.length > 0) {//如果长度大于0,证明还在使用该temp数组。这时候就重新new一个进行返回
arr = [];
}
for (var i = 0, l_i = args.length; i < l_i; i++) {
arr.push(args[i]);
}
return arr;
}
setValue(owner:string, type:string, args:any) {
var valuePool = this.valuePool;
var map = valuePool[owner];
if (!map) {
map = valuePool[owner] = {};
}
map[type] = args;
}
removeValue(owner:string, type:string):any {
var valuePool = this.valuePool;
var map = valuePool[owner];
if (!map) return null;
return map[type];
}
}
var _OWNER_ON:string = 'on';
var _OWNER_ON_NT:string = 'onNextTick';
var _OWNER_ONCE:string = 'once';
var _OWNER_ONCE_NT:string = 'onceNextTick';
var _OWNER_ON_ASYNC:string = 'onAsync';
var _OWNER_ONCE_ASYNC:string = 'onceAsync';
var _emittersNextTick:Emitter[] = [];
var _tempEmittersNextTick:Emitter[] = [];
var _tempEmitters:Emitter[] = [];
var _tempEventArr:any = [];
var _tempArgsArr:any = [];
export class Emitter {
/** 类名 */
public static __n:string;
static __recycler:any[] = [];
static push(obj:any){
this.__recycler.push(obj);
}
static pop(...args):any{
var clazz = this;
var obj = clazz.__recycler.pop();
if(obj) return obj;
else return clazz.create.apply(clazz, args);
}
/** 创建 */
static create(...args:any[]):any {
var Class:any = this;
var obj:any = new Class();
if (obj.init) obj.init.apply(obj, arguments);
return obj;
}
/** 获取单例 */
static getInstance(...args:any[]) {
var Class:any = this;
if (!Class._instance) {
var instance:any = Class._instance = Class.create.apply(Class, arguments);
instance._isInstance = true;
}
return Class._instance;
}
/** 释放单例 */
static release() {
var Class:any = this;
var instance:any = Class._instance;
if (instance) {
if (instance.doDtor) instance.doDtor();
Class._instance = null;
}
}
/** 类名 */
__n:string;
/** 实例对应的类 */
__c:any;
/** 是否是单例 */
_isInstance:boolean;
/** 储藏室 */
_store:Store;
/** 是否已经释放了 */
_hasDtored:boolean;
_initProp():void {
var self = this;
self._store = new Store();
}
constructor() {
var self = this;
self._initProp();
}
public init(...args:any[]) {
}
public dtor() {
var self = this;
if (self._hasDtored) return;
self._hasDtored = true;
self._dtor();
}
_dtor() {
}
//______________以上由于考虑到性能问题,故意重新写了一遍,减少继承____________
/**
* 监听某个事件。可以注册多个。通过emit触发。
* @param event
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
on(event:string, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.register(_OWNER_ON, event, listener, ctx, null);
return self;
}
/**
* 通过优先级进行事件监听注册。通过emit触发。
* @param event
* @param priority
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
onPriority(event:string, priority:number, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.register(_OWNER_ON, event, listener, ctx, priority);
return self;
}
/**
* 监听某个事件。可以注册多个。通过emit触发。(异步模式,listener的第一个传参为异步需要执行的cb)
* @param event
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
onAsync(event:string, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.register(_OWNER_ON_ASYNC, event, listener, ctx, null);
return self;
}
/**
* 通过优先级进行事件监听注册。通过emit触发。(异步模式,listener的第一个传参为异步需要执行的cb)
* @param event
* @param priority
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
onAsyncPriority(event:string, priority:number, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.register(_OWNER_ON_ASYNC, event, listener, ctx, priority);
return self;
}
/**
* 监听某个事件,在下一帧执行。可以注册多个。通过emitNextTick触发。
* @param event
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
onNextTick(event:string, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.register(_OWNER_ON_NT, event, listener, ctx, null);
return self;
}
/**
* 通过优先级进行事件监听注册。通过emitNextTick触发。
* @param event
* @param priority
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
onPriorityNextTick(event:string, priority:number, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.register(_OWNER_ON_NT, event, listener, ctx, priority);
return self;
}
/**
* 注册一次性监听,触发了就移除。可以注册多个。通过emit触发。
* @param event
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
once(event:string, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.register(_OWNER_ONCE, event, listener, ctx, null);
return self;
}
/**
* 通过优先级进行事件监听注册。通过emit触发。
* @param event
* @param priority
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
oncePriority(event:string, priority:number, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.register(_OWNER_ONCE, event, listener, ctx, priority);
return self;
}
/**
* 注册一次性监听,触发了就移除。可以注册多个。通过emit触发。
* @param event
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
onceAsync(event:string, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.register(_OWNER_ONCE_ASYNC, event, listener, ctx, null);
return self;
}
/**
* 通过优先级进行事件监听注册。通过emit触发。
* @param event
* @param priority
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
onceAsyncPriority(event:string, priority:number, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.register(_OWNER_ONCE_ASYNC, event, listener, ctx, priority);
return self;
}
/**
* 注册一次性监听,触发了就移除。可以注册多个。通过emitNextTick触发。
* @param event
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
onceNextTick(event:string, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.register(_OWNER_ONCE_NT, event, listener, ctx, null);
return self;
}
/**
* 注册一次性监听,触发了就移除。可以注册多个。通过emitNextTick触发。
* @param event
* @param priority
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
oncePriorityNextTick(event:string, priority:number, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.register(_OWNER_ONCE, event, listener, ctx, priority);
return self;
}
/**
* 注册单个监听,每次都被最新注册的替换。通过emit触发。
* @param event
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
single(event:string, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.registerSingle(_OWNER_ON, event, listener, ctx);
return self;
}
/**
* 注册单个监听,每次都被最新注册的替换。通过emit触发。
* @param event
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
singleAsync(event:string, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.registerSingle(_OWNER_ON_ASYNC, event, listener, ctx);
return self;
}
/**
* 注册单个监听,每次都被最新注册的替换。通过emitNextTick触发。
* @param event
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
singleNextTick(event:string, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.registerSingle(_OWNER_ON_NT, event, listener, ctx);
return self;
}
/**
* 移除事件监听。
* @param event
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
un(event:string, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.unRegister(_OWNER_ON, event, listener, ctx);
return self;
}
/**
* 移除下一帧类型的事件监听。
* @param event
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
unNextTick(event:string, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.unRegister(_OWNER_ON_NT, event, listener, ctx);
return self;
}
/**
* 移除一次性的事件监听。
* @param event
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
unOnce(event:string, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.unRegister(_OWNER_ONCE, event, listener, ctx);
return self;
}
/**
* 移除下一帧执行的一次性的监听。
* @param event
* @param listener
* @param ctx
* @returns {mo_evt.Emitter}
*/
unOnceNextTick(event:string, listener:Function, ctx?:any):Emitter {
var self = this;
self._store.unRegister(_OWNER_ONCE_NT, event, listener, ctx);
return self;
}
/**
* 移除单个类型的事件监听。
* @param event
* @returns {mo_evt.Emitter}
*/
unSingle(event:string):Emitter {
var self = this;
self._store.unRegisterSingle(_OWNER_ON, event);
return self;
}
/**
* 移除单个类型的并且是下一帧执行类型的事件监听。
* @param event
* @returns {mo_evt.Emitter}
*/
unSingleNextTick(event:string):Emitter {
var self = this;
self._store.unRegisterSingle(_OWNER_ON_NT, event);
return self;
}
/**
* 移除所有立即执行类型的事件监听。
* 如果arguments.length == 0 那么就表示移除所有监听。
* 如果arguments.length == 1 那么就表示移除指定类型的所有监听。
* @param event
* @returns {mo_evt.Emitter}
*/
unAll(event?:string):Emitter {
var self = this;
var l = arguments.length;
var arr = [
_OWNER_ON,
_OWNER_ONCE
];
for (var i = 0, l_i = arr.length; i < l_i; i++) {
var owner = arr[i];
if (l == 0) {
self._store.unRegisterAll(owner);
} else {
self._store.unRegisterAll(owner, event);
}
}
return self;
}
/**
* 移除所有下一帧执行类型的事件监听。
* 如果arguments.length == 0 那么就表示移除所有监听。
* 如果arguments.length == 1 那么就表示移除指定类型的所有监听。
* @param event
* @returns {mo_evt.Emitter}
*/
unAllNextTick(event?:string):Emitter {
var self = this;
var arr = [
_OWNER_ON_NT,
_OWNER_ONCE_NT
];
var l = arguments.length;
for (var i = 0, l_i = arr.length; i < l_i; i++) {
var owner = arr[i];
if (l == 0) {
self._store.unRegisterAll(owner);
} else {
self._store.unRegisterAll(owner, event);
}
}
return self;
}
_emitByListenerInfoArr(owner:string, event:string, arr, args:any[]) {
if (arr) {
var self = this;
arr = arr instanceof Array ? arr : [arr];
if (arr.length == 0) return;
var args = self._store.getTempArgs(owner, event, args);
args.push(event);//事件类型放在倒数第二位置
args.push(self);//发送者放在最后一个位置
for (var i = 0, l_i = arr.length; i < l_i; i++) {
var info = arr[i];
var listener = info.listener;
if (listener) {
listener.apply(info.ctx, args);
}
}
arr.length = 0;//清空引用
args.length = 0;//清空参数
}
}
/**
* 立即发射事件。
* @param event
* @param args
* @returns {mo_evt.Emitter}
*/
emit(event:string, ...args):Emitter {
var self = this, store = self._store, single, tempArr;
//实例级别的注册
//先执行单个的
single = store.getSingle(_OWNER_ON, event);
self._emitByListenerInfoArr(_OWNER_ON, event, single, args);
//再执行一次性的
tempArr = store.getTempArr(_OWNER_ONCE, event);
store.clear(_OWNER_ONCE, event);//进行清除
self._emitByListenerInfoArr(_OWNER_ONCE, event, tempArr, args);
//最后执行多次的
tempArr = store.getTempArr(_OWNER_ON, event);
self._emitByListenerInfoArr(_OWNER_ON, event, tempArr, args);
//类级别的注册
store = self.__c._store;
//先执行单个的
single = store.getSingle(_OWNER_ON, event);
self._emitByListenerInfoArr(_OWNER_ON, event, single, args);
//再执行一次性的
tempArr = store.getTempArr(_OWNER_ONCE, event);
store.clear(_OWNER_ONCE, event);//进行清除
self._emitByListenerInfoArr(_OWNER_ONCE, event, tempArr, args);
//最后执行多次的
tempArr = store.getTempArr(_OWNER_ON, event);
self._emitByListenerInfoArr(_OWNER_ON, event, tempArr, args);
return self;
}
/**
* 立即发射事件。
* @param event
* @param args
* @returns {mo_evt.Emitter}
*/
emitAsync(event:string, onEnd:Function, ctx:any, ...args):Emitter {
var self = this, store = self._store, single, tempArr;
var arr = [];
//实例级别的注册
//先执行单个的
single = store.getSingle(_OWNER_ON_ASYNC, event);
if (single) arr.push(arr);
//再执行一次性的
tempArr = store.getTempArr(_OWNER_ONCE_ASYNC, event);
if (tempArr) {
for (var i = 0, l_i = tempArr.length; i < l_i; i++) {
arr.push(tempArr[i]);
}
}
store.clear(_OWNER_ONCE_ASYNC, event);//进行清除
//最后执行多次的
tempArr = store.getTempArr(_OWNER_ON_ASYNC, event);
if (tempArr) {
for (var i = 0, l_i = tempArr.length; i < l_i; i++) {
arr.push(tempArr[i]);
}
}
//类级别的注册
store = self.__c._store;
//先执行单个的
single = store.getSingle(_OWNER_ON_ASYNC, event);
if (single) arr.push(arr);
//再执行一次性的
tempArr = store.getTempArr(_OWNER_ONCE_ASYNC, event);
if (tempArr) {
for (var i = 0, l_i = tempArr.length; i < l_i; i++) {
arr.push(tempArr[i]);
}
}
store.clear(_OWNER_ONCE_ASYNC, event);//进行清除
//最后执行多次的
tempArr = store.getTempArr(_OWNER_ON_ASYNC, event);
if (tempArr) {
for (var i = 0, l_i = tempArr.length; i < l_i; i++) {
arr.push(tempArr[i]);
}
}
var tempArgs:any[] = [null].concat(args);
tempArgs.push(event);
tempArgs.push(self);
var asyncPool = new hh.AsyncPool(arr, 0, function (info, index, cb1) {
tempArgs[0] = cb1;
info.listener.apply(info.ctx, tempArgs);
}, onEnd, ctx);
asyncPool.flow();
return self;
}
/**
* 在下一帧才发射事件。而且,发射的事件只会发射最后调用emitNextTick的那次。
* @param event
* @param args
* @returns {mo_evt.Emitter}
*/
emitNextTick(event:string, ...args):Emitter {
var self = this;
self._store.setValue(_OWNER_ON_NT, event, args);
if (_emittersNextTick.indexOf(self) < 0) _emittersNextTick.push(self);
return self;
}
/**
* 发射阶段性事件。before and after。
* @param event
* @param func
* @param ctx
* @param args
* @returns {mo_evt.Emitter}
*/
emitPhase(event:string, func:Function, ctx:any, ...args):Emitter {
var self = this;
return self;
}
/**
* 在下一帧才发射阶段性事件。before and after。
* 而且,发射的事件只会发射最后调用emitPhaseNextTick的那次。
* @param event
* @param func
* @param ctx
* @param args
* @returns {mo_evt.Emitter}
*/
emitPhaseNextTick(event:string, func:Function, ctx:any, ...args):Emitter {
var self = this;
return self;
}
//++++++++++++++++++++++++++++++静态方法 开始+++++++++++++++++++++++++++++++++
static _store:Store = new Store();
/**
* 监听某个事件。可以注册多个。通过emit触发。
* @param event
* @param listener
* @param ctx
*/
static on(event:string, listener:Function, ctx?:any):any {
return this.prototype.on.apply(this, arguments);
}
/**
* 通过优先级进行事件监听注册。通过emit触发。
* @param event
* @param priority
* @param listener
* @param ctx
*/
static onPriority(event:string, priority:number, listener:Function, ctx?:any):any {
return this.prototype.onPriority.apply(this, arguments);
}
/**
* 监听某个事件。可以注册多个。通过emit触发。
* @param event
* @param listener
* @param ctx
*/
static onAsync(event:string, listener:Function, ctx?:any):any {
return this.prototype.onAsync.apply(this, arguments);
}
/**
* 通过优先级进行事件监听注册。通过emit触发。
* @param event
* @param priority
* @param listener
* @param ctx
*/
static onAsyncPriority(event:string, priority:number, listener:Function, ctx?:any):any {
return this.prototype.onAsyncPriority.apply(this, arguments);
}
/**
* 监听某个事件,在下一帧执行。可以注册多个。通过emitNextTick触发。
* @param event
* @param listener
* @param ctx
*/
static onNextTick(event:string, listener:Function, ctx?:any):any {
return this.prototype.onNextTick.apply(this, arguments);
}
/**
* 通过优先级进行事件监听注册。通过emitNextTick触发。
* @param event
* @param priority
* @param listener
* @param ctx
*/
static onPriorityNextTick(event:string, priority:number, listener:Function, ctx?:any):any {
return this.prototype.onPriorityNextTick.apply(this, arguments);
}
/**
* 注册一次性监听,触发了就移除。可以注册多个。通过emit触发。
* @param event
* @param listener
* @param ctx
*/
static once(event:string, listener:Function, ctx?:any):any {
return this.prototype.once.apply(this, arguments);
}
/**
* 通过优先级进行一次性事件监听注册。通过emit触发。
* @param event
* @param priority
* @param listener
* @param ctx
*/
static oncePriority(event:string, priority:number, listener:Function, ctx?:any):any {
return this.prototype.oncePriority.apply(this, arguments);
}
/**
* 注册一次性监听,触发了就移除。可以注册多个。通过emit触发。
* @param event
* @param listener
* @param ctx
*/
static onceAsync(event:string, listener:Function, ctx?:any):any {
return this.prototype.onceAsync.apply(this, arguments);
}
/**
* 注册一次性监听,触发了就移除。可以注册多个。通过emit触发。
* @param event
* @param listener
* @param ctx
*/
static onceAsyncPriority(event:string, priority:number, listener:Function, ctx?:any):any {
return this.prototype.onceAsyncPriority.apply(this, arguments);
}
/**
* 注册一次性监听,触发了就移除。可以注册多个。通过emitNextTick触发。
* @param event
* @param listener
* @param ctx
*/
static onceNextTick(event:string, listener:Function, ctx?:any):any {
return this.prototype.onceNextTick.apply(this, arguments);
}
/**
* 通过优先级注册一次性监听,触发了就移除。可以注册多个。通过emitNextTick触发。
* @param event
* @param listener
* @param ctx
*/
static oncePriorityNextTick(event:string, priority:number, listener:Function, ctx?:any):any {
return this.prototype.oncePriorityNextTick.apply(this, arguments);
}
/**
* 注册单个监听,每次都被最新注册的替换。通过emit触发。
* @param event
* @param listener
* @param ctx
*/
static single(event:string, listener:Function, ctx?:any):any {
return this.prototype.single.apply(this, arguments);
}
/**
* 注册单个监听,每次都被最新注册的替换。通过emit触发。
* @param event
* @param listener
* @param ctx
*/
static singleAsync(event:string, listener:Function, ctx?:any):any {
return this.prototype.singleAsync.apply(this, arguments);
}
/**
* 注册单个监听,每次都被最新注册的替换。通过emitNextTick触发。
* @param event
* @param listener
* @param ctx
*/
static singleNextTick(event:string, listener:Function, ctx?:any):any {
return this.prototype.singleNextTick.apply(this, arguments);
}
/**
* 移除事件监听。
* @param event
* @param listener
* @param ctx
*/
static un(event:string, listener:Function, ctx?:any):any {
return this.prototype.un.apply(this, arguments);
}
/**
* 移除下一帧类型的事件监听。
* @param event
* @param listener
* @param ctx
*/
static unNextTick(event:string, listener:Function, ctx?:any):any {
return this.prototype.unNextTick.apply(this, arguments);
}
/**
* 移除一次性的事件监听。
* @param event
* @param listener
* @param ctx
*/
static unOnce(event:string, listener:Function, ctx?:any):any {
return this.prototype.unOnce.apply(this, arguments);
}
/**
* 移除下一帧执行的一次性的监听。
* @param event
* @param listener
* @param ctx
*/
static unOnceNextTick(event:string, listener:Function, ctx?:any):any {
return this.prototype.unOnceNextTick.apply(this, arguments);
}
/**
* 移除单个类型的事件监听。
* @param event
*/
static unSingle(event:string):any {
return this.prototype.unSingle.apply(this, arguments);
}
/**
* 移除单个类型的并且是下一帧执行类型的事件监听。
* @param event
*/
static unSingleNextTick(event:string):any {
return this.prototype.unSingleNextTick.apply(this, arguments);
}
/**
* 移除所有立即执行类型的事件监听。
* 如果arguments.length == 0 那么就表示移除所有监听。
* 如果arguments.length == 1 那么就表示移除指定类型的所有监听。
* @param event
*/
static unAll(event?:string):any {
return this.prototype.unAll.apply(this, arguments);
}
/**
* 移除所有下一帧执行类型的事件监听。
* 如果arguments.length == 0 那么就表示移除所有监听。
* 如果arguments.length == 1 那么就表示移除指定类型的所有监听。
* @param event
*/
static unAllNextTick(event?:string):any {
return this.prototype.unAllNextTick.apply(this, arguments);
}
/**
* 格式化出before类型的event值。
* @param event
* @returns {string}
*/
static formatBeforeEvent(event:string):string {
return event + '.before';
}
/**
* 格式化出after类型的event值。
* @param event
* @returns {string}
*/
static formatAfterEvent(event:string):string {
return event + '.after';
}
}
// 为下一帧事件进行分发
var _emit4NextTick = function () {
_tempEmittersNextTick.length = 0;
if (_emittersNextTick.length > 0) {
//进行模板获取
for (var i = 0, l_i = _emittersNextTick.length; i < l_i; i++) {
var emitter = _emittersNextTick[i];
var store = emitter._store;
var valuePool = store.valuePool;
var map = valuePool[_OWNER_ON_NT];
for (var event in map) {
_tempEmitters.push(emitter);
_tempEventArr.push(event);
_tempArgsArr.push(map[event]);
delete map[event];//当前帧已经可以清除了
}
}
_emittersNextTick.length = 0;
for (var i = 0, l_i = _tempEmitters.length; i < l_i; i++) {
var emitter = _tempEmitters[i];
var event = _tempEventArr[i];
var args = _tempArgsArr[i];
var single, tempArr;
//先执行单个的
single = store.getSingle(_OWNER_ON_NT, event);
emitter._emitByListenerInfoArr(_OWNER_ON_NT, event, single, args);
//再执行一次性的
tempArr = store.getTempArr(_OWNER_ONCE_NT, event);
store.clear(_OWNER_ONCE_NT, event);//进行清除
emitter._emitByListenerInfoArr(_OWNER_ONCE_NT, event, tempArr, args);
//最后执行多次的
tempArr = store.getTempArr(_OWNER_ON_NT, event);
emitter._emitByListenerInfoArr(_OWNER_ON_NT, event, tempArr, args);
//类级别的注册
store = emitter.__c._store;
//先执行单个的
single = store.getSingle(_OWNER_ON_NT, event);
emitter._emitByListenerInfoArr(_OWNER_ON_NT, event, single, args);
//再执行一次性的
tempArr = store.getTempArr(_OWNER_ONCE_NT, event);
store.clear(_OWNER_ONCE_NT, event);//进行清除
emitter._emitByListenerInfoArr(_OWNER_ONCE_NT, event, tempArr, args);
//最后执行多次的
tempArr = store.getTempArr(_OWNER_ON_NT, event);
emitter._emitByListenerInfoArr(_OWNER_ON_NT, event, tempArr, args);
}
_tempEmitters.length = 0;
_tempEventArr.length = 0;
_tempArgsArr.length = 0;
}
};
export class Engine extends Emitter {
/** 循环事件,外部不要轻易使用,而是通过tt.tick进行注册 */
static __TICK:string = '__tick';
/** 下一帧执行事件,外部不要轻易使用,而是通过tt.nextTick进行注册 */
static __NEXT_TICK:string = '__nextTick';
/** 计算裁剪相关 */
static __CAL_CLIP:string = '__calClip';
/** 区域擦除事件,外部不要轻易使用 */
static __CLEAR_RECT:string = '__clearRect';
/** 绘制之后的循环,外部不要轻易使用,而是通过tt.nextTick进行注册 */
static __TICK_AFTER_DRAW:string = '__tickAfterDraw';
/** 处理点击事件 */
static __HANDLE_TOUCH:string = '_handleTouch';
/** 绘制帧率 */
static __DRAW_FPS:string = '__drawFPS';
/** 初始化引擎,外部不要轻易使用 */
static __INIT_CTX:string = '__initCtx';
/** 配置文件初始化后监听 */
static AFTER_CFG:string = 'afterCfg';
/** 引擎初始化后监听 */
static AFTER_CTX:string = 'afterCtx';
/** 启动后监听 */
static AFTER_BOOT:string = 'afterBoot';
/** 开始时间戳 */
_startTime:number;
/** 上一次时间戳 */
_time:number;
/** requestAnimationFrameId */
_reqAniFrameId:number;
/** 主循环是否已经执行 */
_isMainLooping:boolean;
/** canvas对象 */
_canvas:any;
/** canvas对应的context,注意这个不一定是最终的renderContext,因为引擎中还可能会根据具体需求定义renderContext */
canvasCtx:IRenderingContext2D;
/** 判断引擎是否已经初始化完毕 */
isCtxInited:boolean;
/** 矩阵计算队列 */
_matrixQueue:any[];
/** 裁剪计算队列 */
_clipQueue:any[];
/** 渲染命令队列 */
_renderQueue:any[];
/** 舞台,由具体实现传递 */
stage:any;
design:any;
__fpsInfo:any;
//@override
_initProp():void{
super._initProp();
var self = this;
self._matrixQueue = [];
self._clipQueue = [];
self._renderQueue = [];
self.design = {width:0, height:0};
self.__fpsInfo = {
// 次数
count : 0,
frameTime : 0,
fps : 60,
draw : 0,
drawCount : 0,
transCostCount : 0,
matrixCostCount : 0,
clipCostCount : 0,
renderCostCount : 0,
touchCostCount : 0,
transCost : 0,
matrixCost : 0,
clipCost : 0,
renderCost : 0,
touchCost : 0
};
}
//执行主循环
run(){
var self = this, clazz = self.__c;
//设置开始时间
self._startTime = Date.now();
self._time = 0;
self._isMainLooping = false;
var _mainLoop = function () {
var fpsInfo = self.__fpsInfo;
// nextTick相关事件的分发
if(self._isMainLooping) _emit4NextTick();
self._isMainLooping = true;
var curTime = Date.now() - self._startTime;
var deltaTime = curTime - self._time;
// 主循环tick传时间差
self.emit(clazz.__TICK, deltaTime);
// 如果舞台已经初始化好了,就可以开始进行转化了
var d1 = Date.now();
if(self.stage) self.stage._trans(self);
var d2 = Date.now();
var matrixQueue = self._matrixQueue;
while(matrixQueue.length > 0){
var calFunc = matrixQueue.shift();//命令方法
var calFuncCtx = matrixQueue.shift();//命令上下文
calFunc.call(calFuncCtx, engine);
}
var d3 = Date.now();
self.emit(clazz.__CAL_CLIP, self._clipQueue);
var d4 = Date.now();
// 进行上下文绘制区域擦除
var ctx = self.canvasCtx;
if(ctx){
self.emit(clazz.__CLEAR_RECT, ctx);
// 进行主渲染
var queue = self._renderQueue;
while(queue.length > 0){
var cmd = queue.shift();//命令方法
var cmdCtx = queue.shift();//命令上下文
if(cmd) cmd.call(cmdCtx, ctx, self);
}
// 主循环tick传时间差
self.emit(clazz.__TICK_AFTER_DRAW, deltaTime);
}
var d5 = Date.now();
// 点击处理放在绘制完之后,这样可以使得坐标转换使用_trans之后获得的矩阵,可以提高性能
self.emit(clazz.__HANDLE_TOUCH, deltaTime);
var d6 = Date.now();
// 进行下一帧分发
self.emitNextTick(clazz.__NEXT_TICK);
if(ctx){
fpsInfo.count++;
fpsInfo.frameTime += deltaTime;
fpsInfo.transCostCount += d2 - d1;
fpsInfo.matrixCostCount += d3 - d2;
fpsInfo.clipCostCount += d4 - d3;
fpsInfo.renderCostCount += d5 - d4;
fpsInfo.touchCostCount += d6 - d5;
var count = fpsInfo.count;
if(count == 60){
fpsInfo.fps = Math.round(count*1000/fpsInfo.frameTime);
fpsInfo.draw = Math.round(fpsInfo.drawCount/count);
fpsInfo.transCost = Math.round(fpsInfo.transCostCount/count);
fpsInfo.matrixCost = Math.round(fpsInfo.matrixCostCount/count);
fpsInfo.clipCost = Math.round(fpsInfo.clipCostCount/count);
fpsInfo.renderCost = Math.round(fpsInfo.renderCostCount/count);
fpsInfo.touchCost = Math.round(fpsInfo.touchCostCount/count);
fpsInfo.count = 0;
fpsInfo.frameTime = 0;
fpsInfo.drawCount = 0;
fpsInfo.transCostCount = 0;
fpsInfo.matrixCostCount = 0;
fpsInfo.clipCostCount = 0;
fpsInfo.renderCostCount = 0;
fpsInfo.touchCostCount = 0;
}
self.emit(clazz.__DRAW_FPS, ctx, fpsInfo);
}
self._reqAniFrameId = requestAnimationFrame(_mainLoop);
self._time = curTime;
};
_mainLoop();
}
/**
* 初始化canvas
* @private
*/
_initCanvas(){
var self = this;
var canvasId = project.canvas;
var canvas:any = self._canvas = canvasId ? document.getElementById(canvasId) : document.getElementsByTagName('canvas')[0];
var design = self.design;
var w = design.width = project.design.width;
var h = design.height = project.design.height;
if(!canvas) throw '请添加canvas元素!';
canvas.width = w;
canvas.height = h;
self.canvasCtx = canvas.getContext('2d');
}
}
// 引擎主循环tick的触发器,内部使用
export var engine:Engine = new Engine();
export function tick(listener:Function, ctx?:any) {
engine.on(Engine.__TICK, listener, ctx);
}
export function unTick(listener:Function, ctx?:any) {
engine.un(Engine.__TICK, listener, ctx);
}
export function nextTick(listener:Function, ctx?:any) {
engine.onceNextTick(Engine.__NEXT_TICK, listener, ctx);
}
export function unNextTick(listener:Function, ctx?:any) {
engine.unOnceNextTick(Engine.__NEXT_TICK, listener, ctx);
}
// js加载完之后处理
var _onAfterJs = function(cb){
// 启动主循环,但事实上,绘制的主循环还没被注册进去
engine.run();
// 加载完js之后,首先先加载配置文件,这样才能保证引擎相关初始化能够直接通过配置文件读取
project.load(function(){
if(!(<any>hh).isNative){//如果是h5版本,则进行title的设置
var titleEle = document.getElementsByTagName('title')[0];
if(titleEle){
titleEle.innerHTML = hh.project.appName;
}else{
titleEle = document.createElement('title');
titleEle.innerHTML = hh.project.appName;
document.getElementsByTagName('head')[0].appendChild(titleEle);
}
}
// 进行日志初始化
logger.initByConfig(project);
// 分发配置文件加载后监听
engine.emit(Engine.AFTER_CFG);
// 分发异步方式的配置文件加载后监听
engine.emitAsync(Engine.AFTER_CFG, function(){
//初始化canvas相关
engine._initCanvas();
// 分发引擎初始化监听,此时进行引擎的初始化操作
engine.emit(Engine.__INIT_CTX);
// 分发引擎初始化后监听
engine.emit(Engine.AFTER_CTX);
// 分发异步方式的引擎初始化后监听
engine.emitAsync(Engine.AFTER_CTX, function(){
// 分发启动后监听
engine.emit(Engine.AFTER_BOOT);
// 分发异步方式的启动后监听
engine.emitAsync(Engine.AFTER_BOOT, function(){
if(cb) cb();
}, null);
}, null);
}, null);
});
};
export function boot(modules:string[], cb?:Function){
if((<any>hh).MainContext){// TODO 这时候证明是打包模式
_onAfterJs(cb);
}else{
var asyncPool = new AsyncPool(modules, 0, function(item, index, cb1){
hh.net.loadJson(item + '/__module.json', cb1);
}, cb);
asyncPool.onEnd(function(err, moduleJsons){
var list = [];
for (var i = 0, l_i = modules.length; i < l_i; i++) {
var moduleDir = modules[i];
var moduleInfo = moduleJsons[i];
var source = moduleInfo['source'] || '';
if(moduleDir != '' && moduleDir.substring(moduleDir.length - 1) != '/') moduleDir += '/';
if(source != '' && source.substring(source.length - 1) != '/') source += '/';
var file_list = moduleInfo['file_list'];
for (var j = 0, l_j = file_list.length; j < l_j; j++) {
list.push(moduleDir + source + file_list[j]);
}
}
hh.net.loadJs(list, function(){
//接下来加载配置文件
logger.log('js文件加载成功!');
_onAfterJs(cb);
});
}, null);
asyncPool.flow();
}
}
}<file_sep>/**
* Created by Administrator on 2015/6/28.
*/
///<reference path="../ref.ts" />
module sty.resHelper{
export function getItemUrl(resId:number):string{
return 'res/item/11001.png';// TODO
}
export function getS9gUrl(resId:number):string{
return 'res/s9g/00001.png';// TODO
}
export function loadImage(url:string, cb:Function, ctx?:any){
var img = new Image(); // Create new img element
img.addEventListener("load", function() {
cb.call(ctx, null, img);
}, false);
img.src = url; // Set source path
}
export function loadImages(urls:string[], cb:Function, ctx?:any){
var asyncPool = new hh.AsyncPool(urls, 0, function(url, index, cb1){
loadImage(url, cb1);
}, cb, ctx);
asyncPool.flow();
}
}<file_sep>/**
* Created by SmallAiTT on 2015/6/29.
*/
///<reference path="NodeOpt.ts" />
///<reference path="../touch/Touch.ts" />
module hh{
export class Node extends Emitter{
static debug:boolean = true;
/**
* 矩形裁剪
* @param ctx
* @param engine
* @param target
* @constructor
*/
static CLIP_RECT:Function = function(ctx:IRenderingContext2D, engine:Engine, target:Node){
var width = target.width, height = target.height;
ctx.moveTo(0, 0);
ctx.lineTo(width, 0);
ctx.lineTo(width, height);
ctx.lineTo(0, height);
ctx.closePath();
};
static CLIP_ARC:Function = function(ctx:IRenderingContext2D, engine:Engine, target:Node){
var width = target.width, height = target.height;
var max = Math.max(width, height);
var min = Math.min(width, height);
ctx.arc(width/2, height/2, max/2, 0, Math.PI*2);
};
_nodeOpt:NodeOpt;
static Touch:any = Touch;
touch:Touch;
//@override
_initProp(){
super._initProp();
var self = this, clazz = self.__c;
self._nodeOpt = new NodeOpt(clazz);
self.touch = new clazz.Touch();
self.touch.target = self;
}
_dtor(){
super._dtor();
var self = this;
self._nodeOpt.dtor();
self.touch.dtor();
// 解除绑定
self.touch = null;
}
/**
* name
*/
_setName(name:string){
this._nodeOpt.name = name;
}
public set name(name:string){
this._setName(name);
}
public get name():string{
return this._nodeOpt.name;
}
/**
* 宽度
*/
_setWidth(width:number){
this._nodeOpt.width = width;
}
public set width(width:number){
this._setWidth(width);
}
public get width():number{
return this._nodeOpt.width;
}
/**
* 高度
*/
_setHeight(height:number){
this._nodeOpt.height = height;
}
public set height(height:number){
this._setHeight(height);
}
public get height():number{
return this._nodeOpt.height;
}
/**
* x轴位置
*/
_setX(x:number){
this._nodeOpt.x = x;
}
public set x(x:number){
this._setX(x);
}
public get x():number{
return this._nodeOpt.x;
}
/**
* y轴位置
*/
_setY(y:number){
this._nodeOpt.y = y;
}
public set y(y:number){
this._setY(y);
}
public get y():number{
return this._nodeOpt.y;
}
/**
* X轴缩放
*/
_setScaleX(scaleX:number){
this._nodeOpt.scaleX = scaleX;
}
public set scaleX(scaleX:number){
this._setScaleX(scaleX);
}
public get scaleX():number{
return this._nodeOpt.scaleX;
}
/**
* y轴缩放
*/
_setScaleY(scaleY:number){
this._nodeOpt.scaleY = scaleY;
}
public set scaleY(scaleY:number){
this._setScaleY(scaleY);
}
public get scaleY():number{
return this._nodeOpt.scaleY;
}
/**
* x轴锚点
*/
_setAnchorX(anchorX:number){
this._nodeOpt.anchorX = anchorX;
}
public set anchorX(anchorX:number){
this._setAnchorX(anchorX);
}
public get anchorX():number{
return this._nodeOpt.anchorX;
}
/**
* y轴锚点
*/
_setAnchorY(anchorY:number){
this._nodeOpt.anchorY = anchorY;
}
public set anchorY(anchorY:number){
this._setAnchorY(anchorY);
}
public get anchorY():number{
return this._nodeOpt.anchorY;
}
/**
* 旋转
*/
_setRotation(rotation:number){
this._nodeOpt.rotation = rotation;
}
public set rotation(rotation:number){
this._setRotation(rotation);
}
public get rotation():number{
return this._nodeOpt.rotation;
}
/**
* zIndex
*/
_setZIndex(zIndex:number){
this._nodeOpt.zIndex = zIndex;
}
public set zIndex(zIndex:number){
this._setZIndex(zIndex);
}
public get zIndex():number{
return this._nodeOpt.zIndex;
}
/**
* 是否可见。
*/
_setVisible(visible:boolean){
this._nodeOpt.visible = visible;
}
public set visible(visible:boolean){
this._setVisible(visible);
}
public get visible():boolean{
return this._nodeOpt.visible;
}
/**
* 添加子节点。
* @param child
* @returns {hh.Node}
*/
public addChild(child:Node):Node{
var self = this, children = self._nodeOpt.children;
// TODO 需要根据zIndex进行排序
if(children.indexOf(child) < 0){
var cNodeOpt = child._nodeOpt;
// 如果已经在别的节点上了,就先进行移除
if(cNodeOpt.parent) cNodeOpt.parent.rmChild(child);
children.push(child);
cNodeOpt.parent = self;
}
return self;
}
/**
* 移除子节点。
* @param child
* @returns {hh.Node}
*/
public rmChild(child:Node):Node{
var self = this, children = self._nodeOpt.children;
var index = children.indexOf(child);
if(index >= 0) {
children.splice(index, 1);
child._nodeOpt.parent = null;
}
return self;
}
public rmChildren():Node{
var self = this, children = self._nodeOpt.children;
var l = children.length;
while(l > 0){
var child = children.pop();
// 解除父亲绑定
child._nodeOpt.parent = null;
l--;
}
return self;
}
/**
* 移除自身。
* @returns {hh.Node}
*/
public rm():Node{
var self = this, parent = self._nodeOpt.parent;
if(parent) parent.rmChild(self);
return self;
}
/**
* 获取所有子节点。获取到的是另一个children数组,避免外部使用导致污染。
* @returns {Node[]}
*/
public get children():Node[]{
var arr:Node[] = [], children = this._nodeOpt.children;
for (var i = 0, l_i = children.length; i < l_i; i++) {
arr.push(children[i]);
}
return arr;
}
/**
* 布局处理器。
*/
_setLayout(layout:Layout){
this._nodeOpt.layout = layout;
}
public set layout(layout:Layout){
this._setLayout(layout);
}
public get layout():Layout{
return this._nodeOpt.layout;
}
/**
* 裁剪器
* @param clip
* @private
*/
_setClip(clip:Function){
this._nodeOpt.clip = clip;
}
public set clip(clip:Function){
this._setClip(clip);
}
public get clip():Function{
return this._nodeOpt.clip;
}
_doClip(ctx:IRenderingContext2D, engine:Engine){
ctx.save();
ctx.beginPath();
this._nodeOpt.clip(ctx, engine, this);
ctx.clip();
}
_restoreClip(ctx:IRenderingContext2D, engine:Engine){
ctx.restore();
}
/**
* 转换节点。
*/
_trans(engine:Engine){
var self = this, clazz = self.__c, nodeOpt = self._nodeOpt;
var children = nodeOpt.children;
var renderQueue = engine._renderQueue;
nodeOpt.renderQueueRange[0] = renderQueue.length;
if(nodeOpt.drawable) renderQueue.push(self._draw, self);
if(clazz.debug) renderQueue.push(self._drawDebug, self);
if(nodeOpt.clip) {
// 如果当前节点可裁剪,则推送到裁剪计算队列中
engine._clipQueue.push(self);
renderQueue.push(self._doClip, self);
}
nodeOpt.renderQueueRange[1] = renderQueue.length;
// 如果有设置布局,则进行布局处理
var layout = nodeOpt.layout;
if(layout) {
// 清空
layout.onBefore(self);
layout.handle(self);
}
// 进行世界转化,需要推送到渲染队列中,延迟到绘制前进行计算
// 今后还会做dirty的判断,这样就可以更好的提高性能
engine._matrixQueue.push(self._calMatrix, self);
//遍历子节点
for (var i = 0, l_i = children.length; i < l_i; i++) {
var child = children[i];
// 可见才可以继续进行转化
if(child._nodeOpt.visible) child._trans(engine);
}
if(layout){
layout.onAfter(self);
}
nodeOpt.renderQueueRange[2] = renderQueue.length;
if(nodeOpt.clip) renderQueue.push(self._restoreClip, self);
nodeOpt.renderQueueRange[3] = renderQueue.length;
}
/**
* 绘制节点
* @param ctx
* @private
*/
_draw(ctx:IRenderingContext2D, engine:Engine){
var self = this, nodeOpt = self._nodeOpt;
// 设置转化
var matrix = nodeOpt.matrix;
ctx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty);
// 开始渲染节点
self._render(ctx, engine);
}
/**
* 渲染节点。
* @param ctx
* @private
*/
_render(ctx:IRenderingContext2D, engine:Engine){
// 子类在此实现真正的绘制
}
_drawDebug(ctx:IRenderingContext2D, engine:Engine){
// 进行debug模式绘制
var self = this, nodeOpt = self._nodeOpt;
// 设置转化
var matrix = nodeOpt.matrix;
ctx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty);
var width = nodeOpt.width, height = nodeOpt.height;
ctx.save();
if(nodeOpt.debugRectColor) {
ctx.fillStyle = nodeOpt.debugRectColor;
ctx.fillRect(0, 0, width, height);
}
ctx.strokeStyle = 'red';
ctx.fillStyle = 'red';
ctx.strokeRect(0, 0, width, height);
var ps = 10;
ctx.fillRect(width*nodeOpt.anchorX - ps/2, height*nodeOpt.anchorY - ps/2, ps, ps);
ctx.restore();
}
/**
* 计算世界转化
* @private
*/
_calMatrix(){
var self = this;
var nodeOpt = self._nodeOpt, parent = nodeOpt.parent;
var matrix = nodeOpt.matrix;
if(parent) {
var pNodeOpt = parent._nodeOpt;
var pm = pNodeOpt.matrix;
matrix.identityMatrix(pm);
nodeOpt.worldAlpha = pNodeOpt.worldAlpha * nodeOpt.alpha;
}
var offsetX = nodeOpt.width*nodeOpt.anchorX;
var offsetY = nodeOpt.height*nodeOpt.anchorY;
var hackMatrix = (<any>self).__hack_local_matrix;// TODO
if (hackMatrix) {
matrix.append(hackMatrix.a, hackMatrix.b, hackMatrix.c, hackMatrix.d, hackMatrix.tx, hackMatrix.ty);
matrix.append(1, 0, 0, 1, -offsetX, -offsetY);
}
else {
matrix.appendTransform(nodeOpt.x, nodeOpt.y, nodeOpt.scaleX, nodeOpt.scaleY, nodeOpt.rotation,
nodeOpt.skewX, nodeOpt.skewY, offsetX, offsetY);
}
//var scrollRect = do_props._scrollRect;
//if (scrollRect) {
// worldTransform.append(1, 0, 0, 1, -scrollRect.x, -scrollRect.y);
//}
// if (this._texture_to_render){
// var bounds:egret.Rectangle = DisplayObject.getTransformBounds(o._getSize(Rectangle.identity), o._worldTransform);
// o._worldBounds.initialize(bounds.x, bounds.y, bounds.width, bounds.height);
// }
}
}
}<file_sep>/**
* Created by SmallAiTT on 2015/6/26.
*/
///<reference path="../ref.ts" />
///<reference path="STYResHelper.ts" />
module sty{
export var moduleName_graphics = 'Graphics学习';
export var moduleName_text = 'Text学习';
export var moduleName_image = 'Image学习';
export var moduleName_transformations = 'Transformations学习';
export var moduleName_composite = 'Compositing学习';
export var moduleName_clip = 'Clipping学习';
export var moduleName_imageData = 'ImageData学习';
export var moduleName_aria = 'ARIA学习';
}<file_sep>/**
* Created by SmallAiTT on 2015/6/30.
*/
///<reference path="../../hh.ts" />
///<reference path="../base/__module.ts" /><file_sep>/**
* Created by SmallAiTT on 2015/6/30.
*/
module hh{
export class Class{
/** 类名 */
static __n:string;
static __recycler:any[] = [];
static push(obj:any){
this.__recycler.push(obj);
}
static pop(...args):any{
var clazz = this;
var obj = clazz.__recycler.pop();
if(obj) return obj;
else clazz.create.apply(clazz, args);
}
/** 创建 */
static create(...args:any[]):any {
var Class:any = this;
var obj:any = new Class();
if (obj.init) obj.init.apply(obj, arguments);
return obj;
}
/** 获取单例 */
static getInstance(...args:any[]) {
var Class:any = this;
if (!Class._instance) {
var instance:any = Class._instance = Class.create.apply(Class, arguments);
instance._isInstance = true;
}
return Class._instance;
}
/** 释放单例 */
static release() {
var Class:any = this;
var instance:any = Class._instance;
if (instance) {
if (instance.doDtor) instance.doDtor();
Class._instance = null;
}
}
/** 类名 */
__n:string;
/** 实例对应的类 */
__c:any;
/** 是否是单例 */
_isInstance:boolean;
/** 储藏室 */
/** 是否已经释放了 */
_hasDtored:boolean;
_initProp():void {
var self = this;
}
constructor() {
var self = this;
self._initProp();
}
public init(...args:any[]) {
}
public dtor() {
var self = this;
if (self._hasDtored) return;
self._hasDtored = true;
self._dtor();
}
_dtor() {
}
}
export class ColorMatrix extends Class{
// constant for contrast calculations:
static DELTA_INDEX:number[] = [
0, 0.01, 0.02, 0.04, 0.05, 0.06, 0.07, 0.08, 0.1, 0.11,
0.12, 0.14, 0.15, 0.16, 0.17, 0.18, 0.20, 0.21, 0.22, 0.24,
0.25, 0.27, 0.28, 0.30, 0.32, 0.34, 0.36, 0.38, 0.40, 0.42,
0.44, 0.46, 0.48, 0.5, 0.53, 0.56, 0.59, 0.62, 0.65, 0.68,
0.71, 0.74, 0.77, 0.80, 0.83, 0.86, 0.89, 0.92, 0.95, 0.98,
1.0, 1.06, 1.12, 1.18, 1.24, 1.30, 1.36, 1.42, 1.48, 1.54,
1.60, 1.66, 1.72, 1.78, 1.84, 1.90, 1.96, 2.0, 2.12, 2.25,
2.37, 2.50, 2.62, 2.75, 2.87, 3.0, 3.2, 3.4, 3.6, 3.8,
4.0, 4.3, 4.7, 4.9, 5.0, 5.5, 6.0, 6.5, 6.8, 7.0,
7.3, 7.5, 7.8, 8.0, 8.4, 8.7, 9.0, 9.4, 9.6, 9.8,
10.0
];
// identity matrix constant:
static IDENTITY_MATRIX:number[] = [
1,0,0,0,0,
0,1,0,0,0,
0,0,1,0,0,
0,0,0,1,0,
0,0,0,0,1
];
static LENGTH:number = ColorMatrix.IDENTITY_MATRIX.length;
length:number;
// initialization:
constructor(p_matrix?:any) {
super();
var self = this, clazz = self.__c;
p_matrix = self.fixMatrix(p_matrix);
self.copyMatrix(((p_matrix.length == clazz.LENGTH) ? p_matrix : clazz.IDENTITY_MATRIX));
self.length = clazz.LENGTH;
}
reset():void {
var self = this, clazz = self.__c;
for (var i:number=0; i<clazz.LENGTH; i++) {
this[i] = clazz.IDENTITY_MATRIX[i];
}
}
adjustColor(p_brightness:number,p_contrast:number,p_saturation:number,p_hue:number):void {
var self = this, clazz = self.__c;
self.adjustHue(p_hue);
self.adjustContrast(p_contrast);
self.adjustBrightness(p_brightness);
self.adjustSaturation(p_saturation);
}
adjustBrightness(p_val:number):void {
var self = this, clazz = self.__c;
p_val = self.cleanValue(p_val,100);
if (p_val == 0 || isNaN(p_val)) { return; }
self.multiplyMatrix([
1,0,0,0,p_val,
0,1,0,0,p_val,
0,0,1,0,p_val,
0,0,0,1,0,
0,0,0,0,1
]);
}
adjustContrast(p_val:number):void {
var self = this, clazz = self.__c;
p_val = self.cleanValue(p_val,100);
if (p_val == 0 || isNaN(p_val)) { return; }
var x:number;
if (p_val<0) {
x = 127+p_val/100*127
} else {
x = p_val%1;
if (x == 0) {
x = clazz.DELTA_INDEX[p_val];
} else {
//x = clazz.DELTA_INDEX[(p_val<<0)]; // this is how the IDE does it.
x = clazz.DELTA_INDEX[(p_val<<0)]*(1-x)+clazz.DELTA_INDEX[(p_val<<0)+1]*x; // use linear interpolation for more granularity.
}
x = x*127+127;
}
self.multiplyMatrix([
x/127,0,0,0,0.5*(127-x),
0,x/127,0,0,0.5*(127-x),
0,0,x/127,0,0.5*(127-x),
0,0,0,1,0,
0,0,0,0,1
]);
}
adjustSaturation(p_val:number):void {
var self = this, clazz = self.__c;
p_val = self.cleanValue(p_val,100);
if (p_val == 0 || isNaN(p_val)) { return; }
var x:number = 1+((p_val > 0) ? 3*p_val/100 : p_val/100);
var lumR:number = 0.3086;
var lumG:number = 0.6094;
var lumB:number = 0.0820;
self.multiplyMatrix([
lumR*(1-x)+x,lumG*(1-x),lumB*(1-x),0,0,
lumR*(1-x),lumG*(1-x)+x,lumB*(1-x),0,0,
lumR*(1-x),lumG*(1-x),lumB*(1-x)+x,0,0,
0,0,0,1,0,
0,0,0,0,1
]);
}
adjustHue(p_val:number):void {
var self = this, clazz = self.__c;
p_val = self.cleanValue(p_val,180)/180*Math.PI;
if (p_val == 0 || isNaN(p_val)) { return; }
var cosVal:number = Math.cos(p_val);
var sinVal:number = Math.sin(p_val);
var lumR:number = 0.213;
var lumG:number = 0.715;
var lumB:number = 0.072;
self.multiplyMatrix([
lumR+cosVal*(1-lumR)+sinVal*(-lumR),lumG+cosVal*(-lumG)+sinVal*(-lumG),lumB+cosVal*(-lumB)+sinVal*(1-lumB),0,0,
lumR+cosVal*(-lumR)+sinVal*(0.143),lumG+cosVal*(1-lumG)+sinVal*(0.140),lumB+cosVal*(-lumB)+sinVal*(-0.283),0,0,
lumR+cosVal*(-lumR)+sinVal*(-(1-lumR)),lumG+cosVal*(-lumG)+sinVal*(lumG),lumB+cosVal*(1-lumB)+sinVal*(lumB),0,0,
0,0,0,1,0,
0,0,0,0,1
]);
}
concat(p_matrix:number[]):void {
var self = this, clazz = self.__c;
p_matrix = self.fixMatrix(p_matrix);
if (p_matrix.length != clazz.LENGTH) { return; }
self.multiplyMatrix(p_matrix);
}
clone():ColorMatrix {
return new ColorMatrix(this);
}
toString():string {
return "ColorMatrix [ "+Array.prototype.join.call(this, " , ")+" ]";
}
toArray():number[] {
return Array.prototype.slice.call(this, 0,20);
}
// copy the specified matrix's values to this matrix:
copyMatrix(p_matrix:number[]):void {
var self = this, clazz = self.__c;
var l:number = clazz.LENGTH;
for (var i:number=0;i<l;i++) {
this[i] = p_matrix[i];
}
}
// multiplies one matrix against another:
multiplyMatrix(p_matrix:number[]):void {
var self = this, clazz = self.__c;
var col:number[] = [];
for (var i:number=0;i<5;i++) {
for (var j:number=0;j<5;j++) {
col[j] = this[j+i*5];
}
for (j=0;j<5;j++) {
var val:number=0;
for (var k:number=0;k<5;k++) {
val += p_matrix[j+k*5]*col[k];
}
this[j+i*5] = val;
}
}
}
// make sure values are within the specified range, hue has a limit of 180,
cleanValue(p_val:number,p_limit:number):number {
var self = this, clazz = self.__c;
return Math.min(p_limit,Math.max(-p_limit,p_val));
}
// makes sure matrixes are 5x5 (25 long):
fixMatrix(p_matrix:number[]=null):number[] {
var self = this, clazz = self.__c;
if (p_matrix == null) { return clazz.IDENTITY_MATRIX; }
if (p_matrix instanceof ColorMatrix) { p_matrix = p_matrix.slice(0); }
if (p_matrix.length < clazz.LENGTH) {
p_matrix = p_matrix.slice(0,p_matrix.length).concat(clazz.IDENTITY_MATRIX.slice(p_matrix.length,clazz.LENGTH));
} else if (p_matrix.length > clazz.LENGTH) {
p_matrix = p_matrix.slice(0,clazz.LENGTH);
}
return p_matrix;
}
}
var ctx:any;
var img:any;
var _getCtx = function(){
var canvas:any = document.getElementsByTagName('canvas')[0];
if(!canvas) throw '请添加canvas元素!';
canvas.width = 960;
canvas.height = 640;
ctx = canvas.getContext('2d');
};
var _draw = function(){
img = document.createElement('img');
img.onload = function(){
ctx.drawImage(img, 0, 0);
};
var imgUrl = _urlParam.url || '11001.png';
img.src = 'res/' + imgUrl;
};
var _urlParam:any = {};
var _parseParam = function(){
var src = window.location.href;
var index = src.indexOf('?');
if(index > 0){
var str = src.substring(index + 1);
var arr = str.split('&');
for (var i = 0, l_i = arr.length; i < l_i; i++) {
var paramStr = arr[i];
var param = paramStr.split('=');
var pKey = param[0], pValue:any = param[1];
if(pValue.match(/(^\d+$)/)){
pValue = parseInt(pValue);
}else if(pValue.match(/(^\d+.\d+$)/)){
pValue = parseFloat(pValue);
}
_urlParam[pKey] = pValue;
}
}
};
export function refresh(){
console.log('refresh');
var bcsh = [];
var idArr = ['brightness', 'contrast', 'saturation', 'hub'];
for (var i = 0, l_i = idArr.length; i < l_i; i++) {
var id = idArr[i];
var input = <any>document.getElementById(id);
bcsh.push(parseInt(input.value));
}
if(img){
ctx.clearRect(0, 0, 960, 640);
ctx.drawImage(img, 0, 0);
var colorMatrix:ColorMatrix = new ColorMatrix();
colorMatrix.adjustColor(bcsh[0], bcsh[1], bcsh[2], bcsh[3]);
document.getElementById('result').innerHTML = '[' + colorMatrix.toArray().join(',') + ']';
var imageData = ctx.getImageData(0,0,960, 640);
var data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
var srcR = data[i], srcG = data[i+1], srcB = data[i+2], srcA = data[i+3];
data[i] = (colorMatrix[0] * srcR) + (colorMatrix[1] * srcG) + (colorMatrix[2] * srcB) + (colorMatrix[3] * srcA) + colorMatrix[4];
data[i+1] = (colorMatrix[5] * srcR) + (colorMatrix[6] * srcG) + (colorMatrix[7] * srcB) + (colorMatrix[8] * srcA) + colorMatrix[9];
data[i+2] = (colorMatrix[10] * srcR) + (colorMatrix[11] * srcG) + (colorMatrix[12] * srcB) + (colorMatrix[13] * srcA) + colorMatrix[14];
data[i+3] = (colorMatrix[15] * srcR) + (colorMatrix[16] * srcG) + (colorMatrix[17] * srcB) + (colorMatrix[18] * srcA) + colorMatrix[19];
}
ctx.putImageData(imageData, 0, 0);
}
}
_parseParam();
_getCtx();
_draw();
}<file_sep>/**
* Created by SmallAiTT on 2015/7/1.
*/
///<reference path="Res.ts" />
///<reference path="parser/ImgParser.ts" /><file_sep>/// <reference path="../utils/utils.ts" />
/// <reference path="Node.ts" />
module hh{
export class ColorNode extends hh.Node{
//@override
_initProp(){
super._initProp();
var self = this;
self._color = "red";//设置默认颜色为红色
}
/**
* 颜色
*/
_color:string;
_colorDirty:boolean;
_setColor(color:any){
var self = this;
var c = hh.color(color);
if(c != self._color) self._colorDirty = true;
this._color = color;
}
public set color(color:any){
this._setColor(color);
}
public get color():any{
return this._color;
}
//@override
_draw(renderCtx:CanvasRenderingContext2D){
super._draw(renderCtx);
var self = this, clazz = self.__c;
var transX = self._transX, transY = self._transY;
var transWidth = self._transWidth, transHeight = self._transHeight;
renderCtx.fillStyle = self._color;
renderCtx.fillRect(0, 0, transWidth, transHeight);
}
}
}<file_sep>/**
* Created by Administrator on 2015/6/28.
*/
///<reference path="sty_init.ts" />
module sty{
unit.curModuleName = sty.moduleName_transformations;
unit.addMenuItem4Ctx('save-restore', function(ctx:IRenderingContext2D){
ctx.fillRect(0,0,150,150); // Draw a rectangle with default settings
ctx.save(); // Save the default state
ctx.fillStyle = '#09F'; // Make changes to the settings
ctx.fillRect(15,15,120,120); // Draw a rectangle with new settings
ctx.save(); // Save the current state
ctx.fillStyle = '#FFFFFF'; // Make changes to the settings
ctx.globalAlpha = 0.5;
ctx.fillRect(30,30,90,90); // Draw a rectangle with new settings
ctx.restore(); // Restore previous state
ctx.fillRect(45,45,60,60); // Draw a rectangle with restored settings
ctx.restore(); // Restore original state
ctx.fillRect(60,60,30,30); // Draw a rectangle with restored settings
});
unit.addMenuItem4Ctx('translate', function(ctx:IRenderingContext2D){
for (var i=0;i<3;i++) {
for (var j = 0; j < 3; j++) {
ctx.save();
ctx.fillStyle = 'rgb(' + (51 * i) + ',' + (255 - 51 * i) + ',255)';
ctx.translate(10 + j * 50, 10 + i * 50);
ctx.fillRect(0, 0, 25, 25);
ctx.restore();
}
}
});
unit.addMenuItem4Ctx('rotate', function(ctx:IRenderingContext2D){
// left rectangles, rotate from canvas origin
ctx.save();
// blue rect
ctx.fillStyle = "#0095DD";
ctx.fillRect(30,30, 100, 100);
// 先进行旋转,这样接下来绘制的就自动旋转了。
// 也就是说,旋转其实是对ctx进行旋转。
ctx.rotate((Math.PI/180)*25);
// grey rect
ctx.fillStyle = "#4D4E53";
ctx.fillRect(30,30, 100, 100);
ctx.restore();
// right rectangles, rotate from rectangle center
// draw blue rect
ctx.fillStyle = "#0095DD";
ctx.fillRect(150, 30, 100, 100);
ctx.translate(200, 80); // translate to rectangle center
// x = x + 0.5 * width
// y = y + 0.5 * height
ctx.rotate((Math.PI/180)*25); // rotate
ctx.translate(-200, -80); // translate back
// draw grey rect
ctx.fillStyle = "#4D4E53";
ctx.fillRect(150, 30, 100, 100);
});
unit.addMenuItem4Ctx('scale', function(ctx:IRenderingContext2D){
// draw a simple rectangle, but scale it.
ctx.save();
ctx.scale(10, 3);
ctx.fillRect(1,10,10,10);
ctx.restore();
// mirror horizontally
ctx.scale(-1, 1);
ctx.font = "48px serif";
ctx.fillText("MDN", -135, 120);
});
unit.addMenuItem4Ctx('transform', function(ctx:IRenderingContext2D){
var sin = Math.sin(Math.PI/6);
var cos = Math.cos(Math.PI/6);
/*
translate(e, f)
transform(a, b, c, d, e, f)
setTransform(a, b, c, d, e, f)
resetTransform()
a (m11) Horizontal scaling.
b (m12) Horizontal skewing.
c (m21) Vertical skewing.
d (m22) Vertical scaling.
e (dx) Horizontal moving.
f (dy) Vertical moving.
setTransform(a, b, c, d, e, f)
*/
ctx.translate(100, 100);
var c = 0;
for (var i=0; i <= 12; i++) {
c = Math.floor(255 / 12 * i);
ctx.fillStyle = "rgb(" + c + "," + c + "," + c + ")";
ctx.fillRect(0, 0, 100, 10);
ctx.transform(cos, sin, -sin, cos, 0, 0);
}
ctx.setTransform(-1, 0, 0, 1, 100, 100);
ctx.fillStyle = "rgba(255, 128, 255, 0.5)";
ctx.fillRect(0, 0, 100, 100);
});
unit.addMenuItem4Ctx('transform1', function(ctx:IRenderingContext2D){
var sin = Math.sin(Math.PI/6);
var cos = Math.cos(Math.PI/6);
/*
translate(e, f)
transform(a, b, c, d, e, f)
setTransform(a, b, c, d, e, f)
resetTransform()
a (m11) Horizontal scaling.
b (m12) Horizontal skewing.
c (m21) Vertical skewing.
d (m22) Vertical scaling.
e (dx) Horizontal moving.
f (dy) Vertical moving.
setTransform(a, b, c, d, e, f)
*/
ctx.translate(100, 100);
ctx.beginPath();
ctx.moveTo(0, -100);
ctx.lineTo(0, 500);
ctx.closePath();
ctx.stroke();
ctx.beginPath();
ctx.moveTo(-100, 0);
ctx.lineTo(500, 0);
ctx.closePath();
ctx.stroke();
var x = 100, y = 100;
var width= 100, height = 100;
var anchorX = 0, anchorY = 1;
var anchorOffsetX = width*anchorX, anchorOffsetY = height*anchorY;
var pw = 10;
ctx.translate(x, y);
ctx.scale(2, 2);
ctx.rotate(Math.PI/8);
ctx.translate(-anchorOffsetX, -anchorOffsetY);
ctx.strokeStyle = "red";
ctx.strokeRect(0, 0, width, height);
ctx.strokeStyle = "blue";
ctx.strokeRect(anchorOffsetX-pw/2, anchorOffsetY-pw/2, pw, pw);
});
}<file_sep>/**
* Created by SmallAiTT on 2015/7/3.
*/
///<reference path="../../tc_init.ts" />
module tc{
unit.curModuleName = moduleName_Node;
class Node4Matrix1 extends hh.Node{
//@override
_initProp(){
super._initProp();
var self = this;
self._setWidth(100);
self._setHeight(100);
self._setAnchorX(0);
self._setAnchorY(0);
}
//@override
_calMatrix(){
super._calMatrix();
var matrix:hh.Matrix = this._nodeOpt.matrix;
var w = this.width;
var h = this.height;
var arr = [[0, 0], [0, h], [w, 0], [w, h], [w/2, h/2]];
var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, tx = matrix.tx, ty = matrix.ty;
for (var i = 0, l_i = arr.length; i < l_i; i++) {
var arr2 = arr[i];
var x = arr2[0], y = arr2[1];
var x1 = a*x + c*y + tx;
var y1 = b*x + d*y + ty;
log(i, x1, y1);
}
}
}
unit.addMenuItem('Node4Matrix 测试1', function(){
var node = new Node4Matrix1();
node.x = 100;
node.y = 100;
hh.engine.stage.addChild(node);
});
unit.addMenuItem('Node4Matrix 测试2', function(){
var node = new Node4Matrix1();
node.x = 100;
node.y = 100;
node.anchorX = node.anchorY = 0.5;
hh.engine.stage.addChild(node);
});
unit.addMenuItem('Node4Matrix 测试3', function(){
var node = new Node4Matrix1();
node.x = 100;
node.y = 100;
node.anchorX = node.anchorY = 0.5;
node.scaleX = node.scaleY = 0.5;
hh.engine.stage.addChild(node);
});
unit.addMenuItem('Node4Matrix 测试4', function(){
var node = new Node4Matrix1();
node.x = 100;
node.y = 100;
node.anchorX = node.anchorY = 0.5;
node.scaleX = node.scaleY = 0.5;
node.rotation = Math.PI/4;
hh.engine.stage.addChild(node);
});
}<file_sep>/**
* Created by Administrator on 2015/6/28.
*/
///<reference path="sty_init.ts" />
module sty{
unit.curModuleName = moduleName_imageData;
unit.addMenuItem4Ctx('ColorPicker', function(ctx:IRenderingContext2D, param){
var canvas = hh.engine._canvas;
function pick(event) {
var x = event.layerX;
var y = event.layerY;
var pixel = ctx.getImageData(x, y, 1, 1);
var data = pixel.data;
var rgba = 'rgba(' + data[0] + ',' + data[1] +
',' + data[2] + ',' + data[3] + ')';
ctx.clearRect(300, 200, 200, 200);
ctx.fillStyle = rgba;
ctx.fillRect(300, 300, 100, 100);
ctx.fillStyle = 'black';
ctx.fillText(rgba, 300, 300);
}
canvas.addEventListener('mousemove', pick);
param.pick = pick;
resHelper.loadImage(resHelper.getItemUrl(11001), function(err, img){
ctx.drawImage(img, 0, 0);
});
}, function (param) {
var canvas = hh.engine._canvas;
canvas.removeEventListener('mousemove', param.pick);
});
unit.addMenuItem4Ctx('Gray', function(ctx:IRenderingContext2D){
resHelper.loadImage(resHelper.getItemUrl(11001), function(err, img){
var width = img.width, height = img.height;
ctx.drawImage(img, 0, 0);
ctx.drawImage(img, width, 0);
var imageData = ctx.getImageData(0,0,width, height);
var data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
var avg = (data[i] + data[i +1] + data[i +2]) / 3;
data[i] = avg; // red
data[i + 1] = avg; // green
data[i + 2] = avg; // blue
}
ctx.putImageData(imageData, 0, 0);
});
});
unit.addMenuItem4Ctx('Invert', function(ctx:IRenderingContext2D){
resHelper.loadImage(resHelper.getItemUrl(11001), function(err, img){
var width = img.width, height = img.height;
ctx.drawImage(img, 0, 0);
ctx.drawImage(img, width, 0);
var imageData = ctx.getImageData(0,0,width, height);
var data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
data[i] = 255 - data[i]; // red
data[i + 1] = 255 - data[i + 1]; // green
data[i + 2] = 255 - data[i + 2]; // blue
}
ctx.putImageData(imageData, 0, 0);
var grayscale = function() {
for (var i = 0; i < data.length; i += 4) {
var avg = (data[i] + data[i +1] + data[i +2]) / 3;
data[i] = avg; // red
data[i + 1] = avg; // green
data[i + 2] = avg; // blue
}
ctx.putImageData(imageData, 0, 0);
};
});
});
}<file_sep>/**
* Created by SmallAiTT on 2015/6/29.
*/
///<reference path="base/__module.ts" />
///<reference path="texture/Texture.ts" />
///<reference path="texture/Sheet.ts" />
///<reference path="touch/Touch.ts" />
///<reference path="touch/TouchCtx.ts" />
///<reference path="res/__module.ts" />
///<reference path="node/Layout.ts" />
///<reference path="node/NodeOpt.ts" />
///<reference path="node/Node.ts" />
///<reference path="ui/UIImgOpt.ts" />
///<reference path="ui/UIImg.ts" />
///<reference path="ui/UITextOpt.ts" />
///<reference path="ui/UIText.ts" />
///<reference path="ctx_init.ts" /><file_sep>/**
* Created by SmallAiTT on 2015/6/26.
*/
///<reference path="../../hh/hh.ts" />
///<reference path="../../unit/unit.ts" /><file_sep>/**
* Created by SmallAiTT on 2015/7/1.
*/
///<reference path="../../hh/hh.ts" />
///<reference path="../../hh/core/__module.ts" />
module res_helper{
export function getItemUrl(resId:number):string{
return 'item/' + hh.STR.fill(resId, '00000') + '.png';
}
export function getS9gUrl(resId:number):string{
return 's9g/' + hh.STR.fill(resId, '00000') + '.png';
}
}<file_sep>/**
* Created by Administrator on 2015/6/28.
*/
///<reference path="sty_init.ts" />
module sty{
unit.curModuleName = moduleName_clip;
unit.addMenuItem4Ctx('裁剪', function(ctx:IRenderingContext2D){
// 绘制星星
function drawStar(ctx,r){
ctx.save();
ctx.beginPath();
ctx.moveTo(r,0);
for (var i=0;i<9;i++){
ctx.rotate(Math.PI/5);
if(i%2 === 0) {
ctx.lineTo((r/0.525731)*0.200811,0);
} else {
ctx.lineTo(r,0);
}
}
ctx.closePath();
ctx.fill();
ctx.restore();
}
// 先绘制了一个黑色的矩形区域
ctx.fillRect(0,0,150,150);
// 坐标转移到矩形中心位置
ctx.translate(75,75);
// 创建一个圆形的裁剪区,以后绘制的东西只会出现在该区域内
// Create a circular clipping path
ctx.beginPath();
ctx.arc(0,0,60,0,Math.PI*2,true);
ctx.clip();
// 绘制内部蓝色的背景
// draw background
var lingrad = ctx.createLinearGradient(0,-75,0,75);
lingrad.addColorStop(0, '#232256');
lingrad.addColorStop(1, '#143778');
ctx.fillStyle = lingrad;
ctx.fillRect(-75,-75,150,150);
// draw stars
for (var j=1;j<50;j++){
ctx.save();
ctx.fillStyle = '#fff';
ctx.translate(75-Math.floor(Math.random()*150),
75-Math.floor(Math.random()*150));
drawStar(ctx,Math.floor(Math.random()*4)+2);
ctx.restore();
}
});
}<file_sep>///<reference path="Node.ts" />
module hh{
export class Scene extends Node{
}
}<file_sep>///<reference path="../base/mainLoop" />
///<reference path="Node.ts" />
module hh{
export class Root extends Node{
}
export var root:Root, renderCtx:CanvasRenderingContext2D;
export function initRoot(){
var canvas:any = document.getElementById("canvas");
renderCtx = canvas.getContext("2d");
root = new Root();
root.width = canvas.width;
root.height = canvas.height;
mainLoop(function(){
renderCtx.clearRect(0, 0, canvas.width, canvas.height);
root.visit(renderCtx);
});
}
}<file_sep>///<reference path="../node/Node.ts" />
module hh{
export class UIImage extends hh.Node{
/**
* 纹理
*/
_texture:any;
_setTexture(texture:any){
this._texture = texture;
}
public set texture(texture:any){
this._setTexture(texture);
}
public get texture():any{
return this._texture;
}
//@override
_draw(renderCtx:CanvasRenderingContext2D):void{
var self = this;
var texture = self._texture;
if(texture){
renderCtx.drawImage(texture, 0, 0);
}
}
}
}<file_sep>/**
* Created by Administrator on 2015/6/28.
*/
///<reference path="sty_init.ts" />
module sty{
unit.curModuleName = sty.moduleName_text;
unit.addMenuItem4Ctx('普通文本', function(ctx:IRenderingContext2D){
ctx.font = "48px serif";
// text, x, y [, maxWidth]
ctx.fillText("Hello world", 10, 50);
ctx.fillText("Hello world", 10, 100, 100);
});
unit.addMenuItem4Ctx('文本边框——strokeText', function(ctx:IRenderingContext2D){
// A DOMString parsed as CSS font value. The default font is 10px sans-serif.
ctx.font = "48px serif";
// text, x, y [, maxWidth]
ctx.strokeText("Hello world", 10, 50);
ctx.strokeText("Hello world", 10, 100, 100);
});
unit.addMenuItem4Ctx('文本边框——textAlign', function(ctx:IRenderingContext2D){
// A DOMString parsed as CSS font value. The default font is 10px sans-serif.
ctx.font = "48px serif";
ctx.fillStyle = "red";
var arr = ["默认", "start", "end", "left", "right", "center"];
for (var i = 0, l_i = arr.length; i < l_i; i++) {
var y = 50*(i+1);
var obj = arr[i];
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(1000, y);
ctx.closePath();
ctx.stroke();
if(i != 0){
ctx.textAlign = obj;
}
ctx.fillText(obj, 300, y);
}
});
unit.addMenuItem4Ctx('文本边框——textBaseline', function(ctx:IRenderingContext2D){
// A DOMString parsed as CSS font value. The default font is 10px sans-serif.
ctx.font = "48px serif";
ctx.fillStyle = "red";
var arr = ["默认", "top", "hanging", "middle", "alphabetic", "ideographic", "bottom"];
for (var i = 0, l_i = arr.length; i < l_i; i++) {
var y = 50*(i+1);
var obj = arr[i];
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(1000, y);
ctx.closePath();
ctx.stroke();
if(i != 0){
ctx.textAlign = obj;
}
var obj = arr[i];
ctx.textBaseline = obj;
ctx.fillText(obj, 300, y);
}
});
unit.addMenuItem4Ctx('文本边框——direction(未全面支持)', function(ctx:IRenderingContext2D){
// A DOMString parsed as CSS font value. The default font is 10px sans-serif.
ctx.font = "48px serif";
ctx.fillStyle = "red";
var arr = ["默认", "ltr", "rtl", "inherit"];
for (var i = 0, l_i = arr.length; i < l_i; i++) {
var y = 50*(i+1);
var obj = arr[i];
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(1000, y);
ctx.closePath();
ctx.stroke();
if(i != 0){
ctx.direction = obj;
}
ctx.fillText(obj, 300, y);
}
});
unit.addMenuItem4Ctx('文本尺寸——measureText', function(ctx:IRenderingContext2D){
// A DOMString parsed as CSS font value. The default font is 10px sans-serif.
ctx.font = "48px serif";
ctx.fillStyle = "red";
ctx.fillText("文本尺寸", 300, 50);
var text = ctx.measureText("文本尺寸"); // TextMetrics object
ctx.font = "20px serif";
ctx.fillText(JSON.stringify(text), 0, 100);
});
}<file_sep>/// <reference path="../base/logger.ts" />
/// <reference path="../const/logCode.ts" />
module hh {
export function numToColor():string{
return null;
}
export function color(r, g?:number, b?:number){
var length = arguments.length;
var color = null;
if(length == 1){
}else if(length == 3){
}else{
error(logCode.e_2);
}
return color;
}
}<file_sep>/// <reference path="../../boot.ts" />
/**
* asyncjs模块的api模拟。只模拟了部分觉得有用的api。
*/
module hh {
/**
* 序列执行异步任务。
* @param tasks
* @param cb
* @param ctx
* @param atOnce
*/
export function series(
tasks:Array<(cb:(err?:any, arg?:any)=>void)=>void>,
cb:(err:any, results:any[])=>void,
ctx?:any, atOnce?:boolean):void{
var asyncPool = new AsyncPool(tasks, 1, function(func, index, cb1){
func.call(ctx, cb1);
}, cb, ctx);
asyncPool.flow(atOnce);
}
/**
* 平行执行异步任务。
* @param tasks
* @param cb
* @param ctx
* @param atOnce
*/
export function parallel(
tasks:Array<(cb:(err?:any, arg?:any)=>void)=>void>,
cb:(err:any, results:any[])=>void,
ctx?:any, atOnce?:boolean):void{
var asyncPool = new AsyncPool(tasks, 0, function(func, index, cb1){
func.call(ctx, cb1);
}, cb, ctx);
asyncPool.flow(atOnce);
}
/**
* 瀑布模式执行异步任务。
* @param tasks
* @param cb
* @param ctx
* @param atOnce
*/
export function waterfall(
tasks:Array<(...args:any[])=>void>,
cb:(err:any, argFromLastTask?:any)=>void,
ctx?:any, atOnce?:boolean):void{
var args:any[] = [];//参数
var asyncPool = new AsyncPool(tasks, 1, function(func, index, cb1){
args.push(function(err){
//在这里重新设置传递给各个任务的参数
args = Array.prototype.slice.apply(arguments);//保存当前任务的返回值
args.splice(0, 1);//去掉err项
cb1.apply(null, arguments);
});//将回调添加进去
func.apply(ctx, args);
}, function(err, results){
if(!cb) return;//没有回调,不处理
if(err) return cb.call(ctx, err);//如果出错了
cb.call(ctx, null, results[results.length - 1]);
}, null);
asyncPool.flow(atOnce);
}
/**
* 使用map方式迭代执行列表或者对象数据,进行异步操作。
* @param tasks {Array|Object}
* @param iterator 迭代的异步操作
* @param cb
* @param ctx
* @param atOnce
*/
export function map(
tasks:any,
iterator:(value:any, index:any, cb:(err:any, ...args:any[])=>void)=>void,
cb:(err:any, results:any[])=>void,
ctx?:any, atOnce?:boolean):void{
var asyncPool = new AsyncPool(tasks, 0, iterator, cb, ctx);
asyncPool.flow(atOnce);
}
/**
* 使用map方式迭代执行列表或者对象数据,进行异步操作。但是可以限制每次并行的数量。
* @param tasks {Array|Object}
* @param limit 每次并行限制数量
* @param iterator 迭代的异步操作
* @param cb
* @param ctx
* @param atOnce
*/
export function mapLimit(
tasks:any,
limit:number,
iterator:(value:any, index:any, cb:(err:any, ...args:any[])=>void)=>void,
cb:(err:any, results:any[])=>void,
ctx?:any, atOnce?:boolean):void{
var asyncPool = new AsyncPool(tasks, limit, iterator, cb, ctx);
asyncPool.flow(atOnce);
}
}<file_sep>/**
* Created by SmallAiTT on 2015/7/1.
*/
///<reference path="../../tc_init.ts" />
module tc{
unit.curModuleName = moduleName_Res;
unit.addMenuItem('加载图片', function(){
var url = res_helper.getItemUrl(11001);
hh.res.load(url, function(){
var img = hh.res.get(url);
console.log(img);
});
});
}<file_sep>/**
* Created by SmallAiTT on 2015/6/27.
*/
///<reference path="sty_init.ts" />
module sty{
unit.curModuleName = moduleName_graphics;
unit.addMenuItem4Ctx('矩形', function(ctx:IRenderingContext2D){
// 进行颜色填充
ctx.fillStyle='#FF0000';
// 颜色填充还有以下几种方式
//ctx.fillStyle = 'red';
//ctx.fillStyle = 'rgb(255,0,0)';
//ctx.fillStyle = 'rgba(255,0,0,0.5)';
// 填充矩形
ctx.fillRect(25,25,100,100);
// 擦除矩形
ctx.clearRect(45,45,60,60);
// 镂空矩形
ctx.strokeRect(50,50,50,50);
});
unit.addMenuItem4Ctx('直线', function(ctx:IRenderingContext2D){
ctx.moveTo(10,10);
ctx.lineTo(150,50);
ctx.lineTo(10,50);
ctx.stroke();
});
unit.addMenuItem4Ctx('Path2D绘制三角形', function(ctx:IRenderingContext2D){
var path2D:Path2D = new Path2D();
path2D.moveTo(75, 50);
path2D.lineTo(100, 75);
path2D.lineTo(100, 25);
ctx.fill(path2D);
});
unit.addMenuItem4Ctx('Path2D绘制笑脸', function(ctx:IRenderingContext2D){
var path2D:Path2D = new Path2D();
path2D.arc(75, 75, 50, 0, Math.PI*2);// outer circle
path2D.moveTo(110, 75);
path2D.arc(75, 75, 35, 0, Math.PI, false);// Mouth (clockwise)
path2D.moveTo(65, 65);
path2D.arc(60, 65, 5, 0, Math.PI*2, true);// Left eye
path2D.moveTo(95, 65);
path2D.arc(90, 65, 5, 0, Math.PI*2, false);// Right eye
ctx.stroke(path2D);
});
unit.addMenuItem4Ctx('二次方贝塞尔曲线', function(ctx:IRenderingContext2D){
var path2D:Path2D = new Path2D();
path2D.moveTo(75, 25);
path2D.quadraticCurveTo(25, 25, 25, 62.5);
path2D.quadraticCurveTo(25, 100, 50, 100);
path2D.quadraticCurveTo(50, 120, 30, 125);
path2D.quadraticCurveTo(60, 120, 65, 100);
path2D.quadraticCurveTo(125, 100, 125, 62.5);
path2D.quadraticCurveTo(125, 25, 75, 25);
ctx.stroke(path2D);
});
unit.addMenuItem4Ctx('贝塞尔曲线', function(ctx:IRenderingContext2D){
var path2D:Path2D = new Path2D();
path2D.moveTo(75, 40);
path2D.bezierCurveTo(75, 37, 70, 25, 50, 25);
path2D.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5);
path2D.bezierCurveTo(20, 80, 40, 102, 75, 120);
path2D.bezierCurveTo(110, 102, 130, 80, 130, 62.5);
path2D.bezierCurveTo(130, 62.5, 130, 25, 100, 25);
path2D.bezierCurveTo(85, 25, 75, 37, 75, 40);
ctx.stroke(path2D);
});
unit.addMenuItem4Ctx('线结束表现', function(ctx:IRenderingContext2D){
var lineCap = ['butt','round','square'];
// Draw guides
ctx.strokeStyle = '#09f';
ctx.beginPath();
ctx.moveTo(10,10);
ctx.lineTo(140,10);
ctx.moveTo(10,140);
ctx.lineTo(140,140);
ctx.stroke();
// Draw lines
ctx.strokeStyle = 'black';
for (var i=0;i<lineCap.length;i++) {
ctx.lineWidth = 15;
ctx.lineCap = lineCap[i];
ctx.beginPath();
ctx.moveTo(25 + i * 50, 10);
ctx.lineTo(25 + i * 50, 140);
ctx.stroke();
}
});
unit.addMenuItem4Ctx('线衔接表现', function(ctx:IRenderingContext2D){
var ctx = hh.engine.canvasCtx;
var lineJoin = ['round','bevel','miter'];
ctx.lineWidth = 10;
for (var i=0;i<lineJoin.length;i++){
ctx.lineJoin = lineJoin[i];
ctx.beginPath();
ctx.moveTo(-5,5+i*40);
ctx.lineTo(35,45+i*40);
ctx.lineTo(75,5+i*40);
ctx.lineTo(115,45+i*40);
ctx.lineTo(155,5+i*40);
ctx.stroke();
}
});
unit.addMenuItem4Ctx('setLineDash', function(ctx:IRenderingContext2D, param){
var offset = 0;
function draw() {
var canvas = hh.engine._canvas;
ctx.clearRect(0,0, canvas.width, canvas.height);
ctx.setLineDash([4, 2]);
ctx.lineDashOffset = -offset;
ctx.strokeRect(10,10, 100, 100);
}
function march() {
offset++;
if (offset > 16) {
offset = 0;
}
draw();
}
param.func = march;
hh.tick(march);
}, function(param){
hh.unTick(param.func);
});
unit.addMenuItem4Ctx('线性渐变', function(ctx:IRenderingContext2D) {
// Create gradients
var lingrad = ctx.createLinearGradient(0,0,0,150);
lingrad.addColorStop(0, '#00ABEB');
lingrad.addColorStop(0.5, '#fff');
lingrad.addColorStop(0.5, '#26C000');
lingrad.addColorStop(1, '#fff');
var lingrad2 = ctx.createLinearGradient(0,50,0,95);
lingrad2.addColorStop(0.5, '#000');
lingrad2.addColorStop(1, 'rgba(0,0,0,0)');
// assign gradients to fill and stroke styles
ctx.fillStyle = lingrad;
ctx.strokeStyle = lingrad2;
// draw shapes
ctx.fillRect(10,10,130,130);
ctx.strokeRect(50,50,50,50);
});
unit.addMenuItem4Ctx('放射渐变', function(ctx:IRenderingContext2D) {
// Create gradients
// 参数为两个圆,(x1,y1,r1)-(x2,y2,r2)
var radgrad = ctx.createRadialGradient(45,45,10,52,50,30);
radgrad.addColorStop(0, '#A7D30C');
radgrad.addColorStop(0.9, '#019F62');
radgrad.addColorStop(1, 'rgba(1,159,98,0)');
var radgrad2 = ctx.createRadialGradient(105,105,20,112,120,50);
radgrad2.addColorStop(0, '#FF5F98');
radgrad2.addColorStop(0.75, '#FF0188');
radgrad2.addColorStop(1, 'rgba(255,1,136,0)');
var radgrad3 = ctx.createRadialGradient(95,15,15,102,20,40);
radgrad3.addColorStop(0, '#00C9FF');
radgrad3.addColorStop(0.8, '#00B5E2');
radgrad3.addColorStop(1, 'rgba(0,201,255,0)');
var radgrad4 = ctx.createRadialGradient(0,150,50,0,140,90);
radgrad4.addColorStop(0, '#F4F201');
radgrad4.addColorStop(0.8, '#E4C700');
radgrad4.addColorStop(1, 'rgba(228,199,0,0)');
// draw shapes
ctx.fillStyle = radgrad4;
ctx.fillRect(0,0,150,150);
ctx.fillStyle = radgrad3;
ctx.fillRect(0,0,150,150);
ctx.fillStyle = radgrad2;
ctx.fillRect(0,0,150,150);
ctx.fillStyle = radgrad;
ctx.fillRect(0,0,150,150);
});
unit.addMenuItem4Ctx('图案 createPattern', function(ctx:IRenderingContext2D) {
// create new image object to use as pattern
var img = new Image();
img.src = resHelper.getS9gUrl(1);
img.onload = function(){
// create pattern
var ptrn = ctx.createPattern(img,'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0,0,150,150);
}
});
unit.addMenuItem4Ctx('阴影 Shadows', function(ctx:IRenderingContext2D) {
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.shadowBlur = 2;
ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
ctx.font = "20px Times New Roman";
ctx.fillStyle = "Black";
ctx.fillText("Sample String", 5, 30);
ctx.fillRect(100, 100, 100, 100);
});
unit.addMenuItem4Ctx('Canvas fill rules', function(ctx:IRenderingContext2D) {
ctx.beginPath();
ctx.arc(50, 50, 30, 0, Math.PI*2);
ctx.arc(50, 50, 15, 0, Math.PI*2);
ctx.closePath();
ctx.fill("nonzero");
ctx.beginPath();
ctx.arc(150, 150, 30, 0, Math.PI*2);
ctx.arc(150, 150, 15, 0, Math.PI*2);
ctx.closePath();
ctx.fill("evenodd");
});
}<file_sep>/**
* Created by SmallAiTT on 2015/6/30.
*/
///<reference path="ref.ts" />
module hh{
export class ResCfgItem extends Emitter{
static SUCCESS:string = "success";
static ERROR:string = "error";
static FINISH:string = "finish";
url:string;
type:string;
cb:Function;
ctx:any;
// @override
init(url?:string){
super.init();
this.setUrl(url);
}
setUrl(url:string):ResCfgItem{
var self = this;
self.url = url;
if(url){
var extname = hh.PATH.extname(url);
if(extname){
self.type = extname.substring(1).toLowerCase();
}
}else{
self.type = null;
}
return self;
}
_send(err, resData:any){
var self = this, clazz = self.__c;
// 从队列移除
var queue = res._queue;
for (var i = 0, l_i = queue.length; i < l_i; i++) {
var rci = queue[i];
if(rci == self){
queue.splice(i, 1);
break;
}
}
if(!err) {// 成功了就进行数据保存
res._pool[self.url] = resData;
}
self.emit(clazz.FINISH, err, resData);
// 进行回收
self.unAll();
self.url = null;
self.type = null;
self.cb = null;
self.ctx = null;
clazz.push(self);
}
}
export class ResParser extends Emitter{
_map:any;
//@override
_initProp():void{
super._initProp();
var self = this;
self._map = {};
}
load(rci:ResCfgItem){
var self = this;
self._load(rci);
}
_getRealUrl(rci:ResCfgItem){
var url = rci.url;
if(url.indexOf("http:") == 0 || url.indexOf("https:") == 0) return url;
return hh.PATH.join(res.root, url);
}
_load(rci:ResCfgItem){
// 子类在此实现具体加载
}
_onFinish(err, resData:any, rci:ResCfgItem){
var self = this, map = self._map;
// 获取当前资源对应的rci
// 移除
if(err) {// 如果出错了就进行出错处理
self._handleError(err, resData, rci);
}else{// 成功了就进行发送
rci._send(null, self._parse(resData, rci));
}
}
_handleError(err, resData:any, rci:ResCfgItem){
if(err) {
// 子类决定如果错误了要怎么处理
// 这里这么处理:如果错误了就直接返回
logger.error(err);
rci._send(null, null);
}
}
_parse(resData:any, rci:ResCfgItem):any{
// 子类实现具体的解析规则
return resData;
}
}
export class Res extends Emitter{
_pool4Parser:any;
_pool:any;
_pool4JsData:any;
_queue:ResCfgItem[];
/** 资源跟目录 */
root:string;
//@override
_initProp():void{
super._initProp();
var self = this;
self._pool4Parser = {};
self._pool = {};
self._pool4JsData = {};
self._queue = [];
self.root = 'res';
}
_pushToQueue(urlOrRci:any, listener:Function, ctx?:any){
var self = this;
var url = urlOrRci.url || urlOrRci;
var type = urlOrRci.type;
var queue = self._queue;
var RCI = ResCfgItem;
var rci:ResCfgItem;
for (var i = 0, l_i = queue.length; i < l_i; i++) {
rci = queue[i];
if(rci.url == url){
return rci.once(RCI.FINISH, listener, ctx);
}
}
// 没有的话就从回收池中获取一个
rci = RCI.pop();
rci.setUrl(url);
if(type) rci.type = type;
rci.once(RCI.FINISH, listener, ctx);
queue.push(rci);
self._loadRci(rci);
}
_loadRci(rci:ResCfgItem){
var parser = this.getParser(rci.type);
parser.load(rci);
}
/**
* 加载资源。
* @param urls 数组或者单项
* @param cb
* @param ctx
* @returns {hh.Res}
*/
load(urls:any, cb:Function, ctx?:any):Res{
var self = this;
urls = urls instanceof Array ? urls : [urls];
var phase = {
isError:false,
isCbCalled:false,
results:[],
length:urls.length,
cb:cb,
ctx:ctx
};
var handlePhase = function(err, resData:any){
// 已经失败了或者已经执行回调了就不操作
if(phase.isError || phase.isCbCalled) return;
if(err) {
// 如果失败,就直接返回失败
phase.isError = true;
phase.isCbCalled = true;
// 下一帧执行
hh.nextTick(function(){
phase.cb.call(phase.ctx, err);
});
}
else {
// 长度缩减
phase.length--;
if(phase.length == 0){// 都已经加载完了,就执行回调
phase.isCbCalled = true;
// 下一帧执行
hh.nextTick(function(){
phase.cb.call(phase.ctx);
});
}
}
};
for (var i = 0, l_i = urls.length; i < l_i; i++) {
var urlOrRci = urls[i];
var resData = self.get(urlOrRci.url || urlOrRci);
if(resData) {
// 如果已经加载了,那么就直接执行回调
handlePhase(null, resData);
continue;
}
self._pushToQueue(urlOrRci, function(err, resData:any){
handlePhase(err, resData);
}, phase);
}
return self;
}
/**
* 根据url获取资源数据。
* @param url
* @returns {*}
*/
get(url):any{
var self = this, pool4JsData = self._pool4JsData;
var jsData = pool4JsData[url];
if(jsData != null) return jsData;
var pool = self._pool;
var data = pool[url];
if(data != null) return data;
return null;
}
registerParser(ParserClass, ...types:string[]){
var self = this;
var parser = new ParserClass;
var pool4Parser = self._pool4Parser;
for (var i = 0, l_i = types.length; i < l_i; i++) {
pool4Parser[types[i]] = parser;
}
}
getParser(type:string):ResParser{
return this._pool4Parser[type];
}
}
export var res:Res = new Res();
}<file_sep>module hh{
export var LAYOUT_ABSOLUTE:number = 0;//绝对布局
export var LAYOUT_RELATIVE:number = 1;//相对布局
export var LAYOUT_LINEAR_H:number = 2;//线性水平布局 horizontal
export var LAYOUT_LINEAR_V:number = 3;//线性垂直布局 vertical
export var ALIGN_TOP_LEFT:number = 0;
export var ALIGN_TOP_CENTER:number = 1;
export var ALIGN_TOP_RIGHT:number = 2;
export var ALIGN_CENTER_LEFT:number = 10;
export var ALIGN_CENTER:number = 11;
export var ALIGN_CENTER_RIGHT:number = 12;
export var ALIGN_BOTTOM_LEFT:number = 20;
export var ALIGN_BOTTOM_CENTER:number = 21;
export var ALIGN_BOTTOM_RIGHT:number = 22;
export var ALIGN_V_TOP:number = 0;//垂直靠上排列
export var ALIGN_V_CENTER:number = 1;//垂直靠中排列
export var ALIGN_V_BOTTOM:number = 2;//垂直靠下排列
export var ALIGN_H_LEFT:number = 0;//水平靠左排列
export var ALIGN_H_CENTER:number = 1;//水平靠中排列
export var ALIGN_H_RIGHT:number = 2;//水平靠右排列
}<file_sep>module hh{
var tickCount:number = 0;
var maxDetalTime:number = 500;
var totalDetalTime:number = 0;
var fpsEle;
export function profile(frameTime:number){
tickCount++;
totalDetalTime += frameTime;
if(totalDetalTime >= maxDetalTime){
var fps = Math.floor(tickCount * 1000 / totalDetalTime);
tickCount = 0;
totalDetalTime = 0;
if(!fpsEle){
fpsEle = document.getElementById("fps");
}
if(fpsEle){
fpsEle.innerHTML = fps + "";
}
}
}
}<file_sep>/**
* Created by SmallAiTT on 2015/7/1.
*/
///<reference path="../../tc_init.ts" />
module tc{
unit.curModuleName = moduleName_ui;
unit.addMenuItem('UIImg#load', function(){
hh.UIImg.debug = true;
var url = res_helper.getItemUrl(11001);
var img = new hh.UIImg();
img.x = img.y = 150;
img.load(url);
hh.engine.stage.addChild(img);
});
unit.addMenuItem('UIImg#bcsh', function(){
hh.UIImg.debug = true;
var url = res_helper.getItemUrl(11001);
var img = new hh.UIImg();
img.x = img.y = 150;
img.load(url);
img.setBCSH(5, 5, 5, 5);
hh.engine.stage.addChild(img);
});
unit.addMenuItem('UIImg 数量测试100', function(){
hh.UIImg.debug = false;
var url = res_helper.getItemUrl(11001);
hh.res.load(url, function(){
var stage:hh.Node = hh.engine.stage;
var w = stage.width, h = stage.height;
for(var i = 0; i < 100; ++i){
var randX = w*(Math.random());
var randY = h*(Math.random());
var img = new hh.UIImg();
img.x = randX;
img.y = randY;
img.load(url);
stage.addChild(img);
}
});
});
unit.addMenuItem('UIImg 数量测试200', function(){
hh.UIImg.debug = false;
var url = res_helper.getItemUrl(11001);
hh.res.load(url, function(){
var stage:hh.Node = hh.engine.stage;
var w = stage.width, h = stage.height;
for(var i = 0; i < 200; ++i){
var randX = w*(Math.random());
var randY = h*(Math.random());
var img = new hh.UIImg();
img.x = randX;
img.y = randY;
img.load(url);
stage.addChild(img);
}
});
});
unit.addMenuItem('UIImg 数量测试400', function(){
hh.UIImg.debug = false;
var url = res_helper.getItemUrl(11001);
hh.res.load(url, function(){
var stage:hh.Node = hh.engine.stage;
var w = stage.width, h = stage.height;
for(var i = 0; i < 400; ++i){
var randX = w*(Math.random());
var randY = h*(Math.random());
var img = new hh.UIImg();
img.x = randX;
img.y = randY;
img.load(url);
stage.addChild(img);
}
});
});
unit.addMenuItem('UIImg 数量测试600', function(){
hh.UIImg.debug = false;
var url = res_helper.getItemUrl(11001);
hh.res.load(url, function(){
var stage:hh.Node = hh.engine.stage;
var w = stage.width, h = stage.height;
for(var i = 0; i < 600; ++i){
var randX = w*(Math.random());
var randY = h*(Math.random());
var img = new hh.UIImg();
img.x = randX;
img.y = randY;
img.load(url);
stage.addChild(img);
}
});
});
unit.addMenuItem('UIImg clip 区域测试', function(){
hh.UIImg.debug = false;
var url = res_helper.getItemUrl(11001);
hh.res.load(url, function(){
var stage:hh.Node = hh.engine.stage;
var node:hh.Node = new hh.Node();
node.width = node.height = 100;
node.x = node.y = 200;
node.rotation = Math.PI/4;
node.clip = hh.Node.CLIP_RECT;
stage.addChild(node);
var img = new hh.UIImg();
img.x = img.y = 0;
img.load(url);
node.addChild(img);
var img = new hh.UIImg();
img.rotation = Math.PI/4;
img.scaleX = 0.5;
img.x = img.y = 200;
img.load(url);
node.addChild(img);
});
});
unit.addMenuItem('UIImg 数量测试 clip1', function(){
hh.UIImg.debug = false;
var url = res_helper.getItemUrl(11001);
hh.res.load(url, function(){
var stage:hh.Node = hh.engine.stage;
var w = stage.width, h = stage.height;
for(var i = 0; i < 2000; ++i){
var randX = w*(Math.random());
var randY = h*(Math.random());
var img = new hh.UIImg();
img.x = randX;
img.y = randY;
img.load(url);
stage.addChild(img);
}
});
});
unit.addMenuItem('UIImg 数量测试 clip2', function(){
hh.UIImg.debug = false;
var url = res_helper.getItemUrl(11001);
hh.res.load(url, function(){
var stage:hh.Node = hh.engine.stage;
var node:hh.Node = new hh.Node();
node.width = node.height = 100;
node.x = node.y = 200;
node.clip = hh.Node.CLIP_RECT;
stage.addChild(node);
var w = stage.width, h = stage.height;
for(var i = 0; i < 2000; ++i){
var randX = w*(Math.random()) - w/2;
var randY = h*(Math.random()) - h/2;
var img = new hh.UIImg();
img.x = randX;
img.y = randY;
img.load(url);
node.addChild(img);
}
});
});
unit.addMenuItem('UIImg#grid 九宫格', function(){
hh.UIImg.debug = true;
var url = res_helper.getS9gUrl(1);
var img1 = new hh.UIImg();
img1.x = img1.y = 150;
img1.grid = [1, 39, 39, 2, 2];
img1.width = img1.height = 200;
img1.load(url);
hh.engine.stage.addChild(img1);
});
unit.addMenuItem('UIImg九宫格数量100', function(){
hh.UIImg.debug = false;
var url = res_helper.getS9gUrl(1);
hh.res.load(url, function(){
var stage:hh.Node = hh.engine.stage;
var w = stage.width, h = stage.height;
for(var i = 0; i < 100; ++i){
var randX = w*(Math.random());
var randY = h*(Math.random());
var img = new hh.UIImg();
img.x = randX;
img.y = randY;
img.grid = [1, 39, 39, 2, 2];
img.width = img.height = 100;
img.load(url);
stage.addChild(img);
}
});
});
unit.addMenuItem('UIImg#grid 三宫格', function(){
hh.UIImg.debug = true;
var url = res_helper.getS9gUrl(1);
var img1 = new hh.UIImg();
img1.x = img1.y = 150;
img1.grid = [3, 39, 2];
img1.height = 200;
img1.load(url);
hh.engine.stage.addChild(img1);
var url = res_helper.getS9gUrl(1);
var img2 = new hh.UIImg();
img2.x = 300;
img2.y = 150;
img2.grid = [4, 39, 2];
img2.width = 200;
img2.load(url);
hh.engine.stage.addChild(img2);
});
}<file_sep>module hh.logCode{
//系统级别错误
export var e_1:string = "系统错误!";
export var e_2:string = "参数类型错误!";
//系统级别警告
export var w_1:string = "无法重复执行主循环!";
//系统级别信息
//系统级别调试信息
}<file_sep>/**
* Created by SmallAiTT on 2015/7/3.
*/
///<reference path="../../tc_init.ts" />
module tc{
unit.curModuleName = moduleName_Node;
unit.addMenuItem('Node4Clip 矩形', function(){
var node1 = new hh.Node();
node1.x = node1.y = 100;
node1.width = node1.height = 100;
// 设置矩形裁剪
node1.clip = hh.Node.CLIP_RECT;
var node2 = new hh.Node();
node2.x = node2.y = 100;
node2.width = node2.height = 100;
node2._nodeOpt.debugRectColor = 'blue';
hh.engine.stage.addChild(node1);
node1.addChild(node2);
});
unit.addMenuItem('Node4Clip 圆形', function(){
var node1 = new hh.Node();
node1.x = node1.y = 100;
node1.width = node1.height = 100;
// 设置矩形裁剪
node1.clip = hh.Node.CLIP_ARC;
var node2 = new hh.Node();
node2.x = node2.y = 100;
node2.width = node2.height = 100;
node2._nodeOpt.debugRectColor = 'blue';
hh.engine.stage.addChild(node1);
node1.addChild(node2);
});
}<file_sep>module hh{
export class ResCfgItem{
public name:string;
public url:string;
public type:string;
public scale9grid:string;
public cb:()=>void;
public ctx:any;
public logEnabled:boolean = true;
}
export var _pool:any = {};//资源缓存池
export var _resCfg:any = {};//资源配置
export var _aliasCfg:any = {};//资源别名配置
export var _counter:any = {};//资源加载计数器
export var _parserDic:any = {};//资源解析器映射库,key为解析器type。
export var _parserAliasDic:any = {};//资源解析器类型别名映射,key为别名,value为parserType
export var _defaultLimit:number = 100;//并行加载个数
export var resRoot:string = "";//资源根路径
export function loadImage(url:string, option?:any, cb?:any){
var opt = {
isCrossOrigin : true
};
if(cb !== undefined) {
opt.isCrossOrigin = option.isCrossOrigin == null ? opt.isCrossOrigin : option.isCrossOrigin;
}
else if(option !== undefined)
cb = option;
var img = new Image();
if(opt.isCrossOrigin)
img.crossOrigin = "Anonymous";
img.addEventListener("load", function () {
this.removeEventListener('load', arguments.callee, false);
this.removeEventListener('error', arguments.callee, false);
if(cb)
cb(null, img);
});
img.addEventListener("error", function () {
this.removeEventListener('error', arguments.callee, false);
if(cb)
cb("load image failed");
});
img.src = url;
return img;
}
} | 81912f24beaf57b3788ca41ce791f6fb0f684b63 | [
"TypeScript"
]
| 57 | TypeScript | SmallAiTT/holy-high | d11cda467859eb4759206f86f7d1401d59222376 | 91ba1a968439aec48dfd5d68936966e8451d4e02 |
refs/heads/main | <repo_name>KuyaShawn/dating<file_sep>/classes/PremiumMember.php
<?php
/**
* Class PremiumMember
* Represents a premium member of the dating site
*/
class PremiumMember extends Member
{
private $_inDoorInterests;
private $_outDoorInterests;
/**
* PremiumMember constructor.
* @param $_inDoorInterests
* @param $_outDoorInterests
*/
public function __construct($fname = "", $lname = "", $age = 0, $gender = "", $phone = "",
$email = "", $state = "", $seeking = "", $bio = "",
$_inDoorInterests = array(), $_outDoorInterests = array())
{
parent::__construct($fname, $lname, $age, $gender,
$phone, $email, $state, $seeking, $bio);
$this->_inDoorInterests = $_inDoorInterests;
$this->_outDoorInterests = $_outDoorInterests;
}
/**
* @return mixed
*/
public function getInDoorInterests(): array
{
return $this->_inDoorInterests;
}
/**
* @param mixed $inDoorInterests
*/
public function setInDoorInterests($inDoorInterests): void
{
$this->_inDoorInterests = $inDoorInterests;
}
/**
* @return mixed
*/
public function getOutDoorInterests(): array
{
return $this->_outDoorInterests;
}
/**
* @param mixed $outDoorInterests
*/
public function setOutDoorInterests($outDoorInterests): void
{
$this->_outDoorInterests = $outDoorInterests;
}
}<file_sep>/README.md
# dating
The Dating Assignment
<file_sep>/model/validation.php
<?php
class Validation
{
// returns true if name is valid
static function validName($name): bool
{
return preg_match('/^[a-zA-Z]+$/', $name) == 1;
}
static function validAge($age): bool
{
$age = floatval($age);
if (is_nan($age) != 1) {
return ($age >= 18 && $age <= 118);
}
return false;
}
static function validPhone($phone): bool
{
$pattern = '/^\s*(?:\+?(\d{1,3}))?([-. (]*(\d{3})[-. )]*)?((\d{3})[-. ]*(\d{2,4})(?:[-.x ]*(\d+))?)\s*$/';
return preg_match($pattern, $phone) == 1;
}
static function validEmail($email): bool
{
if (filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($email)) {
return true;
}
return false;
}
static function validOutdoor($outdoor): bool
{
$validOutdoor = DataLayer::getOutdoors();
if (!empty($outdoor)) {
foreach ($outdoor as $userOutdoor) {
if (!in_array($userOutdoor, $validOutdoor)) {
return false;
}
}
}
return true;
}
static function validIndoor($indoor): bool
{
$validIndoor = DataLayer::getIndoors();
if (!empty($indoor)) {
foreach ($indoor as $userIndoor) {
if (!in_array($userIndoor, $validIndoor)) {
return false;
}
}
}
return true;
}
}
<file_sep>/controller/controller.php
<?php
class Controller
{
private $_f3; // router
/**
* Controller constructor.
* @param $_f3
*/
public function __construct($f3)
{
$this->_f3 = $f3;
}
function home()
{
// Display the home page
$view = new Template();
echo $view->render('views/home.html');
}
function personal()
{
/* If the form has been submitted, add the data to session
* and send the user to the next order form
*/
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//var_dump($_POST);
$_SESSION = array();
// When "user" clicks on the premium checkbox
$userPremium = isset($_POST['premium']);
if ($userPremium) {
$_SESSION['user'] = new PremiumMember();
} else {
$_SESSION['user'] = new Member();
}
$userFirst = $_POST['fName'];
if (Validation::validName($userFirst)) {
$_SESSION['user']->setFname($userFirst);
} else {
$this->_f3->set('errors["fname"]', "Please input a valid first name");
}
$userLast = $_POST['lName'];
if (Validation::validName($userLast)) {
$_SESSION['user']->setLname($userLast);
} else {
$this->_f3->set('errors["lname"]', "Please input a valid last name");
}
$userAge = $_POST['age'];
if (Validation::validAge($userAge)) {
$_SESSION['user']->setAge($userAge);
} else {
$this->_f3->set('errors["age"]', "Please enter a valid age");
}
$userPhone = $_POST['pNum'];
if (Validation::validPhone($userPhone)) {
$_SESSION['user']->setPhone($userPhone);
} else {
$this->_f3->set('errors["pNum"]', "Please enter a valid phone number");
}
$userGender = $_POST['gender'];
if (!is_null($userGender)) {
$_SESSION['user']->setGender($userGender);
} else {
$this->_f3->set('errors["gender"]', "Please select a valid gender");
}
//Get the data
$this->_f3->set('userFirst', $userFirst);
$this->_f3->set('userLast', $userLast);
$this->_f3->set('userAge', $userAge);
$this->_f3->set('userPhone', $userPhone);
$this->_f3->set('userGender', $userGender);
//If there are no errors, redirect to profile route
if (empty($this->_f3->get('errors'))) {
header('location: profile');
}
}
// Display the Personal info page
$view = new Template();
echo $view->render('views/personal_Info.html');
}
function profile()
{
/* If the form has been submitted, add the data to session
* and send the user to the next order form
*/
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//var_dump($_POST);
$userEmail = $_POST['email'];
if (Validation::validEmail($userEmail)) {
$_SESSION['user']->setEmail($userEmail);
} else {
$this->_f3->set('errors["email"]', "Please enter a valid email address");
}
$userSeeking = $_POST['seeking'];
if (!is_null($userSeeking)) {
$_SESSION['user']->setSeeking($userSeeking);
} else {
$this->_f3->set('errors["seeking"]', "Please choose the gender you're interested in");
}
$userState = $_POST['state'];
$_SESSION['user']->setState($userState);
$userBio = $_POST['bio'];
$_SESSION['user']->setBio($userBio);
//Store the user input in the hive (Part of making the code sticky)
$this->_f3->set('userEmail', $userEmail);
$this->_f3->set('userState', $userState);
$this->_f3->set('userBio', $userBio);
$this->_f3->set('userSeeking', $userSeeking);
//If there are no errors, redirect to profile route
if (empty($this->_f3->get('errors'))) {
header('location: interest');
}
}
$this->_f3->set('states', DataLayer::getStates());
// Display the Profile page
$view = new Template();
echo $view->render('views/profile.html');
}
function interest()
{
if ($_SESSION['user'] instanceof PremiumMember) {
//Initialize variables to store user input as an array
$userIndoor = array();
$userOutdoor = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$userIndoor = $_POST['indoorInterests'] == null ? array() : $_POST['indoorInterests'];
$userOutdoor = $_POST['outdoorInterests'] == null ? array() : $_POST['outdoorInterests'];
if (Validation::validIndoor($userIndoor)) {
$_SESSION['user']->setInDoorInterests($userIndoor);
} else {
$this->_f3->set('errors["indoor"]', "Please enter a valid interest");
}
if (Validation::validOutdoor($userOutdoor)) {
$_SESSION['user']->setOutDoorInterests($userOutdoor);
} else {
$this->_f3->set('errors["outdoor"]', "Please enter a valid interest");
}
if (empty($this->_f3->get('errors'))) {
header('location: summary');
}
}
//Get both interest and then send them to the view
$this->_f3->set('indoor', DataLayer::getIndoors());
$this->_f3->set('outdoor', DataLayer::getOutdoors());
//Store the user input in the hive (Part of making the code sticky)
$this->_f3->set('userIndoor', $userIndoor);
$this->_f3->set('userOutdoor', $userOutdoor);
// Display the Interest page
$view = new Template();
echo $view->render('views/Interest.html');
} else {
header('location: summary');
}
}
function summary()
{
// Display the summary page
$view = new Template();
echo $view->render('views/summary.html');
// This might be problematic
unset($_SESSION['biography']);
}
} | 3bcbf43d2153f88da2fed266a69edf9ef65f596f | [
"Markdown",
"PHP"
]
| 4 | PHP | KuyaShawn/dating | eb085fc9c3280481d94d5c3ef257d8d8ca0b9bd8 | 94383c0755d662f3c00089ba3892100818a4abdf |
refs/heads/master | <file_sep>int Task = '4';
<file_sep>#include <stdio.h> //Standard input and output
#include "input.h"
// declare function
void encryption(char *x, int key);
void CaesarEncrypt() {
// Initialise variables and string
char message[1000];
int i=0;
FILE * input;
input = fopen("input.txt", "r");
if(message == NULL) {
perror("fopen()");
return;
}
fscanf(input, "%d %s", &key, message);
printf("\n\n%d %s\n\n", &key, message);
/* While loop Changes message from lower case to uppercase by testing if ascii value of the
letters are between a and z and then taking away 32 to make them a capital letter*/
while(message[i] != '\0') {//while the i'th value of message does not equal null the loop continues
if (message[i]>= 'a' && message[i] <= 'z')
message[i] = message [i] - 32;
++i;
}
//calls function to encrypt message and then print the result.
encryption(message, key);
printf("%s\n", message);
}
/* Function definition. This function has a while loop that checks if the i'th value is a symbol or a letter
via the first while if statements. If a symbol is found it sends out the value and continues to the next i value.
The capital letters left over are then given a value from A=0 to Z=26 by subtracting 65 from the ascii value.
The encryption key is then added and modulus 26 used which makes letters greater than 25 rotate back to A */
void encryption (char *x,int key){
int i = 0; //initialise integer i to 0 to allow it to start at first array input
while (x[i] != '\0') {//while the i'th value does not equal null the loop continues
if (x[i] < 'A' || x[i] > 'Z'){//All symbols below the ascii 'A' and above ascii 'Z' value are not encrypted
x[i] = x[i];
i++;// adds 1 onto i to move onto the next value
}
else {//while the i'th value of message does not equal null the loop continues
x[i] = ((x[i] - 65 + key ) % 26) + 65;//The letters are given a value between 0 and 25 then encrypted and given back there original ascii number.
i++;
}
}
}<file_sep>#include <stdio.h>
#include <math.h>
#include "input.h"//header file which has the task number in it.
/* User interface: Changing what the Task is equal to in the header file (input.h) will choose between
* which task you would like to do.
*
* Task = '1' Caesar Cipher Encryption with key.
* Task = '2' Caesar Cipher Decryption with key.
* Task = '3' Substitution Cipher Encryption with key.
* Task = '4' Substitution Cipher Decryption with key.
*
* To input the caesar cipher key and message into the function the file "input.txt" must be modified.
* The caesar cipher will read an integer key between 0 and 26 from the first line.
* All functions will read the message to be encrypted/decrypted from the second line.
*
* The substitution key (subkey) must be hardcoded into the string which is on line 30.
*
*/
void encryption(char *x, int key);//declare caesar cipher encryption function.
void decryption(char *x, int key);//declare caesar cipher decryption function.
void substitution_encryption(char *x, char *y);//declare substitution encryption function.
void substitution_decryption(char *x, char *y, char*z);//declare substitution decryption function.
int main() {//main function.
char message[1000];//declare string variable.
int key, i=0;//declare integer variable.
char subkey[] = "<KEY>";//Hardcoded string for substitution key.
char alphabet [] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//Hardcoded string alphabet for decryption of substitution cipher.
FILE * input;//pointer to a file.
FILE * output;//pointer to a file.
input = fopen("input.txt", "r");//open file for reading.
output = fopen ("output.txt", "w");//open file for writing.
fscanf(input, "%d\n%[^\n]s", &key, message);//scans from input file and stores integer as key and string as message.
//if statement to ensure data was read from file and show error if nothing was stored in message.
if(message == NULL) {//if message is equivalent to nothing then an error will be shown.
perror("fopen()");
}
//while loop converts lower case letters to uppercase letters in the message string.
while(message[i] != '\0') {//while the i'th value of message does not equal null the loop continues.
if (message[i]>= 'a' && message[i] <= 'z')//if statement to prove whether the messasge has lower case letters eg. between 'a' and 'z'.
message[i] = message [i] - 32;//subtract 32 onto lower case letters to make them Upper case.
++i;//adds one onto counter so loop goes through complete string.
}
//while loop converts lowercase letters to uppercase.
i = 0;// Reinitialise i to equal 0 so while loop begins at start of string.
while(subkey[i] != '\0') {//while the i'th value of message does not equal null the loop continues. message to upper case letters
if (subkey[i]>= 'a' && subkey[i] <= 'z')//if statement to prove whether the subkey has lower case letters eg. between 'a' and 'z'.
subkey[i] = subkey[i] - 32;//subtract 32 onto lower case letters to make them Upper case.
++i;//adds one onto counter so loop goes through complete string.
}
//This switch case statement chooses what encryption method you would like to do and then completes the function in the case statement.
switch (Task) {
case '1': {// if task = 1 in header file then case 1 is selected.
encryption(message, key);//call encryption function to encrypt message with key.
printf("%s\n", message);//encrypted message is printed to console.
fprintf(output,"%s", message);//encrypted message is printed to file output.txt.
break; //breaks from switch case statement
}
case '2': {// if task = 2 in header file then case 2 is selected.
decryption(message, key);//call encryption function to encrypt message with key.
printf("%s\n", message);//encrypted message is printed to console.
fprintf(output,"%s", message);//decrypted message is printed to file output.txt.
break; //breaks from switch case statement
}
case '3': {//if task = 3 in header file then case 3 is selected.
substitution_encryption(message, subkey);//Call substitution encryption function to encrypt he message with subkey.
printf("%s\n", message);//encrypted message is printed to console.
fprintf(output,"%s", message);//encrypted message is printed to file output.txt.
break; //breaks from switch case statement.
}
case '4': {//if task = 4 in header file then case 4 is selected.
substitution_decryption(message, subkey, alphabet);//Call substitution decryption function to decrypt the message with subkey and using the alphabet.
printf("%s\n", message);//encrypted message is printed to console.
fprintf(output,"%s", message);//decrypted message is printed to file output.txt.
break; //breaks from switch case statement.
}
}
}
// Caesar encryption function------------------------------------------------------------------//
/* Function definition. This function has a while loop that checks if the i'th value is a symbol or a letter
* via the first while if statements. The function has two inputs, an integer named key and a string named message.
* If a symbol is found it sends out the value and continues to the next i value. The capital letters left over are
* then given a value from A=0 to Z=26 by subtracting 65 from the ascii value. The encryption key is then added and
* modulus 26 used which makes letters greater than 25 rotate back to A
*/
void encryption (char *x,int key){
int i = 0; //initialise integer i to 0 to allow it to start at first array input.
while (x[i] != '\0') {//while the i'th value does not equal null the loop continues
if (x[i] < 'A' || x[i] > 'Z'){//All symbols below the ascii 'A' and above ascii 'Z' value are not encrypted.
x[i] = x[i];//i'th value of messsage equals itself if it is not a capital letter.
i++;// adds 1 onto i to move onto the next value.
}
else {//while the i'th value of message does not equal null the loop continues
x[i] = ((x[i] - 65 + key ) % 26) + 65;//The letters are given a value between 0 and 25 then encrypted and given back there original ascii number.
i++;// adds 1 onto i to move onto the next value.
}
}
}
// End of caesar encryption function---------------------------------------------------------------------
// Start of caesar decryption function-------------------------------------------------------------------
/* Function definition. This function has a while loop that checks if the i'th value is a symbol or a letter
* via the first while if statements. The inputs are an integer named key and a string named message. If a symbol is found it sends out the value and continues to the next i'th value.
* The capital letters left over are then given a value from A=0 to Z=26 by subtracting 65 from the ascii value.
* The encryption key is then added and modulus 26 used which makes letters greater than 25 rotate from Z to A
*/
void decryption (char *x,int key) {
int i = 0; //initialise integer i to 0 to allow it to start at first array input
while (x[i] != '\0') {//while the i'th value does not equal null the loop continues
if (x[i] < 'A' || x[i] > 'Z'){//All symbols below the ascii 'A' and above ascii 'Z' value are not encrypted
x[i] = x[i];
i++;// adds 1 onto i to move onto the next value
}
else {//while the i'th value of message does not equal null the loop continues
int a;//declare integer a.
a = (x[i] - 65 - key );//gives letters a value between 0 and 25 then subtracts the key.
if (a < 0) {//modulus operator does not work for negative numbers. If statement checks whether they are negative.
a = a + 26;//If they are negative add 26 so letters less than 'A' rotate back to 'Z'.
x[i] = a % 26 + 65;//use modulus to decrypt letter and add 65 to reassign letters to original ascii value.
}
else // else if letters are already positve then decrypt and reassign back to original ascii value.
x[i] = a % 26 + 65;//The letters are given a value between 0 and 25 then encrypted and given back there original ascii number.
i++;// adds 1 onto i to move onto the next value.
}
}
}
// End of caesar decryption-------------------------------------------------------------------
// Start of substitution encryption function---------------------------------------------------
/* Function definition. The substitution cipher has two inputs which are strings. The message and the substitution key.
* This function will not encrypt white space or symbols. It will only encrypt Upper case letters, the if statement in
* the while loop will ensure this. The else statement does the encryption by giving integer c the value of the i'th
* character of the message minus 65 so it has a value between 0 and 25. Then makes the i'th character of the message
* equal to the c'th character of the encryption key.
*/
void substitution_encryption(char *x, char *y){
int i=0;//initialise counter to 0 to allow function to
while (x[i] != '\0'){//while the i'th value of the message is not equal to a null value the loop continues.
if (x[i] < 'A' || x[i] > 'Z'){//All symbols below the ascii 'A' and above ascii 'Z' value are not encrypted.
x[i] = x[i];// If the message character is not a capital letter then it equals itself.
i++;// adds 1 onto i to move onto the next value
}
else {
int c = x[i] - 65;//int c is given a value
x[i] = y[c];
i++;// adds 1 onto i to move onto the next value
}
}
}
//End substitution encryption function---------------------------------------------
//Start of substitution decryption function-------------------------------------
void substitution_decryption(char *x, char *y, char *z){
int i=0;
while (x[i] != '\0'){
int c=0;
if (x[i] < 'A' || x[i] > 'Z'){//All symbols below the ascii 'A' and above ascii 'Z' value are not encrypted
x[i] = x[i];
i++;// adds 1 onto i to move onto the next value
}
else {
while (c < 30) {
if (x[i] == y[c]){
x[i] = z[c];
break;
}
else
c++;
}
i++;
}
}
}
<file_sep>#include <stdio.h> //Standard input and output
#include <math.h>
#include "input.h"
// declare function
void decryption(char *x, int key);
void CaesarDecrypt() {
// Initialise variables and string
char message[100];
int key, i=0;
/*Prompts user to enter message and key and stores them as string array and integer value k*/
printf("Enter message you want decrypted\n");
scanf("%[^\n]", message);
printf("Enter the encryption key between 0 and 26\n");
scanf("%d", &key);
/* While loop Changes message from lower case to uppercase by testing if ascii value of the
letters are between a and z and then taking away 32 to make them a capital letter*/
while(message[i] != '\0') {//while the i'th value of message does not equal null the loop continues
if (message[i]>= 'a' && message[i] <= 'z')
message[i] = message [i] - 32;
++i;
}
//calls function to encrypt message and then print the result.
decryption(message, key);
printf("%s\n", message);
}
/* Function definition. This function has a while loop that checks if the i'th value is a symbol or a letter
via the first while if statements. If a symbol is found it sends out the value and continues to the next i value.
The capital letters left over are then given a value from A=0 to Z=26 by subtracting 65 from the ascii value.
The encryption key is then added and modulus 26 used which makes letters greater than 25 rotate back to A */
void decryption (char *x,int key) {
int i = 0; //initialise integer i to 0 to allow it to start at first array input
while (x[i] != '\0') {//while the i'th value does not equal null the loop continues
if (x[i] < 'A' || x[i] > 'Z'){//All symbols below the ascii 'A' and above ascii 'Z' value are not encrypted
x[i] = x[i];
i++;// adds 1 onto i to move onto the next value
}
}
}<file_sep>#include <stdio.h>
#include "input.h"
int main() {
FILE * input;
int key = 0;
char message[1000];
input = fopen("input.txt", "r");
if(message == NULL) {
perror("fopen()");
return;
}
fscanf(input, "%d %s", &key, message);
printf("\n\n%d %s, %d, %s\n\n", key, message, new_number, new);
/*printf("%d/n", TASK);
void CaesarEncrypt()
void CaesarDecrypt()
return 0;*/
} | 801d65afe2c112c2948069988a67319784d15ca3 | [
"C"
]
| 5 | C | 3298685/Project-1 | edb4f7ac665cf869b93d70fda271ba609bd04916 | 5edf0558fec0d93956b8e548ee5f63fd4e9d84f8 |
refs/heads/master | <file_sep>/**
* Created by Esri on 16-4-27.
* 获取item的信息
*/
define('widgets/portalRestApi/Content/getItemInfo', [null], function () {
var WidgetGetItemInfo = function () {
var _self = this;
};
WidgetGetItemInfo.prototype = {
//需要token。
doGetItemInfo:function(url,itemId,token){
var _self = this;
var deferredObj = $.ajax({
type: "POST",
url: url + "/sharing/rest/content/items/"+itemId,
data: {
f : "json",
token : token
},
dataType:"json"//dataType不能少
});
return deferredObj;
}
};
return WidgetGetItemInfo;
});<file_sep># Dev2016Web3Ddemo
2016Esri开发者大会3Ddemo
demo放在dev2016目录下。
js4.0 API离线下载地址:https://developers.arcgis.com/downloads/
js4.0 API文档及demo在线浏览地址:https://developers.arcgis.com/javascript/
demo中如果出现需要登录或者无法本地浏览的例子请留言给我!
<file_sep>/**
* Created by Esri on 16-4-22.
* 获取token
*/
define('widgets/portalRestApi/generateToken', [null], function () {
var WidgetGenerateToken = function () {
var _self = this;
};
WidgetGenerateToken.prototype = {
//获取token,发送的是异步请求,返回一个异步对象。
doGenerateToken:function(portalUrl,username,password){
var _self = this;
//因为generateToken这个接口必须是https开头的地址,
//所以最好判断并处理一下portalUrl
var portalUrlNew = _self._handlePortalUrl(portalUrl);
var deferredObj = $.ajax({
type: "POST",
url: portalUrlNew + "/sharing/generateToken",
data: {
username: username,
password: <PASSWORD>,
// referer: "localhost", // URL of the sending app.
referer: location.hostname, // URL of the sending app.
expiration: 60, // Lifetime of the token in minutes.
f: "json"
},
dataType:"json"//dataType不能少
});
return deferredObj;
},
_handlePortalUrl:function(portalUrl){
var portalUrlNew;
//转换http 为 https start-----
if(portalUrl.indexOf("https") <0){
portalUrlNew = portalUrl.replace("http","https");
}else{
portalUrlNew = portalUrl;
}
//转换http 为 https end-----
return portalUrlNew;
}
};
return WidgetGenerateToken;
});
<file_sep>/**
* Created by Esri on 16-4-28.
* item的相关操作
*/
define('widgets/portalRestApi/Content/itemOperation', [null], function () {
var WidgetItemOperation = function () {
var _self = this;
};
WidgetItemOperation.prototype = {
//增加一个item
doAddItem:function(loginInfoObj,dataInfoObj){
var _self = this;
var deferredObj = $.ajax({
type: "POST",
url: loginInfoObj.portalUrl + "/sharing/content/users/" + loginInfoObj.username + "/addItem",
// url: loginInfoObj.portalUrl + "/sharing/rest/content/users/" + loginInfoObj.username + "/addItem",//1、多一个rest 就不行了。需要深入研究
// url: loginInfoObj.portalUrl + "/sharing/content/users/" + loginInfoObj.username +folderId+ "/addItem",//2、当然,在某个文件夹下addItem,需要文件夹的id
data: {
f : "json",
title : dataInfoObj.newsTitle,
text : dataInfoObj.newsContent,
tags : dataInfoObj.newsTags,
token : loginInfoObj.token
},
dataType:"json"//dataType不能少
});
return deferredObj;
},
//删除一个item
doDeleteItem:function(portalUrl,username,itemId,token){
var _self = this;
var deferredObj = $.ajax({
type: "POST",
// url: portalUrl + "/sharing/rest/content/users/" + username + "/items/" + itemId + "/delete?f=json&token=" + token,
url: portalUrl + "/sharing/rest/content/users/" + username + "/items/" + itemId + "/delete",
data: {
token : token,
f : 'json'
},
dataType:"json"//dataType不能少
});
return deferredObj;
}
};
return WidgetItemOperation;
});<file_sep>/*global define,dojo,alert,unescape,ItemInfoPage */
define([
"dojo/_base/declare",
"dojo/dom-construct",
"dojo/_base/lang",
"dojo/dom-attr",
"dojo/dom",
"dojo/text!./templates/gallery.html",
"dijit/_WidgetBase",
"dijit/_TemplatedMixin",
"dijit/_WidgetsInTemplateMixin",
"dojo/query",
"dojo/dom-class",
"dojo/on",
"dojo/Deferred",
"dojo/number",
"dojo/topic",
"dojo/dom-style",
"dojo/dom-geometry"
], function (declare, domConstruct, lang, domAttr, dom,template, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, query, domClass, on, Deferred, number, topic, domStyle, domGeom) {
declare("ItemGallery", [_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
templateString: template,
nls: {},
/**
*@class
*@name widgets/gallery/gallery
*/
postCreate: function () {
//20150826 wfh
domConstruct.place(this.galleryView, query(".esriCTGalleryContent")[0]);
this.own(topic.subscribe("createPods", lang.hitch(this, this.createItemPods)));
//20150817 用观察者模式调用函数还是挺好的 start
this.own(topic.subscribe("setDetailHeaderIcon",lang.hitch(this,this._setDetailHeaderIcon)));//设置详情页面的 HeaderIcon
// this.own(topic.subscribe("setDetailHeaderIcon",lang.hitch(this,this._setDetailHeaderIcon())));//this._setDetailHeaderIcon()是错误的!!
this.own(topic.subscribe("setInitialHeaderIcon",lang.hitch(this,this._setInitialHeaderIcon)));//重新设置 HeaderIcon
//20150817 用观察者模式调用函数还是挺好的 end
if (dojo.configData.values.defaultLayout.toLowerCase() === "list") {
// dojo.gridView = false;
// domClass.replace(query(".icon-header")[0], "icon-grid", "icon-list");
// alert("如果是列表视图");
dojo.gridView = true;
// domClass.replace(query(".icon-header")[0], "icon-list", "icon-grid");
var e = dom.byId("layoutTitleId");
domClass.remove(e,"icon-grid");//样式问题 修改样式!! 20150608
domClass.add(e, "icon-list");
} else {
// alert("如果是网格视图");
// dojo.gridView = true;
// domClass.replace(query(".icon-header")[0], "icon-list", "icon-grid");
dojo.gridView = false;
domClass.replace(query(".icon-header")[0], "icon-grid", "icon-list");
}
if (query(".esriCTSignInIcon")[0]) {
if (domStyle.get(query(".esriCTSignInIcon")[0], "display") === "none") {
dojo.gridView = false;
}
}
this.own(on(this.galleryNext, "click", lang.hitch(this, function () {
var defObj, _self;
// topic.publish("showProgressIndicator");
defObj = new Deferred();
_self = this;
topic.publish("queryGroupItem", null, null, null, defObj, dojo.nextQuery);
defObj.then(function (data) {
var i;
dojo.nextQuery = data.nextQueryParams;
for (i = 0; i < data.results.length; i++) {
dojo.results.push(data.results[i]);
}
_self.createItemPods(data.results);
}, function (err) {
topic.publish("hideProgressIndicator");
alert(err.message);
});
})));
this.own(on(query(".esriCTMenuTabLeft")[0], "click", lang.hitch(this, function () {
// alert("jjjjjjjjjjjjjjjjjjjjjjjj");//原来在这里 click 表头的事件 代码 是在postCreate 里生成的!! 一开始 就生成了。
topic.publish("setInitialHeaderIcon");//重新设置 HeaderIcon
domClass.remove(query(".esriCTLeftPanel")[0],"esriCTDisplayNone");
if (query(".esriCTitemDetails")[0]) {
// if (!query(".esriCTitemDetails")[0]) {
//详细
// alert(1);//没进入
// alert("不用返回query(.esriCTitemDetails)[0]:"+query(".esriCTitemDetails")[0]);
dojo.destroy(query(".esriCTitemDetails")[0]);
domClass.remove(query(".esriCTGalleryContent")[0], "displayNoneAll");
domClass.remove(query(".esriCTApplicationIcon")[0], "esriCTCursorPointer");
domClass.remove(query(".esriCTMenuTabLeft")[0], "esriCTCursorPointer");
}
if (query(".esriCTInnerRightPanelDetails")[0] && (!query(".esriCTNoResults")[0])) {
//主页
// alert(2);//进入
// alert("返回query(.esriCTInnerRightPanelDetails)[0]:"+query(".esriCTInnerRightPanelDetails")[0]+",,,"+"query(.esriCTNoResults)[0]):"+query(".esriCTNoResults")[0]);
domClass.replace(query(".esriCTMenuTabRight")[0], "displayBlockAll", "displayNoneAll");
domClass.add(query(".esriCTInnerRightPanelDetails")[0], "displayNoneAll");
domClass.remove(query(".esriCTGalleryContent")[0], "displayNoneAll");
domClass.remove(query(".esriCTInnerRightPanel")[0], "displayNoneAll");
domClass.remove(query(".esriCTApplicationIcon")[0], "esriCTCursorPointer");
domClass.remove(query(".esriCTMenuTabLeft")[0], "esriCTCursorPointer");
}
})));
//这个地方是响应式!!! 原来如此 值得学习! start
on(window, "resize", lang.hitch(this, function () {
//测试 何时隐藏掉 导航栏 start 优先保证1024分辨率下 应用和导航栏不重叠的width值
// var eTest = dom.byId("resizeTest");
////// !!! domAttr.set(eTest,"innerHTML",window.screen.width);//一直是1600 这个是分辨率 不是窗口的width
// var heightValueTest = dojo.window.getBox().h+"px";
// var widthValueTest = dojo.window.getBox().w;
// var widthValueStrTest = widthValueTest+"px";
// domAttr.set(eTest,"innerHTML",widthValueStrTest);
//测试 何时隐藏掉 导航栏 end
//设置 导航栏、登录按钮、导航栏横向标识、搜索框 隐藏 start 20150814
var widthValue = dojo.window.getBox().w;
var widthValueStr = widthValue+"px";
var screenWidth = window.screen.width;
if(screenWidth == "960"){//每行2个
if(widthValue<760){
this.displayNoneElementLayout();
}else{
this.displayBlockElementLayout();
}
if(widthValue<640){
this.displayNoneElementSearch();
}else{
this.displayBlockElementSearch();
}
}else if(screenWidth == "1024"){//每行3个
if(widthValue<740){
this.displayNoneElementLayout();
}else{
this.displayBlockElementLayout();
}
if(widthValue<640){
this.displayNoneElementSearch();
}else{
this.displayBlockElementSearch();
}
}else if(screenWidth == "1280"){//每行3个
if(widthValue<740){
this.displayNoneElementLayout();
}else{
this.displayBlockElementLayout();
}
if(widthValue<640){
this.displayNoneElementSearch();
}else{
this.displayBlockElementSearch();
}
}else if(screenWidth == "1360"){//每行3个
if(widthValue<740){
this.displayNoneElementLayout();
}else{
this.displayBlockElementLayout();
}
if(widthValue<640){
this.displayNoneElementSearch();
}else{
this.displayBlockElementSearch();
}
}else if(screenWidth == "1366"){//每行3个
if(widthValue<740){
this.displayNoneElementLayout();
}else{
this.displayBlockElementLayout();
}
if(widthValue<640){
this.displayNoneElementSearch();
}else{
this.displayBlockElementSearch();
}
}else if(screenWidth == "1440"){//每行4个
if(widthValue<740){
this.displayNoneElementLayout();
}else{
this.displayBlockElementLayout();
}
if(widthValue<640){
this.displayNoneElementSearch();
}else{
this.displayBlockElementSearch();
}
}else if(screenWidth == "1600"){//每行4个
if(widthValue<740){
this.displayNoneElementLayout();
}else{
this.displayBlockElementLayout();
}
if(widthValue<640){
this.displayNoneElementSearch();
}else{
this.displayBlockElementSearch();
}
}else if(screenWidth == "1680"){//每行4个
if(widthValue<740){
this.displayNoneElementLayout();
}else{
this.displayBlockElementLayout();
}
if(widthValue<640){
this.displayNoneElementSearch();
}else{
this.displayBlockElementSearch();
}
}else if(screenWidth == "1920"){//每行5个
if(widthValue<740){
this.displayNoneElementLayout();
}else{
this.displayBlockElementLayout();
}
if(widthValue<640){
this.displayNoneElementSearch();
}else{
this.displayBlockElementSearch();
}
}
//设置 导航栏、登录按钮 隐藏 end
var leftPanelDescHeight, containerHeight, innerLeftPanelHeight, tagContainerHeight, descHeight, descContainerHeight;
if (domClass.contains(query(".esriCTInnerLeftPanelBottom")[0], "esriCTInnerLeftPanelBottomShift")) {
innerLeftPanelHeight = dojo.window.getBox().h + "px";
domStyle.set(query(".esriCTInnerLeftPanelBottom")[0], "height", innerLeftPanelHeight);
}
if (dojo.configData.groupDescription) {
if (domStyle.get(query(".esriCTSignInIcon")[0], "display") !== "none") {
descHeight = window.innerHeight / 5;
leftPanelDescHeight = window.innerHeight - (domGeom.position(query(".esriCTMenuTab")[0]).h + domGeom.position(query(".esriCTInnerLeftPanelBottom")[0]).h - descHeight) + "px";
domStyle.set(query(".esriCTGroupDesc")[0], "height", leftPanelDescHeight);
}
}
containerHeight = (window.innerHeight - domGeom.position(query(".esriCTMenuTab")[0]).h - 20) + "px";
domStyle.set(query(".esriCTInnerRightPanel")[0], "height", containerHeight);
if (dojo.configData.groupDescription) {
if (domStyle.get(query(".esriCTSignInIcon")[0], "display") === "none") {
domClass.remove(query(".esriCTGroupDesc")[0], "esriCTLeftTextReadLess");
domStyle.set(query(".esriCTExpand")[0], "display", "none");
descContainerHeight = window.innerHeight - (domGeom.position(query(".esriCTGalleryNameSample")[0]).h + 100) + "px";
domStyle.set(query(".esriCTGroupDesc")[0], "height", descContainerHeight);
} else {
domStyle.set(query(".esriCTGroupDesc")[0], "height", "");
if (query(query(".esriCTGroupDesc")[0]).text().length > 400) {
domClass.add(query(".esriCTGroupDesc")[0], "esriCTLeftTextReadLess");
}
domStyle.set(query(".esriCTExpand")[0], "display", "block");
}
}
if (dojo.configData.values.showTagCloud) {
if (domClass.contains(query(".esriCTSignIn")[0], "displayNone")) {
tagContainerHeight = window.innerHeight - (domGeom.position(query(".sortByLabelMbl")[0]).h + domGeom.position(query(".esriCTCategoriesHeader")[0]).h + 40) + "px";
domStyle.set(query(".esriCTPadding")[0], "height", tagContainerHeight);
} else {
tagContainerHeight = window.innerHeight - (domGeom.position(query(".esriCTCategoriesHeader")[0]).h + domGeom.position(query(".esriCTMenuTab")[0]).h + domGeom.position(query(".esriCTInnerLeftPanelTop")[0]).h + 30) + "px";
domStyle.set(query(".esriCTPadding")[0], "height", tagContainerHeight);
}
}
}));
var panelHeight = (window.innerHeight - domGeom.position(query(".esriCTMenuTab")[0]).h - 20) + "px";
domStyle.set(query(".esriCTInnerRightPanel")[0], "height", panelHeight);
},
//这个地方是响应式!!! 原来如此 值得学习! end
displayNoneElementLayout:function(){
var layout = query(".esriCTLayout")[0];//布局(列表 格网)
layout.style.display = "none";
var sort = query(".esriCTSortViews")[0];//排序 使用 样式 来查找 元素
sort.style.display = "none";
},
displayBlockElementLayout:function(){
var layout = query(".esriCTLayout")[0];//布局(列表 格网)
layout.style.display = "block";
var sort = query(".esriCTSortViews")[0];//排序 使用 样式 来查找 元素
sort.style.display = "block";
},
displayNoneElementSearch:function(){
dom.byId("esriCTMenuTabTableId").style.display = "none";//搜索框
},
displayBlockElementSearch:function(){
dom.byId("esriCTMenuTabTableId").style.display = "block";//搜索框
},
/**
* Creates the gallery item pods
* @memberOf widgets/gallery/gallery
*/
createItemPods: function (itemResults, clearContainerFlag) {//clearContainerFlag是用来判断 是否清空itemPodsList(查询不到的时候就清空)
var i, divPodParentList, divPodParent;
if(itemResults.length != 0){//如果查询到结果
if (clearContainerFlag) {
domConstruct.empty(this.itemPodsList);
}
if (query(".esriCTShowMoreResults")[0]) {
if (itemResults.length < 100 || (itemResults.length === 100 && dojo.groupItems.length === 100)) {
domClass.replace(query(".esriCTShowMoreResults")[0], "displayNoneAll", "displayBlockAll");
} else {
domClass.replace(query(".esriCTShowMoreResults")[0], "displayBlockAll", "displayNoneAll");
}
}
for (i = 0; i < itemResults.length; i++) {
if (!dojo.gridView) {
// alert("进行list视图构造");
dom.byId("itemPodsListId").style.marginLeft = "244px";
divPodParentList = domConstruct.create('div', { "class": "esriCTApplicationListBox" }, this.itemPodsList);
this._createThumbnails(itemResults[i], divPodParentList);
this._createListItemOverviewPanel(itemResults[i], divPodParentList);
} else {
// alert("进行grid视图构造");
dom.byId("itemPodsListId").style.marginLeft = "0px";
//默认是 last 最后面 新创建的div 按顺序添加在应用的最后面。 !!! OK
divPodParent = domConstruct.create('div', { "class": "esriCTApplicationBox" }, this.itemPodsList);
this._createThumbnails(itemResults[i], divPodParent);
this._createGridItemOverview(itemResults[i], divPodParent);
}
}
// loadNavigatorEffect();//重新执行一遍 加载 导航效果的代码!!!!!!!!!!!
var t = dom.byId("mainOverFlowDiv");
//------------------不同分辨率下 横向导航、logo样式调整 start---------------------
var screenWidth = window.screen.width;
// banner样式 调整
var bannerElement = dom.byId("bannerImageDivId");// banner 元素
// 横向导航 元素 调整
var parentElement = dom.byId("esriCTMarkId");
// var itemPodsListElement = dom.byId("itemPodsListId");
if(screenWidth == "1024"){//每行3个
parentElement.style.width = "70%";
bannerElement.style.backgroundPosition = "50% 30%";//20150814
}else if(screenWidth == "1600"){//每行4个 图片的尾和应用的尾对齐
parentElement.style.width = "75.5%";//调整排序,视图 工具条 那行
bannerElement.style.backgroundPosition = "50% 30%";//20150814
}else if(screenWidth == "1920"){//每行6个 图片的头和应用的头对齐
parentElement.style.width = "78.8%";
bannerElement.style.backgroundPosition = "50% 30%";//20150814
}else if(screenWidth == "1680"){//每行5个
parentElement.style.width = "75.3%";
bannerElement.style.backgroundPosition = "50% 30%";//20150814
}else if(screenWidth == "1440"){//每行4个
parentElement.style.width = "66.8%";
bannerElement.style.backgroundPosition = "50% 30%";//20150814
}else if(screenWidth == "1366"){//每行4个
parentElement.style.width = "70.4%";
bannerElement.style.backgroundPosition = "50% 30%";//20150814
}else if(screenWidth == "1360"){//每行4个
parentElement.style.width = "70.8%";
bannerElement.style.backgroundPosition = "50% 30%";//20150814
}else if(screenWidth == "1280"){//每行4个
parentElement.style.width = "75.3%";
bannerElement.style.backgroundPosition = "50% 30%";//20150814
}else if(screenWidth == "960"){//每行2个
parentElement.style.width = "49.2%";
bannerElement.style.backgroundPosition = "50% 30%";//20150814
}
//------------------不同分辨率下 横向导航、logo样式调整 end---------------------
//部件 重新调整位置 start
//布局 部件
var layout = query(".esriCTLayout")[0];
layout.style.display = "block";
domConstruct.place(layout,parentElement);
var layoutTitle = dom.byId("layoutTitleId");
layoutTitle.style.color = "#919599";
//排序 部件
var sort = query(".esriCTSortViews")[0];//使用 样式 来查找 元素
sort.style.display = "block";
domConstruct.place(sort,parentElement);
//部件 重新调整位置 end
topic.publish("hideProgressIndicator");
//取消 进度条 wfh 20150805 start
// var spinner = dojo.spinData;
// spinner.stop();
doStopSpinner();
//取消 进度条 wfh 20150805 end
//增加顶部分界线 wfh 20160317 start
dom.byId("MenuTabId").style.borderBottom = "solid 1px #5ac8fa";
//增加顶部分界线 wfh 20160317 end
}
else{//如果未查询到结果
if (clearContainerFlag) {
domConstruct.empty(this.itemPodsList);//那么先清空 itemPodsList
}
if (!dojo.gridView) {
divPodParent = domConstruct.create('div', { "class": "esriCTApplicationBox" }, this.itemPodsList);
domAttr.set(divPodParent,"innerHTML","未查询到任何结果,请重新选择。");
} else {
divPodParent = domConstruct.create('div', { "class": "esriCTApplicationBox" }, this.itemPodsList);
domAttr.set(divPodParent,"innerHTML","未查询到任何结果,请重新选择。");
}
dojo.results = [];//20150811 wfh 用于修复 未查询到结果的情况下 点击 视图切换按钮 显示上次查询成功的 应用列表 的bug
// loadNavigatorEffect();//重新加载 导航栏鼠标移动上去的事件
topic.publish("hideProgressIndicator");
}
},
/**
* Create HTML for grid layout
* @memberOf widgets/gallery/gallery
*/
_createGridItemOverview: function (itemResult, divPodParent) {
var divItemTitleRight, divItemTitleText, divItemType, spanItemType, divItemWatchEye, spanItemWatchEyeText;
var divItemHref, detailItemHref, dividingLine,demoItemHref;
divItemTitleRight = domConstruct.create('div', { "class": "esriCTDivClear" }, divPodParent);
divItemTitleText = domConstruct.create('div', { "class": "esriCTListAppTitle esriCTGridTitleContent esriCTCursorPointer" }, divItemTitleRight);
domAttr.set(divItemTitleText, "innerHTML", (itemResult.title) || (nls.showNullValue));
domAttr.set(divItemTitleText, "title", (itemResult.title) || (nls.showNullValue));
divItemType = domConstruct.create('div', { "class": "esriCTGridItemType" }, divItemTitleRight);//display:none
spanItemType = domConstruct.create('div', { "class": "esriCTInnerGridItemType" }, divItemType);
domAttr.set(spanItemType, "innerHTML", (itemResult.type) || (nls.showNullValue));
domAttr.set(spanItemType, "title", (itemResult.type) || (nls.showNullValue));
//增加一行 详情 | Demo start--------------------用div
divItemHref = domConstruct.create('div',{"class":"esriCTGridItemHref"},divItemTitleRight);
detailItemHref = domConstruct.create('div',{"class":"esriCTListHref esriCTGridHref esriCTCursorPointer"},divItemHref);
domAttr.set(detailItemHref,"innerHTML",nls.detailItem);
dividingLine = domConstruct.create('div',{"class":"esriCTListHref esriCTGridHref esriCTCursorPointer"},divItemHref);
domAttr.set(dividingLine,"innerHTML",nls.dividingLine);
demoItemHref = domConstruct.create('div',{"class":"esriCTListHref esriCTGridHref esriCTCursorPointer"},divItemHref);
domAttr.set(demoItemHref,"innerHTML",nls.demoItem);
//构造 详细、打开时 也要控制 是否可以打开 start //20150812 wfh
if(itemResult.url == null){
demoItemHref.style.color = "gray";
demoItemHref.style.cursor = "not-allowed";
}else{//如果 url值 不为null 还得把样式 调整回来!
demoItemHref.style.color = "#5AC8FA";//原来的蓝色 esriCTListHref 里面的属性
demoItemHref.style.cursor = "pointer";
//只有 url 不为null的应用 才设置 click事件
this.own(on(demoItemHref, "click", lang.hitch(this, function () {
window.open(itemResult.url,'_blank');
// this.showInfoPage(this, itemResult, false);
})));
}
//构造 详细、打开时 也要控制 是否可以打开 end //20150812 wfh
this.own(on(detailItemHref, "click", lang.hitch(this, function () {
topic.publish("setDetailHeaderIcon");//设置详情页面的 HeaderIcon
this.showInfoPage(this, itemResult, true);
})));
//增加一行 详情 | Demo end--------------------
if (dojo.configData.values.showViews) {
divItemWatchEye = domConstruct.create('div', { "class": "esriCTEyeNumViews esriCTEyeNumViewsGrid" }, divItemType);
domConstruct.create('span', { "class": "esriCTEyeIcon icon-eye" }, divItemWatchEye);
spanItemWatchEyeText = domConstruct.create('span', { "class": "view" }, divItemWatchEye);
domAttr.set(spanItemWatchEyeText, "innerHTML", (itemResult.numViews >= 0) ? (number.format(parseInt(itemResult.numViews, 10))) : (nls.showNullValue));
domClass.add(spanItemType, "esriCTGridItemTypeViews");
} else {
domClass.add(spanItemType, "esriCTGridItemTypeNoViews");
}
this.own(on(divItemTitleText, "click", lang.hitch(this, function () {
topic.publish("setDetailHeaderIcon");//设置详情页面的 HeaderIcon
this.showInfoPage(this, itemResult, true);
})));
},
_showDetailPrepare:function(){
var applicationHeaderIconElement = dom.byId("applicationHeaderIconId");
if(window.screen.width == 1024){
// applicationHeaderIconElement.style.marginLeft = "132%";
}else if(window.screen.width == 1600){
// applicationHeaderIconElement.style.marginLeft = "68.5%";
applicationHeaderIconElement.style.marginLeft = "236px";
}else if(window.screen.width == 1920){
applicationHeaderIconElement.style.marginLeft = "249%";
}
else{
}
domClass.add(query(".esriCTLeftPanel")[0],"esriCTDisplayNone");
// topic.publish("showProgressIndicator");
},
_setDetailHeaderIcon:function(){
// 计算 根据 1600 下 236px 列方程计算! 我来了。是的 王院长的话意味深长 20150608星期一 start--------------
var applicationHeaderIconElement = dom.byId("applicationHeaderIconId");
var screenWidth = window.screen.width;
var setLeft;
setLeft = screenWidth*236/1600;
applicationHeaderIconElement.style.marginLeft = setLeft+"px";
},
_setInitialHeaderIcon:function(){
//进行返回 操作
// 计算 根据 1600 下 204px 列方程计算! 我来了。是的 20150608星期一 start--------------
// var applicationHeaderIconElement = dom.byId("applicationHeaderIconId");
// var screenWidth = window.screen.width;
// var setLeft;
// setLeft = screenWidth*204/1600;
// applicationHeaderIconElement.style.marginLeft = setLeft+"px";
// if(screenWidth == "1024"){//因为1024下 重新设计了!
// applicationHeaderIconElement.style.marginLeft = "75px";
// }
//因为是重新 设置了 导航栏的 位置 靠左 所以,好放了 离左面的距离是固定的了。
var applicationHeaderIconElement = dom.byId("applicationHeaderIconId");
applicationHeaderIconElement.style.marginLeft = "244px";
},
/**
* Create the thumbnails displayed for gallery items
* @memberOf widgets/gallery/gallery
*/
_createThumbnails: function (itemResult, divPodParent) {
var divThumbnail, divThumbnailImage, divTagContainer, divTagContent, dataType;
if (!dojo.gridView) {
divThumbnail = domConstruct.create('div', { "class": "esriCTImageContainerList" }, divPodParent);
} else {
divThumbnail = domConstruct.create('div', { "class": "esriCTImageContainer" }, divPodParent);
}
divThumbnailImage = domConstruct.create('div', { "class": "esriCTAppImage" }, divThumbnail);
if (itemResult.thumbnailUrl) {
domStyle.set(divThumbnailImage, "background", 'url(' + itemResult.thumbnailUrl + ') no-repeat center center');
} else {
domClass.add(divThumbnailImage, "esriCTNoThumbnailImage");
}
divTagContainer = domConstruct.create('div', { "class": "esriCTSharingTag" }, divThumbnailImage);
divTagContent = domConstruct.create('div', { "class": "esriCTTag" }, divTagContainer);
if (dojo.configData.values.displaySharingAttribute) {
this._accessLogoType(itemResult, divTagContent);
}
this.own(on(divThumbnailImage, "click", lang.hitch(this, function () {
topic.publish("setDetailHeaderIcon");//设置详情页面的 HeaderIcon
// topic.publish("showProgressIndicator");
this.showInfoPage(this, itemResult, true);
})));
},
/**
* Executed when user clicks on a item thumbnail or clicks the button on the item info page. It performs a query to fetch the type of the selected item.
* @memberOf widgets/gallery/gallery
*/
_showItemOverview: function (itemId, thumbnailUrl, itemResult, data) {
// alert("进入应用");//这个函数执行了两遍
var itemDetails, dataType, tokenString2, downloadPath, tokenString, itemUrl, defObject;
if (data) {
data.thumbnailUrl = thumbnailUrl;
dataType = data.type.toLowerCase();
if ((dataType === "map service") || (dataType === "web map") || (dataType === "feature service") || (dataType === "image service") || (dataType === "kml") || (dataType === "wms")) {
if ((dataType === "web map") && dojo.configData.values.mapViewer.toLowerCase() === "arcgis") {
topic.publish("hideProgressIndicator");
window.open(dojo.configData.values.portalURL + '/home/webmap/viewer.html?webmap=' + itemId, "_self");
} else {
itemDetails = new ItemDetails({ data: data });
itemDetails.startup();
}
if (dojo.downloadWindow) {
dojo.downloadWindow.close();
}
} else {
topic.publish("hideProgressIndicator");
if (data.url) {
dojo.downloadWindow.location = data.url;
} else if (data.itemType.toLowerCase() === "file" && data.type.toLowerCase() === "cityengine web scene") {
dojo.downloadWindow.location = dojo.configData.values.portalURL + "/apps/CEWebViewer/viewer.html?3dWebScene=" + data.id;
} else if (data.itemType.toLowerCase() === "file") {
if (dojo.configData.values.token) {
tokenString2 = "?token=" + dojo.configData.values.token;
} else {
tokenString2 = '';
}
downloadPath = dojo.configData.values.portalURL + "/sharing/content/items/" + itemId + "/data" + tokenString2;
dojo.downloadWindow.location = downloadPath;
} else if (dataType === "operation view" && data.itemType.toLowerCase() === "text") {
if (dojo.configData.values.token) {
tokenString = "&token=" + dojo.configData.values.token;
} else {
tokenString = '';
}
itemUrl = dojo.configData.values.portalURL + "/sharing/rest/content/items/" + data.id + "/data?f=json" + tokenString;
defObject = new Deferred();
topic.publish("queryItemInfo", itemUrl, defObject);
defObject.then(lang.hitch(this, function (result) {
if (dojo.configData.values.token) {
tokenString = "?token=" + dojo.configData.values.token;
} else {
tokenString = '';
}
if (result.desktopLayout) {
downloadPath = dojo.configData.values.portalURL + "/opsdashboard/OperationsDashboard.application?open=" + data.id;
dojo.downloadWindow.location = downloadPath;
} else if (result.tabletLayout) {
downloadPath = dojo.configData.values.portalURL + "/apps/dashboard/index.html#/" + data.id;
dojo.downloadWindow.location = downloadPath;
}
}));
} else {
alert(nls.errorMessages.unableToOpenItem);
if (dojo.downloadWindow) {
dojo.downloadWindow.close();
}
}
}
}
},
/**
* Create a tag on the thumbnail image to indicate the access type of the item
* @memberOf widgets/gallery/gallery
*/
_accessLogoType: function (itemResult, divTagContent) {
var title;
if (itemResult.access === "public") {
title = nls.allText;
} else if (itemResult.access === "org") {
title = nls.orgText;
} else {
title = nls.grpText;
}
if (divTagContent) {
domAttr.set(divTagContent, "innerHTML", title);
}
},
/**
* Create HTML for list layout
* @memberOf widgets/gallery/gallery
*/
_createListItemOverviewPanel: function (itemResult, divPodParent) {
var divContent, divTitle, divItemTitle, divItemTitleRight, divItemTitleText, divItemInfo, divItemType,
divRatings, numberStars, i, imgRating, divItemWatchEye, spanItemWatchEyeText, divItemContent,
divItemSnippet, spanItemReadMore, divEyeIcon;
var divItemHref, detailItemHref, dividingLine,demoItemHref;
divContent = domConstruct.create('div', { "class": "esriCTListContent" }, divPodParent);
divTitle = domConstruct.create('div', { "class": "esriCTAppListTitle" }, divContent);
divItemTitle = domConstruct.create('div', { "class": "esriCTAppListTitleRight" }, divTitle);
divItemTitleRight = domConstruct.create('div', { "class": "esriCTDivClear" }, divItemTitle);
divItemTitleText = domConstruct.create('div', { "class": "esriCTListAppTitle esriCTCursorPointer" }, divItemTitleRight);
domAttr.set(divItemTitleText, "innerHTML", (itemResult.title) || (nls.showNullValue));
divItemInfo = domConstruct.create('div', {}, divItemTitle);
divItemType = domConstruct.create('div', { "class": "esriCTListItemType" }, divItemInfo);//display:none
domAttr.set(divItemType, "innerHTML", (itemResult.type) || (nls.showNullValue));
//增加一行 详情 | Demo start--------------------用div
divItemHref = domConstruct.create('div',{"class":"esriCTGridItemHref"},divItemTitleRight);
detailItemHref = domConstruct.create('div',{"class":"esriCTListHref esriCTGridHref esriCTCursorPointer"},divItemHref);
domAttr.set(detailItemHref,"innerHTML",nls.detailItem);
dividingLine = domConstruct.create('div',{"class":"esriCTListHref esriCTGridHref esriCTCursorPointer"},divItemHref);
domAttr.set(dividingLine,"innerHTML",nls.dividingLine);
demoItemHref = domConstruct.create('div',{"class":"esriCTListHref esriCTGridHref esriCTCursorPointer"},divItemHref);
domAttr.set(demoItemHref,"innerHTML",nls.demoItem);
//构造 详细、打开时 也要控制 是否可以打开 start //20150812 wfh
if(itemResult.url == null){
demoItemHref.style.color = "gray";
demoItemHref.style.cursor = "not-allowed";
}else{//如果 url值 不为null 还得把样式 调整回来!
demoItemHref.style.color = "#5AC8FA";//原来的蓝色 esriCTListHref 里面的属性
demoItemHref.style.cursor = "pointer";
//只有 url 不为null的应用 才设置 click事件
this.own(on(demoItemHref, "click", lang.hitch(this, function () {
window.open(itemResult.url,'_blank');
// this.showInfoPage(this, itemResult, false);
})));
}
//构造 详细、打开时 也要控制 是否可以打开 end //20150812 wfh
this.own(on(detailItemHref, "click", lang.hitch(this, function () {
topic.publish("setDetailHeaderIcon");//设置详情页面的 HeaderIcon
this.showInfoPage(this, itemResult, true);
})));
//增加一行 详情 | Demo end--------------------
if (dojo.configData.values.showRatings) {
divRatings = domConstruct.create('div', { "class": "esriCTRatingsDiv" }, divItemInfo);
numberStars = Math.round(itemResult.avgRating);
for (i = 0; i < 5; i++) {
imgRating = document.createElement("span");
imgRating.value = (i + 1);
divRatings.appendChild(imgRating);
if (i < numberStars) {
domClass.add(imgRating, "icon-star esriCTRatingStarIcon esriCTRatingStarIconColor");
} else {
domClass.add(imgRating, "icon-star-empty esriCTRatingStarIcon esriCTRatingStarIconColor");
}
}
}
if (dojo.configData.values.showViews) {
divItemWatchEye = domConstruct.create('div', { "class": "esriCTEyeNumViews esriCTEyeNumViewsList" }, divItemInfo);
divEyeIcon = domConstruct.create('span', { "class": "esriCTEyeIcon icon-eye" }, divItemWatchEye);
if (dojo.configData.values.showRatings) {
domClass.add(divEyeIcon, "esriCTEyeIconPadding");
}
spanItemWatchEyeText = domConstruct.create('span', { "class": "view" }, divItemWatchEye);
domAttr.set(spanItemWatchEyeText, "innerHTML", (itemResult.numViews >= 0) ? (number.format(parseInt(itemResult.numViews, 10))) : (nls.showNullValue));
}
divItemContent = domConstruct.create('div', { "class": "esriCTListAppContentList" }, divContent);
divItemSnippet = domConstruct.create('div', { "class": "esriCTAppHeadline" }, divItemContent);
if (itemResult.snippet) {
spanItemReadMore = domConstruct.create('span', {}, divItemSnippet);
domAttr.set(spanItemReadMore, "innerHTML", itemResult.snippet);
}
this.own(on(divItemTitleText, "click", lang.hitch(this, function () {
topic.publish("setDetailHeaderIcon");//设置详情页面的 HeaderIcon
domClass.add(query(".esriCTLeftPanel")[0],"esriCTDisplayNone");
// topic.publish("showProgressIndicator");
this.showInfoPage(this, itemResult, true);
})));
},
showInfoPage: function (_self, itemResult, itemFlag) {
// alert("itemFlag:"+itemFlag+",,self:"+self);//window
var infoPage = new ItemInfoPage();
infoPage.displayPanel(itemResult, _self, itemFlag);
}
});
declare("ItemInfoPage", null, {
/**
* Create the HTML for item info page
* @memberOf widgets/gallery/gallery
*/
displayPanel: function (itemResult, _self, itemFlag) {
var numberOfComments, numberOfRatings, numberOfViews, itemReviewDetails, itemDescription, accessContainer, accessInfo, itemCommentDetails, itemViewDetails, itemText, containerHeight, dataArray, itemUrl, defObject, tokenString, dataType;
if (dojo.configData.values.token) {
tokenString = "&token=" + dojo.configData.values.token;
// alert(" if (dojo.configData.values.token:"+tokenString);//没进入
} else {
tokenString = '';
// alert("not if (dojo.configData.values.token:"+tokenString);//进入了
}
itemUrl = dojo.configData.values.portalURL + "/sharing/content/items/" + itemResult.id + "?f=json" + tokenString;
defObject = new Deferred();
defObject.then(lang.hitch(this, function (data) {
if (data) {
dataArray = {};
if (data.itemType === "file" && data.type.toLowerCase() !== "kml" && data.type.toLowerCase() !== "cityengine web scene") {//没进入
domAttr.set(_self.btnTryItNow, "innerHTML", nls.downloadButtonText);
domClass.add(_self.btnTryItNow, "esriCTDownloadButton");
} else if (data.type.toLowerCase() === "operation view") {//没进入
if (dojo.configData.values.token) {
tokenString = "&token=" + dojo.configData.values.token;
} else {
tokenString = '';
}
itemUrl = dojo.configData.values.portalURL + "/sharing/content/items/" + data.id + "/data?f=json" + tokenString;
defObject = new Deferred();
topic.publish("queryItemInfo", itemUrl, defObject);
defObject.then(lang.hitch(this, function (result) {
if (result.desktopLayout) {
domAttr.set(_self.btnTryItNow, "innerHTML", nls.downloadButtonText);
} else if (result.tabletLayout) {
domAttr.set(_self.btnTryItNow, "innerHTML", nls.tryItButtonText);
domAttr.set(_self.btnBackToAppViewNow, "innerHTML", nls.backToAppViewButtonText);//这行代码没进来
}
}));
} else {//进入了
domAttr.set(_self.btnTryItNow, "innerHTML", nls.tryItButtonText);
domAttr.set(_self.btnBackToAppViewNow, "innerHTML", nls.backToAppViewButtonText);//这行代码先起作用。
domClass.remove(_self.btnTryItNow, "esriCTDownloadButton");
//如果 item 没有 URL 值 就变黑,鼠标移动上去不变小手,而且不让打开 start //20150811 wfh
// if(itemResult.URL == null){ URL 不对
if(itemResult.url == null){
_self.btnTryItNow.style.color = "gray";//设置 打开 button 的颜色
_self.btnTryItNow.style.cursor = "not-allowed";//设置 打开 button 能否打开
// domAttr.set(_self.btnTryItNow, "color", "gray");
// domAttr.set(_self.btnTryItNow, "cursor", "not-allowed");// text no-drop default not-allowed
_self.appThumbnail.style.cursor = "not-allowed";//设置缩略图 能否打开 20150812
}else{//如果 url值 不为null 还得把样式 调整回来!
_self.btnTryItNow.style.color = "#007AC2";
_self.btnTryItNow.style.cursor = "pointer";
_self.appThumbnail.style.cursor = "pointer";
}
//如果 item 没有 URL 值 就变黑,鼠标移动上去不变小手,而且不让打开 end //20150811 wfh
}
dataArray = {
id: data.id,
itemType: data.itemType,
type: data.type,
url: data.url,
title: data.title,
description: data.description
};
if (itemFlag) {
this._createPropertiesContent(data, _self.detailsContent);
} else {
// alert("hello");
// aler("hello");//我说怎么不往下执行了! 原来是这里出错了!
_self._showItemOverview(itemResult.id, itemResult.thumbnailUrl, itemResult, dataArray);
}
/**
* if showComments flag is set to true in config file
*/
if (dojo.configData.values.showComments) {
this._createCommentsContainer(itemResult, _self.detailsContent);
}
}else{
alert("noData:"+data);
}
//隐藏 标题 指引 这行不能删
topic.publish("hideProgressIndicator");//通过发布 主题的方式 触发函数(触发订阅者的函数!!!如下,appHeader.js文件里有对该主题的订阅!!! 所以,会触发 相应的操作。)
// topic.subscribe("showProgressIndicator", lang.hitch(this, this.showProgressIndicator));
// topic.subscribe("hideProgressIndicator", lang.hitch(this, this.hideProgressIndicator));
}), function (err) {
alert(err.message);
topic.publish("hideProgressIndicator");
});
topic.publish("queryItemInfo", itemUrl, defObject);
if (itemFlag) {
// alert("itemFlag是什么?"+itemFlag); //true
//替换为小手形状(主页图标、各个小部件:搜索,排序...而中间的文本没有变成小手!!),但是主页图标 点击没有反应!
domClass.replace(query(".esriCTApplicationIcon")[0], "esriCTCursorPointer", "esriCTCursorDefault");
domClass.replace(query(".esriCTMenuTabLeft")[0], "esriCTCursorPointer", "esriCTCursorDefault");//中间的文本变小手
domClass.replace(query(".esriCTMenuTabRight")[0], "displayNoneAll", "displayBlockAll");//移除 标头panel 其它的部件(搜索,排序,布局,登录)
domClass.replace(query(".esriCTInnerRightPanel")[0], "displayNoneAll", "displayBlockAll");//这行注释掉后 进不去应用了。
domClass.remove(query(".esriCTInnerRightPanelDetails")[0], "displayNoneAll");//注释掉这行,进去应用 但是是空白 返回操作仍然可以。
//使用domConstruct.destroy可以销毁节点及其所有子节点,而domConstruct.empty则只销毁所给节点的子节点,其参数为DOM节点或节点的ID字符串。
domConstruct.empty(_self.detailsContent);//这两行是用来 销毁 描述的子节点的(里面有应用的描述内容,如果不销毁,下一个应用的描述不会更新!!)
domConstruct.empty(_self.ratingsContainer);
containerHeight = (window.innerHeight - domGeom.position(query(".esriCTMenuTab")[0]).h - 25) + "px";
domStyle.set(query(".esriCTInnerRightPanelDetails")[0], "height", containerHeight);
if (itemResult.thumbnailUrl) {
domClass.remove(_self.appThumbnail, "esriCTNoThumbnailImage");
domStyle.set(_self.appThumbnail, "background", 'url(' + itemResult.thumbnailUrl + ') no-repeat center center');
} else {
domClass.add(_self.appThumbnail, "esriCTNoThumbnailImage");
}
domAttr.set(_self.applicationType, "innerHTML", (itemResult.type) || (nls.showNullValue));
domAttr.set(_self.applicationAPI, "innerHTML", (itemResult.typeKeywords[0]) || (nls.showNullValue));
// domAttr.set(_self.applicationTwoDCode, "innerHTML", (itemResult.typeKeywords[0]) || (nls.showNullValue));
//拼接 二维码 图片 地址 start
//如果 标签里有 “二维码” 这个标签 就拼接 二维码图片地址,并显示 手机扫一扫 这5个字 否则 就隐藏掉 手机扫一扫 这5个字
var phoneScanElement = dom.byId("phoneScanId");
var tagsArray = itemResult.tags;
if(tagsArray.indexOf("二维码") != -1){
phoneScanElement.style.display = "block";
}else{
phoneScanElement.style.display = "none";
}
var itemTitle = itemResult.title;
var backgroundImageVar = 'http://solutions.arcgisonline.cn/portal/home/images/qrcode/'+itemTitle+'.png';
var backgroundImageVarNew = encodeURI(backgroundImageVar);//对字符串 进行编码! 20150821 星期五 wfh
var backgroundImageElement = dom.byId("applicationTwoDCodeId");
backgroundImageElement.style.backgroundImage = 'url('+backgroundImageVarNew+')';
backgroundImageElement.style.color = "blue";
//拼接 二维码 图片 地址 end
domAttr.set(_self.appTitle, "innerHTML", itemResult.title || "");
if (dojo.configData.values.showViews) {
numberOfComments = (itemResult.numComments) || "0";
numberOfRatings = (itemResult.numRatings) || "0";
numberOfViews = (itemResult.numViews) ? (number.format(parseInt(itemResult.numViews, 10))) : "0";
if (dojo.configData.values.showComments) {
itemCommentDetails = numberOfComments + " " + nls.numberOfCommentsText + ", ";
} else {
itemCommentDetails = "";
}
if (dojo.configData.values.showRatings) {
itemReviewDetails = numberOfRatings + " " + nls.numberOfRatingsText + ", ";
} else {
itemReviewDetails = "";
}
itemViewDetails = numberOfViews + " " + nls.numberOfViewsText;
itemText = "(" + itemCommentDetails + itemReviewDetails + itemViewDetails + ")";
domAttr.set(_self.numOfCommentsViews, "innerHTML", itemText);
}
domAttr.set(_self.itemSnippet, "innerHTML", itemResult.snippet || "");
//动态生成 描述
domConstruct.create('div', { "class": "esriCTReviewHeader", "innerHTML": nls.appDesText }, _self.detailsContent);
itemDescription = domConstruct.create('div', { "class": "esriCTText esriCTReviewContainer esriCTBottomBorder" }, _self.detailsContent);
if (dojo.configData.values.showLicenseInfo) {
accessContainer = domConstruct.create('div', { "class": "esriCTReviewContainer esriCTBottomBorder" }, _self.detailsContent);
domConstruct.create('div', { "class": "esriCTReviewHeader", "innerHTML": nls.accessConstraintsText }, accessContainer);
accessInfo = domConstruct.create('div', { "class": "esriCTText" }, accessContainer);
domAttr.set(accessInfo, "innerHTML", itemResult.licenseInfo || "");
}
domAttr.set(_self.btnTryItNow, "innerHTML", "");//先设置 为 ""
this._createItemDescription(itemResult, _self, itemDescription);
if (_self._btnTryItNowHandle) {
/** 再移除监听
* remove the click event handler if it already exists, to prevent the binding of the event multiple times
*/
_self._btnTryItNowHandle.remove();
}
//移除 返回应用视图 按钮 的 监听事件 事件也是属性! start
// if (_self.btnBackToAppViewNow) {
// /**这个就把 按钮移除了!!!!!!!!!!!!!!!!
// * remove the click event handler if it already exists, to prevent the binding of the event multiple times
// */
// _self.btnBackToAppViewNow.remove();
// }
if (_self._btnBackToAppViewNowHandle) {
/**
* remove the click event handler if it already exists, to prevent the binding of the event multiple times
*/
_self._btnBackToAppViewNowHandle.remove();
}
//移除 返回应用视图 按钮 的 监听事件 end
//详细页面中 控制 打开button是否添加click事件 start //20150812 wfh
if(itemResult.url == null){
}else{
dataType = itemResult.type.toLowerCase();
_self._btnTryItNowHandle = on(_self.btnTryItNow, "click", lang.hitch(this, function () {
if ((domAttr.get(_self.btnTryItNow, "innerHTML") === nls.downloadButtonText) || ((dataType !== "map service") && (dataType !== "web map") && (dataType !== "feature service") && (dataType !== "image service") && (dataType !== "kml") && (dataType !== "wms"))) {
dojo.downloadWindow = window.open('', "_blank");
}
this._showTryItNowView(_self.btnTryItNow, itemResult, _self, dataArray);
}));
}
//详细页面中 控制 打开button是否添加click事件 end //20150812 wfh
//添加 返回应用视图的 点击事件 start
_self._btnBackToAppViewNowHandle = on(_self.btnBackToAppViewNow, "click", lang.hitch(this, function () {
//下面这个if判断执行了!!! 先去掉
// if ((domAttr.get(_self.btnBackToAppViewNow, "innerHTML") === nls.downloadButtonText) || ((dataType !== "map service") && (dataType !== "web map") && (dataType !== "feature service") && (dataType !== "image service") && (dataType !== "kml") && (dataType !== "wms"))) {
// dojo.downloadWindow = window.open('', "_blank");
// }
topic.publish("setInitialHeaderIcon");//重新设置 HeaderIcon
domClass.remove(query(".esriCTLeftPanel")[0],"esriCTDisplayNone");
if (query(".esriCTitemDetails")[0]) {
// alert("不用返回query(.esriCTitemDetails)[0]:"+query(".esriCTitemDetails")[0]);
dojo.destroy(query(".esriCTitemDetails")[0]);
domClass.remove(query(".esriCTGalleryContent")[0], "displayNoneAll");
domClass.remove(query(".esriCTApplicationIcon")[0], "esriCTCursorPointer");
domClass.remove(query(".esriCTMenuTabLeft")[0], "esriCTCursorPointer");
}
if (query(".esriCTInnerRightPanelDetails")[0] && (!query(".esriCTNoResults")[0])) {
// alert("返回query(.esriCTInnerRightPanelDetails)[0]:"+query(".esriCTInnerRightPanelDetails")[0]+",,,"+"query(.esriCTNoResults)[0]):"+query(".esriCTNoResults")[0]);
domClass.replace(query(".esriCTMenuTabRight")[0], "displayBlockAll", "displayNoneAll");
domClass.add(query(".esriCTInnerRightPanelDetails")[0], "displayNoneAll");
domClass.remove(query(".esriCTGalleryContent")[0], "displayNoneAll");
domClass.remove(query(".esriCTInnerRightPanel")[0], "displayNoneAll");
domClass.remove(query(".esriCTApplicationIcon")[0], "esriCTCursorPointer");
domClass.remove(query(".esriCTMenuTabLeft")[0], "esriCTCursorPointer");
}
}));
//添加 返回应用视图的 点击事件 end
if (_self._appThumbnailClickHandle) {
/**
* remove the click event handler if it already exists, to prevent the binding of the event multiple times
*/
_self._appThumbnailClickHandle.remove();
}
//详细页面中 控制 缩略图 是否添加click事件 start //20150812 wfh
if(itemResult.url == null){
}else{
_self._appThumbnailClickHandle = on(_self.appThumbnail, "click", lang.hitch(this, function () {
if ((dataType !== "map service") && (dataType !== "web map") && (dataType !== "feature service") && (dataType !== "image service") && (dataType !== "kml") && (dataType !== "wms")) {
dojo.downloadWindow = window.open('', "_blank");
}
this._showTryItNowView(_self.appThumbnail, itemResult, _self, dataArray);
}));
}
//详细页面中 控制 缩略图 是否添加click事件 end //20150812 wfh
}else{
}
},
_showTryItNowView: function (container, itemResult, _self, dataArray) {
var itemId, thumbnailUrl;
// topic.publish("showProgressIndicator");
itemId = domAttr.get(container, "selectedItem");
thumbnailUrl = domAttr.get(container, "selectedThumbnail");
_self._showItemOverview(itemId, thumbnailUrl, itemResult, dataArray);
},
/**
* Extract the item info (tags, extent) and display it in the created properties container
* @memberOf widgets/gallery/gallery
*/
_createPropertiesContent: function (itemInfo, detailsContent) {
var tagsContent, i, itemTags, sizeContent, itemSizeValue, itemSize, tagsContainer, sizeContainer;
tagsContainer = domConstruct.create('div', { "class": "esriCTReviewContainer esriCTBottomBorder" }, detailsContent);
// wfh 5 5.1 标签
// domConstruct.create('div', { "innerHTML": nls.tagsText, "class": "esriCTReviewHeader" }, tagsContainer);
// tagsContent = domConstruct.create('div', {}, tagsContainer);
// for (i = 0; i < itemInfo.tags.length; i++) {
// if (i === 0) {
// itemTags = itemInfo.tags[i];
// } else {
// itemTags = itemTags + ", " + itemInfo.tags[i];
// }
// }
// domConstruct.create('div', { "class": "esriCTText", "innerHTML": itemTags }, tagsContent);
// sizeContainer = domConstruct.create('div', { "class": "esriCTReviewContainer esriCTBottomBorder" }, detailsContent);
// wfh 5 5.2 大小
// domConstruct.create('div', { "class": "esriCTReviewHeader", "innerHTML": nls.sizeText }, sizeContainer);
// sizeContent = domConstruct.create('div', {}, sizeContainer);
// if (itemInfo.size > 1048576) {
// itemSizeValue = itemInfo.size / 1048576;
// itemSize = Math.round(itemSizeValue) + " " + nls.sizeUnitMB;
// } else {
// itemSizeValue = itemInfo.size / 1024;
// itemSize = Math.round(itemSizeValue) + " " + nls.sizeUnitKB;
// }
// domConstruct.create('div', { "class": "esriCTText", "innerHTML": itemSize }, sizeContent);
},
/**
* Create the item description container
* @memberOf widgets/gallery/gallery
*/
_createItemDescription: function (itemResult, _self, itemDescription) {
var numberStars, i, imgRating;
domAttr.set(itemDescription, "innerHTML", itemResult.description || "");
domAttr.set(_self.itemSubmittedBy, "innerHTML", (itemResult.owner) || (nls.showNullValue));
/**
* if showRatings flag is set to true in config file
*/
if (dojo.configData.values.showRatings) {
numberStars = Math.round(itemResult.avgRating);
for (i = 0; i < 5; i++) {
imgRating = document.createElement("span");
imgRating.value = (i + 1);
_self.ratingsContainer.appendChild(imgRating);
if (i < numberStars) {
domClass.add(imgRating, "icon-star esriCTRatingStarIcon esriCTRatingStarIconColor");
} else {
domClass.add(imgRating, "icon-star-empty esriCTRatingStarIcon esriCTRatingStarIconColor");
}
}
}
domAttr.set(_self.btnTryItNow, "selectedItem", itemResult.id);
domAttr.set(_self.btnTryItNow, "selectedThumbnail", itemResult.thumbnailUrl);
domAttr.set(_self.appThumbnail, "selectedItem", itemResult.id);
domAttr.set(_self.appThumbnail, "selectedThumbnail", itemResult.thumbnailUrl);
},
/**
* Query the item to fetch comments and display the data in the comments container displayed on the item info page
* @memberOf widgets/gallery/gallery
*/
_createCommentsContainer: function (itemResult, detailsContent) {
var reviewContainer = domConstruct.create('div', { "class": "esriCTReviewContainer esriCTBottomBorder" }, detailsContent);
domConstruct.create('div', { "class": "esriCTReviewHeader", "innerHTML": nls.reviewText }, reviewContainer);
itemResult.getComments().then(function (result) {
var i, divReview, divReviewHeader, divReviewText, comment;
if (result.length > 0) {
for (i = 0; i < result.length; i++) {
divReview = domConstruct.create('div', { "class": "esriCTReview" }, reviewContainer);
divReviewHeader = domConstruct.create('div', { "class": "esriCTReviewBold" }, divReview);
divReviewText = domConstruct.create('div', { "class": "esriCTReviewText esriCTBreakWord" }, divReview);
domAttr.set(divReviewHeader, "innerHTML", (result[i].created) ? (result[i].created.toLocaleDateString()) : (nls.showNullValue));
try {
comment = decodeURIComponent(result[i].comment);
} catch (e) {
comment = unescape(result[i].comment);
}
domAttr.set(divReviewText, "innerHTML", (result[i].comment) ? comment : (nls.showNullValue));
}
} else {
divReview = domConstruct.create('div', { "class": "esriCTDivClear" }, reviewContainer);
domConstruct.create('div', { "class": "esriCTBreakWord" }, divReview);
}
}, function () {
var divReview;
divReview = domConstruct.create('div', { "class": "esriCTDivClear" }, reviewContainer);
domConstruct.create('div', { "class": "esriCTBreakWord" }, divReview);
});
}
});
});
<file_sep>/**
* Created by Esri on 16-4-27.
* 文件夹的相关操作
*/
define('widgets/portalRestApi/Content/folderOperation', [null], function () {
var WidgetFolderOperation = function () {
var _self = this;
};
WidgetFolderOperation.prototype = {
//需要token。
doCreateFolder:function(url,username,folderName,token){
var _self = this;
var deferredObj = $.ajax({
type: "POST",
url: url + "/sharing/rest/content/users/"+username+"/createFolder",
data: {
folderName:folderName,
title:folderName,
f : "json",
token : token
},
dataType:"json"//dataType不能少
});
return deferredObj;
}
};
return WidgetFolderOperation;
}); | 2a6087181bd71b03824052c2f07727a9a1b6825b | [
"JavaScript",
"Markdown"
]
| 6 | JavaScript | JustinZhangGIS/Dev2016Web3Ddemo | 7cffdbb99b23d9f3ee812bb60d5d8d2a48557882 | d3b5dc1b0bce61e40c2e73448096498134732daf |
refs/heads/master | <file_sep>import {Component, forwardRef, Input, OnChanges, OnInit} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALIDATORS, NG_VALUE_ACCESSOR} from '@angular/forms';
import {PeacockSharedService} from '../../../services/peacockShared.service';
@Component({
selector: 'pe-switch',
templateUrl: './inputswitch.component.html',
providers: [
PeacockSharedService,
{provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => InputSwitchComponent), multi: true},
{provide: NG_VALIDATORS, useExisting: forwardRef(() => InputSwitchComponent), multi: true}
]
})
export class InputSwitchComponent implements OnInit, ControlValueAccessor, OnChanges {
/**
* On label switch
* @type {string}
*/
@Input() onLabel = 'ON';
/**
* Off label switch
* @type {string}
*/
@Input() offLabel = 'OFF';
/**
* Input label
* @type {string}
*/
@Input() inputLabel;
/**
* Id of the filter input
* @type {string}
*/
public randomId = '';
/**
* Switch input value
* @type {boolean}
* @private
*/
private _switchValue = false;
get switchValue() {
return this._switchValue;
}
set switchValue(value) {
this._switchValue = (value == true);
this.emitValueChange();
}
/**
* Propagate change for Model
*/
propagateChange: any = () => {};
/**
* Validation Function for the model
*/
validateFn: any = () => {};
/**
* On touch element dropdown
*/
onTouched = () => {};
constructor(private peacockSharedService: PeacockSharedService) {
this.randomId = 'switch-' + this.peacockSharedService.makeRandomString();
}
ngOnInit() {
}
/**
* Emit change value
*/
emitValueChange() {
this.propagateChange(this.switchValue);
}
/**
* emit value when the dropdown value was changed
*/
ngOnChanges() {
this.emitValueChange();
}
/**
* Writ the value in the ngModel
* @param value
*/
writeValue(value) {
if (value) {
this.switchValue = value;
}
}
/**
* Register changes (send to ngModel)
* @param fn
*/
registerOnChange(fn) {
this.propagateChange = fn;
}
/**
* Register changes when element touched
* @param fn
*/
registerOnTouched(fn) {
this.onTouched = fn;
}
/**
* Validate control ngModel
* @param {FormControl} c
* @return {any}
*/
validate(c: FormControl) {
return this.validateFn(c);
}
}
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
@Component({
selector: 'pe-confirm-modal',
templateUrl: './confirm-modal.component.html'
})
export class ConfirmModalComponent implements OnInit {
/**
* (two way binding) output for data
* @type {EventEmitter<any>}
*/
@Output() visibleChange = new EventEmitter();
/**
* To show or hide the modal
* @type {boolean}
*/
private _visible = false;
@Input()
get visible() {
return this._visible;
}
set visible(value) {
this._visible = value;
this.visibleChange.emit(this.visible);
}
/**
* Title of the modal
* @type {string}
*/
@Input()
modalTitle = '';
/**
* custom Style class for the modal
* @type {string}
*/
@Input()
styleClass = '';
/**
* To show or hide the close button
* @type {boolean}
*/
@Input()
closable = true;
/**
* Event to emitter (CANCEL or CONFIRM)
*/
@Output()
event = new EventEmitter();
/**
* Label for cancel button
* @type {string}
*/
@Input()
cancelLabel = 'Cancel';
/**
* Label for cancel button
* @type {string}
*/
@Input()
confirmLabel = 'Confirm';
constructor() {
}
ngOnInit() {
}
/**
* close the modal
*/
closeModal() {
this.visible = false;
}
/**
* Function to emit the value of the action Buttons
* @param action
*/
actionClick(action) {
this.event.emit({action: action});
this.closeModal();
}
}
<file_sep>import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'dropdownFilter'
})
export class DropdownFilterPipe implements PipeTransform {
transform(value: any, args?: any): any {
if (!value) {
return [];
}
if (!args || args == '') {
return value;
}
args = args.toLowerCase();
return value.filter( it => {
return it.option.label.toLowerCase().includes(args);
});
}
}
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
@Component({
selector: 'pe-table',
templateUrl: './table.component.html'
})
export class BasicTableComponent implements OnInit {
/**
* input Cols data
* (sample) => [ {field : 'firstName', header: '<NAME>'}, {field : 'lastName', header: '<NAME>'} ... ]
* @type {Array}
*/
private _cols: any = [];
@Input()
set cols(cols: any) {
for (let col of cols) {
if (!col.sort) {
cols['sort'] = null;
}
}
this._cols = cols;
}
get cols(): any {
return this._cols;
}
/**
* Input data of table
* (sample) => [ {lastName : '<NAME>', firstName: '<NAME>'}, ... ]
* @type {Array}
*/
// @Input() data: any = [];
private _data: any = [];
private backUpData: any = [];
@Input()
set data(data: any) {
this._data = data;
this.backUpData = data;
this.totalItems = data.length; // set the total items variable to length of data
}
get data(): any {
return this._data;
}
/**
* Action object : to show action for each row
* (sample) => [
* {
* label: 'modifier',
* icon: 'fa fa-edit',
* classStyle: 'btn btn-pill btn-warning',
* when: {
* field: 'firstName',
* value: 'sabri',
* operator: '=='
* }
* }
* ]
* @type {any}
*/
@Input() actionCol = null;
/**
* Event to emitted
* @type {EventEmitter<any>}
*/
@Output() event = new EventEmitter();
/**
* Input class name of table
* @type {string}
*/
@Input() class = 'table table-striped';
/**
* true or false to show the paginator of table
* @type {boolean}
*/
private _pagination = true;
@Input()
set pagination(pagination: boolean) {
this._pagination = pagination;
if (!pagination) {
this.itemsPerPage = this.data.length;
}
}
get pagination(): boolean {
return this._pagination;
}
/**
* Items Per Page for the pagination (Default is 10)
* @type {number}
*/
private _itemsPerPage = 10;
@Input()
set itemsPerPage(value) {
if (!this.pagination) {
this._itemsPerPage = this.data.length;
} else {
this._itemsPerPage = value;
}
}
get itemsPerPage() {
return this._itemsPerPage;
}
/**
* Array to show items per page
* @type {[number , number , number]}
*/
@Input() arrayItemsPerPage = [10, 15, 20, 25];
/**
* Next label pagination
* @type {string}
*/
@Input() nextLabel = 'Next';
/**
* Previous Label pagination
* @type {string}
*/
@Input() previousLabel = 'Previous';
/**
* Show item per page Label
* @type {string}
*/
@Input() showItemPerPageLabel = 'Show';
/**
* Label showed when the data is empty
* @type {string}
*/
@Input() emptyDataLabel = 'Data is empty !!';
/**
* Label for total element in the table
* @type {string}
*/
@Input() totalLabel = 'Total : ';
/**
* The current page
* @type {number}
*/
public currentPage = 1;
/**
* Total elements in data
* @type {number}
*/
public totalItems = 0;
constructor() {
}
ngOnInit() {
}
/**
* Get the row/cols Data from object
* (sample) if colField is composed "car.color" then return the data col of car color
* @param row
* @param colField
* @return {any}
*/
getColData(row, colField) {
if (colField.indexOf('.') > -1) {
let itm = row;
for (let i of colField.split('.')) {
itm = itm[i];
}
return itm.toString();
} else {
return row[colField].toString();
}
}
/**
* check the condition and return
* true : if the condition applied or you don't have a condition
* fasle : if not
* If the condition don't have a operator by default is "=="
* @param row
* @param conditions [{ paramValue: 'the value to will be compared', value: 'the Value to be checked', operator: '==' }, { field: 'theFieldName', value: 'the Value to be checked', operator: '==' }]
* @return {boolean}
*/
isShowed(row, conditions) {
if (conditions) {
let conditionToEvaluate = '';
for (let i = 0; i < conditions.length; i++) {
// if the condition dont have an opearator
if (!conditions[i].operator) {
conditions[i].operator = '==';
}
// add and opeartor if you have multiple condition
if (i > 0) {
conditionToEvaluate += ' && ';
}
let data;
// if is a field of the object
if (conditions[i].field) {
data = this.getColData(row, conditions[i].field);
}
// if is a simple condition (from out value)
if (conditions[i].paramValue) {
data = conditions[i].paramValue;
}
conditionToEvaluate += '\'' + data + '\'' + conditions[i].operator + '\'' + conditions[i].value + '\'';
}
return eval(conditionToEvaluate);
} else {
return true;
}
}
/**
* Emit the event action and the row data
* @param row
* @param action
*/
actionClick(row, action) {
this.event.emit({data: row, action: action});
}
/**
* Sort the dynamic object array
* @param field
*/
sort(field) {
this.data = this.backUpData;
this.data.sort(this.dynamicSortArray(field, this.processSort(field)));
}
/**
* check the sort ASC or DESC for field in parameters and set the others fields to null
* transform the sort from (ASC to DESC) or (DESC to ASC) for a field in parameters
* return null if not fund any element
* return true if the sort will be ascendant (ASC)
* return false if the sort will be descendant (DESC)
* @param field
* @return {any}
*/
processSort(field) {
let res = null;
for (let i = 0; i < this.cols.length; i++) {
// search the cols for field in parameters else sort will be null
if (this.cols[i].field == field) {
if (this.cols[i].sort != null) {
// if sort 'asc' then will be 'desc' or inverse
if (this.cols[i].sort == 'asc') {
this.cols[i].sort = 'desc';
res = false;
} else {
this.cols[i].sort = 'asc';
res = true;
}
} else {
// if the sort is null will be by default 'asc'
this.cols[i].sort = 'asc';
res = true;
}
} else {
this.cols[i].sort = null;
}
}
return res;
}
/**
* sort dynamic array of element
* @param property
* @returns {(a, b) => number}
*/
dynamicSortArray(property, ascending) {
let _this = this;
let sortOrder = 1;
if (!ascending) {
sortOrder = -1;
}
return function (a, b) {
let result = (_this.getColData(a, property).toString().toLowerCase() < _this.getColData(b, property).toString().toLowerCase()) ? -1 : (_this.getColData(a, property).toString().toLowerCase() > _this.getColData(b, property).toString().toLowerCase()) ? 1 : 0;
return result * sortOrder;
};
}
/**
* Page is changed event
* @param event
*/
pageChanged(event) {
this.currentPage = event;
}
}
<file_sep>import {Component, EventEmitter, forwardRef, Input, OnChanges, OnInit, Output, Renderer2} from '@angular/core';
import {PeacockSharedService} from '../../../services/peacockShared.service';
import {ControlValueAccessor, FormControl, NG_VALIDATORS, NG_VALUE_ACCESSOR} from '@angular/forms';
@Component({
selector: 'pe-dropdown',
templateUrl: './dropdown-form.component.html',
providers: [
PeacockSharedService,
{provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => DropdownFormComponent), multi: true},
{provide: NG_VALIDATORS, useExisting: forwardRef(() => DropdownFormComponent), multi: true}
]
})
export class DropdownFormComponent implements OnInit, ControlValueAccessor, OnChanges {
/**
* Id of the filter input
* @type {string}
*/
public randomId = '';
/**
* to show or hide the options list
* @type {boolean}
*/
public dropdownActive = false;
/**
* show the filter input
* @type {boolean}
*/
@Input() filtered = false;
/**
* select multiple
* @type {boolean}
*/
@Input() multiple = false;
/**
* Filter input text placeholder label
* @type {string}
*/
@Input() filterLabel = 'Filter';
/**
* Label selected items
* @type {string}
*/
@Input() selectedItemLabel = 'Items Selected';
/**
* default text for select input
* @type {string}
*/
public _tmpPlaceholder: any = '';
@Input() placeholder: any = '';
/**
* Options list
* Sample : [ {label : 'my label', value: 'my-value'}, ... ]
* @type {Array}
*/
private _options = [];
@Input()
get options() {
return this._options;
}
set options(value) {
this._options = value;
this.initDropdown();
}
/**
* Event to emitted when you select an item from the list
* @type {EventEmitter<any>}
*/
@Output() selected = new EventEmitter();
/**
* Event to emitte when the item is deleted from the selected list
* @type {EventEmitter<any>}
*/
@Output() deleted = new EventEmitter();
/**
* (two way binding) output for value
* @type {EventEmitter<any>}
*/
@Output() valueChange = new EventEmitter();
/**
* selected values
* @type {any}
* @private
*/
private _value: any = {};
@Input()
/**
* Get the selected value
* @return {any}
*/
get value() {
return this._value;
}
/**
* Set the selected value
* @param val
*/
set value(val) {
this._value = val;
// 1- Emit the event value
this.emitValueChange();
// 2- init the dropdown
this.initDropdown();
}
/**
* list of all options with value is selected or not
* sample : [ {option: options-from-Input-Options, selected : true/false, index : 0}, ....]
* @type {Array}
*/
public dropdownOptions = [];
/**
* Selected Items
* @type {Array}
*/
public selectedItems = [];
/**
* Filter value for input
* @type {string}
*/
public filter = '';
/**
* Propagate change for Model
*/
propagateChange: any = () => {};
/**
* Validation Function for the model
*/
validateFn: any = () => {};
/**
* On touch element dropdown
*/
onTouched = () => {};
constructor(private peacockSharedService: PeacockSharedService, private renderer: Renderer2) {
this.randomId = 'filter-' + this.peacockSharedService.makeRandomString();
}
ngOnInit() {
}
/**
* Init dropdown attributes
*/
initDropdown() {
this.dropdownOptions = [];
this.selectedItems = [];
this._tmpPlaceholder = [];
// 1- init the selected array from option list and add selected status and index in the list
for (let i = 0; i < this.options.length; i++) {
let item: any = {
option: this.options[i],
selected: this.isSelected(this.options[i]),
index: i
};
this.dropdownOptions.push(item);
// add to selected item
if (item.selected) {
this._tmpPlaceholder.push(item.option.label);
this.selectedItems.push(item);
}
}
}
/**
* Return if element Value in selected value or not
* @param elementValue
* @return {boolean}
*/
isSelected(element) {
if (this.value.constructor === [].constructor) {
// if the value is array type (multiple select)
for (let item of this.value) {
// compare two element
if (this.peacockSharedService.isEqual(item, element.value)) {
return true;
}
}
// return false if not fund in value list
return false;
} else if (this.value.constructor === ''.constructor || !isNaN(this.value)) {
// if the value is string type (single select)
if (this.value === element.value) {
// this._tmpPlaceholder = element.label;
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* Open and close the dropdown
*/
openCloseDropdown() {
this.dropdownActive = !this.dropdownActive;
setTimeout(() => {
if (this.filtered) {
let elementToFocus = this.randomId;
// elementToFocus += '-list';
let onElement = this.renderer.selectRootElement('#input_filter-' + elementToFocus);
onElement.focus();
}
}, 200);
}
/**
* Close the dropdown
*/
closeDropdown() {
setTimeout(() => {
this.dropdownActive = false;
}, 200);
}
/**
* Build the value array if the dropdown is multiple select
* Build the array label (_tmpPlaceholder)
*/
buildValue() {
this._value = [];
this._tmpPlaceholder = [];
this.selectedItems = [];
for (let item of this.dropdownOptions) {
if (item.selected) {
this._value.push(this.options[item.index].value);
this._tmpPlaceholder.push(this.options[item.index].label);
this.selectedItems.push(item);
}
}
}
removeItem(option) {
// 1- Deselect item
this.dropdownOptions[option.index].selected = false;
// 2- build value list
this.buildValue();
// 3- Reset dropdown
this.initDropdown();
// 4- Emit the event value
this.emitValueChange();
// 5- Send event for DELETED item
this.deleted.emit(this.dropdownOptions[option.index].option);
}
/**
* Select item from list
* @param option
*/
selectItem(option) {
// let selectedIndex = this.searchOption(option.value);
let selectedIndex = option.index;
// 1- Close the dropdown list
this.openCloseDropdown();
// 2- check if the dropdown is multiple select or simple
if (this.multiple) {
// 2.1- if item selected is not selected before giv him true else false
this.dropdownOptions[selectedIndex].selected = !option.selected;
// 2.2- build the array value from selected items
this.buildValue();
// 2.3- reset dropdown
this.initDropdown();
} else {
// 2.1- set the selected value
this._value = option.option.value;
// 2.2- reset Dropdown
this.initDropdown();
// 2.3- replace text place holder with the selected label
this.placeholder = option.option.label;
}
// 3- Emit the event value
this.emitValueChange();
// 4- Send event for selected item
this.selected.emit(this.dropdownOptions[selectedIndex].option);
}
/**
* Emit change value
*/
emitValueChange() {
this.valueChange.emit(this.value);
this.propagateChange(this.value);
}
/**
* emit value when the dropdown value was changed
*/
ngOnChanges() {
// // 1- If multiple appliyed required dropdown
// if (this.multiple) {
// // this.validateFn = requiredDropdown();
// }
// 2- emit changes value
this.emitValueChange();
}
/**
* Writ the value in the ngModel
* @param value
*/
writeValue(value) {
if (value) {
this.value = value;
}
}
/**
* Register changes (send to ngModel)
* @param fn
*/
registerOnChange(fn) {
this.propagateChange = fn;
}
/**
* Register changes when element touched
* @param fn
*/
registerOnTouched(fn) {
this.onTouched = fn;
}
/**
* Validate control ngModel
* @param {FormControl} c
* @return {any}
*/
validate(c: FormControl) {
return this.validateFn(c);
}
}
/**
* Custom control
* @return {(c: FormControl) => {requireds: boolean}}
*/
export function requiredDropdown() {
return (c: FormControl) => {
let err = {
requireds: true
};
return (c.value && c.value.length == 0) ? err : null;
}
}
<file_sep>import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
@Component({
selector: 'pe-form-table',
templateUrl: './form-table.component.html'
})
export class FormTableComponent implements OnInit {
/**
* input Cols data
* (sample) => [ {name : 'firstName', header: '<NAME>'}, {name : 'lastName', header: '<NAME>'} ... ]
* @type {Array}
*/
private _cols: any = [];
@Input()
set cols(config: any) {
for (let col of config.fields) {
if (!col.sort) {
config.fields['sort'] = null;
}
}
this._cols = config.fields;
// this.action = config.action;
}
get cols(): any {
return this._cols;
}
private _config: any = [];
@Input()
set config(config: any) {
this._config = config;
this._cols = config.fields;
this.actionCol = config.dataActions;
if (this.actionCol.actions === undefined || this.actionCol.actions.length <= 0) {
this.actionCol.actions = [
{event: 'ADD'},
{event: 'UPDATE'},
{event: 'DELETE'}
];
}
}
get config(): any {
return this._config;
}
/**
* Input data of table
* (sample) => [ {lastName : '<NAME>', firstName: '<NAME>'}, ... ]
* @type {Array}
*/
// @Input() data: any = [];
private _data: any = [];
private backUpData: any = [];
@Output() dataChange = new EventEmitter();
@Input()
set data(data: any) {
this._data = data;
this.backUpData = data;
this.totalItems = data.length; // set the total items variable to length of data
this.dataChange.emit(this.data);
}
get data(): any {
return this._data;
}
/**
* Action object : to show action for each row
* (sample) => [
* {
* label: 'modifier',
* icon: 'fa fa-edit',
* classStyle: 'btn btn-pill btn-warning',
* when: {
* name: 'firstName',
* value: 'sabri',
* operator: '=='
* }
* }
* ]
* @type {any}
*/
@Input() actionCol = null;
/**
* Event to emitted
* @type {EventEmitter<any>}
*/
@Output() event = new EventEmitter();
/**
* Input class name of table
* @type {string}
*/
@Input() class = 'table table-striped';
/**
* true or false to show the paginator of table
* @type {boolean}
*/
private _pagination = true;
@Input()
set pagination(pagination: boolean) {
this._pagination = pagination;
if (!pagination) {
this.itemsPerPage = this.data.length;
}
}
get pagination(): boolean {
return this._pagination;
}
/**
* Items Per Page for the pagination (Default is 10)
* @type {number}
*/
private _itemsPerPage = 10;
@Input()
set itemsPerPage(value) {
if (!this.pagination) {
this._itemsPerPage = this.data.length;
} else {
this._itemsPerPage = value;
}
}
get itemsPerPage() {
return this._itemsPerPage;
}
/**
* Array to show items per page
* @type {[number , number , number]}
*/
@Input() arrayItemsPerPage = [5, 10, 15, 20, 25];
/**
* Next label pagination
* @type {string}
*/
@Input() nextLabel = 'Next';
/**
* Previous Label pagination
* @type {string}
*/
@Input() previousLabel = 'Previous';
/**
* Show item per page Label
* @type {string}
*/
@Input() showItemPerPageLabel = 'Show';
/**
* Label showed when the data is empty
* @type {string}
*/
@Input() emptyDataLabel = 'Data is empty !!';
/**
* Label for total element in the table
* @type {string}
*/
@Input() totalLabel = 'Total : ';
/**
* Label for add button
* @type {string}
*/
@Input() addLabel = 'Add';
/**
* Label for add delete
* @type {string}
*/
@Input() deleteLabel = 'Delete';
/**
* Label for add update
* @type {string}
*/
@Input() updateLabel = 'Update';
/**
* the add modal title
* @type {string}
*/
@Input() addModalTitle = 'Ajouter';
/**
* the update modal title
* @type {string}
*/
@Input() updateModalTitle = 'Modifier';
/**
* the delete modal title
* @type {string}
*/
@Input() deleteModalTitle = 'Supprimer';
/**
* the delete message inside the modal
* @type {string}
*/
@Input() deleteModalMessage = 'Do you want to delete this element ?';
/**
* modal save button label
* @type {string}
*/
@Input() modalSaveButton = 'Save';
/**
* modal cancel button label
* @type {string}
*/
@Input() modalCancelButton = 'Cancel';
/**
* modal delete button label
* @type {string}
*/
@Input() modalDeleteButton = 'Delete';
/**
* card label
* @type {string}
*/
@Input() cardLabel = 'Authorized IPs';
/**
* The current page
* @type {number}
*/
public currentPage = 1;
/**
* Total elements in data
* @type {number}
*/
public totalItems = 0;
public modalView = false;
public modalDelete = false;
public modalUpdate = false;
public row_index = -1;
public myForm = {};
public formConf = {
classStyle: '',
fields: [],
actions: []
};
_tmpTableRow = {};
constructor() {
}
ngOnInit() {
}
/**
* Get the row/cols Data from object
* (sample) if colField is composed "car.color" then return the data col of car color
* @param row
* @param colField
* @return {any}
*/
getColData(row, colField) {
if (colField.indexOf('.') > -1) {
let itm = row;
for (let i of colField.split('.')) {
itm = itm[i];
}
return itm.toString();
} else {
return row[colField].toString();
}
}
/**
* check the condition and return
* true : if the condition applied or you don't have a condition
* fasle : if not
* If the condition don't have a operator by default is "=="
* @param row
* @param conditions [{ paramValue: 'the value to will be compared',
* value: 'the Value to be checked', operator: '==' },
* { name: 'theFieldName', value: 'the Value to be checked', operator: '==' }]
* @return {boolean}
*/
isShowed(row, action) {
switch (action.event) {
case 'UPDATE':
action.classStyle = 'btn btn-warning';
action.label = this.updateLabel;
return true;
case 'DELETE':
action.classStyle = 'btn btn-danger';
action.label = this.deleteLabel;
return true;
case 'ADD':
return false;
default:
return false;
}
}
/**
* check the action boutton for the add button
* @param action
* @returns {boolean}
*/
isAddBtn(action) {
switch (action.event) {
case 'ADD':
action.classStyle = 'btn btn-success';
action.label = this.addLabel;
return true;
default:
return false;
}
}
/**
* switch the action show the modal
* @param row
* @param action
* @param row_no
* @returns {boolean}
*/
actionClick(row, action, row_no?) {
this.row_index = (row_no + ((this.currentPage - 1) * this.itemsPerPage));
switch (action) {
case 'ADD':
this.myForm = {};
this.initFromConfig();
this.modalView = true;
break;
case 'UPDATE':
this.myForm = row;
this._tmpTableRow = Object.assign({}, row);
this.initFromConfig();
this.modalUpdate = true;
break;
case 'DELETE':
this.modalDelete = true;
break;
default:
return false;
}
}
/**
* Sort the dynamic object array
* @param name
*/
sort(name) {
this.data = this.backUpData;
this.data.sort(this.dynamicSortArray(name, this.processSort(name)));
}
/**
* check the sort ASC or DESC for name in parameters and set the others fields to null
* transform the sort from (ASC to DESC) or (DESC to ASC) for a name in parameters
* return null if not fund any element
* return true if the sort will be ascendant (ASC)
* return false if the sort will be descendant (DESC)
* @param name
* @return {any}
*/
processSort(name) {
let res = null;
for (let i = 0; i < this.cols.length; i++) {
// search the cols for name in parameters else sort will be null
if (this.cols[i].name == name) {
if (this.cols[i].sort != null) {
// if sort 'asc' then will be 'desc' or inverse
if (this.cols[i].sort == 'asc') {
this.cols[i].sort = 'desc';
res = false;
} else {
this.cols[i].sort = 'asc';
res = true;
}
} else {
// if the sort is null will be by default 'asc'
this.cols[i].sort = 'asc';
res = true;
}
} else {
this.cols[i].sort = null;
}
}
return res;
}
/**
* sort dynamic array of element
* @param property
* @returns {(a, b) => number}
*/
dynamicSortArray(property, ascending) {
let _this = this;
let sortOrder = 1;
if (!ascending) {
sortOrder = -1;
}
return function (a, b) {
let result = (_this.getColData(a, property).toString().toLowerCase() < _this.getColData(b, property).toString().toLowerCase()) ? -1 : (_this.getColData(a, property).toString().toLowerCase() > _this.getColData(b, property).toString().toLowerCase()) ? 1 : 0;
return result * sortOrder;
};
}
/**
* Page is changed event
* @param event
*/
pageChanged(event) {
this.currentPage = event;
}
/**
* remove the an element from the list
*/
deleteModal(event) {
if (event.action === 'CONFIRM') {
this.data.splice(this.row_index, 1);
this.data = this.data;
this.modalDelete = false;
this.row_index = -1;
}
}
/**
* hide the delete modal
*/
hideDeleteModal() {
this.modalDelete = false;
}
/**
* action for the add modal
* @param event
* @returns {boolean}
*/
addElement(event) {
let _tmp = [];
if (event.formValid && event.action === 'SAVE') {
_tmp.push(this.myForm);
this.data = _tmp.concat(this.data);
this.modalView = false;
this.initFromConfig();
}
if (event.action === 'RESET') {
this.modalView = false;
}
}
}
/**
* action for the update modal
* @param event
* @returns {boolean}
*/
updateElement(event) {
if (event.formValid && event.action === 'SAVE') {
this.modalUpdate = false;
this.initFromConfig();
}
if (event.action === 'RESET') {
this.data[this.row_index] = this._tmpTableRow;
this.initFromConfig();
this.modalUpdate = false;
this._tmpTableRow = {};
}
}
/**
* init the form config inside the model
*/
initFromConfig() {
this.formConf = {
classStyle: '',
fields: this._config.fields,
actions: [
{
label: this.modalCancelButton,
type: 'RESET',
eventName: 'RESET',
icon: 'fa fa-ban',
classStyle: 'btn btn-warning col-md-3 offset-md-3 mr-1',
},
{
label: this.modalSaveButton,
type: 'submit',
eventName: 'SAVE',
icon: 'fa fa-save',
classStyle: 'btn btn-primary col-md-3',
}
]
};
}
}
<file_sep>import {Component, Input, OnInit} from '@angular/core';
@Component({
selector: 'pe-basic-loader',
templateUrl: './basic.component.html'
})
export class BasicLoaderComponent implements OnInit {
@Input() visible = true;
@Input() fullPage = true;
@Input() loadingLabel = 'Loading';
@Input() loadingIcon ;
constructor() { }
ngOnInit() {
}
}
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
@Component({
selector: 'pe-modal',
templateUrl: './modal.component.html'
})
export class ModalComponent implements OnInit {
/**
* (two way binding) output for data
* @type {EventEmitter<any>}
*/
@Output() visibleChange = new EventEmitter();
/**
* To show or hide the modal
* @type {boolean}
*/
private _visible = false;
@Input()
get visible() {
return this._visible;
}
set visible(value) {
this._visible = value;
this.visibleChange.emit(this.visible);
}
/**
* Title of the modal
* @type {string}
*/
@Input()
modalTitle = '';
/**
* custom Style class for the modal
* @type {string}
*/
@Input()
styleClass = '';
/**
* To show or hide the close button
* @type {boolean}
*/
@Input()
closable = true;
constructor() {
}
ngOnInit() {
}
/**
* close the modal
*/
closeModal() {
this.visible = false;
}
}
<file_sep>export * from './loader/loader.module';
export * from './table/table.module';
export * from './forms/forms.module';
export * from './modal/modal.module';
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
@Component({
selector: 'pe-filtered-table',
templateUrl: './filtred-table.component.html'
})
export class FilteredTableComponent implements OnInit {
/**
* Data back Up
* @type {Array}
* @private
*/
public _backUpData = [];
public _data = [];
/**
* Form data two way binding
* @type {{}}
*/
public formData = {};
/**
* Data rows
* @type {Array}
*/
@Input()
set data(value) {
this._data = value;
this._backUpData = value;
}
get data() {
return this._data;
}
/**
* Cols config
* @type {Array}
*/
@Input()
cols: any = [];
/**
* Action col
* @type {Array}
*/
@Input()
actionCol: any = [];
/**
* Event to emited
* @type {EventEmitter<any>}
*/
@Output()
event = new EventEmitter();
/**
* event emited
* @type {EventEmitter<any>}
*/
@Output()
btnEvent = new EventEmitter();
/**
* NB Items per page
* @type {number}
*/
@Input()
itemsPerPage = 10;
/**
* Array to show items per page
* @type {[number , number , number]}
*/
@Input() arrayItemsPerPage = [10, 15, 20, 25];
/**
* Next label pagination
* @type {string}
*/
@Input() nextLabel = 'Next';
/**
* Previous Label pagination
* @type {string}
*/
@Input() previousLabel = 'Previous';
/**
* Show item per page Label
* @type {string}
*/
@Input() showItemPerPageLabel = 'Show';
/**
* Label showed when the data is empty
* @type {string}
*/
@Input() emptyDataLabel = 'Data is empty !!';
/**
* Label search button
* @type {string}
*/
_searchLabel = 'Search';
@Input()
get searchLabel() {
return this._searchLabel;
}
set searchLabel(value) {
this._searchLabel = value;
this.initConf();
}
/**
* Label reset button
* @type {string}
*/
_resetLabel = 'Reset';
@Input()
get resetLabel() {
return this._resetLabel;
}
set resetLabel(value) {
this._resetLabel = value;
this.initConf();
}
/**
* Label for the card which contain the filter
* @type {string}
*/
@Input() filterCardLabel = 'Filter';
/**
* Label for the card which contain the data table
* @type {string}
*/
@Input() tableCardLabel = 'Result';
/**
* Array for the button before the data table
* @type {any[]}
*/
@Input() btnCols = [];
/**
* Show the filter zone if we have at least one filtered column (by default the zone is hidden)
* @type {boolean}
*/
public isEnableFilter = false;
/**
* Show or hide the filter section
* @type {boolean}
*/
@Input() showFiler = true;
/**
* Config form Filter
* @type {{}}
*/
searchConfig = {};
constructor() {
}
ngOnInit() {
this.initConf();
}
/**
* Init form Filter
*/
initSearchConfig() {
this.searchConfig = {
actions: [
{
label: this.resetLabel,
eventName: 'RESET',
icon: 'fa fa-ban',
classStyle: 'btn btn-outline-warning col-md-3 offset-md-3 mr-1',
},
{
label: this.searchLabel,
eventName: 'SEARCH',
icon: 'fa fa-search',
classStyle: 'btn btn-outline-primary col-md-3',
}
],
fields: []
};
}
/**
* Init config for form search
*/
initConf() {
this.initSearchConfig();
let nbrFilteredColumns = 0;
for (let col of this.cols) {
if (col.filtered) {
nbrFilteredColumns++;
this.isEnableFilter = true;
if (col.filtered.type) {
this.searchConfig['fields'].push({
type: col.filtered.type,
label: col.header,
name: col.field,
classStyle: 'col-md-6',
values: col.filtered.values
});
} else {
this.searchConfig['fields'].push({
type: 'text',
label: col.header,
name: col.field,
classStyle: 'col-md-6'
});
}
}
}
if (nbrFilteredColumns <= 1) {
for (let field of this.searchConfig['fields']) {
field['classStyle'] = 'col-md-12';
}
}
}
/**
* Send the event to the caller
* @param event
*/
clicked(event) {
this.event.emit(event);
}
/**
* On click form
* @param event
*/
formChange(event) {
if (event.action == 'SEARCH') {
this.search();
} else if (event.action == 'RESET') {
this.resetForm();
}
}
/**
* Search elements
*/
search() {
let searchRes = this._backUpData;
console.log(this.formData)
for (let col of this.cols) {
if (col.filtered) {
searchRes = searchRes.filter(element => (this.formData[col.field].trim() != '') ? this.getColData(element, col.field).toLowerCase().includes(this.formData[col.field].trim().toLowerCase()) : element);
}
}
this._data = searchRes;
}
/**
* Reset object of the search form
*/
resetForm() {
this._data = this._backUpData;
this.formData = {};
for (let col of this.cols) {
if (col.filtered) {
this.formData[col.field] = '';
}
}
}
/**
* Get the row/cols Data from object
* (sample) if colField is composed "car.color" then return the data col of car color
* @param row
* @param colField
* @return {any}
*/
getColData(row, colField) {
if (colField.indexOf('.') > -1) {
let itm = row;
for (let i of colField.split('.')) {
itm = itm[i];
}
return itm.toString();
} else {
return row[colField].toString();
}
}
/**
* function to show and hide the filter card body
*/
hideAndShowFilter(): void {
this.showFiler = !this.showFiler;
}
/**
* send the event to the caller
* @param {string} eventName
*/
clickedBtn(eventName: string) {
this.btnEvent.emit({action: eventName});
}
}
<file_sep>import {Injectable} from '@angular/core';
@Injectable()
export class PeacockSharedService {
public ip = '';
constructor() {
}
/**
* Get the Ip address
* @return {boolean}
*/
public localIps() {
let _window: any = window;
var ip;
_window.RTCPeerConnection = _window.RTCPeerConnection || _window.mozRTCPeerConnection || _window.webkitRTCPeerConnection || false;
if (_window.RTCPeerConnection) {
ip = [];
var pc: any = new RTCPeerConnection({iceServers: []}), noop = function () {
};
pc.createDataChannel('');
pc.createOffer(pc.setLocalDescription.bind(pc), noop);
pc.onicecandidate = function (event) {
if (event && event.candidate && event.candidate.candidate) {
var s = event.candidate.candidate.split('\n');
ip.push(s[0].split(' ')[4]);
}
};
}
this.ip = ip;
}
/**
* Make a random String length 5
* @return {string}
*/
makeRandomString(length = 5) {
let text = '';
let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
/**
* Compare two JSON objects
* true : if equals
* false: if not
* @param obj1
* @param obj2
*/
public isEqual(obj1, obj2) {
let objectConstructor = {}.constructor;
if (Object.keys(obj1).length == Object.keys(obj2).length) {
for (let key in obj1) {
if (obj1[key].constructor === objectConstructor) {
if (!this.isEqual(obj1[key], obj2[key])) {
return false;
}
} else if (Array.isArray(obj1[key]) && Array.isArray(obj2[key])) {
for (let i in obj2[key]) {
if (!this.isEqual(obj1[key][i], obj2[key][i])) {
return false;
}
}
} else if (obj1[key] != obj2[key]) {
return false;
}
}
return true;
} else {
return false;
}
}
}
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
@Component({
selector: 'pe-image-form',
templateUrl: './image-form.component.html'
})
export class ImageFormComponent implements OnInit {
public base64textString = '';
public _data = '';
public _tmp = null;
public extension = '';
public type = '';
public datatest: any;
public isMaxSize = false;
@Output() selected = new EventEmitter();
/**
* extension file to will be accepted
* file_extension A file extension starting with the STOP character, e.g: .gif, .jpg, .png, .doc
* audio/* All sound files are accepted
* video/* All video files are accepted
* image/* All image files are accepted
* media_type A valid media type, with no parameters. Look at IANA Media Types for a complete list of standard media types
* @type {string}
*/
@Input() accept = '*';
/**
* Style
* @type {string}
*/
@Input() classStyle = 'btn btn-default';
/**
* (two way binding) output for data
* @type {EventEmitter<any>}
*/
@Output() dataChange = new EventEmitter();
/**
* (two way binding) Input data
* @return {{}}
*/
@Input()
get data() {
return this._data;
}
set data(value) {
this._data = value;
this.dataChange.emit(this._data);
this.selected.emit(this._tmp);
}
/**
* upload label
* @type {string}
*/
@Input() uploadLabel = null;
/**
* max size of file
* @type {number}
*/
max: number;
@Input()
set maxSize(value) {
this.max = (value === undefined) ? 2097152 : (value * 1048576);
}
get maxSize() {
return this.max;
}
/**
* alert message when file size > maxSize
* @type {string}
*/
maxLabel: string;
@Input()
set maxSizeLabel(value) {
this.maxLabel = (value === undefined) ? `File size must be inferior to ` : value;
}
get maxSizeLabel() {
return this.maxLabel;
}
constructor() {
}
ngOnInit() {
}
handleFileSelect(evt) {
let files = evt.target.files;
this.isMaxSize = false;
let file = files[0];
if (files && file && file.size < this.maxSize) {
this.extension = file.name.split('.').pop();
this.type = file.type;
let reader = new FileReader();
reader.onload = this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(file);
} else {
this.isMaxSize = true;
this.data = this._data;
this.datatest = undefined;
}
}
_handleReaderLoaded(readerEvt) {
this._tmp = [];
let binaryString = readerEvt.target.result;
this.base64textString = btoa(binaryString);
this._tmp['type'] = this.type;
this._tmp['extension'] = this.extension;
if (this.isImage(this.extension)) {
this._tmp['base64'] = `data:${this.type};base64,${this.base64textString}`;
} else {
this._tmp['base64'] = this.base64textString;
}
this.data = this._tmp['base64'];
}
/**
* check the file type
* @param ext
* @returns {boolean}
*/
isImage(ext) {
console.log(ext.toString().toLowerCase());
switch (ext.toString().toLowerCase()) {
case 'png':
case 'jpg':
case 'gif':
case 'jpeg':
return true;
default:
return false;
}
}
}
<file_sep>import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {BasicFormComponent} from './basic-form/basic-form.component';
import {ImageFormComponent} from './image-form/image-form.component';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {FormTableComponent} from '../forms/form-table/form-table.component';
import {NgxPaginationModule} from 'ngx-pagination';
import {ModalModule} from '../modal/modal.module';
import {DropdownFormComponent} from './dropdown-form/dropdown-form.component';
import {DropdownFilterPipe} from './dropdown-form/dropdown-filter.pipe';
import {PickListComponent} from './pick-list/pick-list.component';
import {InputSwitchComponent} from './inputswitch/inputswitch.component';
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
NgxPaginationModule,
ModalModule
],
declarations: [
BasicFormComponent,
ImageFormComponent,
FormTableComponent,
DropdownFormComponent,
DropdownFilterPipe,
PickListComponent,
InputSwitchComponent
],
exports: [
BasicFormComponent,
ImageFormComponent,
FormTableComponent,
DropdownFormComponent,
PickListComponent,
InputSwitchComponent
]
})
export class PeacockFormsModule {
}
<file_sep>## @peacockng/components
Peacock NG : UI Components for Angular
## Installation
To install this library, run:
```bash
$ npm install [email protected] --save
$ npm install [email protected] --save
```
```bash
$ npm install @peacockng/components --save
```
## Consuming
Once you have installed the library, you can import it in any Angular application:
1 - Import PeacockNg Style in `.angular-cli.json`:
```json
....
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.css",
"../node_modules/@peacockng/components/css/style.css",
....
],
...
```
2- In your Angular `AppModule`:
```typescript
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
// Import UI componenets modules from @peacockng/components
import { LoaderModule } from '@peacockng/components';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
// Specify the module as an import
LoaderModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
3- Once the module is imported, you can use its components, directives and pipes in your Angular application:
```xml
<!-- You can now use your library component in app.component.html -->
<h1>
{{title}}
</h1>
<pe-basic-loader [visible]="true"
[loadingLabel]="'LOADING'"></pe-basic-loader>
```
## Development
To generate all `*.js`, `*.d.ts`, `*.css` and `*.metadata.json` files:
```bash
$ npm run build
```
To lint all `*.ts` files:
```bash
$ npm run lint
```
## Consuming in a local application during development
To consume the library in a local application in development mode, you can follow the following steps:
1- Compile the PeacockNg components library
```bash
$ npm run build
```
2- Create a symlink in the global node_modules directory to the dist directory.
```bash
$ cd dist
$ npm link
```
3- Create a new Angular app. Let's assume you use angular-cli:
```bash
$ cd /your-projects-path
$ ng new my-app
```
4- Navigate to the my-app directory:
```bash
$ cd my-app
```
5- From the my-app directory, link the global sample-library directory to node_modules of the my-app directory:
```bash
$ npm link sample-library
```
6- Import modules and `consuming`
7- Run the server
```bash
$ ng serve --preserve-symlinks
```
To make sure the consuming application searches for the peer dependencies in the application's node_modules directory.
## License
MIT © [<NAME>](mailto:<EMAIL>)
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormControl, FormGroup, NgForm, Validators} from '@angular/forms';
@Component({
selector: 'pe-form',
templateUrl: './basic-form.component.html'
})
export class BasicFormComponent implements OnInit {
public _config = {};
/**
* (two way binding) output for data
* @type {EventEmitter<any>}
*/
@Output() dataChange = new EventEmitter();
/**
* Event output to send actions and data
* @type {EventEmitter<any>}
*/
@Output() formClicked = new EventEmitter();
/**
* Data form object
* @type {{}}
*/
formObject = {};
/**
* Config params
* @param value
*/
@Input()
set config(value) {
this._config = value;
this.initForm();
}
get config() {
return this._config;
}
/**
* (two way binding) Input data
* @return {{}}
*/
@Input()
get data() {
return this.formObject;
}
set data(value) {
this.formObject = value;
this.dataChange.emit(this.formObject);
// INIT argument if is not defined object
if (!this.formObject) {
this.initForm();
}
}
/**
* Form group control
*/
formGroup: FormGroup;
constructor() {
}
ngOnInit() {
this.initForm();
}
/**
* Initialise the form group and object value if not defined in Input
*/
initForm() {
let formControlGroup = {};
for (let field of this.config['fields']) {
if (!this.data[field.name] && !this.isTitleType(field.type)) {
// if is checkbox the init will be table else is empty
if (this.isInputGroup(field.type) && field.type.toLowerCase().indexOf('checkbox') > -1) {
this.data[field.name] = [];
} else {
this.data[field.name] = '';
}
}
// check if the param fields have a name or not if have name then build the control params
if (field.name) {
let isDisabled = (field.disabled) ? field.disabled : false;
formControlGroup[field.name] = new FormControl({
value: this.data[field.name],
disabled: isDisabled
}, this.getValidators(field));
}
}
this.formGroup = new FormGroup(formControlGroup);
}
/**
* Build list of validators
* @param field
* @return {Array}
*/
getValidators(field) {
if (field.validators && field.validators.length > 0) {
let validators = [];
for (let val of field.validators) {
switch (val.control.toLowerCase()) {
case 'required':
validators.push(Validators.required);
break;
case 'min':
validators.push(Validators.min(val.value));
break;
case 'max':
validators.push(Validators.max(val.value));
break;
default:
break;
}
}
return validators;
} else {
return [];
}
}
/**
* Send action event to the caller components
* @param action
*/
eventEmit(action, form?: NgForm) {
if (form) {
this.formClicked.emit({data: this.data, action: action, formValid: form.valid});
} else {
this.formClicked.emit({data: this.data, action: action});
}
}
/**
* Check if the type is a title
* @param fieldType
* @return {boolean}
*/
isTitleType(fieldType) {
switch (fieldType.toLowerCase()) {
case 'title':
return true;
default:
return false;
}
}
/**
* Check if the field is an input type if is undifined return true and after will be text type
* @param fieldType
* @return {boolean}
*/
isSimpleInputType(fieldType) {
if (fieldType) {
switch (fieldType.toLowerCase()) {
case 'text':
return true;
case 'password':
return true;
case 'email':
return true;
case 'tel':
return true;
case 'date':
return true;
default:
return false;
}
} else {
return true;
}
}
/**
* Xheck if the fiels is an input type number
* @param fieldType
* @return {boolean}
*/
isNumberInput(fieldType) {
switch (fieldType.toLowerCase()) {
case 'number':
return true;
default:
return false;
}
}
/**
* check if the field is select type or not
* @param fieldType
* @return {boolean}
*/
isSelectType(fieldType) {
switch (fieldType.toLowerCase()) {
case 'select':
return true;
default:
return false;
}
}
/**
* Check if the field type is type group (Checkbox or radio)
* @param fieldType
* @return {boolean}
*/
isInputGroup(fieldType) {
switch (fieldType.toLowerCase()) {
case 'radio' || 'radio-group':
return true;
case 'checkbox' || 'checkbox-group':
return true;
default:
return false;
}
}
/**
* Check if the actions is a submit or reset
* - OK : true
* - NOK : false
* - if type not defined : false
* @param actionType
* @return {boolean}
*/
isFormButton(actionType) {
if (actionType) {
switch (actionType.toLowerCase()) {
case 'submit':
return true;
case 'reset':
return true;
default:
return false;
}
} else {
return false;
}
}
/**
* check if the field type is an image
* @param fieldType
* @returns {boolean}
*/
isImage(fieldType) {
switch (fieldType.toLowerCase()) {
case 'image' || 'img':
return true;
default:
return false;
}
}
/**
* check if the field type is an image
* @param fieldType
* @returns {boolean}
*/
isTable(fieldType) {
switch (fieldType.type.toLowerCase()) {
case 'table':
return true;
default:
return false;
}
}
/**
* check if the field is a dropdown type or not
* @param fieldType
* @return {boolean}
*/
isDropdownType(field) {
switch (field.type.toLowerCase()) {
case 'dropdown':
return true;
default:
return false;
}
}
/**
* check if the fiels is a switch type
* @param field
* @return {boolean}
*/
isSwitchType(field) {
switch (field.type.toLowerCase()) {
case 'switch':
return true;
default:
return false;
}
}
/**
* Check if the field type is standard type or custom
* @param field
* @return {boolean}
*/
isStandardType(field) {
switch (field) {
case this.isDropdownType(field):
return false;
case this.isSwitchType(field):
return false;
default:
return true;
}
}
/**
* check if the field name is invalid or not
* when the field touched or the form submitted
* - true : form Invalid
* - false : form valid
* @param fieldName
*/
isInvalid(fieldName, ngForm?: NgForm) {
return this.formGroup.controls[fieldName].invalid && (this.formGroup.controls[fieldName].touched || (ngForm && ngForm.submitted));
}
/**
* check if the field is Invalid or not and test controls
* - true : field (name) is invalid controls
* - false : by default
* @param fieldName
* @param controlName
* @param {NgForm} ngForm
* @return {boolean}
*/
controlTest(fieldName, controlName, ngForm: NgForm) {
switch (controlName.toLowerCase()) {
case 'required':
return this.isInvalid(fieldName, ngForm) && this.formGroup.controls[fieldName].errors.required;
case 'min':
return this.isInvalid(fieldName, ngForm) && this.formGroup.controls[fieldName].errors.min;
case 'max':
return this.isInvalid(fieldName, ngForm) && this.formGroup.controls[fieldName].errors.max;
default:
return false;
}
}
}
<file_sep>import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {BasicTableComponent} from './basic-table/table.component';
import {NgxPaginationModule} from 'ngx-pagination';
import {FormsModule} from '@angular/forms';
import {FilteredTableComponent} from './filtred-table/filtred-table.component';
import {PeacockFormsModule} from '../forms/forms.module';
import {FormTableComponent} from '../forms/form-table/form-table.component';
import {ModalModule} from '../modal/modal.module';
@NgModule({
imports: [
CommonModule,
FormsModule,
NgxPaginationModule,
PeacockFormsModule,
ModalModule
],
declarations: [BasicTableComponent, FilteredTableComponent],
exports: [BasicTableComponent, FilteredTableComponent]
})
export class TableModule {
}
| 5d91158afbb3df85a1b69f806d38cca1c4f71e44 | [
"Markdown",
"TypeScript"
]
| 16 | TypeScript | sabri-bahrini/peacockng | d8f2eec5bdffe2ae2897a242a5d6829a686f39d1 | 4388680800494805df31c31119d314657a1b8536 |
refs/heads/master | <repo_name>alienfast/middleman-aws<file_sep>/lib/middleman-aws/tasks/middleman-aws.rake
#------------------------------------------------------------------------
# Rakefile
#------------------------------------------------------------------------
require 'yaml'
require 'uri'
namespace :mm do
desc 'Remove all files in the build directory'
task :clobber do |t, args|
# kill the old package dir
rm_r 'build' rescue nil
end
desc 'Compile all files into the build directory'
task :build do
puts '## Compiling static pages'
status = system 'bundle exec middleman build'
puts status ? 'Build successful.' : 'Build failed.'
end
desc 'Deploy to S3 and invalidate Cloudfront after a Git commit/push'
task :deploy do
puts '## Deploy starting...'
cd 'build' do
system 'git add -u'
message = "Site updated at #{Time.now}"
puts "## Commiting: #{message}"
system "git commit -m \"#{message}\""
end
aws_env = "AWS_ACCESS_KEY=#{credentials[:access_key_id]} AWS_SECRET=#{credentials[:secret_access_key]}"
puts '## Syncing to S3...'
system "#{aws_env} bundle exec middleman s3_sync"
puts '## Invalidating cloudfront...'
system "#{aws_env} bundle exec middleman invalidate"
puts '## Deploy complete.'
end
desc 'One step clobber, build, deploy'
task :publish => [:clobber, :build, :deploy] do
end
desc 'Serve the site'
task :serve do
system 'bundle exec middleman serve'
end
desc 'Show config'
task :show_config do |t, args|
puts "\n----------------------------------------------------------------------------------"
puts 'Configuration:'
puts "\t:working directory: #{Rake.original_dir}"
puts "\t:project: #{project}"
puts "\t:aws_secrets_file: #{aws_secrets_file}"
puts "\t:access_key_id: #{credentials[:access_key_id]}"
puts "----------------------------------------------------------------------------------\n"
end
def credentials
unless File.exists?(aws_secrets_file)
puts "\nWarning: Config file is missing: #{aws_secrets_file}.\nFile contents should look like:\naccess_key_id: XXXX\nsecret_access_key: XXXX\n\n."
end
# load from a user directory i.e. ~/.aws/acme.yml
credentials = File.exists?(aws_secrets_file) ? YAML::load_file(aws_secrets_file) : {}
access_key_id = credentials.fetch('access_key_id') { ENV['AWS_ACCESS_KEY_ID'] }
secret_access_key = credentials.fetch('secret_access_key') { ENV['AWS_SECRET_ACCESS_KEY'] }
{
access_key_id: access_key_id,
secret_access_key: secret_access_key
}
end
def aws_secrets_file
File.expand_path("~/.aws/#{project}.yml")
end
def project
File.basename(Rake.original_dir)
end
end
<file_sep>/Rakefile
require 'bundler/gem_tasks'
# require 'bundler'
# Bundler::GemHelper.install_tasks
# require 'cucumber/rake/task'
#
# Cucumber::Rake::Task.new(:cucumber, 'Run features that should pass') do |t|
# t.cucumber_opts = "--color --tags ~@wip --strict --format #{ENV['CUCUMBER_FORMAT'] || 'Fivemat'}"
# end
#
# require 'rake/clean'
#
# task test: ['cucumber']
#
# task default: :test
<file_sep>/samples/config.rb
#------------------------------------------------------------------------
# Typical custom configuration each project
#------------------------------------------------------------------------
# Build config
configure :build do
# activate :minify_css
# activate :minify_javascript
# activate :asset_hash
end
# activate :external_pipeline,
# name: :gulp,
# command: build? ? './node_modules/gulp/bin/gulp.js' : './node_modules/gulp/bin/gulp.js default:watch',
# source: 'dist'
# Custom helpers
# helpers do
# def body_classes
# "#{page_classes} #{data.page.bodyClasses}"
# end
# end
#------------------------------------------------------------------------
# Configuration variables specific to each project
#------------------------------------------------------------------------
SITE_NAME = 'AlienFast Acme'
URL_ROOT = 'http://acme.alienfast.com'
AWS_BUCKET = 'acme.alienfast.com'
AWS_CLOUDFRONT_DISTRIBUTION_ID = 'xxxxxxxxxxxx'
#------------------------------------------------------------------------
# Common configuration below here, should not need to be changed.
#------------------------------------------------------------------------
# Sent in on CLI by rake task
#------------------------------------------------------------------------
AWS_ACCESS_KEY = ENV['AWS_ACCESS_KEY']
AWS_SECRET = ENV['AWS_SECRET']
# Default layout
page '/*', layout: 'application'
# With no layout
page '/*.xml', layout: false
page '/*.json', layout: false
page '/*.txt', layout: false
# Reload the browser automatically whenever files change
configure :development do
activate :livereload, ignore: [ /.idea\// ]
end
activate :directory_indexes
# # Use relative paths
# activate :relative_assets
# set :relative_links, true
# Haml config
set :haml, { :attr_wrapper => '"' }
# https://github.com/Aupajo/middleman-search_engine_sitemap
set :url_root, URL_ROOT
activate :search_engine_sitemap
# https://github.com/fredjean/middleman-s3_sync
activate :s3_sync do |s3_sync|
s3_sync.bucket = AWS_BUCKET # The name of the S3 bucket you are targeting. This is globally unique.
# s3_sync.region = 'us-east-1' # The AWS region for your bucket. (S3 no longer requires this, dummy input?)
s3_sync.aws_access_key_id = AWS_ACCESS_KEY
s3_sync.aws_secret_access_key = AWS_SECRET
s3_sync.delete = false # We delete stray files by default.
# s3_sync.after_build = false # We do not chain after the build step by default.
# s3_sync.prefer_gzip = true
# s3_sync.path_style = true
# s3_sync.reduced_redundancy_storage = false
# s3_sync.acl = 'public-read'
# s3_sync.encryption = false
# s3_sync.prefix = ''
# s3_sync.version_bucket = false
end
# https://github.com/andrusha/middleman-cloudfront
activate :cloudfront do |cf|
cf.access_key_id = AWS_ACCESS_KEY
cf.secret_access_key = AWS_SECRET
cf.distribution_id = AWS_CLOUDFRONT_DISTRIBUTION_ID
# cf.filter = /\.html$/i
end<file_sep>/middleman-aws.gemspec
# -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
Gem::Specification.new do |s|
s.name = 'middleman-aws'
s.version = '4.0.0'
s.platform = Gem::Platform::RUBY
s.authors = ['<NAME>']
s.email = ['<EMAIL>']
s.description = <<-TEXT
Simple set of middleman rake tasks to build and deploy to AWS using s3_sync and cloudfront invalidation
TEXT
s.summary = <<-TEXT
Simple set of middleman rake tasks to build and deploy to AWS using s3_sync and cloudfront invalidation
TEXT
s.homepage = 'https://github.com/alienfast/middleman-aws'
s.license = 'MIT'
s.files = `git ls-files`.split($/).reject { |f| f =~ /^samples\// }
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ['lib']
# The version of middleman-core your extension depends on
s.add_runtime_dependency 'middleman-core', ['>= 4.0.0']
s.add_dependency 'middleman-s3_sync', '>=4.0.0' # https://github.com/fredjean/middleman-s3_sync
# s.add_dependency 'middleman-cloudfront', '>=4.0.0' # https://github.com/andrusha/middleman-cloudfront
s.add_dependency 'rake'
end
<file_sep>/README.md
middleman-aws
=============
Simple set of [middleman](http://middlemanapp.com/) rake tasks to build and deploy to AWS using s3_sync and cloudfront invalidation.
# Installation and Configuration
### Step 1: Add gems to the Gemfile
See the [sample Gemfile](samples/Gemfile) for full configuration.
```ruby
gem 'middleman-aws', '>=4.0.0'
gem 'middleman-s3_sync', '>=4.0.0'
gem 'middleman-cloudfront',
#'>=4.0.0' waiting for release of PR https://github.com/andrusha/middleman-cloudfront/pull/23
github: 'rosskevin/middleman-cloudfront', branch: 'middleman-4'
```
### Step 2: Require this gem in the Rakefile
require 'middleman-aws'
### Step 3: AWS credentials
#### Option 1 - secrets file
e.g. `~/.aws/acme.yml`
This should contain the access and secret keys generated from the selected IAM user. This is the only file that will need to reside outside the repository. `acme` is equivalent to the directory name for your project.
Don't worry, validation will make sure you have the path right.
```ruby
access_key_id: XXXXXX
secret_access_key: XXXXXX
```
#### Option 2 - ENV variables
If you don't create secrets file, then environment variables `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` will be used.
#### Option 3 - IAM
If a secrets file is not present (option 1), there are no ENV variables (option 2), then request to AWS will fail (unless middleman-aws is used on EC2 instance with correct IAM role, then AWS will take care of authorising requests).
### Step 4: Add the necessary s3_sync and Cloudfront sections to your config
See the [sample config.rb](samples/config.rb) for full configuration. Be sure to set the following variables:
```ruby
#------------------------------------------------------------------------
# Configuration variables specific to each project
#------------------------------------------------------------------------
SITE_NAME = 'AlienFast Acme'
URL_ROOT = 'http://acme.alienfast.com'
AWS_BUCKET = 'acme.alienfast.com'
AWS_CLOUDFRONT_DISTRIBUTION_ID = 'xxxxxxxxxxxx'
```
# Usage
Run the desired rake task. It's as simple as `rake mm:publish` in one step, or you can choose to do things one step at a time.
See the available rake tasks below or run `rake -T`
# Available Rake Tasks
rake mm:build # Compile all files in the build directory
rake mm:clobber # Remove all files in the build direcory
rake mm:deploy # Deploy to S3 and invalidate Cloudfront after a Git commit/push
rake mm:serve # Run the preview server at http://localhost:4567
rake mm:publish # One step clobber, build, deploy
rake mm:show_config # Show config
# Real World Sample
If you are just getting started with middleman and want to get a quick jumpstart on your `Gemfile` and `congfig.rb`,
check out the source in the `samples` directory.
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
## Copyright
Copyright (c) 2014-2016 AlienFast, LLC. See MIT LICENSE.txt for further details.
<file_sep>/samples/Gemfile
#------------------------------------------------------------------------
# Gemfile
#------------------------------------------------------------------------
source 'http://rubygems.org'
gem 'rake'
gem 'middleman', '>= 4.0.0'
gem 'middleman-livereload'
gem 'middleman-search_engine_sitemap'
#------------------------------------------------------------------------
# Deployment - requires additional configuration. See links below
gem 'middleman-aws' # https://github.com/alienfast/middleman-aws
# Even though already required by the middleman-aws gem, it appears middleman does not
# pick up transitive dependency extensions early enough to avoid the
# "== Unknown Extension:" error. Add these to your main project
# (I wish this was unnecessary but don't know how to work around it)
# https://github.com/fredjean/middleman-s3_sync
gem 'middleman-s3_sync', '>=4.0.0'
# https://github.com/andrusha/middleman-cloudfront
gem 'middleman-cloudfront',
#'>=4.0.0' waiting for release of PR https://github.com/andrusha/middleman-cloudfront/pull/23
github: 'rosskevin/middleman-cloudfront', branch: 'middleman-4'
#------------------------------------------------------------------------
# Other dependencies below here.
<file_sep>/Gemfile
# If you have OpenSSL installed, we recommend updating
# the following line to use "https"
source 'http://rubygems.org'
# Specify your gem's dependencies in middleman-aws.gemspec
gemspec
# FIXME: temporary branch - move back to spec when PR is accepted
gem 'middleman-cloudfront',
#'>=4.0.0' waiting for release of PR https://github.com/andrusha/middleman-cloudfront/pull/23
github: 'rosskevin/middleman-cloudfront', branch: 'middleman-4'
#:path => '~/projects/middleman-cloudfront'
group :development do
gem 'rake'
gem 'rdoc'
gem 'yard'
end
group :test do
gem 'cucumber'
gem 'fivemat'
gem 'aruba'
gem 'rspec'
end
<file_sep>/lib/middleman-aws.rb
if defined?(Rake)
Rake.add_rakelib(File.expand_path('../middleman-aws/tasks', __FILE__))
end | fedcc96bf539caedccc546af4738177621e4c2f1 | [
"Markdown",
"Ruby"
]
| 8 | Ruby | alienfast/middleman-aws | 378c6422c856954641b81475c1221bbdfe660a83 | 0881c1fcc5880b7a53ee20f8f0dd98b7520e79f5 |
refs/heads/master | <repo_name>airblade/acts_as_enterprisey<file_sep>/lib/air_blade/acts_as_enterprisey.rb
module AirBlade #:nodoc:
module ActsAsEnterprisey #:nodoc:
def self.included(base) #:nodoc
base.extend ActMethods
end
module ActMethods
# Delays the execution of finder methods in an enterprisey fashion.
#
# Options:
# [:delay] the number of seconds to sleep before executing a find. Defaults to <tt>2</tt> seconds.
# [:random] whether or not to randomise the delay between <tt>0</tt> and <tt>:delay</tt>. Defaults to +false+.
#
# Examples:
# acts_as_enterprisey :delay => 3
# acts_as_enterprisey :random => true
# acts_as_enterprisey :delay => 5, :random => true
def acts_as_enterprisey(options = {})
options[:delay] ||= 2
options[:random] ||= false
# Only need to define these once on a class
unless included_modules.include? InstanceMethods
class_inheritable_accessor :enterprisey_options
extend ClassMethods
include InstanceMethods
end
self.enterprisey_options = options
end
end
module ClassMethods
# Performs a normal +find+ after sleeping as specified
# in the options to +acts_as_enterprisey+.
def find(*args)
sleep (enterprisey_options[:random] ? rand(enterprisey_options[:delay]) : enterprisey_options[:delay])
super
end
end
module InstanceMethods
end
end
end
<file_sep>/README.markdown
# ActsAsEnterprisey
## Introduction
Let's face it, we all want the big bucks. And we all know Consultancy Law No. 1:
Your Rates Are Proportional To Your App's Enterpriseyness
Or, as Shakespeare would have said:
Enterprisey Apps Invite, Nay Demand, Enterprisey Rates. Verily, Sunshine.
Rails make life easy for us but -- and it's a big but -- we don't want it to look easy. `acts_as_enterprisey` is your friend.
How does `acts_as_enterprisey` make webapp development look hard? Well, the only way your client can judge your app is by playing around with it. What better gives the feeling of heavy weights being lifted behind the scenes than slow response times? Exactly. That's what `acts_as_enterprisey` does.
So while your client clicks, ...waits..., and then gets the page, you can blather on heroically about wrestling with clustered indexes, cache expiration strategies, `n log n` seek times, <i>etc ad nauseam</i>.
## Usage
Simply insert `acts_as_enterprisey` in your `ActiveRecord` model. That's it. (It wouldn't be much use if you actually had to do some work to make it look hard, would it?)
For example:
class ShuttleLaunchSequencer < ActiveRecord::Base
acts_as_enterprisey
end
This slows down all the `ShuttleLaunchSequencer`'s finders by 2 seconds.
Another example:
class GpsSatelliteBeacon < ActiveRecord::Base
acts_as_enterprisey :delay => 3, :random => true
end
This slows down the `GpsSatelliteBeacon`'s finders by a random delay between 0 and 3 seconds.
You can feel your rates rising already. I know it.
## Strategy
Clients pay you to solve their technical problems. They want to feel like they're getting their money's worth. Especially after you start submitting enterprisey invoices.
So make their wishes come true: it's only fair. Ethical, even. Crank the delay up as the deadline approaches, make them sweat, display fortitude and perseverance, etc. And when they can't take it (the app's sluggishness, your bills, whatever) any more, whip out the `acts_as_enterprisey` from your models and book the flights to Vegas.
## Installation
Install in the usual Rails way:
script/plugin install git://github.com/airblade/acts_as_enterprisey.git
## Author
Sometimes plausible deniability is best.
But, for the record, you can blame [<NAME>](mailto:<EMAIL>) at [AirBlade Software](http://airbladesoftware.com).
## See Also
Acts as ASP.NET:
https://web.archive.org/web/20080416051943/http://www.railsjedi.com/posts/15-Acts-as-ASP-NET-a-Ruby-on-Rails-Plugin-
A much more impressive effort than this slapdash thing.
## Licence
`acts_as_enterprisey` is available under the MIT licence. See MIT-LICENCE for the details.
Copyright (c) 2006 <NAME>
<file_sep>/init.rb
ActiveRecord::Base.send(:include, AirBlade::ActsAsEnterprisey)
| 729779160f884f000c6729d0d44f8c53b6af2cc3 | [
"Markdown",
"Ruby"
]
| 3 | Ruby | airblade/acts_as_enterprisey | c60fb0675002a2cea975a208387d7ee237ac4f9a | af42b82521ce72fa2488a2bb75c4cd00d40c9db3 |
refs/heads/master | <file_sep>
# Rooms-Vue
## Installation
`npm install`
`npm run start`
<file_sep>//здесь все генерации темплейта,
//просто отрисовывает сущность
//import room from './generator';
console.log('render.js')
const _paths = {
patternContainer: {
room: '.rooms__patterns',
record: '.records__patterns'
},
pattern: {
room: '#room',
record: '#record'
}
};
function renderRooms(list, template) {
const pattern = document.querySelector(`${_paths.patternContainer.room} ${_paths.pattern.room}`);
list.forEach(item => {
const room = pattern.cloneNode(true);
room.classList.remove('pattern');
const title = room.querySelector('.room__title'),
img = room.querySelector('.room__img img'),
descr = room.querySelector('.room__description'),
area = room.querySelector('.room__area'),
levels = room.querySelector('.room__levels'),
floor = room.querySelector('.room__floor'),
type = room.querySelector('.room__type')
title.innerHTML = `Room ${item.number}`;
img.src = item.src;
descr.innerHTML = item.description();
area.innerHTML = `<strong>area:</strong> ${item.area} m<sup>2</sup>`;
levels.innerHTML = `<strong>levels:</strong> ${item.levels}`;
const fl = item.floor();
(fl === 'none') ?
floor.style.display = 'none':
floor.innerHTML = `<strong>floor:</strong> ${fl}`;
if (item.repair) type.classList.add('repair-class')
if (item.type == 'office') {
type.classList.add('office-class')
}
type.innerHTML = item.type
//button.dataset.id = item.id;
//button.dataset.title = item.title;
room.removeAttribute('id');
template.appendChild(room);
});
}
export default {
renderRooms
}; | 2aeac83cdd773096531c48d57e5327b1d3979883 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | helga-hai/Rooms-Vue | 854630730f00f3b0355d69f6c5748eddf0238d8a | d977796ba2bf1dbb110647aa3aee99eb7f09b05f |
refs/heads/master | <repo_name>js13kGames/404-Princess<file_sep>/README.md
# 404 Princess
## About this game
404 Princess is a PC adventure game, designed to provide players an interactive entertainment with several different endings. Playing the role of a heroic knight, determined to rescue the princess and save the kingdom plagued by monsters and diseases, will provide players expressive gameplay experiences. Fight the monsters, find the key, rescue the princess and make an everlasting history for your own.
## Prologue:
Leo is a powerful and brave knight protecting the royal families in the Tinn, one of seven magical forest realms. The royalties and peasants are living happily and pleasantly among these seven worlds. Beautiful butterflies dance among flowers; birds chirping on the trees. Everyone live a life of contentment. However, until one day, the evil high priest in Tinn summons the largest prehistoric monsters and incurable diseases to kill all the residents and ravage the Tinn. Luckily, the Princess of Tinn locks herself in a secret chamber in Royal Castle, struggling to escape from the massacre. As a courageous knight, Leo must rescue the princess.Hurry up, recue the defenseless princess!
### How to play the game
W = ↑,S = ↓,A = ←,D = →, 1 = HP up, 2 = MP up, 3 = Speed up, Mouseevent Left : Sword, Right: Fire
### Enemy
###### Dragon,HP>>250~50,ATK>>10+LUK,Speed>>0,
###### Tyrannosaur,HP>>150 ,AT>>35,Speed>>1.5
###### Wizard,HP>>200,ATK>>10+LUK(Slow Down!),Speed>>1,
###### Boss,HP>>500,ATK>>50(Body),Speed>>.25
### Leo
###### HP>>500
###### MP>>500
###### Speed>>0~3(Max)
###### ATk>>25~50
<file_sep>/MapLevel.js
/////Fix Map>>using code W L F to record.
let CheckMap = ["13W", "13L", "13A", "1A11F", "2A11F", "11F2A", "12F1A", "1A",'12F'];
let DirectionMap = ['0344444444471',"34444444444471", "0666666666682", "07666666666682", "03444444444447", "34444444444447", "07666666666668", "76666666666681", "6666666666661", "0666666666666",'169D','169F','13W144F13A','13W156F','156F13A'];
let FloorArea =['A4AA5AA1A','3D2A5AA1A','3D2A5A3E2','6C91A5A38','62A5A47C8','62A7D4A78','49A5B97C8','AAAAAAA0A'];
let KeyPos =[{x:608,y:300},{x:30,y:100},{x:30,y:100},{x:30,y:100},{x:500,y:100},{x:608,y:600},{x:30,y:100},{x:0,y:0}];
let Door_=[[{x:608,y:0,F:1,I:0},{x:608,y:0,F:1,I:0}],[{x:608,y:0,F:2,I:0},{x:0,y:192,F:3,I:1}],[{x:1024,y:0,F:3,I:0},{x:192,y:832,F:0,I:0}],[{x:192,y:800,F:4,I:0},{x:608,y:384,F:7,I:3}],[{x:1024,y:416,F:5,I:0},{x:608,y:384,F:7,I:1}],[{x:608,y:384,F:7,I:2},{x:1024,y:416,F:6,I:0}],[{x:608,y:0,F:7,I:0},{x:78,y:0,F:7,I:4}]];
let Level=A=>{
let e = FloorArea[A];
let X=0,Y=0;
for(var i =0;i<e.length;i++){
let Index = e[i];
if(X==3){
X=0;
Y++;
}
if(Index=='A')Index=10;
if(Index=='B')Index=11;
if(Index=='C')Index=12;
if(Index=='D')Index=13;
if(Index=='E')Index=14;
MAP_create(DirectionMap[Index],X*416,Y*416,13,13,32,A+1);
X++;
}
if(A<7){
for(var i=0;i<2;i++)
new door(Door_[A][i].x,Door_[A][i].y,Door_[A][i].F,Door_[A][i].I);
}
let sort = (a,b)=> a.Ally-b.Ally;
Map_object_Array.sort(sort);
new MAP_FIX(KeyPos[A].x,KeyPos[A].y,7,3,3,40);
}
/////
//// Map generator
////The concept is from LZW zip algorithm.
////But there is a difference in that its line(width and height) are fixed W, H
function MAP_create(floor,startX,startY,MAPWIDTH,MAPHEIGHT,TileSize,A){
let tempsum =0;
let new_record = [];
let EnemyCount = A<3?A:A<8?3:0;
for(var i =0;i<floor.length;i++){
if(isNaN(floor[i])){
new_record.push({x:tempsum,y:floor[i]});
tempsum = 0;
}else{
tempsum=tempsum*10+parseInt(floor[i]);
}
}
let X=startX;
for(var i =0;i<new_record.length;i++){
for(var j =0;j<new_record[i].x;j++,X+=TileSize){
if(X>=MAPHEIGHT*TileSize+startX){
startY+=TileSize;
X = startX;
}
if (new_record[i].y=='W') {
new MAP_OBJECT(X,startY,9,2,5,32);
}else if(new_record[i].y=='A'){
new MAP_OBJECT(X,startY,10,2,5,32);
}else if(new_record[i].y=='D'){
}else if(new_record[i].y=='L')
new MAP_OBJECT(X,startY,11,2,5,32);
else{
new MAP_OBJECT(X,startY,RandTwo(12,13),2,4,32);
let newPosx = X+RandTwo(0,14);
let newPosy = startY+RandTwo(0,14);
if(RandInt(9)>7){
new MAP_FIX(newPosx,newPosy,8,3,RandTwo(8,9),20);
}else{
if(RandInt(5)==3&&EnemyCount>0&&newPosx!=625){
if(A<2){
new Dragon(newPosx,newPosy,32,30);
}else{
let AA = RandInt(4);
if(AA==1)new Dragon(newPosx,newPosy,32,250)
if(AA==2)new Tyrannosaur(newPosx,newPosy,32,150);
if(AA==3)new Wizard(newPosx,newPosy,32,200);
if(A>5&&RandInt(10)==1)new Boss(newPosx+64,newPosy+64,60,500);
}
EnemyCount--;
}
}
}
}
}
}
class MAP_OBJECT extends object{
//0-3:red-yellow key,4:floor,5,6,7>wall,8 door 9 bottle 10 barrel
constructor(x,y,tx,ty,Ally=0,collisionSize,Life=1){
super(x,y,collisionSize-4);
this.Life = Life;
this.MaxLife = Life;
this.Ally=Ally;
this.C=collisionSize;
this.tx= tx;
this.ty= ty;
this.Attack = 0;
this.R=0;
this.Treasure = 0;
}
Die(){return !this.Life}
Damage(d){
if (this.Die())return 0;
this.Life = max(this.Life-d,0);
if(!this.Life){
for(var i=0;i<10;i++)
new Dead(this.pos,this.C);
for(var i =0;i<this.Treasure;i++){
let x = this.pos.x + RandTwo(-this.C,this.C);
let y = this.pos.y + RandTwo(-this.C,this.C);
let type = RandIntBetween(0,2);
new MAP_FIX(x,y,type+11,3,type,20);
}
this.Destroy();
SoundList(1)
}
}
Render(){
DrawImageT(ctx,this.pos,this.tx,this.ty,this.C);
}
}
class MAP_FIX extends MAP_OBJECT{
//x,y,tx,ty,Ally=0,collisionSize=32,Life=1
constructor(x,y,tx,ty,Ally=0,c=32,Life=1){
super(x,y,tx,ty,Ally,c,Life);
this.Frame = new PositionXY(0,0);
this.Treasure = RandInt(6%2);
}
Damage(a){
super.Damage();
for(var i =0;i<this.Treasure;i++){
let x = this.pos.x + RandIntBetween(-25,25);
let y = this.pos.y + RandIntBetween(-25,25);
let type = RandIntBetween(0,2);
new MAP_FIX(x,y,type+11,3,type,20);
}
}
Update(){
if(this.Ally<=3){
this.pos.y+= this.Frame.y;
if(this.pos.y>this.old.y+1||this.Frame.y>1){
this.Frame.y-=.1;
}else{
this.Frame.y+=.1;
}
}else{
Map_object_Array.forEach(e=>{
let T = (this!=e&&e.pos!=null)?this.CollisionR(e):0;
if(T&&e.Ally>=5&&e!=this&&this.Ally!=3){
this.Life--;
this.Damage(0);
}
});
this.tx = this.Ally>8?9:10;
}
}
}
class door extends MAP_OBJECT{
constructor(x,y,F,I){
super(x,y,8,3,8,32);
this.F = F;
this.I = I;
NextDoor.push(this);
}
GoNext(){
if (!this.I||!Connected){
NextFloor(this.F,this.I);
}
}
Render(){
if (!this.I||!Connected){
super.Render();
}
}
}
<file_sep>/Event.js
<script>
onmousedown=e=>{
let a = e.which;
MousedownA[a]=new PositionXY((e.x-width/2),(e.y-height/2));
MouseDown=1;
}
onmouseup=e=>{MouseDown=0;MousedownA=[];}
onmousemove=e=>{}
oncontextmenu=e=>false
onkeydown=e=>{
var i = e.which;
var a=[87,83,65,68];
KeyEvent=a.indexOf(i)>=0?1:0;
KeyIn[i]=1;
}
onkeyup=e=>{
KeyIn[e.which]=0;
KeyEvent=KeyIn.some(e=>e!=0)?1:0;
}
</script>
| c48559e9d5123ffd352f7d80f734623f2eeba2bd | [
"Markdown",
"JavaScript"
]
| 3 | Markdown | js13kGames/404-Princess | d43906deec7ca141046ace8104226a4bc4045548 | e5cbbc8d927f3adce0c1f0f9f39ce3d76e9e5672 |
refs/heads/main | <file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 5 13:58:21 2021
@author: vanessamsantana
"""
# REFERENCE POST: https://stackoverflow.com/questions/53374233/mit-programming-in-python-problem-set-1-part-c
def calculateSavings(current_Savings, monthly_Salary, portion_saved, downpayment_months):
semi_annual_raise = 0.07
monthly_invest_return = 0
r = 0.04 #annual return at end of each month
for downpayment_months in range(1, 37):
if (downpayment_months%6 == 0):
annual_salary = monthly_Salary * 12
annual_salary = annual_salary + (annual_salary*semi_annual_raise)
monthly_Salary = annual_salary/12
current_Savings = current_Savings + (monthly_Salary * portion_saved)
current_Savings = current_Savings + monthly_invest_return
monthly_invest_return = current_Savings*(r/12)
current_Savings = round(current_Savings, 0)
# print("Current savings: " + str(current_Savings) + ", on month " + str(downpayment_months))
return (current_Savings)
x = 1.0
epsilon = 100
numGuesses = 0
low = 0.0
high = max(0.0, x)
ans = (high + low)/2.0
portion_saved = ans
portion_down_payment = 0.25
# monthly_invest_return = 0
current_savings = 0.0
# annual_salary = 300000 #150000
total_cost = 1000000.0
downpayment_months = 36
downpayment_amount = total_cost*portion_down_payment
# print("Down payment: " + str(downpayment_amount))
# print()
annual_salary = input("Enter the starting salary: ")
print()
annual_salary = float(annual_salary)
monthly_salary = annual_salary/12
while abs(current_savings - downpayment_amount) >= epsilon:
# portion_saved = round(portion_saved, 4)
current_savings = calculateSavings(current_savings, monthly_salary, portion_saved, 1)
# print("Saved Percentage: " + str(portion_saved))
# print("Current savings in " + str(downpayment_months) + " months: " + str(current_savings))
# print()
if (current_savings < downpayment_amount):
low = ans
current_savings = 0
elif (current_savings > downpayment_amount + epsilon):
high = ans
current_savings = 0
if (numGuesses > 50):
print("It is not possible to pay the down payment in " + str(downpayment_months) + " months.")
print()
break
ans = (high + low)/2.0
ans = round(ans, 4)
portion_saved = ans
numGuesses = numGuesses + 1
if (numGuesses < 50):
print("Best Savings Rate: " + str(portion_saved))
print("Down payment: " + str(downpayment_amount))
print("Final savings amount: " + str(current_savings))
print("Steps in Bisection Search: " + str(numGuesses))
| 42fb54adfee49cbb6748f69005aba445945a1d4e | [
"Python"
]
| 1 | Python | vsantanait/House-Hunting-Best-Rate | 67e75eb44a4a86fb704035cf4218ded1481dd927 | e5486a899a94394e27f278867f5f513da07717eb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.