repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
oversecio/oversec_crypto | crypto/src/main/java/io/oversec/one/crypto/symbase/BaseSymmetricCryptoHandler.kt | 1 | 9553 | package io.oversec.one.crypto.symbase
import android.content.Context
import android.content.Intent
import com.google.protobuf.ByteString
import io.oversec.one.crypto.*
import io.oversec.one.crypto.proto.Inner
import io.oversec.one.crypto.proto.Outer
import io.oversec.one.crypto.sym.KeyNotCachedException
import io.oversec.one.crypto.sym.SymUtil
import io.oversec.one.crypto.sym.SymmetricKeyPlain
import roboguice.util.Ln
import java.io.IOException
import java.security.GeneralSecurityException
abstract class BaseSymmetricCryptoHandler(ctx: Context) : AbstractCryptoHandler(ctx) {
protected val mKeyCache: KeyCache = KeyCache.getInstance(ctx)
protected abstract val method: EncryptionMethod
override val displayEncryptionMethod: Int
get() = R.string.encryption_method_sym
@Throws(KeyNotCachedException::class)
protected abstract fun getKeyByHashedKeyId(
keyhash: Long,
salt: ByteArray,
cost: Int,
encryptedText: String?
): SymmetricKeyPlain?
@Throws(UserInteractionRequiredException::class)
protected fun tryDecrypt(
symMsg: Outer.MsgTextSymV0,
encryptedText: String?
): SymmetricDecryptResult {
if (symMsg.hasMsgTextChaChaV0()) {
val chachaMsg = symMsg.msgTextChaChaV0
val pkcl = chachaMsg.perKeyCiphertextList
var key: SymmetricKeyPlain? = null
var matchingPkc: Outer.MsgTextChaChaV0_KeyAndSaltAndCiphertext? = null
for (pkc in pkcl) {
// sym: key exists, but is not cached -> throws KeyNotCachedException, OK
// simple (if key exists it is always cached)
key = getKeyByHashedKeyId(
pkc.keyhash,
pkc.salt.toByteArray(),
chachaMsg.costKeyhash,
encryptedText
)
if (key != null) {
matchingPkc = pkc
break
}
}
if (key == null) {
Ln.d("SYM: NO MATCHING KEY")
//sym: if key exists but not cached we will not reach here, a KeyNotCachedException will have been thrown before
//sym: if key doesn't exists, return SYM_NO_MATCHING_KEY
//simple: if key doesn't exist, throw a userInteraction exception to enter the key
val keyHashes = LongArray(pkcl.size) {
pkcl[it].keyhash
}
val salts = Array(pkcl.size) {
pkcl[it].salt.toByteArray()
}
handleNoKeyFoundForDecryption(
keyHashes,
salts,
chachaMsg.costKeyhash,
encryptedText
)
return SymmetricDecryptResult(
method,
BaseDecryptResult.DecryptError.SYM_NO_MATCHING_KEY
)
} else {
Ln.d("SYM: try decrypt with key %s", key.id)
var rawData: ByteArray? = null
try {
requireNotNull(matchingPkc)
rawData = tryDecryptChacha(matchingPkc, key)
} catch (e: Exception) {
e.printStackTrace()
}
return if (rawData != null) {
Ln.d("SYM: try last used key SUCCESS")
SymmetricDecryptResult(method, rawData, key.id)
} else {
Ln.d("SYM: DECRYPTION FAILED")
SymmetricDecryptResult(
method,
BaseDecryptResult.DecryptError.SYM_DECRYPT_FAILED
)
}
}
}
Ln.d("SYM: DECRYPTION FAILED")
return SymmetricDecryptResult(method, BaseDecryptResult.DecryptError.SYM_UNSUPPORTED_CIPHER)
}
@Throws(UserInteractionRequiredException::class)
protected abstract fun handleNoKeyFoundForDecryption(
keyHashes: LongArray,
salts: Array<ByteArray>,
costKeyhash: Int,
encryptedText: String?
)
@Throws(
IOException::class,
GeneralSecurityException::class,
UserInteractionRequiredException::class
)
override fun encrypt(
innerData: Inner.InnerData,
params: AbstractEncryptionParams,
actionIntent: Intent?
): Outer.Msg {
val p = params as BaseSymmetricEncryptionParams
return encrypt(innerData.toByteArray(), p.keyIds)
}
@Throws(
GeneralSecurityException::class,
UserInteractionRequiredException::class,
IOException::class
)
override fun encrypt(
plainText: String,
params: AbstractEncryptionParams,
actionIntent: Intent?
): Outer.Msg {
val p = params as BaseSymmetricEncryptionParams
return encrypt(plainText.toByteArray(charset("UTF-8")), p.keyIds)
}
@Throws(GeneralSecurityException::class, IOException::class, KeyNotCachedException::class)
private fun encrypt(plain: ByteArray, keyIds: List<Long>): Outer.Msg {
val cost_key_id = KeyUtil.BCRYPT_SESSIONKEYID_COST_DEFAULT //TODO make configurable
val builderMsg = Outer.Msg.newBuilder()
val symMsgBuilder = builderMsg.msgTextSymV0Builder
val chachaMsgBuilder = symMsgBuilder.msgTextChaChaV0Builder
chachaMsgBuilder.costKeyhash = cost_key_id
for (keyId in keyIds) {
val pkcBuilder = chachaMsgBuilder.addPerKeyCiphertextBuilder()
val salt = KeyUtil.getRandomBytes(SALT_LENGTH)
val iv = KeyUtil.getRandomBytes(IV_LENGTH)
val hashedKeyId = KeyUtil.calcSessionKeyId(keyId, salt, cost_key_id)
val plainKey = mKeyCache.get(keyId) //throws KeyNotCached
val ciphertext = KeyUtil.encryptSymmetricChaCha(plain, salt, iv, plainKey)
pkcBuilder.iv = ByteString.copyFrom(iv)
pkcBuilder.keyhash = hashedKeyId
pkcBuilder.salt = ByteString.copyFrom(salt)
pkcBuilder.ciphertext = ByteString.copyFrom(ciphertext)
}
KeyUtil.erase(plain)
symMsgBuilder.setMsgTextChaChaV0(chachaMsgBuilder)
setMessage(builderMsg, symMsgBuilder)
val msg = builderMsg.build()
Ln.d("BCRYPT: ...encrypt")
return msg
}
protected abstract fun setMessage(
builderMsg: Outer.Msg.Builder,
symMsgBuilder: Outer.MsgTextSymV0.Builder
)
@Throws(
IOException::class,
GeneralSecurityException::class,
OversecChacha20Poly1305.MacMismatchException::class
)
protected fun tryDecryptChacha(
matchingPkc: Outer.MsgTextChaChaV0_KeyAndSaltAndCiphertext,
key: SymmetricKeyPlain
): ByteArray {
return KeyUtil.decryptSymmetricChaCha(
matchingPkc.ciphertext.toByteArray(),
matchingPkc.salt.toByteArray(),
matchingPkc.iv.toByteArray(),
key
)
}
companion object {
const val IV_LENGTH = 8
const val SALT_LENGTH = 16 //DO NOT CHANGE, needs to match Bcrypt.SALT_SIZE_BYTES
fun getRawMessageJson(msg: Outer.Msg): String? {
var chachaMsg: Outer.MsgTextChaChaV0? = null;
if (msg.hasMsgTextSymSimpleV0()) {
val symSimpleV0Msg = msg.msgTextSymSimpleV0
if (symSimpleV0Msg.hasMsgTextChaChaV0()) {
chachaMsg = symSimpleV0Msg.msgTextChaChaV0
}
} else
if (msg.hasMsgTextSymV0()) {
val symV0Msg = msg.msgTextSymV0
if (symV0Msg.hasMsgTextChaChaV0()) {
chachaMsg = symV0Msg.msgTextChaChaV0
}
}
if (chachaMsg != null) {
val sb = StringBuilder()
sb.append("{")
sb.append("\n")
sb.append(" \"cipher\":\"chacha20+poly1305\"")
sb.append(",\n")
sb.append(" \"cost_keyhash\":").append(chachaMsg.costKeyhash)
sb.append(",\n")
sb.append(" \"per_key_encrypted_data\": [")
sb.append("\n")
val pkcl = chachaMsg.perKeyCiphertextList
for (pkc in pkcl) {
sb.append(" {")
sb.append("\n")
sb.append(" \"keyhash\":\"")
.append(SymUtil.byteArrayToHex(SymUtil.long2bytearray(pkc.keyhash)))
.append("\"")
sb.append(",\n")
sb.append(" \"salt\":\"")
.append(SymUtil.byteArrayToHex(pkc.salt.toByteArray())).append("\"")
sb.append(",\n")
sb.append(" \"iv\":\"")
.append(SymUtil.byteArrayToHex(pkc.iv.toByteArray())).append("\"")
sb.append(",\n")
sb.append(" \"ciphertext\":\"")
.append(SymUtil.byteArrayToHex(pkc.ciphertext.toByteArray()))
.append("\"")
sb.append("\n")
sb.append(" }")
sb.append("\n")
}
sb.append(" ]")
sb.append("}")
return sb.toString()
} else {
return null
}
}
}
}
| gpl-3.0 | 1375372a536ae94a01b1dd9a865434de | 33.117857 | 128 | 0.557731 | 4.597209 | false | false | false | false |
ibinti/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/driver/ExtendedJTreeDriver.kt | 1 | 20303 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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 com.intellij.testGuiFramework.driver
import com.intellij.testGuiFramework.cellReader.ExtendedJTreeCellReader
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.computeOnEdt
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.computeOnEdtWithTry
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.runOnEdt
import com.intellij.ui.LoadingNode
import org.fest.assertions.Assertions
import org.fest.reflect.core.Reflection
import org.fest.swing.cell.JTreeCellReader
import org.fest.swing.core.MouseButton
import org.fest.swing.core.MouseClickInfo
import org.fest.swing.core.Robot
import org.fest.swing.driver.ComponentPreconditions
import org.fest.swing.driver.JTreeDriver
import org.fest.swing.driver.JTreeLocation
import org.fest.swing.exception.ActionFailedException
import org.fest.swing.exception.LocationUnavailableException
import org.fest.swing.exception.WaitTimedOutError
import org.fest.swing.timing.Condition
import org.fest.swing.timing.Pause
import org.fest.swing.util.Pair
import org.fest.swing.util.Triple
import org.fest.util.Lists
import org.fest.util.Preconditions
import java.awt.Point
import java.awt.Rectangle
import javax.annotation.Nonnull
import javax.swing.JPopupMenu
import javax.swing.JTree
import javax.swing.plaf.basic.BasicTreeUI
import javax.swing.tree.TreePath
/**
* To avoid confusions of parsing path from one String let's accept only splitted path into array of strings
*/
class ExtendedJTreeDriver(robot: Robot) : JTreeDriver(robot) {
private val pathFinder = ExtendedJTreePathFinder()
private val location = JTreeLocation()
fun clickPath(tree: JTree, pathStrings: List<String>, mouseClickInfo: MouseClickInfo)
= clickPath(tree, pathStrings, mouseClickInfo.button(), mouseClickInfo.times())
fun clickPath(tree: JTree, pathStrings: List<String>, button: MouseButton = MouseButton.LEFT_BUTTON, times: Int = 1) {
val point = scrollToPath(tree, pathStrings)
robot.click(tree, point, button, times)
}
//XPath contains order number of similar nodes: clickXPath("test(1)", "Java") - here (1) means the first node
fun clickXPath(tree: JTree, xPathStrings: List<String>, button: MouseButton = MouseButton.LEFT_BUTTON, times: Int = 1) {
val point = scrollToXPath(tree, xPathStrings)
robot.click(tree, point, button, times)
}
fun checkPathExists(tree: JTree, pathStrings: List<String>) {
matchingPathFor(tree = tree, pathStrings = pathStrings, isUniquePath = false)
}
fun nodeValue(tree: JTree, pathStrings: List<String>): String? = nodeText(tree, pathStrings)
fun doubleClickPath(tree: JTree, pathStrings: List<String>) {
val p = scrollToPath(tree, pathStrings)
doubleClick(tree, p)
}
fun rightClickPath(tree: JTree, pathStrings: List<String>) {
val p = scrollToPath(tree, pathStrings)
rightClick(tree, p)
}
fun expandPath(tree: JTree, pathStrings: List<String>) {
val info = scrollToMatchingPathAndGetToggleInfo(tree, pathStrings)
if (!info.first) toggleCell(tree, info.second!!, info.third)
}
fun collapsePath(tree: JTree, pathStrings: List<String>) {
val info = scrollToMatchingPathAndGetToggleInfo(tree, pathStrings)
if (info.first) toggleCell(tree, info.second!!, info.third)
}
fun selectPath(tree: JTree, pathStrings: List<String>) {
selectMatchingPath(tree, pathStrings)
}
fun scrollToPath(tree: JTree, pathStrings: List<String>): Point {
robot.waitForIdle()
return scrollToMatchingPath(tree, pathStrings).third!!
}
fun scrollToXPath(tree: JTree, xPathStrings: List<String>): Point {
robot.waitForIdle()
return scrollToMatchingXPath(tree, xPathStrings).third!!
}
fun showPopupMenu(tree: JTree, pathStrings: List<String>): JPopupMenu {
val info = scrollToMatchingPath(tree, pathStrings)
robot.waitForIdle()
return robot.showPopupMenu(tree, info.third!!)
}
fun drag(tree: JTree, pathStrings: List<String>) {
val p = selectMatchingPath(tree, pathStrings)
drag(tree, p)
}
fun drop(tree: JTree, pathStrings: List<String>) {
drop(tree, scrollToMatchingPath(tree, pathStrings).third!!)
}
///OVERRIDDEN FUNCTIONS/////
override fun clickPath(tree: JTree, path: String) = clickPath(tree, listOf(path))
override fun clickPath(tree: JTree, path: String, button: MouseButton) = clickPath(tree, listOf(path), button)
override fun clickPath(tree: JTree, path: String, mouseClickInfo: MouseClickInfo) = clickPath(tree, listOf(path), mouseClickInfo)
override fun checkPathExists(tree: JTree, path: String) {
matchingPathFor(tree, listOf(path))
}
override fun nodeValue(tree: JTree, path: String): String? = nodeValue(tree, listOf(path))
override fun nodeValue(tree: JTree, row: Int): String? = nodeText(tree, row, location)
override fun doubleClickPath(tree: JTree, path: String) = doubleClickPath(tree, listOf(path))
override fun rightClickPath(tree: JTree, path: String) = rightClickPath(tree, listOf(path))
override fun expandPath(tree: JTree, path: String) = expandPath(tree, listOf(path))
override fun collapsePath(tree: JTree, path: String) = collapsePath(tree, listOf(path))
override fun selectPath(tree: JTree, path: String) = selectPath(tree, listOf(path))
override fun showPopupMenu(tree: JTree, path: String) = showPopupMenu(tree, listOf(path))
override fun drag(tree: JTree, path: String) = drag(tree, listOf(path))
override fun drop(tree: JTree, path: String) = drop(tree, listOf(path))
///--------------------/////
///PRIVATE FUNCTIONS/////
private fun doubleClick(tree: JTree, p: Point) {
robot.click(tree, p, MouseButton.LEFT_BUTTON, 2)
}
private fun rightClick(@Nonnull tree: JTree, @Nonnull p: Point) {
robot.click(tree, p, MouseButton.RIGHT_BUTTON, 1)
}
private fun scrollToMatchingPath(tree: JTree, pathStrings: List<String>): Triple<TreePath, Boolean, Point> {
val matchingPath = verifyJTreeIsReadyAndFindMatchingPath(tree, pathStrings)
makeVisible(tree, matchingPath, false)
val info = scrollToPathToSelect(tree, matchingPath, location)
return Triple.of(matchingPath, info.first, info.second)
}
private fun scrollToMatchingXPath(tree: JTree, xPathStrings: List<String>): Triple<TreePath, Boolean, Point> {
val matchingPath = verifyJTreeIsReadyAndFindMatchingXPath(tree, xPathStrings)
makeVisible(tree, matchingPath, false)
val info = scrollToPathToSelect(tree, matchingPath, location)
return Triple.of(matchingPath, info.first, info.second)
}
private fun scrollToPathToSelect(@Nonnull tree: JTree, @Nonnull path: TreePath, @Nonnull location: JTreeLocation): Pair<Boolean, Point> {
return computeOnEdt {
val isSelected = tree.selectionCount == 1 && tree.isPathSelected(path)
Pair.of(isSelected, scrollToTreePath(tree, path, location))
}!!
}
private fun scrollToTreePath(tree: JTree, path: TreePath, location: JTreeLocation): Point {
val boundsAndCoordinates = location.pathBoundsAndCoordinates(tree, path)
tree.scrollRectToVisible(boundsAndCoordinates.first as Rectangle)
return boundsAndCoordinates.second!!
}
private fun scrollToMatchingPathAndGetToggleInfo(tree: JTree,
pathStrings: List<String>): Triple<Boolean, Point, Int> {
return computeOnEdt {
ComponentPreconditions.checkEnabledAndShowing(tree)
val matchingPath = matchingPathFor(tree, pathStrings)
val point = scrollToTreePath(tree, matchingPath, location)
Triple.of(tree.isExpanded(matchingPath), point, tree.toggleClickCount)
}!!
}
private fun makeVisible(tree: JTree, path: TreePath, expandWhenFound: Boolean): Boolean {
var changed = false
if (path.pathCount > 1) {
changed = makeParentVisible(tree, path)
}
if (!expandWhenFound) {
return changed
}
else {
expandTreePath(tree, path)
waitForChildrenToShowUp(tree, path)
return true
}
}
private fun waitForChildrenToShowUp(@Nonnull tree: JTree, @Nonnull path: TreePath) {
val timeout = robot.settings().timeoutToBeVisible().toLong()
try {
pause(timeout) { childCount(tree, path) != 0 }
}
catch (waitTimedOutError: WaitTimedOutError) {
throw LocationUnavailableException(waitTimedOutError.message!!)
}
}
private fun makeParentVisible(tree: JTree, path: TreePath): Boolean {
val changed = makeVisible(tree, Preconditions.checkNotNull(path.parentPath), true)
if (changed) robot.waitForIdle()
return changed
}
internal class ExtendedJTreePathFinder {
private var cellReader: JTreeCellReader? = null
init {
this.replaceCellReader(ExtendedJTreeCellReader())
}
fun findMatchingPath(tree: JTree, pathStrings: List<String>): TreePath {
val model = tree.model
val newPathValues = Lists.newArrayList<Any>()
var node: Any = model.root
val pathElementCount = pathStrings.size
for (stringIndex in 0..pathElementCount - 1) {
val pathString = pathStrings[stringIndex]
if (stringIndex == 0 && tree.isRootVisible) {
if (pathString != value(tree, node)) throw pathNotFound(pathStrings)
newPathValues.add(node)
}
else {
try {
node = traverseChildren(tree, node, pathString) ?: throw pathNotFound(pathStrings)
}
catch(e: LoadingNodeException) { //if we met loading node let's tell it to caller and probably expand path to clarify this node
e.treePath = TreePath(newPathValues.toTypedArray())
throw e
}
newPathValues.add(node)
}
}
return TreePath(newPathValues.toTypedArray())
}
private fun traverseChildren(tree: JTree,
node: Any,
pathString: String): Any? {
var match: Any? = null
val model = tree.model
val childCount = model.getChildCount(node)
for (childIndex in 0..childCount - 1) {
val child = model.getChild(node, childIndex)
if (child is LoadingNode) throw LoadingNodeException(child, null)
if (pathString == value(tree, child)) {
if (match != null) throw multipleMatchingNodes(pathString, value(tree, node))
match = child
}
}
return match
}
fun findMatchingPath(tree: JTree, pathStrings: List<String>, isUniquePath: Boolean = true): TreePath {
if (isUniquePath) return findMatchingPath(tree, pathStrings)
val model = tree.model
if (tree.isRootVisible) {
if (pathStrings[0] != value(tree, model.root)) throw pathNotFound(pathStrings)
if (pathStrings.size == 1) return TreePath(arrayOf<Any>(model.root))
val result: TreePath = findMatchingPath(tree, model.root, pathStrings.subList(1, pathStrings.size)) ?: throw pathNotFound(
pathStrings)
return TreePath(arrayOf<Any>(model.root, *result.path))
}
else {
return findMatchingPath(tree, model.root, pathStrings) ?: throw pathNotFound(pathStrings)
}
}
/**
* this method tries to find any path. If tree contains multiple of searchable path it still accepts
*/
private fun findMatchingPath(tree: JTree, node: Any, pathStrings: List<String>): TreePath? {
val model = tree.model
val childCount = model.getChildCount(node)
for (childIndex in 0..childCount - 1) {
val child = model.getChild(node, childIndex)
if (child is LoadingNode) throw LoadingNodeException(child, null)
if (pathStrings.size == 1 && value(tree, child) == pathStrings[0]) {
return TreePath(arrayOf<Any>(child))
}
else {
if (pathStrings[0] == value(tree, child)) {
val childResult = findMatchingPath(tree, child, pathStrings.subList(1, pathStrings.size))
if (childResult != null) return TreePath(arrayOf<Any>(child, *childResult.path))
}
}
}
return null
}
fun findMatchingXPath(tree: JTree, xPathStrings: List<String>): TreePath {
val model = tree.model
if (tree.isRootVisible) {
if (xPathStrings[0] != value(tree, model.root)) throw pathNotFound(xPathStrings)
if (xPathStrings.size == 1) return TreePath(arrayOf<Any>(model.root))
val result: TreePath = findMatchingXPath(tree, model.root, xPathStrings.subList(1, xPathStrings.size)) ?: throw pathNotFound(
xPathStrings)
return TreePath(arrayOf<Any>(model.root, *result.path))
}
else {
return findMatchingXPath(tree, model.root, xPathStrings) ?: throw pathNotFound(xPathStrings)
}
}
private fun findMatchingXPath(tree: JTree, node: Any, xPathStrings: List<String>): TreePath? {
val model = tree.model
val childCount = model.getChildCount(node)
val order = xPathStrings[0].getOrder() ?: 0
val original = if (xPathStrings[0].hasOrder()) xPathStrings[0].subSequence(0,
xPathStrings[0].length - 2 - (order.toString().length))
else xPathStrings[0]
var currentOrder = 0
for (childIndex in 0..childCount - 1) {
val child = model.getChild(node, childIndex)
if (original == value(tree, child)) {
if (currentOrder == order) {
if (xPathStrings.size == 1) {
return TreePath(arrayOf<Any>(child))
} else {
val childResult = findMatchingXPath(tree, child, xPathStrings.subList(1, xPathStrings.size))
if (childResult != null) return TreePath(arrayOf<Any>(child, *childResult.path))
}
} else {
currentOrder++
}
}
}
return null
}
private fun String.hasOrder(): Boolean =
Regex("\\(\\d\\)").find(this)?.value?.isNotEmpty() ?: false
private fun String.getOrder(): Int? {
val find: MatchResult = Regex("\\(\\d\\)").find(this) ?: return null
return find.value.removeSurrounding("(", ")").toInt()
}
private fun pathNotFound(path: List<String>): LocationUnavailableException {
throw LocationUnavailableException("Unable to find path \"$path\"")
}
private fun multipleMatchingNodes(pathString: String, parentText: Any): LocationUnavailableException {
throw LocationUnavailableException("There is more than one node with value '$pathString' under \"$parentText\"")
}
private fun value(tree: JTree, modelValue: Any): String {
return cellReader!!.valueAt(tree, modelValue)!!
}
fun replaceCellReader(newCellReader: JTreeCellReader) {
cellReader = newCellReader
}
fun cellReader(): JTreeCellReader {
return cellReader!!
}
}
/**
* node that has as child LoadingNode
*/
class LoadingNodeException(val node: Any, var treePath: TreePath?) : Exception("Meet loading node: $node")
private fun childCount(tree: JTree, path: TreePath): Int {
return computeOnEdt {
val lastPathComponent = path.lastPathComponent
tree.model.getChildCount(lastPathComponent)
}!!
}
private fun nodeText(tree: JTree, row: Int, location: JTreeLocation): String? {
return computeOnEdt {
val matchingPath = location.pathFor(tree, row)
pathFinder.cellReader().valueAt(tree, Preconditions.checkNotNull(matchingPath.lastPathComponent))
}
}
private fun nodeText(tree: JTree, pathStrings: List<String>): String? {
return computeOnEdt {
val matchingPath = matchingPathWithRootIfInvisible(tree, pathStrings, true)
pathFinder.cellReader().valueAt(tree, matchingPath.lastPathComponent!!)
}
}
private fun verifyJTreeIsReadyAndFindMatchingPath(tree: JTree, pathStrings: List<String>): TreePath {
return computeOnEdt {
ComponentPreconditions.checkEnabledAndShowing(tree)
matchingPathWithRootIfInvisible(tree, pathStrings, true)
}!!
}
private fun verifyJTreeIsReadyAndFindMatchingXPath(tree: JTree, xPathStrings: List<String>): TreePath {
return computeOnEdt {
ComponentPreconditions.checkEnabledAndShowing(tree)
matchingXPathWithRootIfInvisible(tree, xPathStrings, false)
}!!
}
/**
* we are trying to find TreePath for a tree, if we met loading node (LoadingTreeNode)
*/
private fun matchingPathFor(tree: JTree, pathStrings: List<String>, countDownAttempts: Int = 30, isUniquePath: Boolean = true): TreePath {
if (countDownAttempts == 0) throw Exception("Unable to find path($pathStrings) for tree: $tree, attempts count exceeded")
try {
return computeOnEdtWithTry {
matchingPathWithRootIfInvisible(tree, pathStrings, isUniquePath)
}!!
}
catch (e: LoadingNodeException) {
if (e.treePath != null) expandTreePath(tree, e.treePath!!)
return matchingPathFor(tree, pathStrings, countDownAttempts - 1, isUniquePath)
}
}
private fun matchingPathWithRootIfInvisible(tree: JTree, pathStrings: List<String>, isUniquePath: Boolean): TreePath {
val matchingPath = pathFinder.findMatchingPath(tree, pathStrings, isUniquePath)
return addRootIfInvisible(tree, matchingPath)
}
private fun matchingXPathWithRootIfInvisible(tree: JTree, xPathStrings: List<String>, isUniquePath: Boolean): TreePath {
val matchingPath = pathFinder.findMatchingXPath(tree, xPathStrings)
return addRootIfInvisible(tree, matchingPath)
}
private fun addRootIfInvisible(@Nonnull tree: JTree, @Nonnull path: TreePath): TreePath {
val root = tree.model.root
if (!tree.isRootVisible && root != null) {
if (path.pathCount > 0 && root === path.getPathComponent(0)) {
return path
}
else {
val pathAsArray = path.path
if (pathAsArray == null) {
return TreePath(Lists.newArrayList(*arrayOf(root)))
}
else {
val newPath = Lists.newArrayList(*pathAsArray)
newPath.add(0, root)
return TreePath(newPath.toTypedArray())
}
}
}
else {
return path
}
}
private fun expandTreePath(tree: JTree, path: TreePath) {
runOnEdt {
val realPath = addRootIfInvisible(tree, path)
if (!tree.isExpanded(path)) tree.expandPath(realPath)
}
}
private fun toggleCell(@Nonnull tree: JTree, @Nonnull p: Point, toggleClickCount: Int) {
if (toggleClickCount == 0) {
toggleRowThroughTreeUI(tree, p)
robot.waitForIdle()
}
else {
robot.click(tree, p, MouseButton.LEFT_BUTTON, toggleClickCount)
}
}
private fun toggleRowThroughTreeUI(@Nonnull tree: JTree, @Nonnull p: Point) {
runOnEdt {
if (tree.ui !is BasicTreeUI)
throw ActionFailedException.actionFailure("Can't toggle row for ${tree.ui}")
else
toggleExpandState(tree, p)
}
}
private fun toggleExpandState(@Nonnull tree: JTree, @Nonnull pathLocation: Point) {
val path = tree.getPathForLocation(pathLocation.x, pathLocation.y)
val treeUI = tree.ui
Assertions.assertThat(treeUI).isInstanceOf(BasicTreeUI::class.java)
Reflection.method("toggleExpandState").withParameterTypes(*arrayOf<Class<*>>(TreePath::class.java)).`in`(treeUI).invoke(
*arrayOf<Any>(path))
}
private fun selectMatchingPath(tree: JTree, pathStrings: List<String>): Point {
val info = scrollToMatchingPath(tree, pathStrings)
robot.waitForIdle()
val where = info.third!!
if (!info.second) robot.click(tree, where)
return where
}
private fun pause(timeout: Long, condition: () -> Boolean) {
Pause.pause(object : Condition("ExtendedJTreeDriver wait condition:") {
override fun test() = condition()
})
}
}
| apache-2.0 | bcb2d22b0c2ccd73f15d3aa1a754ff4b | 36.598148 | 142 | 0.690834 | 4.220121 | false | false | false | false |
grote/Transportr | app/src/main/java/de/grobox/transportr/utils/OnboardingBuilder.kt | 1 | 2127 | /*
* Transportr
*
* Copyright (c) 2013 - 2021 Torsten Grote
*
* This program 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/>.
*/
package de.grobox.transportr.utils
import android.app.Activity
import androidx.core.content.ContextCompat
import android.util.TypedValue
import de.grobox.transportr.R
import uk.co.samuelwall.materialtaptargetprompt.MaterialTapTargetPrompt
import uk.co.samuelwall.materialtaptargetprompt.extras.backgrounds.CirclePromptBackground
import uk.co.samuelwall.materialtaptargetprompt.extras.backgrounds.RectanglePromptBackground
import uk.co.samuelwall.materialtaptargetprompt.extras.focals.CirclePromptFocal
import uk.co.samuelwall.materialtaptargetprompt.extras.focals.RectanglePromptFocal
class OnboardingBuilder(activity: Activity) : MaterialTapTargetPrompt.Builder(activity) {
init {
backgroundColour = ContextCompat.getColor(activity, R.color.primary)
promptBackground = RectanglePromptBackground()
promptFocal = RectanglePromptFocal()
setFocalPadding(R.dimen.buttonSize)
val typedValue = TypedValue()
activity.theme.resolveAttribute(android.R.attr.windowBackground, typedValue, true)
focalColour = typedValue.data
}
}
class IconOnboardingBuilder(activity: Activity) : MaterialTapTargetPrompt.Builder(activity) {
init {
backgroundColour = ContextCompat.getColor(activity, R.color.primary)
promptBackground = CirclePromptBackground()
promptFocal = CirclePromptFocal()
}
} | gpl-3.0 | 4c19770aa69753979eebda7c8fad91ae | 37 | 93 | 0.760696 | 4.237052 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/entity/media/CalendarEntry.kt | 2 | 2317 | package me.proxer.library.entity.media
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import me.proxer.library.entity.ProxerDateItem
import me.proxer.library.entity.ProxerIdItem
import me.proxer.library.enums.CalendarDay
import me.proxer.library.internal.adapter.DelimitedStringSet
import java.util.Date
/**
* Entity holding the data of a single calendar entry.
*
* @property entryId The id of the associated [me.proxer.library.entity.info.Entry].
* @property name The name.
* @property episode The next episode to be aired.
* @property episodeTitle The title of the next episode to be aired. May be empty.
* @property timezone The timezone of the country, the episode is aired in.
* @property industryId The id of the television channel, transmitting the episode. "0" if not set.
* @property industryName The name of the television channel, transmitting the episode. May be null.
* @property weekDay The day of the week, the episode is aired.
* @property uploadDate The date (and time), the episode will be uploaded.
* This is just an estimated value and can be imprecise.
* @property genres The genres.
* @property ratingSum The sum of all ratings.
* @property ratingAmount The amount of ratings.
*
* @author Ruben Gees
*/
@JsonClass(generateAdapter = true)
data class CalendarEntry(
@Json(name = "id") override val id: String,
@Json(name = "eid") val entryId: String,
@Json(name = "entryname") val name: String,
@Json(name = "episode") val episode: Int,
@Json(name = "episodeTitle") val episodeTitle: String,
@Json(name = "time") override val date: Date,
@Json(name = "timezone") val timezone: String,
@Json(name = "iid") val industryId: String,
@Json(name = "industryname") val industryName: String?,
@Json(name = "weekday") val weekDay: CalendarDay,
@Json(name = "uptime") val uploadDate: Date,
@field:DelimitedStringSet(valuesToKeep = ["Slice of Life"]) @Json(name = "genre") val genres: Set<String>,
@Json(name = "rate_sum") val ratingSum: Int,
@Json(name = "rate_count") val ratingAmount: Int
) : ProxerIdItem, ProxerDateItem {
/**
* Returns the average of all ratings.
*/
val rating = when {
ratingAmount <= 0 -> 0f
else -> ratingSum.toFloat() / ratingAmount.toFloat()
}
}
| gpl-3.0 | f29cdf7c20b794961990ce7aaac2c193 | 41.127273 | 110 | 0.711265 | 3.761364 | false | false | false | false |
hendraanggrian/picasso-transformations | example/src/com/example/pikasso/PersistentBottomSheetBehavior.kt | 1 | 1642 | package com.example.pikasso
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat.getDrawable
import androidx.core.view.GravityCompat.START
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.bottomsheet.BottomSheetBehavior
import kotlinx.android.synthetic.main.activity_example.*
class PersistentBottomSheetBehavior @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : BottomSheetBehavior<AppBarLayout>(context, attrs) {
init {
val activity = context as ExampleActivity
addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
override fun onSlide(view: View, i: Float) {}
override fun onStateChanged(view: View, state: Int) = activity.run {
when {
state == STATE_HIDDEN -> setState(STATE_COLLAPSED) // persistent
state == STATE_EXPANDED -> {
pasteItem.isVisible = true
toggleExpandItem.icon = getDrawable(this, R.drawable.ic_collapse)
toggleExpandItem.title = "Collapse"
}
state == STATE_COLLAPSED -> {
pasteItem.isVisible = false
toggleExpandItem.icon = getDrawable(this, R.drawable.ic_expand)
toggleExpandItem.title = "Expand"
}
activity.drawer.isDrawerOpen(START) -> drawer.closeDrawer(START)
}
}
})
}
} | mit | 17f6a6c35a2fdf1eb53f26c627ae99aa | 41.128205 | 89 | 0.620585 | 5.246006 | false | false | false | false |
tonyofrancis/Fetch | fetchmigrator/src/main/java/com/tonyodev/fetchmigrator/helpers/TypeConverters.kt | 1 | 3888 | package com.tonyodev.fetchmigrator.helpers
import android.database.Cursor
import com.tonyodev.fetch2.EnqueueAction
import com.tonyodev.fetch2.Error
import com.tonyodev.fetch2.Priority
import com.tonyodev.fetch2.Status
import com.tonyodev.fetch2.database.DownloadInfo
import com.tonyodev.fetch2.database.FetchDatabaseManagerWrapper
import com.tonyodev.fetch2.util.DEFAULT_DOWNLOAD_ON_ENQUEUE
import com.tonyodev.fetch2core.Extras
import com.tonyodev.fetchmigrator.fetch1.DatabaseHelper
import com.tonyodev.fetchmigrator.fetch1.DownloadTransferPair
import com.tonyodev.fetchmigrator.fetch1.FetchConst
import org.json.JSONObject
fun v1CursorToV2DownloadInfo(cursor: Cursor, databaseManagerWrapper: FetchDatabaseManagerWrapper): DownloadTransferPair {
val id = cursor.getLong(DatabaseHelper.INDEX_ID)
val status = cursor.getInt(DatabaseHelper.INDEX_COLUMN_STATUS)
val url = cursor.getString(DatabaseHelper.INDEX_COLUMN_URL)
val file = cursor.getString(DatabaseHelper.INDEX_COLUMN_FILEPATH)
val error = cursor.getInt(DatabaseHelper.INDEX_COLUMN_ERROR)
val total = cursor.getLong(DatabaseHelper.INDEX_COLUMN_FILE_SIZE)
val priority = cursor.getInt(DatabaseHelper.INDEX_COLUMN_PRIORITY)
val downloaded = cursor.getLong(DatabaseHelper.INDEX_COLUMN_DOWNLOADED_BYTES)
val headers = cursor.getString(DatabaseHelper.INDEX_COLUMN_HEADERS)
val downloadInfo = databaseManagerWrapper.getNewDownloadInfoInstance()
downloadInfo.id = (url.hashCode() * 31) + file.hashCode()
downloadInfo.url = url
downloadInfo.file = file
downloadInfo.status = getStatusFromV1ForV2(status)
downloadInfo.total = total
downloadInfo.downloaded = downloaded
downloadInfo.headers = fromHeaderStringToMap(headers)
downloadInfo.priority = getPriorityFromV1ForV2(priority)
downloadInfo.error = getErrorFromV1ForV2(error)
downloadInfo.enqueueAction = EnqueueAction.REPLACE_EXISTING
downloadInfo.identifier = downloadInfo.id.toLong()
downloadInfo.downloadOnEnqueue = DEFAULT_DOWNLOAD_ON_ENQUEUE
downloadInfo.extras = Extras.emptyExtras
return DownloadTransferPair(downloadInfo, id)
}
fun getStatusFromV1ForV2(v1StatusCode: Int): Status {
return when (v1StatusCode) {
FetchConst.STATUS_QUEUED -> Status.QUEUED
FetchConst.STATUS_DOWNLOADING -> Status.DOWNLOADING
FetchConst.STATUS_DONE -> Status.COMPLETED
FetchConst.STATUS_ERROR -> Status.FAILED
FetchConst.STATUS_PAUSED -> Status.PAUSED
FetchConst.STATUS_REMOVED -> Status.REMOVED
FetchConst.STATUS_NOT_QUEUED -> Status.NONE
else -> Status.NONE
}
}
fun getPriorityFromV1ForV2(v1PriorityCode: Int): Priority {
return when (v1PriorityCode) {
FetchConst.PRIORITY_HIGH -> Priority.HIGH
FetchConst.PRIORITY_NORMAL -> Priority.NORMAL
else -> Priority.LOW
}
}
fun getErrorFromV1ForV2(v1ErrorCode: Int): Error {
return when (v1ErrorCode) {
-1 -> Error.NONE
FetchConst.ERROR_FILE_NOT_CREATED -> Error.FILE_NOT_CREATED
FetchConst.ERROR_CONNECTION_TIMEOUT -> Error.CONNECTION_TIMED_OUT
FetchConst.ERROR_UNKNOWN_HOST -> Error.UNKNOWN_HOST
FetchConst.ERROR_HTTP_NOT_FOUND -> Error.HTTP_NOT_FOUND
FetchConst.ERROR_WRITE_PERMISSION_DENIED -> Error.WRITE_PERMISSION_DENIED
FetchConst.ERROR_NO_STORAGE_SPACE -> Error.NO_STORAGE_SPACE
FetchConst.ERROR_SERVER_ERROR -> Error.EMPTY_RESPONSE_FROM_SERVER
FetchConst.ERROR_REQUEST_ALREADY_EXIST -> Error.REQUEST_ALREADY_EXIST
FetchConst.ERROR_ENQUEUE_ERROR -> Error.FETCH_DATABASE_ERROR
else -> Error.UNKNOWN
}
}
fun fromHeaderStringToMap(headerString: String): Map<String, String> {
val map = mutableMapOf<String, String>()
val json = JSONObject(headerString)
json.keys().forEach {
map[it] = json.getString(it)
}
return map
} | apache-2.0 | d558648ca523c3a111363f2d2c865cc0 | 42.696629 | 121 | 0.754887 | 3.95122 | false | false | false | false |
katanagari7c1/wolverine-comics-kotlin | app/src/main/kotlin/dev/katanagari7c1/wolverine/presentation/main/data_loader/ComicListDataLoader.kt | 1 | 782 | package dev.katanagari7c1.wolverine.presentation.main.data_loader
import dev.katanagari7c1.wolverine.domain.entity.Comic
import dev.katanagari7c1.wolverine.domain.use_case.ComicFindFromOffsetUseCase
import dev.katanagari7c1.wolverine.domain.use_case.ComicSaveOrUpdateUseCase
class ComicListDataLoader (
val loadWithOffsetUseCase: ComicFindFromOffsetUseCase,
val saveUseCase: ComicSaveOrUpdateUseCase
) {
val numberOfItemsToLoad = 50
private var offset = 0
private var endReached = false
fun load():List<Comic> {
if (!endReached) {
val comics = this.loadWithOffsetUseCase.execute(this.offset, this.numberOfItemsToLoad)
this.saveUseCase.execute(comics)
this.offset += comics.size
this.endReached = comics.isEmpty()
return comics
}
return listOf()
}
} | mit | 4ddf3fd4fcbd81ecd4376fd08f6b6bf9 | 26.964286 | 89 | 0.796675 | 3.491071 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/shows/RemoveShowDialogFragment.kt | 1 | 3682 | package com.battlelancer.seriesguide.shows
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.core.os.bundleOf
import androidx.core.view.isGone
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.lifecycleScope
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.SgApp
import com.battlelancer.seriesguide.databinding.DialogRemoveBinding
import com.battlelancer.seriesguide.provider.SgRoomDatabase
import com.battlelancer.seriesguide.sync.SgSyncAdapter
import com.battlelancer.seriesguide.util.safeShow
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* Dialog to remove a show from the database.
*/
class RemoveShowDialogFragment : AppCompatDialogFragment() {
private var binding: DialogRemoveBinding? = null
private var showId: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
showId = requireArguments().getLong(ARG_LONG_SHOW_ID)
if (showId == 0L) dismiss()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val binding = DialogRemoveBinding.inflate(layoutInflater)
this.binding = binding
showProgressBar(true)
binding.buttonNegative.setText(android.R.string.cancel)
binding.buttonNegative.setOnClickListener { dismiss() }
binding.buttonPositive.setText(R.string.delete_show)
lifecycleScope.launchWhenStarted {
val titleOrNull = withContext(Dispatchers.IO) {
SgRoomDatabase.getInstance(requireContext()).sgShow2Helper().getShowTitle(showId)
}
withContext(Dispatchers.Main) {
if (titleOrNull == null) {
// Failed to find show.
Toast.makeText(context, R.string.delete_error, Toast.LENGTH_LONG).show()
dismiss()
return@withContext
}
binding.also {
it.textViewRemove.text = getString(R.string.confirm_delete, titleOrNull)
it.buttonPositive.setOnClickListener {
if (!SgSyncAdapter.isSyncActive(requireContext(), true)) {
SgApp.getServicesComponent(requireContext()).showTools()
.removeShow(showId)
dismiss()
}
}
showProgressBar(false)
}
}
}
return MaterialAlertDialogBuilder(requireContext())
.setView(binding.root)
.create()
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
private fun showProgressBar(isVisible: Boolean) {
binding?.also {
it.progressBarRemove.isGone = !isVisible
it.textViewRemove.isGone = isVisible
it.buttonPositive.isEnabled = !isVisible
}
}
companion object {
private const val ARG_LONG_SHOW_ID = "show_id"
@JvmStatic
fun show(showId: Long, fragmentManager: FragmentManager, context: Context): Boolean {
if (SgSyncAdapter.isSyncActive(context, true)) {
return false
}
return RemoveShowDialogFragment().apply {
arguments = bundleOf(ARG_LONG_SHOW_ID to showId)
}.safeShow(fragmentManager, "remove-show-dialog")
}
}
} | apache-2.0 | c7037087d79f22bef58300323065f8b1 | 34.757282 | 97 | 0.642314 | 5.245014 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/statistics/StatisticHelper.kt | 1 | 28099 | package ca.josephroque.bowlingcompanion.statistics
import android.os.Parcel
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game10AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game11AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game12AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game13AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game14AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game15AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game16AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game17AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game18AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game19AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game1AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game20AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game2AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game3AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game4AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game5AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game6AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game7AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game8AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.average.Game9AverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.AcesSparedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.AcesStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.ChopOffsSparedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.ChopOffsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.HeadPinsSparedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.HeadPinsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.LeftChopOffsSparedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.LeftChopOffsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.LeftSplitsSparedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.LeftSplitsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.LeftTwelvesSparedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.LeftTwelvesStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.LeftsSparedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.LeftsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.RightChopOffsSparedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.RightChopOffsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.RightSplitsSparedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.RightSplitsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.RightTwelvesSparedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.RightTwelvesStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.RightsSparedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.RightsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.SplitsSparedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.SplitsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.TwelvesSparedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.firstball.TwelvesStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.foul.FoulsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.general.BowlerNameStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.general.GameNameStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.general.LeagueNameStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.general.SeriesNameStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.matchplay.GamesLostStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.matchplay.GamesTiedStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.matchplay.GamesWonStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.overall.GameAverageStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.overall.HighSingleStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.overall.LeftOfMiddleHitsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.overall.MiddleHitsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.overall.NumberOfGamesStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.overall.RightOfMiddleHitsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.overall.SpareConversionsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.overall.StrikeMiddleHitsStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.overall.StrikesStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.overall.TotalPinfallStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.pinsleftondeck.AveragePinsLeftStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.pinsleftondeck.TotalPinsLeftStatistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf10Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf11Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf12Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf13Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf14Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf15Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf16Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf17Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf18Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf19Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf20Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf2Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf3Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf4Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf5Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf6Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf7Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf8Statistic
import ca.josephroque.bowlingcompanion.statistics.impl.series.HighSeriesOf9Statistic
/**
* Copyright (C) 2018 Joseph Roque
*
* Helper methods for statistics.
*/
object StatisticHelper {
fun getFreshStatistics(): MutableList<Statistic> = mutableListOf(
// General
BowlerNameStatistic(),
LeagueNameStatistic(),
SeriesNameStatistic(),
GameNameStatistic(),
// Overall
HighSingleStatistic(),
TotalPinfallStatistic(),
NumberOfGamesStatistic(),
GameAverageStatistic(),
MiddleHitsStatistic(),
LeftOfMiddleHitsStatistic(),
RightOfMiddleHitsStatistic(),
StrikeMiddleHitsStatistic(),
StrikesStatistic(),
SpareConversionsStatistic(),
// First Ball
HeadPinsStatistic(),
HeadPinsSparedStatistic(),
LeftsStatistic(),
LeftsSparedStatistic(),
RightsStatistic(),
RightsSparedStatistic(),
AcesStatistic(),
AcesSparedStatistic(),
ChopOffsStatistic(),
ChopOffsSparedStatistic(),
LeftChopOffsStatistic(),
LeftChopOffsSparedStatistic(),
RightChopOffsStatistic(),
RightChopOffsSparedStatistic(),
SplitsStatistic(),
SplitsSparedStatistic(),
LeftSplitsStatistic(),
LeftSplitsSparedStatistic(),
RightSplitsStatistic(),
RightSplitsSparedStatistic(),
TwelvesStatistic(),
TwelvesSparedStatistic(),
LeftTwelvesStatistic(),
LeftTwelvesSparedStatistic(),
RightTwelvesStatistic(),
RightTwelvesSparedStatistic(),
// Fouls
FoulsStatistic(),
// Pins Left on Deck
TotalPinsLeftStatistic(),
AveragePinsLeftStatistic(),
// Average
Game1AverageStatistic(),
Game2AverageStatistic(),
Game3AverageStatistic(),
Game4AverageStatistic(),
Game5AverageStatistic(),
Game6AverageStatistic(),
Game7AverageStatistic(),
Game8AverageStatistic(),
Game9AverageStatistic(),
Game10AverageStatistic(),
Game11AverageStatistic(),
Game12AverageStatistic(),
Game13AverageStatistic(),
Game14AverageStatistic(),
Game15AverageStatistic(),
Game16AverageStatistic(),
Game17AverageStatistic(),
Game18AverageStatistic(),
Game19AverageStatistic(),
Game20AverageStatistic(),
// Series
HighSeriesOf2Statistic(),
HighSeriesOf3Statistic(),
HighSeriesOf4Statistic(),
HighSeriesOf5Statistic(),
HighSeriesOf6Statistic(),
HighSeriesOf7Statistic(),
HighSeriesOf8Statistic(),
HighSeriesOf9Statistic(),
HighSeriesOf10Statistic(),
HighSeriesOf11Statistic(),
HighSeriesOf12Statistic(),
HighSeriesOf13Statistic(),
HighSeriesOf14Statistic(),
HighSeriesOf15Statistic(),
HighSeriesOf16Statistic(),
HighSeriesOf17Statistic(),
HighSeriesOf18Statistic(),
HighSeriesOf19Statistic(),
HighSeriesOf20Statistic(),
// Match Play
GamesWonStatistic(),
GamesLostStatistic(),
GamesTiedStatistic()
)
fun readParcelable(p: Parcel, id: Int): Statistic {
return when (id) {
BowlerNameStatistic.Id -> p.readParcelable<BowlerNameStatistic>(BowlerNameStatistic::class.java.classLoader)!!
LeagueNameStatistic.Id -> p.readParcelable<LeagueNameStatistic>(LeagueNameStatistic::class.java.classLoader)!!
SeriesNameStatistic.Id -> p.readParcelable<SeriesNameStatistic>(SeriesNameStatistic::class.java.classLoader)!!
GameNameStatistic.Id -> p.readParcelable<GameNameStatistic>(GameNameStatistic::class.java.classLoader)!!
HighSingleStatistic.Id -> p.readParcelable<HighSingleStatistic>(HighSingleStatistic::class.java.classLoader)!!
TotalPinfallStatistic.Id -> p.readParcelable<TotalPinfallStatistic>(TotalPinfallStatistic::class.java.classLoader)!!
NumberOfGamesStatistic.Id -> p.readParcelable<NumberOfGamesStatistic>(NumberOfGamesStatistic::class.java.classLoader)!!
GameAverageStatistic.Id -> p.readParcelable<GameAverageStatistic>(GameAverageStatistic::class.java.classLoader)!!
MiddleHitsStatistic.Id -> p.readParcelable<MiddleHitsStatistic>(MiddleHitsStatistic::class.java.classLoader)!!
LeftOfMiddleHitsStatistic.Id -> p.readParcelable<LeftOfMiddleHitsStatistic>(LeftOfMiddleHitsStatistic::class.java.classLoader)!!
RightOfMiddleHitsStatistic.Id -> p.readParcelable<RightOfMiddleHitsStatistic>(RightOfMiddleHitsStatistic::class.java.classLoader)!!
StrikeMiddleHitsStatistic.Id -> p.readParcelable<StrikeMiddleHitsStatistic>(StrikeMiddleHitsStatistic::class.java.classLoader)!!
StrikesStatistic.Id -> p.readParcelable<StrikesStatistic>(StrikesStatistic::class.java.classLoader)!!
SpareConversionsStatistic.Id -> p.readParcelable<SpareConversionsStatistic>(SpareConversionsStatistic::class.java.classLoader)!!
HeadPinsStatistic.Id -> p.readParcelable<HeadPinsStatistic>(HeadPinsStatistic::class.java.classLoader)!!
HeadPinsSparedStatistic.Id -> p.readParcelable<HeadPinsSparedStatistic>(HeadPinsSparedStatistic::class.java.classLoader)!!
LeftsStatistic.Id -> p.readParcelable<LeftsStatistic>(LeftsStatistic::class.java.classLoader)!!
LeftsSparedStatistic.Id -> p.readParcelable<LeftsSparedStatistic>(LeftsSparedStatistic::class.java.classLoader)!!
RightsStatistic.Id -> p.readParcelable<RightsStatistic>(RightsStatistic::class.java.classLoader)!!
RightsSparedStatistic.Id -> p.readParcelable<RightsSparedStatistic>(RightsSparedStatistic::class.java.classLoader)!!
AcesStatistic.Id -> p.readParcelable<AcesStatistic>(AcesStatistic::class.java.classLoader)!!
AcesSparedStatistic.Id -> p.readParcelable<AcesSparedStatistic>(AcesSparedStatistic::class.java.classLoader)!!
ChopOffsStatistic.Id -> p.readParcelable<ChopOffsStatistic>(ChopOffsStatistic::class.java.classLoader)!!
ChopOffsSparedStatistic.Id -> p.readParcelable<ChopOffsSparedStatistic>(ChopOffsSparedStatistic::class.java.classLoader)!!
LeftChopOffsStatistic.Id -> p.readParcelable<LeftChopOffsStatistic>(LeftChopOffsStatistic::class.java.classLoader)!!
LeftChopOffsSparedStatistic.Id -> p.readParcelable<LeftChopOffsSparedStatistic>(LeftChopOffsSparedStatistic::class.java.classLoader)!!
RightChopOffsStatistic.Id -> p.readParcelable<RightChopOffsStatistic>(RightChopOffsStatistic::class.java.classLoader)!!
RightChopOffsSparedStatistic.Id -> p.readParcelable<RightChopOffsSparedStatistic>(RightChopOffsSparedStatistic::class.java.classLoader)!!
SplitsStatistic.Id -> p.readParcelable<SplitsStatistic>(SplitsStatistic::class.java.classLoader)!!
SplitsSparedStatistic.Id -> p.readParcelable<SplitsSparedStatistic>(SplitsSparedStatistic::class.java.classLoader)!!
LeftSplitsStatistic.Id -> p.readParcelable<LeftSplitsStatistic>(LeftSplitsStatistic::class.java.classLoader)!!
LeftSplitsSparedStatistic.Id -> p.readParcelable<LeftSplitsSparedStatistic>(LeftsSparedStatistic::class.java.classLoader)!!
RightSplitsStatistic.Id -> p.readParcelable<RightSplitsStatistic>(RightSplitsStatistic::class.java.classLoader)!!
RightSplitsSparedStatistic.Id -> p.readParcelable<RightSplitsSparedStatistic>(RightsSparedStatistic::class.java.classLoader)!!
TwelvesStatistic.Id -> p.readParcelable<TwelvesStatistic>(TwelvesStatistic::class.java.classLoader)!!
TwelvesSparedStatistic.Id -> p.readParcelable<TwelvesSparedStatistic>(TwelvesSparedStatistic::class.java.classLoader)!!
LeftTwelvesStatistic.Id -> p.readParcelable<LeftTwelvesStatistic>(LeftTwelvesStatistic::class.java.classLoader)!!
LeftTwelvesSparedStatistic.Id -> p.readParcelable<LeftTwelvesSparedStatistic>(LeftTwelvesSparedStatistic::class.java.classLoader)!!
RightTwelvesStatistic.Id -> p.readParcelable<RightTwelvesStatistic>(RightTwelvesStatistic::class.java.classLoader)!!
RightTwelvesSparedStatistic.Id -> p.readParcelable<RightTwelvesSparedStatistic>(RightTwelvesSparedStatistic::class.java.classLoader)!!
FoulsStatistic.Id -> p.readParcelable<FoulsStatistic>(FoulsStatistic::class.java.classLoader)!!
TotalPinsLeftStatistic.Id -> p.readParcelable<TotalPinsLeftStatistic>(TotalPinsLeftStatistic::class.java.classLoader)!!
AveragePinsLeftStatistic.Id -> p.readParcelable<AveragePinsLeftStatistic>(AveragePinsLeftStatistic::class.java.classLoader)!!
Game1AverageStatistic.Id -> p.readParcelable<Game1AverageStatistic>(Game1AverageStatistic::class.java.classLoader)!!
Game2AverageStatistic.Id -> p.readParcelable<Game2AverageStatistic>(Game2AverageStatistic::class.java.classLoader)!!
Game3AverageStatistic.Id -> p.readParcelable<Game3AverageStatistic>(Game3AverageStatistic::class.java.classLoader)!!
Game4AverageStatistic.Id -> p.readParcelable<Game4AverageStatistic>(Game4AverageStatistic::class.java.classLoader)!!
Game5AverageStatistic.Id -> p.readParcelable<Game5AverageStatistic>(Game5AverageStatistic::class.java.classLoader)!!
Game6AverageStatistic.Id -> p.readParcelable<Game6AverageStatistic>(Game6AverageStatistic::class.java.classLoader)!!
Game7AverageStatistic.Id -> p.readParcelable<Game7AverageStatistic>(Game7AverageStatistic::class.java.classLoader)!!
Game8AverageStatistic.Id -> p.readParcelable<Game8AverageStatistic>(Game8AverageStatistic::class.java.classLoader)!!
Game9AverageStatistic.Id -> p.readParcelable<Game9AverageStatistic>(Game9AverageStatistic::class.java.classLoader)!!
Game10AverageStatistic.Id -> p.readParcelable<Game10AverageStatistic>(Game10AverageStatistic::class.java.classLoader)!!
Game11AverageStatistic.Id -> p.readParcelable<Game11AverageStatistic>(Game11AverageStatistic::class.java.classLoader)!!
Game12AverageStatistic.Id -> p.readParcelable<Game12AverageStatistic>(Game12AverageStatistic::class.java.classLoader)!!
Game13AverageStatistic.Id -> p.readParcelable<Game13AverageStatistic>(Game13AverageStatistic::class.java.classLoader)!!
Game14AverageStatistic.Id -> p.readParcelable<Game14AverageStatistic>(Game14AverageStatistic::class.java.classLoader)!!
Game15AverageStatistic.Id -> p.readParcelable<Game15AverageStatistic>(Game15AverageStatistic::class.java.classLoader)!!
Game16AverageStatistic.Id -> p.readParcelable<Game16AverageStatistic>(Game16AverageStatistic::class.java.classLoader)!!
Game17AverageStatistic.Id -> p.readParcelable<Game17AverageStatistic>(Game17AverageStatistic::class.java.classLoader)!!
Game18AverageStatistic.Id -> p.readParcelable<Game18AverageStatistic>(Game18AverageStatistic::class.java.classLoader)!!
Game19AverageStatistic.Id -> p.readParcelable<Game19AverageStatistic>(Game19AverageStatistic::class.java.classLoader)!!
Game20AverageStatistic.Id -> p.readParcelable<Game20AverageStatistic>(Game20AverageStatistic::class.java.classLoader)!!
HighSeriesOf2Statistic.Id -> p.readParcelable<HighSeriesOf2Statistic>(HighSeriesOf2Statistic::class.java.classLoader)!!
HighSeriesOf3Statistic.Id -> p.readParcelable<HighSeriesOf3Statistic>(HighSeriesOf3Statistic::class.java.classLoader)!!
HighSeriesOf4Statistic.Id -> p.readParcelable<HighSeriesOf4Statistic>(HighSeriesOf4Statistic::class.java.classLoader)!!
HighSeriesOf5Statistic.Id -> p.readParcelable<HighSeriesOf5Statistic>(HighSeriesOf5Statistic::class.java.classLoader)!!
HighSeriesOf6Statistic.Id -> p.readParcelable<HighSeriesOf6Statistic>(HighSeriesOf6Statistic::class.java.classLoader)!!
HighSeriesOf7Statistic.Id -> p.readParcelable<HighSeriesOf7Statistic>(HighSeriesOf7Statistic::class.java.classLoader)!!
HighSeriesOf8Statistic.Id -> p.readParcelable<HighSeriesOf8Statistic>(HighSeriesOf8Statistic::class.java.classLoader)!!
HighSeriesOf9Statistic.Id -> p.readParcelable<HighSeriesOf9Statistic>(HighSeriesOf9Statistic::class.java.classLoader)!!
HighSeriesOf10Statistic.Id -> p.readParcelable<HighSeriesOf10Statistic>(HighSeriesOf10Statistic::class.java.classLoader)!!
HighSeriesOf11Statistic.Id -> p.readParcelable<HighSeriesOf11Statistic>(HighSeriesOf11Statistic::class.java.classLoader)!!
HighSeriesOf12Statistic.Id -> p.readParcelable<HighSeriesOf12Statistic>(HighSeriesOf12Statistic::class.java.classLoader)!!
HighSeriesOf13Statistic.Id -> p.readParcelable<HighSeriesOf13Statistic>(HighSeriesOf13Statistic::class.java.classLoader)!!
HighSeriesOf14Statistic.Id -> p.readParcelable<HighSeriesOf14Statistic>(HighSeriesOf14Statistic::class.java.classLoader)!!
HighSeriesOf15Statistic.Id -> p.readParcelable<HighSeriesOf15Statistic>(HighSeriesOf15Statistic::class.java.classLoader)!!
HighSeriesOf16Statistic.Id -> p.readParcelable<HighSeriesOf16Statistic>(HighSeriesOf16Statistic::class.java.classLoader)!!
HighSeriesOf17Statistic.Id -> p.readParcelable<HighSeriesOf17Statistic>(HighSeriesOf17Statistic::class.java.classLoader)!!
HighSeriesOf18Statistic.Id -> p.readParcelable<HighSeriesOf18Statistic>(HighSeriesOf18Statistic::class.java.classLoader)!!
HighSeriesOf19Statistic.Id -> p.readParcelable<HighSeriesOf19Statistic>(HighSeriesOf19Statistic::class.java.classLoader)!!
HighSeriesOf20Statistic.Id -> p.readParcelable<HighSeriesOf20Statistic>(HighSeriesOf20Statistic::class.java.classLoader)!!
GamesWonStatistic.Id -> p.readParcelable<GamesWonStatistic>(GamesWonStatistic::class.java.classLoader)!!
GamesLostStatistic.Id -> p.readParcelable<GamesLostStatistic>(GamesLostStatistic::class.java.classLoader)!!
GamesTiedStatistic.Id -> p.readParcelable<GamesTiedStatistic>(GamesTiedStatistic::class.java.classLoader)!!
else -> throw IllegalArgumentException("$id is not a valid Statistic id.")
}
}
fun getStatistic(id: Long): Statistic {
return when (id.toInt()) {
BowlerNameStatistic.Id -> BowlerNameStatistic()
LeagueNameStatistic.Id -> LeagueNameStatistic()
SeriesNameStatistic.Id -> SeriesNameStatistic()
GameNameStatistic.Id -> GameNameStatistic()
HighSingleStatistic.Id -> HighSingleStatistic()
TotalPinfallStatistic.Id -> TotalPinfallStatistic()
NumberOfGamesStatistic.Id -> NumberOfGamesStatistic()
GameAverageStatistic.Id -> GameAverageStatistic()
MiddleHitsStatistic.Id -> MiddleHitsStatistic()
LeftOfMiddleHitsStatistic.Id -> LeftOfMiddleHitsStatistic()
RightOfMiddleHitsStatistic.Id -> RightOfMiddleHitsStatistic()
StrikeMiddleHitsStatistic.Id -> StrikeMiddleHitsStatistic()
StrikesStatistic.Id -> StrikesStatistic()
SpareConversionsStatistic.Id -> SpareConversionsStatistic()
HeadPinsStatistic.Id -> HeadPinsStatistic()
HeadPinsSparedStatistic.Id -> HeadPinsSparedStatistic()
LeftsStatistic.Id -> LeftsStatistic()
LeftsSparedStatistic.Id -> LeftsSparedStatistic()
RightsStatistic.Id -> RightsStatistic()
RightsSparedStatistic.Id -> RightsSparedStatistic()
AcesStatistic.Id -> AcesStatistic()
AcesSparedStatistic.Id -> AcesSparedStatistic()
ChopOffsStatistic.Id -> ChopOffsStatistic()
ChopOffsSparedStatistic.Id -> ChopOffsSparedStatistic()
LeftChopOffsStatistic.Id -> LeftChopOffsStatistic()
LeftChopOffsSparedStatistic.Id -> LeftChopOffsSparedStatistic()
RightChopOffsStatistic.Id -> RightChopOffsStatistic()
RightChopOffsSparedStatistic.Id -> RightChopOffsSparedStatistic()
SplitsStatistic.Id -> SplitsStatistic()
SplitsSparedStatistic.Id -> SplitsSparedStatistic()
LeftSplitsStatistic.Id -> LeftSplitsStatistic()
LeftSplitsSparedStatistic.Id -> LeftSplitsSparedStatistic()
RightSplitsStatistic.Id -> RightSplitsStatistic()
RightSplitsSparedStatistic.Id -> RightSplitsSparedStatistic()
TwelvesStatistic.Id -> TwelvesStatistic()
TwelvesSparedStatistic.Id -> TwelvesSparedStatistic()
LeftTwelvesStatistic.Id -> LeftTwelvesStatistic()
LeftTwelvesSparedStatistic.Id -> LeftTwelvesSparedStatistic()
RightTwelvesStatistic.Id -> RightTwelvesStatistic()
RightTwelvesSparedStatistic.Id -> RightTwelvesSparedStatistic()
FoulsStatistic.Id -> FoulsStatistic()
TotalPinsLeftStatistic.Id -> TotalPinsLeftStatistic()
AveragePinsLeftStatistic.Id -> AveragePinsLeftStatistic()
Game1AverageStatistic.Id -> Game1AverageStatistic()
Game2AverageStatistic.Id -> Game2AverageStatistic()
Game3AverageStatistic.Id -> Game3AverageStatistic()
Game4AverageStatistic.Id -> Game4AverageStatistic()
Game5AverageStatistic.Id -> Game5AverageStatistic()
Game6AverageStatistic.Id -> Game6AverageStatistic()
Game7AverageStatistic.Id -> Game7AverageStatistic()
Game8AverageStatistic.Id -> Game8AverageStatistic()
Game9AverageStatistic.Id -> Game9AverageStatistic()
Game10AverageStatistic.Id -> Game10AverageStatistic()
Game11AverageStatistic.Id -> Game11AverageStatistic()
Game12AverageStatistic.Id -> Game12AverageStatistic()
Game13AverageStatistic.Id -> Game13AverageStatistic()
Game14AverageStatistic.Id -> Game14AverageStatistic()
Game15AverageStatistic.Id -> Game15AverageStatistic()
Game16AverageStatistic.Id -> Game16AverageStatistic()
Game17AverageStatistic.Id -> Game17AverageStatistic()
Game18AverageStatistic.Id -> Game18AverageStatistic()
Game19AverageStatistic.Id -> Game19AverageStatistic()
Game20AverageStatistic.Id -> Game20AverageStatistic()
HighSeriesOf2Statistic.Id -> HighSeriesOf2Statistic()
HighSeriesOf3Statistic.Id -> HighSeriesOf3Statistic()
HighSeriesOf4Statistic.Id -> HighSeriesOf4Statistic()
HighSeriesOf5Statistic.Id -> HighSeriesOf5Statistic()
HighSeriesOf6Statistic.Id -> HighSeriesOf6Statistic()
HighSeriesOf7Statistic.Id -> HighSeriesOf7Statistic()
HighSeriesOf8Statistic.Id -> HighSeriesOf8Statistic()
HighSeriesOf9Statistic.Id -> HighSeriesOf9Statistic()
HighSeriesOf10Statistic.Id -> HighSeriesOf10Statistic()
HighSeriesOf11Statistic.Id -> HighSeriesOf11Statistic()
HighSeriesOf12Statistic.Id -> HighSeriesOf12Statistic()
HighSeriesOf13Statistic.Id -> HighSeriesOf13Statistic()
HighSeriesOf14Statistic.Id -> HighSeriesOf14Statistic()
HighSeriesOf15Statistic.Id -> HighSeriesOf15Statistic()
HighSeriesOf16Statistic.Id -> HighSeriesOf16Statistic()
HighSeriesOf17Statistic.Id -> HighSeriesOf17Statistic()
HighSeriesOf18Statistic.Id -> HighSeriesOf18Statistic()
HighSeriesOf19Statistic.Id -> HighSeriesOf19Statistic()
HighSeriesOf20Statistic.Id -> HighSeriesOf20Statistic()
GamesWonStatistic.Id -> GamesWonStatistic()
GamesLostStatistic.Id -> GamesLostStatistic()
GamesTiedStatistic.Id -> GamesTiedStatistic()
else -> throw IllegalArgumentException("$id is not a valid Statistic id.")
}
}
fun getAdjacentStatistics(id: Long, canBeGraphed: Boolean = true): Pair<Statistic?, Statistic?> {
// FIXME: Find a better way to get the title of multiple statistics than creating the entire list
val statistics = getFreshStatistics()
if (canBeGraphed) statistics.retainAll { it.canBeGraphed }
val statIndex = statistics.indexOfFirst { it.id == id }
var previousStatistic: Statistic? = null
var nextStatistic: Statistic? = null
if (statIndex > 0) previousStatistic = statistics[statIndex - 1]
if (statIndex < statistics.lastIndex) nextStatistic = statistics[statIndex + 1]
return Pair(previousStatistic, nextStatistic)
}
}
| mit | f72eb7777d8d64322f5044fc52d208a8 | 71.607235 | 149 | 0.771842 | 4.673042 | false | false | false | false |
santirivera92/wtnv-android | app/src/main/java/com/razielsarafan/wtnv/view/AudioPlayerView.kt | 1 | 5220 | package com.razielsarafan.wtnv.view
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import com.razielsarafan.wtnv.R
import com.razielsarafan.wtnv.controller.service.ListenService
class AudioPlayerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr), View.OnClickListener, SeekBar.OnSeekBarChangeListener, View.OnTouchListener, Runnable {
private val imageViewPlayPause: ImageView
private val textViewInfo: TextView
private val textViewStart: TextView
private val textViewEnd: TextView
private val seekBarPlayer: SeekBar
private val layoutPodcasts: View
private var listenService: ListenService? = null
override fun onTouch(v: View, event: MotionEvent): Boolean {
return seekBarPlayer.onTouchEvent(event)
}
init {
View.inflate(context, R.layout.view_player, this)
seekBarPlayer = findViewById(R.id.progressBarPlayer) as SeekBar
seekBarPlayer.setOnSeekBarChangeListener(this)
layoutPodcasts = findViewById(R.id.layoutPodcasts)
textViewInfo = findViewById(R.id.textViewInfoPodcast) as TextView
textViewStart = findViewById(R.id.textViewStart) as TextView
textViewEnd = findViewById(R.id.textViewEnd) as TextView
imageViewPlayPause = findViewById(R.id.imageViewPlayPause) as ImageView
imageViewPlayPause.setImageResource(if (ListenService.playing) R.drawable.pause else R.drawable.play)
imageViewPlayPause.setOnClickListener(this)
layoutPodcasts.setOnTouchListener(this)
seekBarPlayer.visibility = View.INVISIBLE
audioPlayerView = this
if (ListenService.listenService != null) {
setListenService(ListenService.listenService!!)
}
post(this)
}
fun setListenService(listenService: ListenService) {
this.listenService = listenService
seekBarPlayer.visibility = View.VISIBLE
}
override fun onClick(view: View) {
if (ListenService.playing) {
listenService!!.pause()
} else {
listenService!!.play()
}
}
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (listenService != null) {
val duration = listenService!!.getmPlayer()!!.duration / 1000
val position = progress / 1000
if (duration >= 10 * 60) {
val minutesPosition = position / 60
val secondsPosition = position % 60
textViewStart.text = String.format("%02d:%02d'", minutesPosition, secondsPosition)
} else {
val minutesPosition = position / 60
val secondsPosition = position % 60
textViewStart.text = String.format("%d:%02d'", minutesPosition, secondsPosition)
}
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
isSeeking = true
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
listenService!!.seekTo(seekBar.progress)
isSeeking = false
}
override fun run() {
if (!isSeeking) {
imageViewPlayPause.setImageResource(if (ListenService.playing) R.drawable.pause else R.drawable.play)
if (listenService != null) {
val mp = listenService!!.getmPlayer()
if (mp != null) {
try {
if (ListenService.stopped) {
visibility = View.GONE
} else {
seekBarPlayer.progress = mp.currentPosition
if (seekBarPlayer.max != mp.duration) {
visibility = View.VISIBLE
seekBarPlayer.max = mp.duration
val duration = mp.duration / 1000
if (duration >= 10 * 60) {
val minutes = duration / 60
val seconds = duration % 60
textViewEnd.text = String.format("%02d:%02d'", minutes, seconds)
} else {
val minutes = duration / 60
val seconds = duration % 60
textViewEnd.text = String.format("%d:%02d'", minutes, seconds)
}
}
}
} catch (ex: Exception) {
visibility = View.GONE
}
}
val ep = ListenService.currentEpisode
if (ep != null)
textViewInfo.text = ep.title
}
}
postDelayed(this, 500)
}
companion object {
private var isSeeking = false
var audioPlayerView: AudioPlayerView? = null
}
}
| gpl-2.0 | 731a26c43dbcfd83f0b537f04aa8d00f | 37.955224 | 250 | 0.581226 | 5.225225 | false | false | false | false |
Kotlin/anko | anko/library/generated/sqlite/src/main/java/SqlParserHelpers.kt | 4 | 14818 | @file:JvmMultifileClass
@file:JvmName("SQLiteParserHelpersKt")
package org.jetbrains.anko.db
import android.database.sqlite.SQLiteException
fun <T1, R> rowParser(parser: (T1) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 1) {
throw SQLiteException("Invalid row: 1 column required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1)
}
}
}
fun <T1, T2, R> rowParser(parser: (T1, T2) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 2) {
throw SQLiteException("Invalid row: 2 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2)
}
}
}
fun <T1, T2, T3, R> rowParser(parser: (T1, T2, T3) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 3) {
throw SQLiteException("Invalid row: 3 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3)
}
}
}
fun <T1, T2, T3, T4, R> rowParser(parser: (T1, T2, T3, T4) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 4) {
throw SQLiteException("Invalid row: 4 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4)
}
}
}
fun <T1, T2, T3, T4, T5, R> rowParser(parser: (T1, T2, T3, T4, T5) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 5) {
throw SQLiteException("Invalid row: 5 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5)
}
}
}
fun <T1, T2, T3, T4, T5, T6, R> rowParser(parser: (T1, T2, T3, T4, T5, T6) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 6) {
throw SQLiteException("Invalid row: 6 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 7) {
throw SQLiteException("Invalid row: 7 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 8) {
throw SQLiteException("Invalid row: 8 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 9) {
throw SQLiteException("Invalid row: 9 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 10) {
throw SQLiteException("Invalid row: 10 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 11) {
throw SQLiteException("Invalid row: 11 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 12) {
throw SQLiteException("Invalid row: 12 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 13) {
throw SQLiteException("Invalid row: 13 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 14) {
throw SQLiteException("Invalid row: 14 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 15) {
throw SQLiteException("Invalid row: 15 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 16) {
throw SQLiteException("Invalid row: 16 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 17) {
throw SQLiteException("Invalid row: 17 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16, columns[16] as T17)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 18) {
throw SQLiteException("Invalid row: 18 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16, columns[16] as T17, columns[17] as T18)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 19) {
throw SQLiteException("Invalid row: 19 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16, columns[16] as T17, columns[17] as T18, columns[18] as T19)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 20) {
throw SQLiteException("Invalid row: 20 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16, columns[16] as T17, columns[17] as T18, columns[18] as T19, columns[19] as T20)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 21) {
throw SQLiteException("Invalid row: 21 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16, columns[16] as T17, columns[17] as T18, columns[18] as T19, columns[19] as T20, columns[20] as T21)
}
}
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, R> rowParser(parser: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22) -> R): RowParser<R> {
return object : RowParser<R> {
override fun parseRow(columns: Array<Any?>): R {
if (columns.size != 22) {
throw SQLiteException("Invalid row: 22 columns required")
}
@Suppress("UNCHECKED_CAST")
return parser(columns[0] as T1, columns[1] as T2, columns[2] as T3, columns[3] as T4, columns[4] as T5, columns[5] as T6, columns[6] as T7, columns[7] as T8, columns[8] as T9, columns[9] as T10, columns[10] as T11, columns[11] as T12, columns[12] as T13, columns[13] as T14, columns[14] as T15, columns[15] as T16, columns[16] as T17, columns[17] as T18, columns[18] as T19, columns[19] as T20, columns[20] as T21, columns[21] as T22)
}
}
}
| apache-2.0 | 40537159efd2540f8ba951f6ccedc6ba | 49.746575 | 446 | 0.573897 | 2.698106 | false | false | false | false |
VicMikhailau/MaskedEditText | MaskedEditText/src/main/java/com/vicmikhailau/maskededittext/MaskedWatcher.kt | 1 | 3003 | package com.vicmikhailau.maskededittext
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import java.lang.ref.WeakReference
class MaskedWatcher(maskedFormatter: MaskedFormatter, editText: EditText) : TextWatcher {
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private val mMaskFormatter: WeakReference<MaskedFormatter> = WeakReference(maskedFormatter)
private val mEditText: WeakReference<EditText> = WeakReference(editText)
private var oldFormattedValue = ""
private var oldCursorPosition: Int = 0
// ===========================================================
// Listeners, methods for/from Interfaces
// ===========================================================
private fun setFormattedText(formattedString: IFormattedString) {
val editText = mEditText.get() ?: return
val deltaLength = formattedString.length - oldFormattedValue.length
editText.removeTextChangedListener(this)
editText.setText(formattedString)
editText.addTextChangedListener(this)
var newCursorPosition = oldCursorPosition
if (deltaLength > 0) {
newCursorPosition += deltaLength
} else if (deltaLength < 0) {
newCursorPosition -= 1
} else {
var mask: Mask? = null
mMaskFormatter.get()?.mMask?.let { mask = it }
var maskLength = 0
mMaskFormatter.get()?.maskLength?.let { maskLength = it}
newCursorPosition = 1.coerceAtLeast(newCursorPosition.coerceAtMost(maskLength))
var isPopulate = false
mask?.get(newCursorPosition - 1)?.isPrepopulate?.let { isPopulate = it }
if (isPopulate)
newCursorPosition -= 1
}
newCursorPosition = 0.coerceAtLeast(newCursorPosition.coerceAtMost(formattedString.length))
editText.setSelection(newCursorPosition)
}
override fun afterTextChanged(s: Editable?) {
if (s == null)
return
var value = s.toString()
var maskLength = 0
mMaskFormatter.get()?.maskLength?.let { maskLength = it}
if (value.length > oldFormattedValue.length && maskLength < value.length) {
value = oldFormattedValue
}
val formattedString = mMaskFormatter.get()?.formatString(value)
formattedString?.let { setFormattedText(it) }
oldFormattedValue = formattedString.toString()
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
mEditText.get()?.selectionStart?.let { this.oldCursorPosition = it }
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
}
| apache-2.0 | ca4036fbe522c502b8988a9b7e1812bf | 33.918605 | 99 | 0.577423 | 5.333925 | false | false | false | false |
luiqn2007/miaowo | app/src/main/java/org/miaowo/miaowo/other/ChatListAnimator.kt | 1 | 18851 | package org.miaowo.miaowo.other
import android.animation.ValueAnimator
import android.support.v4.view.ViewCompat
import android.support.v4.view.ViewPropertyAnimatorListener
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.SimpleItemAnimator
import android.view.View
import java.util.*
/**
* 聊天消息列表动画
* Created by luqin on 17-4-26.
*/
class ChatListAnimator : SimpleItemAnimator() {
// 本次将执行的动画列表
private val mPendingRemovals = ArrayList<RecyclerView.ViewHolder>()
private val mPendingAdditions = ArrayList<RecyclerView.ViewHolder>()
private val mPendingMoves = ArrayList<MoveInfo>()
private val mPendingChanges = ArrayList<ChangeInfo>()
// 动画栈
private val mAdditionsList = ArrayList<ArrayList<RecyclerView.ViewHolder>>()
private val mMovesList = ArrayList<ArrayList<MoveInfo>>()
private val mChangesList = ArrayList<ArrayList<ChangeInfo>>()
// 正在执行的动画列表
private val mAddAnimations = ArrayList<RecyclerView.ViewHolder>()
private val mMoveAnimations = ArrayList<RecyclerView.ViewHolder>()
private val mRemoveAnimations = ArrayList<RecyclerView.ViewHolder>()
private val mChangeAnimations = ArrayList<RecyclerView.ViewHolder>()
// 视图移动动画信息
private data class MoveInfo constructor(var holder: RecyclerView.ViewHolder, var fromX: Int, var fromY: Int, var toX: Int, var toY: Int) {
val deltaX by lazyOf(toX - fromX)
val deltaY by lazyOf(toY - fromY)
}
// 视图改变动画信息
private data class ChangeInfo constructor(var oldHolder: RecyclerView.ViewHolder?, var newHolder: RecyclerView.ViewHolder?,
var fromX: Int, var fromY: Int, var toX: Int, var toY: Int) {
val deltaX by lazyOf(toX - fromX)
val deltaY by lazyOf(toY - fromY)
fun hasOldHolder() = oldHolder != null
fun hasNewHolder() = newHolder != null
fun noHolder() = oldHolder == null && newHolder == null
}
override fun runPendingAnimations() {
val removalsPending = !mPendingRemovals.isEmpty()
val movesPending = !mPendingMoves.isEmpty()
val changesPending = !mPendingChanges.isEmpty()
val additionsPending = !mPendingAdditions.isEmpty()
if (!removalsPending && !movesPending && !additionsPending && !changesPending) return
// remove
mPendingRemovals.forEach{ animateRemoveImpl(it) }
mPendingRemovals.clear()
// move
if (movesPending) {
val moves = ArrayList<MoveInfo>()
moves.addAll(mPendingMoves)
mMovesList.add(moves)
mPendingMoves.clear()
val mover = Runnable {
moves.forEach { animateMoveImpl(it) }
moves.clear()
mMovesList.remove(moves)
}
if (removalsPending) {
val view = moves[0].holder.itemView
ViewCompat.postOnAnimationDelayed(view, mover, removeDuration)
} else
mover.run()
}
// change
if (changesPending) {
val changes = ArrayList<ChangeInfo>()
changes.addAll(mPendingChanges)
mChangesList.add(changes)
mPendingChanges.clear()
val changer = Runnable{
changes.forEach { animateChangeImpl(it) }
changes.clear()
mChangesList.remove(changes)
}
if (removalsPending) {
val holder = changes[0].oldHolder
ViewCompat.postOnAnimationDelayed(holder!!.itemView, changer, removeDuration)
} else
changer.run()
}
// add
if (additionsPending) {
val additions = ArrayList<RecyclerView.ViewHolder>()
additions.addAll(mPendingAdditions)
mAdditionsList.add(additions)
mPendingAdditions.clear()
val adder = Runnable {
additions.forEach { animateAddImpl(it) }
additions.clear()
mAdditionsList.remove(additions)
}
if (removalsPending || movesPending || changesPending) {
val removeDuration = if (removalsPending) removeDuration else 0
val moveDuration = if (movesPending) moveDuration else 0
val changeDuration = if (changesPending) changeDuration else 0
val totalDelay = removeDuration + Math.max(moveDuration, changeDuration)
val view = additions[0].itemView
ViewCompat.postOnAnimationDelayed(view, adder, totalDelay)
} else
adder.run()
}
}
override fun animateRemove(holder: RecyclerView.ViewHolder): Boolean {
resetAnimation(holder)
mPendingRemovals.add(holder)
return true
}
private fun animateRemoveImpl(holder: RecyclerView.ViewHolder) {
val rView = holder.itemView
val animation = ViewCompat.animate(rView)
mRemoveAnimations.add(holder)
animation.setDuration(removeDuration)
.alpha(0f).setListener(object : VpaListenerAdapter() {
override fun onAnimationStart(view: View) {
dispatchRemoveStarting(holder)
}
override fun onAnimationEnd(view: View) {
animation.setListener(null)
resetView(view)
dispatchRemoveFinished(holder)
mRemoveAnimations.remove(holder)
dispatchFinishedWhenDone()
}
}).start()
}
override fun animateAdd(holder: RecyclerView.ViewHolder): Boolean {
resetAnimation(holder)
holder.itemView.alpha = 0f
holder.itemView.translationX = (if (holder.itemViewType == Const.MY) 320 else -320).toFloat()
holder.itemView.translationY = 320f
mPendingAdditions.add(holder)
return true
}
private fun animateAddImpl(holder: RecyclerView.ViewHolder) {
val rView = holder.itemView
val animation = ViewCompat.animate(rView)
mAddAnimations.add(holder)
animation.alpha(1f).translationX(0f).translationY(0f).setDuration(addDuration).setListener(object : VpaListenerAdapter() {
override fun onAnimationStart(view: View) = dispatchAddStarting(holder)
override fun onAnimationCancel(view: View) = resetView(view)
override fun onAnimationEnd(view: View) {
animation.setListener(null)
dispatchAddFinished(holder)
mAddAnimations.remove(holder)
dispatchFinishedWhenDone()
}
}).start()
}
override fun animateMove(holder: RecyclerView.ViewHolder, fromX: Int, fromY: Int,
toX: Int, toY: Int): Boolean {
var aFromX = fromX
var aFromY = fromY
val view = holder.itemView
aFromX += holder.itemView.translationX.toInt()
aFromY += holder.itemView.translationY.toInt()
resetAnimation(holder)
val deltaX = toX - aFromX
val deltaY = toY - aFromY
if (deltaX == 0 && deltaY == 0) {
dispatchMoveFinished(holder)
return false
}
if (deltaX != 0) view.translationX = (-deltaX).toFloat()
if (deltaY != 0) view.translationY = (-deltaY).toFloat()
mPendingMoves.add(MoveInfo(holder, aFromX, aFromY, toX, toY))
return true
}
private fun animateMoveImpl(info: MoveInfo) {
val rView = info.holder.itemView
val deltaX = info.deltaX
val deltaY = info.deltaY
if (deltaX != 0) ViewCompat.animate(rView).translationX(0f)
if (deltaY != 0) ViewCompat.animate(rView).translationY(0f)
val animation = ViewCompat.animate(rView)
mMoveAnimations.add(info.holder)
animation.setDuration(moveDuration).setListener(object : VpaListenerAdapter() {
override fun onAnimationStart(view: View) = dispatchMoveStarting(info.holder)
override fun onAnimationCancel(view: View) {
if (deltaX != 0) view.translationX = 0f
if (deltaY != 0) view.translationY = 0f
}
override fun onAnimationEnd(view: View) {
animation.setListener(null)
dispatchMoveFinished(info.holder)
mMoveAnimations.remove(info.holder)
dispatchFinishedWhenDone()
}
}).start()
}
override fun animateChange(oldHolder: RecyclerView.ViewHolder, newHolder: RecyclerView.ViewHolder?,
fromX: Int, fromY: Int, toX: Int, toY: Int): Boolean {
if (oldHolder === newHolder) return animateMove(oldHolder, fromX, fromY, toX, toY)
val prevTranslationX = oldHolder.itemView.translationX
val prevTranslationY = oldHolder.itemView.translationY
val prevAlpha = oldHolder.itemView.alpha
resetAnimation(oldHolder)
val deltaX = (toX.toFloat() - fromX.toFloat() - prevTranslationX).toInt()
val deltaY = (toY.toFloat() - fromY.toFloat() - prevTranslationY).toInt()
// recover prev translation state after ending animation
oldHolder.itemView.translationX = prevTranslationX
oldHolder.itemView.translationY = prevTranslationY
oldHolder.itemView.alpha = prevAlpha
if (newHolder != null) {
// carry over translation values
resetAnimation(newHolder)
newHolder.itemView.translationX = (-deltaX).toFloat()
newHolder.itemView.translationY = (-deltaY).toFloat()
newHolder.itemView.alpha = 0f
}
mPendingChanges.add(ChangeInfo(oldHolder, newHolder, fromX, fromY, toX, toY))
return true
}
private fun animateChangeImpl(changeInfo: ChangeInfo) {
if (changeInfo.hasOldHolder()) {
val oldView = changeInfo.oldHolder!!.itemView
val oldViewAnim = ViewCompat.animate(oldView).setDuration(
changeDuration)
mChangeAnimations.add(changeInfo.oldHolder!!)
oldViewAnim.translationX(changeInfo.deltaX.toFloat())
oldViewAnim.translationY(changeInfo.deltaY.toFloat())
oldViewAnim.alpha(0f).setListener(object : VpaListenerAdapter() {
override fun onAnimationStart(view: View) = dispatchChangeStarting(changeInfo.oldHolder, true)
override fun onAnimationEnd(view: View) {
oldViewAnim.setListener(null)
resetView(view)
dispatchChangeFinished(changeInfo.oldHolder, true)
mChangeAnimations.remove(changeInfo.oldHolder!!)
dispatchFinishedWhenDone()
}
}).start()
}
if (changeInfo.hasNewHolder()) {
val newView = changeInfo.newHolder!!.itemView
val newViewAnimation = ViewCompat.animate(newView)
mChangeAnimations.add(changeInfo.newHolder!!)
newViewAnimation.translationX(0f).translationY(0f).setDuration(changeDuration).alpha(1f).setListener(object : VpaListenerAdapter() {
override fun onAnimationStart(view: View) = dispatchChangeStarting(changeInfo.newHolder, false)
override fun onAnimationEnd(view: View) {
newViewAnimation.setListener(null)
resetView(newView)
dispatchChangeFinished(changeInfo.newHolder, false)
mChangeAnimations.remove(changeInfo.newHolder!!)
dispatchFinishedWhenDone()
}
}).start()
}
}
private fun endChangeAnimation(infoList: MutableList<ChangeInfo>, item: RecyclerView.ViewHolder) {
infoList.indices.reversed()
.map { infoList[it] }
.filter { endChangeAnimationIfNecessary(it, item) && it.noHolder() }
.forEach { infoList.remove(it) }
}
private fun endChangeAnimationIfNecessary(changeInfo: ChangeInfo) {
if (changeInfo.hasOldHolder()) endChangeAnimationIfNecessary(changeInfo, changeInfo.oldHolder!!)
if (changeInfo.hasNewHolder()) endChangeAnimationIfNecessary(changeInfo, changeInfo.newHolder!!)
}
private fun endChangeAnimationIfNecessary(changeInfo: ChangeInfo, item: RecyclerView.ViewHolder): Boolean {
var oldItem = false
when {
changeInfo.newHolder === item -> changeInfo.newHolder = null
changeInfo.oldHolder === item -> {
changeInfo.oldHolder = null
oldItem = true
}
else -> return false
}
resetView(item.itemView)
dispatchChangeFinished(item, oldItem)
return true
}
override fun endAnimation(item: RecyclerView.ViewHolder) {
val view = item.itemView
// this will trigger end callback which should set properties to their target values.
ViewCompat.animate(view).cancel()
for (i in mPendingMoves.indices.reversed()) {
val moveInfo = mPendingMoves[i]
if (moveInfo.holder === item) {
resetView(view)
dispatchMoveFinished(item)
mPendingMoves.removeAt(i)
}
}
endChangeAnimation(mPendingChanges, item)
if (mPendingRemovals.remove(item)) {
resetView(view)
dispatchRemoveFinished(item)
}
if (mPendingAdditions.remove(item)) {
resetView(view)
dispatchAddFinished(item)
}
for (i in mChangesList.indices.reversed()) {
val changes = mChangesList[i]
endChangeAnimation(changes, item)
if (changes.isEmpty()) mChangesList.removeAt(i)
}
for (i in mMovesList.indices.reversed()) {
val moves = mMovesList[i]
for (j in moves.indices.reversed()) {
val moveInfo = moves[j]
if (moveInfo.holder === item) {
view.translationY = 0f
view.translationX = 0f
dispatchMoveFinished(item)
moves.removeAt(j)
if (moves.isEmpty()) mMovesList.removeAt(i)
break
}
}
}
for (i in mAdditionsList.indices.reversed()) {
val additions = mAdditionsList[i]
if (additions.remove(item)) {
resetView(view)
dispatchAddFinished(item)
if (additions.isEmpty()) mAdditionsList.removeAt(i)
}
}
}
private fun resetAnimation(holder: RecyclerView.ViewHolder) {
holder.itemView.clearAnimation()
holder.itemView.animate().interpolator = ValueAnimator().interpolator
endAnimation(holder)
}
private fun resetView(view: View) {
view.alpha = 1f
view.translationX = 0f
view.translationY = 0f
}
override fun isRunning(): Boolean {
return !mPendingAdditions.isEmpty() ||
!mPendingChanges.isEmpty() ||
!mPendingMoves.isEmpty() ||
!mPendingRemovals.isEmpty() ||
!mMoveAnimations.isEmpty() ||
!mRemoveAnimations.isEmpty() ||
!mAddAnimations.isEmpty() ||
!mChangeAnimations.isEmpty() ||
!mMovesList.isEmpty() ||
!mAdditionsList.isEmpty() ||
!mChangesList.isEmpty()
}
private fun dispatchFinishedWhenDone() {
if (!isRunning) dispatchAnimationsFinished()
}
override fun endAnimations() {
for (i in mPendingMoves.indices.reversed()) {
val item = mPendingMoves[i]
val view = item.holder.itemView
view.translationY = 0f
view.translationX = 0f
dispatchMoveFinished(item.holder)
mPendingMoves.removeAt(i)
}
for (i in mPendingRemovals.indices.reversed()) {
val item = mPendingRemovals[i]
dispatchRemoveFinished(item)
mPendingRemovals.removeAt(i)
}
for (i in mPendingAdditions.indices.reversed()) {
val item = mPendingAdditions[i]
val view = item.itemView
resetView(view)
dispatchAddFinished(item)
mPendingAdditions.removeAt(i)
}
for (i in mPendingChanges.indices.reversed())
endChangeAnimationIfNecessary(mPendingChanges[i])
mPendingChanges.clear()
if (!isRunning) return
for (i in mMovesList.indices.reversed()) {
val moves = mMovesList[i]
for (j in moves.indices.reversed()) {
val moveInfo = moves[j]
val item = moveInfo.holder
val view = item.itemView
view.translationY = 0f
view.translationX = 0f
dispatchMoveFinished(moveInfo.holder)
moves.removeAt(j)
if (moves.isEmpty()) mMovesList.remove(moves)
}
}
for (i in mAdditionsList.indices.reversed()) {
val additions = mAdditionsList[i]
for (j in additions.indices.reversed()) {
val item = additions[j]
resetView(item.itemView)
dispatchAddFinished(item)
additions.removeAt(j)
if (additions.isEmpty()) mAdditionsList.remove(additions)
}
}
for (i in mChangesList.indices.reversed()) {
val changes = mChangesList[i]
for (j in changes.indices.reversed()) {
endChangeAnimationIfNecessary(changes[j])
if (changes.isEmpty()) mChangesList.remove(changes)
}
}
cancelAll(mRemoveAnimations)
cancelAll(mMoveAnimations)
cancelAll(mAddAnimations)
cancelAll(mChangeAnimations)
dispatchAnimationsFinished()
}
private fun cancelAll(viewHolders: List<RecyclerView.ViewHolder>) {
for (i in viewHolders.indices.reversed()) {
ViewCompat.animate(viewHolders[i].itemView).cancel()
}
}
override fun canReuseUpdatedViewHolder(viewHolder: RecyclerView.ViewHolder,
payloads: List<Any>) =
!payloads.isEmpty() || super.canReuseUpdatedViewHolder(viewHolder, payloads)
private open class VpaListenerAdapter : ViewPropertyAnimatorListener {
override fun onAnimationStart(view: View) {}
override fun onAnimationEnd(view: View) {}
override fun onAnimationCancel(view: View) {}
}
}
| apache-2.0 | 2808465c639cb31aeecd9136898c506c | 39.958515 | 144 | 0.602004 | 4.854814 | false | false | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/zip.kt | 1 | 9053 | /*
* Copyright 2016 Karl Tauber
*
* 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 com.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Zip
import org.apache.tools.ant.types.FileSet
import org.apache.tools.ant.types.ResourceCollection
import org.apache.tools.ant.types.selectors.AndSelector
import org.apache.tools.ant.types.selectors.ContainsRegexpSelector
import org.apache.tools.ant.types.selectors.ContainsSelector
import org.apache.tools.ant.types.selectors.DateSelector
import org.apache.tools.ant.types.selectors.DependSelector
import org.apache.tools.ant.types.selectors.DepthSelector
import org.apache.tools.ant.types.selectors.DifferentSelector
import org.apache.tools.ant.types.selectors.ExtendSelector
import org.apache.tools.ant.types.selectors.FileSelector
import org.apache.tools.ant.types.selectors.FilenameSelector
import org.apache.tools.ant.types.selectors.MajoritySelector
import org.apache.tools.ant.types.selectors.NoneSelector
import org.apache.tools.ant.types.selectors.NotSelector
import org.apache.tools.ant.types.selectors.OrSelector
import org.apache.tools.ant.types.selectors.PresentSelector
import org.apache.tools.ant.types.selectors.SelectSelector
import org.apache.tools.ant.types.selectors.SizeSelector
import org.apache.tools.ant.types.selectors.TypeSelector
import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun Ant.zip(
destfile: String? = null,
basedir: String? = null,
compress: Boolean? = null,
filesonly: Boolean? = null,
update: Boolean? = null,
duplicate: Duplicate? = null,
whenempty: WhenEmpty? = null,
encoding: String? = null,
keepcompression: Boolean? = null,
comment: String? = null,
level: Int? = null,
roundup: Boolean? = null,
preserve0permissions: Boolean? = null,
uselanguageencodingflag: Boolean? = null,
createunicodeextrafields: UnicodeExtraField? = null,
fallbacktoutf8: Boolean? = null,
zip64mode: Zip64ModeAttribute? = null,
includes: String? = null,
excludes: String? = null,
defaultexcludes: Boolean? = null,
includesfile: String? = null,
excludesfile: String? = null,
casesensitive: Boolean? = null,
followsymlinks: Boolean? = null,
nested: (KZip.() -> Unit)? = null)
{
Zip().execute("zip") { task ->
if (destfile != null)
task.setDestFile(project.resolveFile(destfile))
if (basedir != null)
task.setBasedir(project.resolveFile(basedir))
if (compress != null)
task.setCompress(compress)
if (filesonly != null)
task.setFilesonly(filesonly)
if (update != null)
task.setUpdate(update)
if (duplicate != null)
task.setDuplicate(Zip.Duplicate().apply { this.value = duplicate.value })
if (whenempty != null)
task.setWhenempty(Zip.WhenEmpty().apply { this.value = whenempty.value })
if (encoding != null)
task.setEncoding(encoding)
if (keepcompression != null)
task.setKeepCompression(keepcompression)
if (comment != null)
task.setComment(comment)
if (level != null)
task.setLevel(level)
if (roundup != null)
task.setRoundUp(roundup)
if (preserve0permissions != null)
task.setPreserve0Permissions(preserve0permissions)
if (uselanguageencodingflag != null)
task.setUseLanguageEncodingFlag(uselanguageencodingflag)
if (createunicodeextrafields != null)
task.setCreateUnicodeExtraFields(Zip.UnicodeExtraField().apply { this.value = createunicodeextrafields.value })
if (fallbacktoutf8 != null)
task.setFallBackToUTF8(fallbacktoutf8)
if (zip64mode != null)
task.setZip64Mode(Zip.Zip64ModeAttribute().apply { this.value = zip64mode.value })
if (includes != null)
task.setIncludes(includes)
if (excludes != null)
task.setExcludes(excludes)
if (defaultexcludes != null)
task.setDefaultexcludes(defaultexcludes)
if (includesfile != null)
task.setIncludesfile(project.resolveFile(includesfile))
if (excludesfile != null)
task.setExcludesfile(project.resolveFile(excludesfile))
if (casesensitive != null)
task.setCaseSensitive(casesensitive)
if (followsymlinks != null)
task.setFollowSymlinks(followsymlinks)
if (nested != null)
nested(KZip(task))
}
}
class KZip(override val component: Zip) :
IFileSelectorNested,
IResourceCollectionNested,
ISelectSelectorNested,
IAndSelectorNested,
IOrSelectorNested,
INotSelectorNested,
INoneSelectorNested,
IMajoritySelectorNested,
IDateSelectorNested,
ISizeSelectorNested,
IFilenameSelectorNested,
IExtendSelectorNested,
IContainsSelectorNested,
IPresentSelectorNested,
IDepthSelectorNested,
IDependSelectorNested,
IContainsRegexpSelectorNested,
IDifferentSelectorNested,
ITypeSelectorNested,
IModifiedSelectorNested
{
fun zipgroupfileset(dir: String? = null, file: String? = null, includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, defaultexcludes: Boolean? = null, casesensitive: Boolean? = null, followsymlinks: Boolean? = null, maxlevelsofsymlinks: Int? = null, erroronmissingdir: Boolean? = null, nested: (KFileSet.() -> Unit)? = null) {
component.addZipGroupFileset(FileSet().apply {
component.project.setProjectReference(this)
_init(dir, file, includes, excludes, includesfile, excludesfile, defaultexcludes, casesensitive, followsymlinks, maxlevelsofsymlinks, erroronmissingdir, nested)
})
}
fun include(name: String? = null, If: String? = null, unless: String? = null) {
component.createInclude().apply {
_init(name, If, unless)
}
}
fun includesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createIncludesFile().apply {
_init(name, If, unless)
}
}
fun exclude(name: String? = null, If: String? = null, unless: String? = null) {
component.createExclude().apply {
_init(name, If, unless)
}
}
fun excludesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createExcludesFile().apply {
_init(name, If, unless)
}
}
fun patternset(includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, nested: (KPatternSet.() -> Unit)? = null) {
component.createPatternSet().apply {
component.project.setProjectReference(this)
_init(includes, excludes, includesfile, excludesfile, nested)
}
}
override fun _addFileSelector(value: FileSelector) = component.add(value)
override fun _addResourceCollection(value: ResourceCollection) = component.add(value)
override fun _addSelectSelector(value: SelectSelector) = component.addSelector(value)
override fun _addAndSelector(value: AndSelector) = component.addAnd(value)
override fun _addOrSelector(value: OrSelector) = component.addOr(value)
override fun _addNotSelector(value: NotSelector) = component.addNot(value)
override fun _addNoneSelector(value: NoneSelector) = component.addNone(value)
override fun _addMajoritySelector(value: MajoritySelector) = component.addMajority(value)
override fun _addDateSelector(value: DateSelector) = component.addDate(value)
override fun _addSizeSelector(value: SizeSelector) = component.addSize(value)
override fun _addFilenameSelector(value: FilenameSelector) = component.addFilename(value)
override fun _addExtendSelector(value: ExtendSelector) = component.addCustom(value)
override fun _addContainsSelector(value: ContainsSelector) = component.addContains(value)
override fun _addPresentSelector(value: PresentSelector) = component.addPresent(value)
override fun _addDepthSelector(value: DepthSelector) = component.addDepth(value)
override fun _addDependSelector(value: DependSelector) = component.addDepend(value)
override fun _addContainsRegexpSelector(value: ContainsRegexpSelector) = component.addContainsRegexp(value)
override fun _addDifferentSelector(value: DifferentSelector) = component.addDifferent(value)
override fun _addTypeSelector(value: TypeSelector) = component.addType(value)
override fun _addModifiedSelector(value: ModifiedSelector) = component.addModified(value)
}
enum class Duplicate(val value: String) { ADD("add"), PRESERVE("preserve"), FAIL("fail") }
enum class WhenEmpty(val value: String) { FAIL("fail"), SKIP("skip"), CREATE("create") }
enum class UnicodeExtraField(val value: String) { NEVER("never"), ALWAYS("always"), NOT_ENCODEABLE("not-encodeable") }
enum class Zip64ModeAttribute(val value: String) { NEVER("never"), ALWAYS("always"), AS_NEEDED("as-needed") }
| apache-2.0 | ce4d67305e0df2f91012c9c621bfa770 | 42.946602 | 385 | 0.752679 | 3.687576 | false | false | false | false |
jitsi/jitsi-videobridge | jvb/src/main/kotlin/org/jitsi/videobridge/Main.kt | 1 | 7202 | /*
* Copyright @ 2018 - present 8x8, Inc.
*
* 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 org.jitsi.videobridge
import org.eclipse.jetty.servlet.ServletHolder
import org.glassfish.jersey.servlet.ServletContainer
import org.ice4j.ice.harvest.MappingCandidateHarvesters
import org.jitsi.config.JitsiConfig
import org.jitsi.metaconfig.MetaconfigLogger
import org.jitsi.metaconfig.MetaconfigSettings
import org.jitsi.rest.JettyBundleActivatorConfig
import org.jitsi.rest.createServer
import org.jitsi.rest.enableCors
import org.jitsi.rest.isEnabled
import org.jitsi.rest.servletContextHandler
import org.jitsi.shutdown.ShutdownServiceImpl
import org.jitsi.utils.logging2.LoggerImpl
import org.jitsi.utils.queue.PacketQueue
import org.jitsi.videobridge.ice.Harvesters
import org.jitsi.videobridge.rest.root.Application
import org.jitsi.videobridge.stats.MucStatsTransport
import org.jitsi.videobridge.stats.StatsCollector
import org.jitsi.videobridge.stats.VideobridgeStatistics
import org.jitsi.videobridge.util.TaskPools
import org.jitsi.videobridge.version.JvbVersionService
import org.jitsi.videobridge.websocket.ColibriWebSocketService
import org.jitsi.videobridge.xmpp.XmppConnection
import org.jitsi.videobridge.xmpp.config.XmppClientConnectionConfig
import org.jxmpp.stringprep.XmppStringPrepUtil
import java.time.Clock
import kotlin.concurrent.thread
import kotlin.system.exitProcess
import org.jitsi.videobridge.websocket.singleton as webSocketServiceSingleton
fun main() {
val logger = LoggerImpl("org.jitsi.videobridge.Main")
setupMetaconfigLogger()
setSystemPropertyDefaults()
// Some of our dependencies bring in slf4j, which means Jetty will default to using
// slf4j as its logging backend. The version of slf4j brought in, however, is too old
// for Jetty so it throws errors. We use java.util.logging so tell Jetty to use that
// as its logging backend.
// TODO: Instead of setting this here, we should integrate it with the infra/debian scripts
// to be passed.
System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.JavaUtilLog")
// Reload the Typesafe config used by ice4j, because the original was initialized before the new system
// properties were set.
JitsiConfig.reloadNewConfig()
val versionService = JvbVersionService().also {
logger.info("Starting jitsi-videobridge version ${it.currentVersion}")
}
startIce4j()
XmppStringPrepUtil.setMaxCacheSizes(XmppClientConnectionConfig.config.jidCacheSize)
PacketQueue.setEnableStatisticsDefault(true)
val xmppConnection = XmppConnection().apply { start() }
val shutdownService = ShutdownServiceImpl()
val videobridge = Videobridge(
xmppConnection, shutdownService, versionService.currentVersion, VersionConfig.config.release, Clock.systemUTC()
).apply { start() }
val healthChecker = videobridge.jvbHealthChecker
val statsCollector = StatsCollector(VideobridgeStatistics(videobridge, xmppConnection)).apply {
start()
addTransport(MucStatsTransport(xmppConnection), XmppClientConnectionConfig.config.presenceInterval.toMillis())
}
val publicServerConfig = JettyBundleActivatorConfig(
"org.jitsi.videobridge.rest",
"videobridge.http-servers.public"
)
val publicHttpServer = if (publicServerConfig.isEnabled()) {
logger.info("Starting public http server")
val websocketService = ColibriWebSocketService(publicServerConfig.isTls)
webSocketServiceSingleton().setColibriWebSocketService(websocketService)
createServer(publicServerConfig).also {
websocketService.registerServlet(it.servletContextHandler, videobridge)
it.start()
}
} else {
logger.info("Not starting public http server")
null
}
val privateServerConfig = JettyBundleActivatorConfig(
"org.jitsi.videobridge.rest.private",
"videobridge.http-servers.private"
)
val privateHttpServer = if (privateServerConfig.isEnabled()) {
logger.info("Starting private http server")
val restApp = Application(
videobridge,
xmppConnection,
statsCollector,
versionService.currentVersion,
healthChecker
)
createServer(privateServerConfig).also {
it.servletContextHandler.addServlet(
ServletHolder(ServletContainer(restApp)),
"/*"
)
it.servletContextHandler.enableCors()
it.start()
}
} else {
logger.info("Not starting private http server")
null
}
// Block here until the bridge shuts down
shutdownService.waitForShutdown()
logger.info("Bridge shutting down")
healthChecker.stop()
xmppConnection.stop()
statsCollector.stop()
try {
publicHttpServer?.stop()
privateHttpServer?.stop()
} catch (t: Throwable) {
logger.error("Error shutting down http servers", t)
}
videobridge.stop()
stopIce4j()
TaskPools.SCHEDULED_POOL.shutdownNow()
TaskPools.CPU_POOL.shutdownNow()
TaskPools.IO_POOL.shutdownNow()
exitProcess(0)
}
private fun setupMetaconfigLogger() {
val configLogger = LoggerImpl("org.jitsi.config")
MetaconfigSettings.logger = object : MetaconfigLogger {
override fun warn(block: () -> String) = configLogger.warn(block)
override fun error(block: () -> String) = configLogger.error(block)
override fun debug(block: () -> String) = configLogger.debug(block)
}
}
private fun setSystemPropertyDefaults() {
val defaults = getSystemPropertyDefaults()
defaults.forEach { (key, value) ->
if (System.getProperty(key) == null) {
System.setProperty(key, value)
}
}
}
private fun getSystemPropertyDefaults(): Map<String, String> {
val defaults = mutableMapOf<String, String>()
// Make legacy ice4j properties system properties.
val cfg = JitsiConfig.SipCommunicatorProps
val ice4jPropNames = cfg.getPropertyNamesByPrefix("org.ice4j", false)
ice4jPropNames?.forEach { key ->
cfg.getString(key)?.let { value ->
defaults.put(key, value)
}
}
return defaults
}
private fun startIce4j() {
// Start the initialization of the mapping candidate harvesters.
// Asynchronous, because the AWS and STUN harvester may take a long
// time to initialize.
thread(start = true) {
MappingCandidateHarvesters.initialize()
}
}
private fun stopIce4j() {
// Shut down harvesters.
Harvesters.closeStaticConfiguration()
}
| apache-2.0 | ca072495ee9c671d5ef31983afb34f6e | 34.653465 | 119 | 0.721744 | 4.504065 | false | true | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/circleci/CircleCIAuthInterceptor.kt | 1 | 2795 | package com.baulsupp.okurl.services.circleci
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.Oauth2AuthInterceptor
import com.baulsupp.okurl.authenticator.ValidatedCredentials
import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.completion.ApiCompleter
import com.baulsupp.okurl.completion.BaseUrlCompleter
import com.baulsupp.okurl.completion.CompletionVariableCache
import com.baulsupp.okurl.completion.UrlList
import com.baulsupp.okurl.credentials.CredentialsStore
import com.baulsupp.okurl.credentials.Token
import com.baulsupp.okurl.credentials.TokenValue
import com.baulsupp.okurl.kotlin.query
import com.baulsupp.okurl.kotlin.queryList
import com.baulsupp.okurl.secrets.Secrets
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
class CircleCIAuthInterceptor : Oauth2AuthInterceptor() {
override val serviceDefinition = Oauth2ServiceDefinition(
"circleci.com", "CircleCI API", "circleci",
"https://circleci.com/docs/api/v1-reference/", "https://circleci.com/account/api"
)
override suspend fun intercept(chain: Interceptor.Chain, credentials: Oauth2Token): Response {
var request = chain.request()
val token = credentials.accessToken
val newUrl = request.url.newBuilder().addQueryParameter("circle-token", token).build()
val builder = request.newBuilder()
if (request.url.encodedPath.startsWith("/api/v1.1/")) {
builder.addHeader("Accept", "application/json")
}
request = builder.url(newUrl).build()
return chain.proceed(request)
}
override suspend fun authorize(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
authArguments: List<String>
): Oauth2Token =
Oauth2Token(Secrets.prompt("CircleCI Personal API Token", "circleci.token", "", true))
override suspend fun validate(
client: OkHttpClient,
credentials: Oauth2Token
): ValidatedCredentials =
ValidatedCredentials(
client.query<User>(
"https://circleci.com/api/v1.1/me",
TokenValue(credentials)
).name
)
override suspend fun apiCompleter(
prefix: String,
client: OkHttpClient,
credentialsStore: CredentialsStore,
completionVariableCache: CompletionVariableCache,
tokenSet: Token
): ApiCompleter {
val urlList = UrlList.fromResource(name())
val completer = BaseUrlCompleter(urlList!!, hosts(credentialsStore), completionVariableCache)
completer.withCachedVariable(name(), "project-path") {
client.queryList<Project>("https://circleci.com/api/v1.1/projects", tokenSet)
.map { it.vcs_type + "/" + it.username + "/" + it.reponame }
}
return completer
}
}
| apache-2.0 | 96eb5d0587ee4446845c7933a2aae2a4 | 33.9375 | 97 | 0.757424 | 4.333333 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/concurrent/EventLoop.kt | 4 | 1383 | /*
* Copyright 2018 the original author or 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 org.gradle.kotlin.dsl.concurrent
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.TimeUnit
internal
class EventLoop<T>(
name: String = "Gradle Kotlin DSL Event Loop",
val loop: (() -> T?) -> Unit
) {
fun accept(event: T): Boolean {
if (q.offer(event, offerTimeoutMillis, TimeUnit.MILLISECONDS)) {
consumer.poke()
return true
}
return false
}
private
val q = ArrayBlockingQueue<T>(64)
private
var consumer = ResurrectingThread(name = name) {
loop(::poll)
}
private
fun poll(): T? = q.poll(pollTimeoutMillis, TimeUnit.MILLISECONDS)
}
private
const val offerTimeoutMillis = 50L
internal
const val pollTimeoutMillis = 5_000L
| apache-2.0 | f874cb9fcaccf301b4ec76b84534872d | 24.145455 | 75 | 0.689805 | 4.153153 | false | false | false | false |
wuan/bo-android2 | app/src/main/java/org/blitzortung/android/data/DataBuilder.kt | 1 | 2890 | package org.blitzortung.android.data
import com.beust.klaxon.JsonObject
import com.beust.klaxon.double
import com.beust.klaxon.int
import org.blitzortung.android.data.raster.RasterParameters
import org.blitzortung.android.data.strike.DefaultStrike
import org.blitzortung.android.data.strike.RasterElement
import org.blitzortung.android.lib.TimeFormat
import org.json.JSONArray
import org.json.JSONException
object DataBuilder {
fun createDefaultStrike(referenceTimestamp: Long, jsonArray: JSONArray): DefaultStrike {
try {
return DefaultStrike(
timestamp = referenceTimestamp - 1000 * jsonArray.getInt(0),
longitude = jsonArray.getDouble(1).toFloat(),
latitude = jsonArray.getDouble(2).toFloat(),
lateralError = jsonArray.getDouble(3).toFloat(),
altitude = 0,
amplitude = jsonArray.getDouble(4).toFloat(),
stationCount = jsonArray.getInt(5).toShort())
} catch (e: JSONException) {
throw IllegalStateException("error with JSON format while parsing strike data", e)
}
}
fun createRasterParameters(response: JsonObject, info: String): RasterParameters {
return RasterParameters(
minLongitude = response.double("x0")!!.toFloat(),
maxLatitude = response.double("y1")!!.toFloat(),
longitudeDelta = response.double("xd")!!.toFloat(),
latitudeDelta = response.double("yd")!!.toFloat(),
longitudeBins = response.int("xc")!!,
latitudeBins = response.int("yc")!!,
info = info)
}
fun createRasterElement(rasterParameters: RasterParameters, referenceTimestamp: Long, jsonArray: JSONArray): RasterElement {
return RasterElement(
timestamp = referenceTimestamp + 1000 * jsonArray.getInt(3),
longitude = rasterParameters.getCenterLongitude(jsonArray.getInt(0)),
latitude = rasterParameters.getCenterLatitude(jsonArray.getInt(1)),
multiplicity = jsonArray.getInt(2))
}
fun createStation(jsonArray: JSONArray): Station {
val name = jsonArray.getString(1)
val longitude = jsonArray.getDouble(3).toFloat()
val latitude = jsonArray.getDouble(4).toFloat()
var offlineSince: Long = Station.OFFLINE_SINCE_NOT_SET
if (jsonArray.length() >= 6) {
val offlineSinceString = jsonArray.getString(5)
if (offlineSinceString.length > 0) {
offlineSince = TimeFormat.parseTimeWithMilliseconds(offlineSinceString)
}
}
return Station(
name = name,
longitude = longitude,
latitude = latitude,
offlineSince = offlineSince
)
}
}
| gpl-3.0 | 2c79e7041fd5831f757a970f215cc102 | 39.704225 | 128 | 0.626298 | 5.088028 | false | false | false | false |
fnouama/intellij-community | plugins/settings-repository/src/git/GitRepositoryManager.kt | 5 | 10601 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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 org.jetbrains.settingsRepository.git
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.NotNullLazyValue
import com.intellij.openapi.util.ShutDownTracker
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.SmartList
import org.eclipse.jgit.api.AddCommand
import org.eclipse.jgit.api.errors.UnmergedPathsException
import org.eclipse.jgit.errors.TransportException
import org.eclipse.jgit.ignore.IgnoreNode
import org.eclipse.jgit.lib.ConfigConstants
import org.eclipse.jgit.lib.Constants
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.lib.RepositoryState
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import org.eclipse.jgit.transport.*
import org.jetbrains.jgit.dirCache.AddLoadedFile
import org.jetbrains.jgit.dirCache.DeleteDirectory
import org.jetbrains.jgit.dirCache.deletePath
import org.jetbrains.jgit.dirCache.edit
import org.jetbrains.keychain.CredentialsStore
import org.jetbrains.settingsRepository.*
import org.jetbrains.settingsRepository.RepositoryManager.Updater
import java.io.File
import java.io.IOException
import kotlin.concurrent.write
class GitRepositoryManager(private val credentialsStore: NotNullLazyValue<CredentialsStore>, dir: File) : BaseRepositoryManager(dir) {
val repository: Repository
get() {
var r = _repository
if (r == null) {
r = FileRepositoryBuilder().setWorkTree(dir).build()
_repository = r
if (ApplicationManager.getApplication()?.isUnitTestMode != true) {
ShutDownTracker.getInstance().registerShutdownTask { _repository?.close() }
}
}
return r!!
}
// we must recreate repository if dir changed because repository stores old state and cannot be reinitialized (so, old instance cannot be reused and we must instantiate new one)
var _repository: Repository? = null
val credentialsProvider: CredentialsProvider by lazy {
JGitCredentialsProvider(credentialsStore, repository)
}
private var ignoreRules: IgnoreNode? = null
override fun createRepositoryIfNeed(): Boolean {
ignoreRules = null
if (isRepositoryExists()) {
return false
}
repository.create()
repository.disableAutoCrLf()
return true
}
override fun deleteRepository() {
ignoreRules = null
super.deleteRepository()
val r = _repository
if (r != null) {
_repository = null
r.close()
}
}
override fun getUpstream(): String? {
return StringUtil.nullize(repository.config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL))
}
override fun setUpstream(url: String?, branch: String?) {
repository.setUpstream(url, branch ?: Constants.MASTER)
}
override fun isRepositoryExists(): Boolean {
val repo = _repository
if (repo == null) {
return dir.exists() && FileRepositoryBuilder().setWorkTree(dir).setup().objectDirectory.exists()
}
else {
return repo.objectDatabase.exists()
}
}
override fun hasUpstream() = getUpstream() != null
override fun addToIndex(file: File, path: String, content: ByteArray, size: Int) {
repository.edit(AddLoadedFile(path, content, size, file.lastModified()))
}
override fun deleteFromIndex(path: String, isFile: Boolean) {
repository.deletePath(path, isFile, false)
}
override fun commit(indicator: ProgressIndicator?, syncType: SyncType?, fixStateIfCannotCommit: Boolean): Boolean {
lock.write {
try {
// will be reset if OVERWRITE_LOCAL, so, we should not fix state in this case
return commitIfCan(indicator, if (!fixStateIfCannotCommit || syncType == SyncType.OVERWRITE_LOCAL) repository.repositoryState else repository.fixAndGetState())
}
catch (e: UnmergedPathsException) {
if (syncType == SyncType.OVERWRITE_LOCAL) {
LOG.warn("Unmerged detected, ignored because sync type is OVERWRITE_LOCAL", e)
return false
}
else {
indicator?.checkCanceled()
LOG.warn("Unmerged detected, will be attempted to resolve", e)
resolveUnmergedConflicts(repository)
indicator?.checkCanceled()
return commitIfCan(indicator, repository.fixAndGetState())
}
}
}
}
private fun commitIfCan(indicator: ProgressIndicator?, state: RepositoryState): Boolean {
if (state.canCommit()) {
return commit(repository, indicator)
}
else {
LOG.warn("Cannot commit, repository in state ${state.description}")
return false
}
}
override fun getAheadCommitsCount() = repository.getAheadCommitsCount()
override fun commit(paths: List<String>) {
}
override fun push(indicator: ProgressIndicator?) {
LOG.debug("Push")
val refSpecs = SmartList(RemoteConfig(repository.config, Constants.DEFAULT_REMOTE_NAME).pushRefSpecs)
if (refSpecs.isEmpty()) {
val head = repository.getRef(Constants.HEAD)
if (head != null && head.isSymbolic) {
refSpecs.add(RefSpec(head.leaf.name))
}
}
val monitor = indicator.asProgressMonitor()
for (transport in Transport.openAll(repository, Constants.DEFAULT_REMOTE_NAME, Transport.Operation.PUSH)) {
for (attempt in 0..1) {
transport.credentialsProvider = credentialsProvider
try {
val result = transport.push(monitor, transport.findRemoteRefUpdatesFor(refSpecs))
if (LOG.isDebugEnabled) {
printMessages(result)
for (refUpdate in result.remoteUpdates) {
LOG.debug(refUpdate.toString())
}
}
break;
}
catch (e: TransportException) {
if (e.status == TransportException.Status.NOT_PERMITTED) {
if (attempt == 0) {
credentialsProvider.reset(transport.uri)
}
else {
throw AuthenticationException(e)
}
}
else {
wrapIfNeedAndReThrow(e)
}
}
finally {
transport.close()
}
}
}
}
override fun fetch(indicator: ProgressIndicator?): Updater {
val pullTask = Pull(this, indicator ?: EmptyProgressIndicator())
val refToMerge = pullTask.fetch()
return object : Updater {
override var definitelySkipPush = false
// KT-8632
override fun merge(): UpdateResult? = lock.write {
val committed = commit(pullTask.indicator)
if (refToMerge == null && !committed && getAheadCommitsCount() == 0) {
definitelySkipPush = true
return null
}
else {
return pullTask.pull(prefetchedRefToMerge = refToMerge)
}
}
}
}
override fun pull(indicator: ProgressIndicator?) = Pull(this, indicator).pull()
override fun resetToTheirs(indicator: ProgressIndicator) = Reset(this, indicator).reset(true)
override fun resetToMy(indicator: ProgressIndicator, localRepositoryInitializer: (() -> Unit)?) = Reset(this, indicator).reset(false, localRepositoryInitializer)
override fun canCommit() = repository.repositoryState.canCommit()
fun renameDirectory(pairs: Map<String, String?>): Boolean {
var addCommand: AddCommand? = null
val toDelete = SmartList<DeleteDirectory>()
for ((oldPath, newPath) in pairs) {
val old = File(dir, oldPath)
if (!old.exists()) {
continue
}
LOG.info("Rename $oldPath to $newPath")
val files = old.listFiles()
if (files != null) {
val new = if (newPath == null) dir else File(dir, newPath)
for (file in files) {
try {
if (file.isHidden) {
FileUtil.delete(file)
}
else {
file.renameTo(File(new, file.name))
if (addCommand == null) {
addCommand = AddCommand(repository)
}
addCommand.addFilepattern(if (newPath == null) file.name else "$newPath/${file.name}")
}
}
catch (e: Throwable) {
LOG.error(e)
}
}
toDelete.add(DeleteDirectory(oldPath))
}
try {
FileUtil.delete(old)
}
catch (e: Throwable) {
LOG.error(e)
}
}
if (toDelete.isEmpty() && addCommand == null) {
return false
}
repository.edit(toDelete)
if (addCommand != null) {
addCommand.call()
}
repository.commit(with(IdeaCommitMessageFormatter()) { StringBuilder().appendCommitOwnerInfo(true) }.append("Get rid of \$ROOT_CONFIG$ and \$APP_CONFIG").toString())
return true
}
private fun getIgnoreRules(): IgnoreNode? {
var node = ignoreRules
if (node == null) {
val file = File(dir, Constants.DOT_GIT_IGNORE)
if (file.exists()) {
node = IgnoreNode()
file.inputStream().use { node!!.parse(it) }
ignoreRules = node
}
}
return node
}
override fun isPathIgnored(path: String): Boolean {
// add first slash as WorkingTreeIterator does "The ignore code wants path to start with a '/' if possible."
return getIgnoreRules()?.isIgnored("/$path", false) == IgnoreNode.MatchResult.IGNORED
}
}
fun printMessages(fetchResult: OperationResult) {
if (LOG.isDebugEnabled) {
val messages = fetchResult.messages
if (!StringUtil.isEmptyOrSpaces(messages)) {
LOG.debug(messages)
}
}
}
class GitRepositoryService : RepositoryService {
override fun isValidRepository(file: File): Boolean {
if (File(file, Constants.DOT_GIT).exists()) {
return true
}
// existing bare repository
try {
FileRepositoryBuilder().setGitDir(file).setMustExist(true).build()
}
catch (e: IOException) {
return false
}
return true
}
} | apache-2.0 | 939890c6a8849e9a53062da7e8b83108 | 30.933735 | 179 | 0.66739 | 4.44114 | false | false | false | false |
GiantTreeLP/processing-ui | src/main/kotlin/org/gtlp/ui/views/labels/TextLabel.kt | 1 | 2401 | package org.gtlp.ui.views.labels
import org.gtlp.ui.PWindow
import org.gtlp.ui.rect
import org.gtlp.util.math.Vector
import processing.core.PApplet
import java.awt.Color
/**
* A simple label to be drawn on a [PApplet]
* @see [PWindow]
*/
class TextLabel(text: String = "", override val parent: PWindow, override var pos: Vector,
override var size: Vector = Vector.ZERO) : AbstractLabel<TextLabel>(parent, pos, size, text) {
/**
* Background color
*/
var colorBg = Color(0, 0, 0, 0)
/**
* Text color
*/
var colorText: Color = Color.BLACK
/**
* Factory method to set the background color (RGB 0 - 255)
*
* @param r red value
* @param g green value
* @param b blue value
* @param alpha alpha value
*
* @return this
*
* @see background
*/
fun background(r: Int, g: Int, b: Int, alpha: Int = 255): TextLabel {
colorBg = Color(r, g, b, alpha)
return this
}
/**
* Factory method to set the background color
*
* @param c the [Color] for the background of this label
*
* @return this
*
* @see background
*/
fun background(c: Color): TextLabel {
colorBg = c
return this
}
/**
* Factory method to set the text color (RGB 0 - 255)
*
* @param r red value
* @param g green value
* @param b blue value
* @param alpha alpha value
*
* @return this
*
* @see color
*/
fun color(r: Int, g: Int, b: Int, alpha: Int = 255): TextLabel {
colorText = Color(r, g, b, alpha)
return this
}
/**
* Factory method to set the text color
*
* @param c the color for the text of this label
*
* @return this
*
* @see color
*/
fun color(c: Color): TextLabel {
colorText = c
return this
}
override fun draw() {
parent.apply {
val pos = [email protected]
val size = [email protected]
noStroke()
rect(colorBg, pos, size)
fill(colorText.rgb)
textSize(textSize)
textAlign(alignX, alignY)
if (size == Vector.ZERO) {
text(text, pos.x, pos.y)
} else {
text(text, pos.x, pos.y, size.x, size.y)
}
}
}
} | lgpl-3.0 | 0e18a63423f1ffc7f8a0ef6f1c8cb43f | 21.87619 | 110 | 0.529779 | 3.781102 | false | false | false | false |
SUPERCILEX/Robot-Scouter | buildSrc/src/main/kotlin/com/supercilex/robotscouter/build/tasks/GenerateChangelog.kt | 1 | 2306 | package com.supercilex.robotscouter.build.tasks
import org.ajoberstar.grgit.Grgit
import org.gradle.api.DefaultTask
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFile
import org.gradle.api.provider.ListProperty
import org.gradle.api.tasks.OutputFiles
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.submit
import org.gradle.kotlin.dsl.support.serviceOf
import org.gradle.workers.WorkAction
import org.gradle.workers.WorkParameters
import org.gradle.workers.WorkerExecutor
internal abstract class GenerateChangelog : DefaultTask() {
@get:OutputFiles
protected val files by lazy {
val base = project.layout.projectDirectory.dir("src/main/play/release-notes/en-US")
listOf(base.file("internal.txt"), base.file("alpha.txt"))
}
@TaskAction
fun generateChangelog() {
project.serviceOf<WorkerExecutor>().noIsolation().submit(Generator::class) {
projectDir.set(project.projectDir)
changelogFiles.set(files)
}
}
abstract class Generator : WorkAction<Generator.Params> {
override fun execute() {
Grgit.open {
currentDir = parameters.projectDir.get().asFile
}.use {
val recentCommits = it.log {
maxCommits = 10
}
val changelog = recentCommits
.map { "- ${it.shortMessage}" }
.generate()
for (output in parameters.changelogFiles.get()) {
output.asFile.writeText(changelog)
}
}
}
private tailrec fun List<String>.generate(): String {
val candidate = """
|Recent changes:
|${joinToString("\n")}
|Report bugs and view the full changelog here:
|https://github.com/SUPERCILEX/Robot-Scouter/commits/master
""".trimMargin()
// The Play Store allows a max of 500 chars
return if (candidate.length > 500) subList(1, size).generate() else candidate
}
interface Params : WorkParameters {
val projectDir: DirectoryProperty
val changelogFiles: ListProperty<RegularFile>
}
}
}
| gpl-3.0 | 39aea122e6398e518d758335b1d2a6e3 | 32.911765 | 91 | 0.615351 | 4.735113 | false | false | false | false |
Kotlin/dokka | core/src/main/kotlin/utilities/ServiceLocator.kt | 1 | 4114 | package org.jetbrains.dokka.utilities
import java.io.File
import java.net.URISyntaxException
import java.net.URL
import java.util.*
import java.util.jar.JarFile
import java.util.zip.ZipEntry
data class ServiceDescriptor(val name: String, val category: String, val description: String?, val className: String)
class ServiceLookupException(message: String) : Exception(message)
object ServiceLocator {
fun <T : Any> lookup(clazz: Class<T>, category: String, implementationName: String): T {
val descriptor = lookupDescriptor(category, implementationName)
return lookup(clazz, descriptor)
}
fun <T : Any> lookup(
clazz: Class<T>,
descriptor: ServiceDescriptor
): T {
val loadedClass = javaClass.classLoader.loadClass(descriptor.className)
val constructor = loadedClass.constructors.firstOrNull { it.parameterTypes.isEmpty() } ?: throw ServiceLookupException("Class ${descriptor.className} has no corresponding constructor")
val implementationRawType: Any =
if (constructor.parameterTypes.isEmpty()) constructor.newInstance() else constructor.newInstance(constructor)
if (!clazz.isInstance(implementationRawType)) {
throw ServiceLookupException("Class ${descriptor.className} is not a subtype of ${clazz.name}")
}
@Suppress("UNCHECKED_CAST")
return implementationRawType as T
}
private fun lookupDescriptor(category: String, implementationName: String): ServiceDescriptor {
val properties = javaClass.classLoader.getResourceAsStream("dokka/$category/$implementationName.properties")?.use { stream ->
Properties().let { properties ->
properties.load(stream)
properties
}
} ?: throw ServiceLookupException("No implementation with name $implementationName found in category $category")
val className = properties["class"]?.toString() ?: throw ServiceLookupException("Implementation $implementationName has no class configured")
return ServiceDescriptor(implementationName, category, properties["description"]?.toString(), className)
}
fun URL.toFile(): File {
assert(protocol == "file")
return try {
File(toURI())
} catch (e: URISyntaxException) { //Try to handle broken URLs, with unescaped spaces
File(path)
}
}
fun allServices(category: String): List<ServiceDescriptor> {
val entries = this.javaClass.classLoader.getResources("dokka/$category")?.toList() ?: emptyList()
return entries.flatMap {
when (it.protocol) {
"file" -> it.toFile().listFiles()?.filter { it.extension == "properties" }?.map { lookupDescriptor(category, it.nameWithoutExtension) } ?: emptyList()
"jar" -> {
JarFile(URL(it.file.substringBefore("!")).toFile()).use { file ->
val jarPath = it.file.substringAfterLast("!").removePrefix("/").removeSuffix("/")
file.entries()
.asSequence()
.filter { entry -> !entry.isDirectory && entry.path == jarPath && entry.extension == "properties" }
.map { entry ->
lookupDescriptor(category, entry.fileName.substringBeforeLast("."))
}.toList()
}
}
else -> emptyList()
}
}
}
}
inline fun <reified T : Any> ServiceLocator.lookup(category: String, implementationName: String): T = lookup(T::class.java, category, implementationName)
inline fun <reified T : Any> ServiceLocator.lookup(desc: ServiceDescriptor): T = lookup(T::class.java, desc)
private val ZipEntry.fileName: String
get() = name.substringAfterLast("/", name)
private val ZipEntry.path: String
get() = name.substringBeforeLast("/", "").removePrefix("/")
private val ZipEntry.extension: String?
get() = fileName.let { fn -> if ("." in fn) fn.substringAfterLast(".") else null }
| apache-2.0 | 2dd1151ca122e714c0c2692ab2b8532d | 42.765957 | 192 | 0.638794 | 5.123288 | false | false | false | false |
Doctoror/FuckOffMusicPlayer | presentation/src/main/java/com/doctoror/fuckoffmusicplayer/presentation/library/genres/GenresFragment.kt | 2 | 2719 | /*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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 com.doctoror.fuckoffmusicplayer.presentation.library.genres
import android.os.Bundle
import android.support.v4.app.ActivityOptionsCompat
import com.doctoror.fuckoffmusicplayer.R
import com.doctoror.fuckoffmusicplayer.domain.genres.GenresProvider
import com.doctoror.fuckoffmusicplayer.presentation.Henson
import com.doctoror.fuckoffmusicplayer.presentation.library.LibraryListFragment
import com.doctoror.fuckoffmusicplayer.presentation.library.genrealbums.GenreAlbumsActivity
import dagger.android.support.AndroidSupportInjection
import javax.inject.Inject
class GenresFragment : LibraryListFragment() {
@Inject
lateinit var genresProvider: GenresProvider
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this)
}
override fun obtainConfig() = Config(
canShowEmptyView = true,
dataSource = { genresProvider.load(it) },
emptyMessage = getText(R.string.No_genres_found),
recyclerAdapter = createRecyclerAdapter()
)
private fun createRecyclerAdapter(): GenresRecyclerAdapter {
val context = context ?: throw IllegalStateException("Context is null")
val adapter = GenresRecyclerAdapter(context)
adapter.setOnGenreClickListener { position, genreId, genre ->
onGenreClick(position, genreId, genre)
}
return adapter
}
private fun onGenreClick(position: Int, genreId: Long,
genre: String?) {
activity?.let {
val intent = Henson.with(it).gotoGenreAlbumsActivity()
.genre(genre)
.genreId(genreId)
.build()
var options: Bundle? = null
val itemView = getItemView(position)
if (itemView != null) {
options = ActivityOptionsCompat.makeSceneTransitionAnimation(it, itemView,
GenreAlbumsActivity.TRANSITION_NAME_ROOT).toBundle()
}
startActivity(intent, options)
}
}
}
| apache-2.0 | c5b19f023c05becdf2534305be9e9a53 | 36.246575 | 91 | 0.690695 | 4.952641 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/test/java/com/garpr/android/repositories/PlayersRepositoryTest.kt | 1 | 2808 | package com.garpr.android.repositories
import com.garpr.android.data.models.Endpoint
import com.garpr.android.data.models.LitePlayer
import com.garpr.android.data.models.PlayersBundle
import com.garpr.android.data.models.Region
import com.garpr.android.networking.AbsServerApi
import com.garpr.android.test.BaseTest
import io.reactivex.Single
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class PlayersRepositoryTest : BaseTest() {
private lateinit var playersRepository: PlayersRepository
private val serverApi = ServerApiOverride()
@Before
override fun setUp() {
super.setUp()
playersRepository = PlayersRepositoryImpl(serverApi)
}
@Test
fun testGetPlayersWithEmptyPlayersBundle() {
serverApi.playersBundle = EMPTY_PLAYERS_BUNDLE
val bundle = playersRepository.getPlayers(NORCAL)
.blockingGet()
assertTrue(bundle.players.isNullOrEmpty())
}
@Test
fun testGetPlayersWithPlayersBundle() {
serverApi.playersBundle = PLAYERS_BUNDLE
val bundle = playersRepository.getPlayers(NORCAL)
.blockingGet()
assertEquals(4, bundle.players?.size)
assertEquals(BLARGH, bundle.players?.get(0))
assertEquals(NMW, bundle.players?.get(1))
assertEquals(SNAP, bundle.players?.get(2))
assertEquals(UMARTH, bundle.players?.get(3))
}
companion object {
private val BLARGH = LitePlayer(
id = "58885df9d2994e3d56594112",
name = "blargh"
)
private val NMW = LitePlayer(
id = "583a4a15d2994e0577b05c8a",
name = "NMW"
)
private val SNAP = LitePlayer(
id = "59213f1ad2994e1d79144956",
name = "Snap"
)
private val UMARTH = LitePlayer(
id = "5877eb55d2994e15c7dea977",
name = "Umarth"
)
private val EMPTY_PLAYERS_BUNDLE = PlayersBundle()
private val PLAYERS_BUNDLE = PlayersBundle(
players = listOf(UMARTH, BLARGH, SNAP, NMW)
)
private val NORCAL = Region(
displayName = "Norcal",
id = "norcal",
endpoint = Endpoint.GAR_PR
)
}
private class ServerApiOverride(
internal var playersBundle: PlayersBundle? = null
) : AbsServerApi() {
override fun getPlayers(region: Region): Single<PlayersBundle> {
val playersBundle = this.playersBundle
return if (playersBundle == null) {
Single.error(NullPointerException())
} else {
Single.just(playersBundle)
}
}
}
}
| unlicense | e91bed8f37356f0b88f67b93312c9ade | 27.363636 | 72 | 0.618946 | 4.3875 | false | true | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/cargo/icons/CargoIconProvider.kt | 1 | 1103 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.icons
import com.intellij.ide.IconProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.cargo.CargoConstants
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.ext.cargoWorkspace
import javax.swing.Icon
class CargoIconProvider : IconProvider() {
override fun getIcon(element: PsiElement, flags: Int): Icon? = when (element) {
is PsiFile -> getFileIcon(element)
else -> null
}
private fun getFileIcon(element: PsiFile): Icon? = when {
element.name == CargoConstants.MANIFEST_FILE -> CargoIcons.ICON
element.name == CargoConstants.LOCK_FILE -> CargoIcons.LOCK_ICON
element is RsFile && isBuildRs(element) -> CargoIcons.BUILD_RS_ICON
else -> null
}
private fun isBuildRs(element: RsFile): Boolean =
element.name == CargoConstants.BUILD_RS_FILE
&& element.containingDirectory?.virtualFile == element.cargoWorkspace?.contentRoot
}
| mit | 4e1ea0086eacc1f853bd088909ef4550 | 33.46875 | 94 | 0.712602 | 4.070111 | false | false | false | false |
MitI-7/LamuneSoda | src/com/github/MitI_7/contest/AOJ.kt | 1 | 3311 | package com.github.MitI_7.contest
import com.github.MitI_7.Settings
import com.intellij.openapi.components.ServiceManager
import com.squareup.okhttp.FormEncodingBuilder
import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.Request
import com.squareup.okhttp.Response
import java.net.CookieManager
import java.util.concurrent.TimeUnit
class AOJ() : ContestSite {
var client = OkHttpClient()
val settings = ServiceManager.getService(Settings::class.java)
init {
val cookieManager = CookieManager()
cookieManager.setCookiePolicy(java.net.CookiePolicy.ACCEPT_ALL)
this.client.cookieHandler = cookieManager
this.client.setConnectTimeout(Settings.TIMEOUT, TimeUnit.SECONDS)
}
override fun submit(lesson_id: String, problem_no: String, language: String, source_code: String): String {
val form = FormEncodingBuilder().addEncoded("userID", this.settings.AOJUserID)
.addEncoded("password", this.settings.AOJPassword)
.addEncoded("lessonID", lesson_id)
.addEncoded("problemNO", problem_no)
.add("language", language)
.add("sourceCode", source_code)
val url = "http://judge.u-aizu.ac.jp/onlinejudge/webservice/submit"
var response: Response? = null
try {
response = this.client.newCall(Request.Builder().url(url).post(form.build()).build()).execute()
if (!response.isSuccessful) {
return "submission error: code is $response.code()"
}
return this.make_message(response.body().string(), lesson_id, problem_no, language)
} catch (e: Exception) {
return "submission error: $e.toString()"
} finally {
response!!.body().close()
}
}
override fun get_language_set(lesson_id: String, problem_no: String): Set<String> = setOf(
"C",
"C++",
"JAVA",
"C++11",
"C++14",
"C#",
"D",
"Ruby",
"Python",
"Python3",
"PHP",
"JavaScript",
"Scala",
"Haskell",
"OCaml")
override fun get_default_language(): String {
val settings = ServiceManager.getService(Settings::class.java)
return settings.AOJDefaultLanguage
}
fun make_message(html: String, lesson_id: String, problem_no: String, language: String): String {
if ("Invalid problem" in html) {
return "submission error: lesson_id \"$lesson_id\" or problem_no \"$problem_no\" is invalid."
} else if ("Wrong problemNO" in html) {
return "submission error: problem_no \"$problem_no\" is wrong."
} else if ("UserID or Password is Wrong" in html) {
return "submission error: UserID or Password is Wrong."
} else if ("Invalid language" in html) {
return "submission error: language \"$language\" is Wrong."
}
return "submit(lessonID: $lesson_id, problemNO: $problem_no, language: $language)"
}
companion object {
val NAME = "AOJ"
}
} | apache-2.0 | bffb3726fdd1387b08e5d4ac7517a711 | 36.636364 | 111 | 0.578375 | 4.456258 | false | false | false | false |
JimSeker/ui | Advanced/ViewPagerDemo_kt/app/src/main/java/edu/cs4730/viewpagerdemo_kt/FragLeft.kt | 1 | 1808 | package edu.cs4730.viewpagerdemo_kt
import android.widget.TextView
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import edu.cs4730.viewpagerdemo_kt.R
/**
* This is a simple fragment to display data and it the "left" most fragment in the viewpager.
* The code here is identical to the code in the right fragment.
*/
class FragLeft : Fragment() {
lateinit var tx: TextView
lateinit var mViewModel: DataViewModel
var TAG = "Left"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "OnCreate")
if (savedInstanceState != null) {
Log.d(TAG, "OnCreate savedInstanceState")
}
mViewModel = ViewModelProvider(requireActivity()).get(DataViewModel::class.java)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
Log.d("Left", "OnCreateView")
val view = inflater.inflate(R.layout.left, container, false)
tx = view.findViewById(R.id.tvleft)
mViewModel.dataLeft.observe(viewLifecycleOwner, { data -> tx.text = data })
return view
}
override fun onPause() {
super.onPause()
Log.d(TAG, "onPause()")
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume()")
}
override fun onDestroyView() {
super.onDestroyView()
Log.d(TAG, "onDestroyView()")
}
override fun onSaveInstanceState(outState: Bundle) {
Log.d(TAG, "OnSaveInstanceState")
super.onSaveInstanceState(outState)
}
} | apache-2.0 | d46b6b400a630a641281697bf803c80d | 28.655738 | 94 | 0.668142 | 4.377724 | false | false | false | false |
It-projects-Ke-401-CA/CruelAlarm | app/src/main/java/com/weiaett/cruelalarm/img_proc/ComparisonReceiver.kt | 1 | 1297 | package com.weiaett.cruelalarm.img_proc
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import java.io.File
import java.io.FileInputStream
val RECEIVER = "MatchReceiver"
class ComparisonReceiver(val matchView: ImageView, val statusView: TextView) : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d(RECEIVER, "Response received")
val result: String? = intent.getStringExtra(ComparatorService.RESULT)
if (result != null){
val pathname = intent.getStringExtra(ComparatorService.MATCH_IMAGE)
Log.d(RECEIVER, pathname)
val cached = File(pathname)
try {
val stream = FileInputStream(cached)
val bitmap = BitmapFactory.decodeStream(stream)
matchView.setImageBitmap(bitmap)
statusView.text = result
} catch (e: Exception) {
Log.e("MatchMain", "IOException", e)
}
}else{
val state = intent.getStringExtra(ComparatorService.STATE)
statusView.text = state
}
}
} | gpl-3.0 | 4c89e61e6348996fa0c62b0e8469e0bc | 32.282051 | 100 | 0.663069 | 4.632143 | false | false | false | false |
encircled/jPut | jput-core/src/main/java/cz/encircled/jput/Statistics.kt | 1 | 848 | package cz.encircled.jput
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.math.sqrt
fun List<Long>.deviation(): Double = sqrt(variance())
fun List<Long>.variance(): Double {
return if (isEmpty()) 0.0
else {
val average = average()
var temp = 0.0
for (a in this) temp += (a - average).pow(2.0)
temp / size
}
}
/**
* List must be ordered
*
* @param rank target percentile
* @return values below `percentile`
*/
fun List<Long>.percentile(rank: Double): List<Long> {
validatePercentile(rank)
for (i in 1 until size) {
check(get(i) >= get(i - 1)) { "List must be ordered!" }
}
return subList(0, (size * rank).roundToInt())
}
private fun validatePercentile(rank: Double) {
check(rank in 0.0..1.0) { "Wrong percentile [$rank], must be [0 < Q <= 1]" }
}
| apache-2.0 | e4a5dd0d4eb47e709b30fd7dc087c7f1 | 22.555556 | 80 | 0.615566 | 3.299611 | false | false | false | false |
fan123199/V2ex-simple | app/src/main/java/im/fdx/v2ex/utils/extensions/StringExt.kt | 1 | 1007 | package im.fdx.v2ex.utils.extensions
/**
* Created by fdx on 2017/7/3.
* fdx will maintain it
*/
/**
* 将链接转成完整链接,一般用 GoodTextView
*/
fun String.fullUrl() = this.replace("href=\"/member/", "href=\"https://www.v2ex.com/member/")
.replace("href=\"/i/", "href=\"https://i.v2ex.co/")
.replace("href=\"/t/", "href=\"https://www.v2ex.com/t/")
.replace("href=\"/go/", "href=\"https://www.v2ex.com/go/")
.replace("<img src=\"//", "<img src=\"https://")
fun String.getNum(): String {
var str2 = ""
if (isNotBlank()) {
(0 until length)
.filter { this[it].toInt() in 48..57 }
.forEach { str2 += this[it] }
}
return str2
}
/**
* 获取 @abcd #rownum
* return rownum
*/
fun String.getRowNum(name: String): Int {
val str = """(?<=${name}\s{1,4}#)\d+"""
val findAll = Regex(str).findAll(this)
if (findAll.none()) {
return -1
}
return findAll.first().value.toInt()
} | apache-2.0 | fbd4924fa6f03e0aada1d212ecfec9dc | 22.285714 | 93 | 0.532242 | 3.034161 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osmnotes/NoteController.kt | 1 | 4214 | package de.westnordost.streetcomplete.data.osmnotes
import android.util.Log
import de.westnordost.streetcomplete.data.osm.mapdata.BoundingBox
import de.westnordost.streetcomplete.data.osm.mapdata.LatLon
import de.westnordost.streetcomplete.ktx.format
import java.lang.System.currentTimeMillis
import java.util.concurrent.CopyOnWriteArrayList
import javax.inject.Inject
import javax.inject.Singleton
/** Manages access to the notes storage */
@Singleton class NoteController @Inject constructor(
private val dao: NoteDao
) {
/* Must be a singleton because there is a listener that should respond to a change in the
* database table */
/** Interface to be notified of new notes, updated notes and notes that have been deleted */
interface Listener {
/** called when a number of notes has been added, updated or deleted */
fun onUpdated(added: Collection<Note>, updated: Collection<Note>, deleted: Collection<Long>)
/** called when all notes have been cleared */
fun onCleared()
}
private val listeners: MutableList<Listener> = CopyOnWriteArrayList()
/** Replace all notes in the given bounding box with the given notes */
fun putAllForBBox(bbox: BoundingBox, notes: Collection<Note>) {
val time = currentTimeMillis()
val oldNotesById = mutableMapOf<Long, Note>()
val addedNotes = mutableListOf<Note>()
val updatedNotes = mutableListOf<Note>()
synchronized(this) {
dao.getAll(bbox).associateByTo(oldNotesById) { it.id }
for (note in notes) {
if (oldNotesById.containsKey(note.id)) {
updatedNotes.add(note)
} else {
addedNotes.add(note)
}
oldNotesById.remove(note.id)
}
dao.putAll(notes)
dao.deleteAll(oldNotesById.keys)
}
val seconds = (currentTimeMillis() - time) / 1000.0
Log.i(TAG,"Persisted ${addedNotes.size} and deleted ${oldNotesById.size} notes in ${seconds.format(1)}s")
onUpdated(added = addedNotes, updated = updatedNotes, deleted = oldNotesById.keys)
}
fun get(noteId: Long): Note? = dao.get(noteId)
/** delete a note because the note does not exist anymore on OSM (has been closed) */
fun delete(noteId: Long) {
val deleteSuccess = synchronized(this) { dao.delete(noteId) }
if (deleteSuccess) {
onUpdated(deleted = listOf(noteId))
}
}
/** put a note because the note has been created/changed on OSM */
fun put(note: Note) {
val hasNote = synchronized(this) { dao.get(note.id) != null }
if (hasNote) onUpdated(updated = listOf(note))
else onUpdated(added = listOf(note))
dao.put(note)
}
fun deleteOlderThan(timestamp: Long, limit: Int? = null): Int {
val ids: List<Long>
val deletedCount: Int
synchronized(this) {
ids = dao.getIdsOlderThan(timestamp, limit)
if (ids.isEmpty()) return 0
deletedCount = dao.deleteAll(ids)
}
Log.i(TAG, "Deleted $deletedCount old notes")
onUpdated(deleted = ids)
return ids.size
}
fun clear() {
dao.clear()
listeners.forEach { it.onCleared() }
}
fun getAllPositions(bbox: BoundingBox): List<LatLon> = dao.getAllPositions(bbox)
fun getAll(bbox: BoundingBox): List<Note> = dao.getAll(bbox)
fun getAll(noteIds: Collection<Long>): List<Note> = dao.getAll(noteIds)
/* ------------------------------------ Listeners ------------------------------------------- */
fun addListener(listener: Listener) {
listeners.add(listener)
}
fun removeListener(listener: Listener) {
listeners.remove(listener)
}
private fun onUpdated(added: Collection<Note> = emptyList(), updated: Collection<Note> = emptyList(), deleted: Collection<Long> = emptyList()) {
if (added.isEmpty() && updated.isEmpty() && deleted.isEmpty()) return
listeners.forEach { it.onUpdated(added, updated, deleted) }
}
companion object {
private const val TAG = "NoteController"
}
}
| gpl-3.0 | 5bc82788e48f220b4bd7da0a6ab69049 | 33.826446 | 148 | 0.627907 | 4.412565 | false | false | false | false |
matkoniecz/StreetComplete | app/src/test/java/de/westnordost/streetcomplete/data/elementfilter/BooleanExpressionBuilderTest.kt | 2 | 3353 | package de.westnordost.streetcomplete.data.elementfilter
import org.junit.Test
import org.junit.Assert.*
class BooleanExpressionBuilderTest {
@Test fun leaf() { check("a") }
@Test fun and() { check("a*b") }
@Test fun or() { check("a+b") }
@Test fun and3() { check("a*b*c") }
@Test fun or3() { check("a+b+c") }
@Test fun andOr() { check("a*b+c") }
@Test fun orAnd() { check("a+b*c") }
@Test fun andInOr() { check("a+b*c+d") }
@Test fun andInOr2() { check("a*b+c*d") }
@Test fun brackets0() { check("(a)", "a") }
@Test fun brackets1() { check("(a*b)", "a*b") }
@Test fun brackets2() { check("(a+b)", "a+b") }
@Test fun brackets3() { check("((a*b))", "a*b") }
@Test fun brackets4() { check("((a+b))", "a+b") }
@Test fun brackets5() { check("(a+b)*c") }
@Test fun brackets6() { check("a*(b+c)") }
@Test fun brackets7() { check("a*(b+c)*d") }
@Test fun brackets8() { check("(a*b)+c", "a*b+c") }
@Test fun brackets9() { check("(a*b)*c", "a*b*c") }
@Test fun brackets10() { check("(a+b)+c", "a+b+c") }
@Test fun brackets11() { check("a+(b*c)", "a+b*c") }
@Test fun brackets12() { check("a*(b*c)", "a*b*c") }
@Test fun brackets13() { check("a+(b+c)", "a+b+c") }
@Test fun brackets14() { check("(a*b+c)", "a*b+c") }
@Test fun brackets15() { check("(a+b*c)", "a+b*c") }
@Test fun brackets16() { check("(((a+b*c)))", "a+b*c") }
@Test fun merge1() { check("a+(b+(c+(d)))", "a+b+c+d") }
@Test fun merge2() { check("a*(b*(c*(d)))", "a*b*c*d") }
@Test fun merge3() { check("a*(b+(c*(d)))", "a*(b+c*d)") }
@Test fun merge4() { check("a+(b*(c+(d)))", "a+b*(c+d)") }
@Test fun merge5() { check("(((a)+b)+c)+d", "a+b+c+d") }
@Test fun merge6() { check("(((a)*b)*c)*d", "a*b*c*d") }
@Test fun merge7() { check("(((a)+b)*c)+d", "(a+b)*c+d") }
@Test fun merge8() { check("(((a)*b)+c)*d", "(a*b+c)*d") }
@Test fun merge9() { check("(a+b*c)*d", "(a+b*c)*d") }
@Test fun merge10() { check("(a+b*c)*d*(e+f*g)*h", "(a+b*c)*d*(e+f*g)*h") }
@Test fun flatten1() { check("((a*b)*c)*d*(e*f)", "a*b*c*d*e*f") }
@Test fun flatten2() { check("(a+b*(c+d)+e)*f", "(a+b*(c+d)+e)*f") }
@Test(expected = IllegalStateException::class)
fun `closed too many brackets 1`() { TestBooleanExpressionParser.parse("a+b)") }
@Test(expected = IllegalStateException::class)
fun `closed too many brackets 2`() { TestBooleanExpressionParser.parse("(a+b))") }
@Test(expected = IllegalStateException::class)
fun `closed too many brackets 3`() { TestBooleanExpressionParser.parse("((b+c)*a)+d)") }
@Test(expected = IllegalStateException::class)
fun `closed too few brackets 1`() { TestBooleanExpressionParser.parse("(a+b") }
@Test(expected = IllegalStateException::class)
fun `closed too few brackets 2`() { TestBooleanExpressionParser.parse("((a+b)") }
@Test(expected = IllegalStateException::class)
fun `closed too few brackets 3`() { TestBooleanExpressionParser.parse("((a*(b+c))") }
private fun check(input: String, expected: String = input) {
val tree = TestBooleanExpressionParser.parse(input)
assertEquals(expected, translateOutput(tree.toString()))
}
private fun translateOutput(output: String) = output.replace(" and ", "*").replace(" or ", "+")
}
| gpl-3.0 | c3ab88b8f93415b8df882fd39236d4ef | 38.916667 | 99 | 0.553236 | 2.839119 | false | true | false | false |
songzhw/Hello-kotlin | AdvancedJ/temp/rxjava2/operator/defer/DeferDemo.kt | 1 | 2291 | package rxjava2.operator.defer
import io.reactivex.Observable
import java.io.IOException
class Dog(var name: String) {
fun observe(): Observable<String> {
return Observable.just(name)
}
}
fun justDemo() {
val dog = Dog("one")
val observable = dog.observe()
dog.name = "two"
observable.subscribe { println("dog name = $it") } //=> one
}
// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
/*
defer(callable) : 在发生订阅关系时,callable.call();
*/
class Corgi(var name: String) {
fun observe(): Observable<String> {
// defer参数是一个Callable, 其实是public interface Callable<V> { V call() ; }
// defer的这个Callable限定死了得返回一个Observable<T>
return Observable.defer {
Observable.just(name)
}
}
}
fun deferDemo() {
val dog = Corgi("one")
val observable = dog.observe()
dog.name = "two"
observable.subscribe { println("Corgi name = $it") } //=> two
}
// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
class ShibaInu(var name: String) {
fun observe(): Observable<String> {
return Observable.create { emitter ->
emitter.onNext(name)
emitter.onComplete()
}
}
}
fun createDemo() {
val dog = ShibaInu("one")
val observable = dog.observe()
dog.name = "two"
observable.subscribe { println("ShibaInu name = $it") } //=> two
}
// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
// 一个更真实的例子: 只有真正订阅了时, 才去存数据
object db {
fun <T> writeToDisk(t: T) {}
fun close() {}
}
fun saveData(valueToSave: String): Observable<String> {
return Observable.defer {
try {
db.writeToDisk(valueToSave)
} catch (e: Exception) {
Observable.error<String>(e)
} finally {
db.close()
}
Observable.just(valueToSave)
}
}
// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
fun main(args: Array<String>) {
println(" - - - - - - - - - - - - ")
justDemo()
println(" - - - - - - - - - - - - ")
deferDemo()
println(" - - - - - - - - - - - - ")
createDemo()
println(" - - - - - - - - - - - - ")
} | apache-2.0 | c8114040e4976c185cbeff3d44db1bb5 | 20.076923 | 82 | 0.487449 | 3.094633 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/ChangeAdvancementTreeDecoder.kt | 1 | 1204 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.codec.play
import io.netty.handler.codec.DecoderException
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.packet.PacketDecoder
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.vanilla.packet.type.play.ChangeAdvancementTreePacket
object ChangeAdvancementTreeDecoder : PacketDecoder<ChangeAdvancementTreePacket> {
override fun decode(ctx: CodecContext, buf: ByteBuffer): ChangeAdvancementTreePacket {
val type = buf.readVarInt()
if (type == 0) {
val id = buf.readString()
return ChangeAdvancementTreePacket.Open(id)
} else if (type == 1) {
return ChangeAdvancementTreePacket.Close
}
throw DecoderException("Unknown type: $type")
}
}
| mit | c5a25bac4458b5b3799c82326e0491f3 | 37.83871 | 93 | 0.73588 | 4.34657 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/protobuf/commonMain/src/kotlinx/serialization/protobuf/internal/Streams.kt | 1 | 6852 | /*
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.protobuf.internal
import kotlinx.serialization.*
internal class ByteArrayInput(private var array: ByteArray, private val endIndex: Int = array.size) {
private var position: Int = 0
val availableBytes: Int get() = endIndex - position
fun slice(size: Int): ByteArrayInput {
ensureEnoughBytes(size)
val result = ByteArrayInput(array, position + size)
result.position = position
position += size
return result
}
fun read(): Int {
return if (position < endIndex) array[position++].toInt() and 0xFF else -1
}
fun readExactNBytes(bytesCount: Int): ByteArray {
ensureEnoughBytes(bytesCount)
val b = ByteArray(bytesCount)
val length = b.size
// Are there any bytes available?
val copied = if (endIndex - position < length) endIndex - position else length
array.copyInto(destination = b, destinationOffset = 0, startIndex = position, endIndex = position + copied)
position += copied
return b
}
private fun ensureEnoughBytes(bytesCount: Int) {
if (bytesCount > availableBytes) {
throw SerializationException("Unexpected EOF, available $availableBytes bytes, requested: $bytesCount")
}
}
fun readString(length: Int): String {
val result = array.decodeToString(position, position + length)
position += length
return result
}
fun readVarint32(): Int {
if (position == endIndex) {
eof()
}
// Fast-path: unrolled loop for single and two byte values
var currentPosition = position
var result = array[currentPosition++].toInt()
if (result >= 0) {
position = currentPosition
return result
} else if (endIndex - position > 1) {
result = result xor (array[currentPosition++].toInt() shl 7)
if (result < 0) {
position = currentPosition
return result xor (0.inv() shl 7)
}
}
return readVarint32SlowPath()
}
fun readVarint64(eofAllowed: Boolean): Long {
if (position == endIndex) {
if (eofAllowed) return -1
else eof()
}
// Fast-path: single and two byte values
var currentPosition = position
var result = array[currentPosition++].toLong()
if (result >= 0) {
position = currentPosition
return result
} else if (endIndex - position > 1) {
result = result xor (array[currentPosition++].toLong() shl 7)
if (result < 0) {
position = currentPosition
return result xor (0L.inv() shl 7)
}
}
return readVarint64SlowPath()
}
private fun eof() {
throw SerializationException("Unexpected EOF")
}
private fun readVarint64SlowPath(): Long {
var result = 0L
var shift = 0
while (shift < 64) {
val byte = read()
result = result or ((byte and 0x7F).toLong() shl shift)
if (byte and 0x80 == 0) {
return result
}
shift += 7
}
throw SerializationException("Input stream is malformed: Varint too long (exceeded 64 bits)")
}
private fun readVarint32SlowPath(): Int {
var result = 0
var shift = 0
while (shift < 32) {
val byte = read()
result = result or ((byte and 0x7F) shl shift)
if (byte and 0x80 == 0) {
return result
}
shift += 7
}
throw SerializationException("Input stream is malformed: Varint too long (exceeded 32 bits)")
}
}
internal class ByteArrayOutput {
private companion object {
/*
* Map number of leading zeroes -> varint size
* See the explanation in this blogpost: https://richardstartin.github.io/posts/dont-use-protobuf-for-telemetry
*/
private val VAR_INT_LENGTHS = IntArray(65) {
(63 - it) / 7
}
}
private var array: ByteArray = ByteArray(32)
private var position: Int = 0
private fun ensureCapacity(elementsToAppend: Int) {
if (position + elementsToAppend <= array.size) {
return
}
val newArray = ByteArray((position + elementsToAppend).takeHighestOneBit() shl 1)
array.copyInto(newArray)
array = newArray
}
fun size(): Int {
return position
}
fun toByteArray(): ByteArray {
val newArray = ByteArray(position)
array.copyInto(newArray, startIndex = 0, endIndex = this.position)
return newArray
}
fun write(buffer: ByteArray) {
val count = buffer.size
if (count == 0) {
return
}
ensureCapacity(count)
buffer.copyInto(
destination = array,
destinationOffset = this.position,
startIndex = 0,
endIndex = count
)
this.position += count
}
fun write(output: ByteArrayOutput) {
val count = output.size()
ensureCapacity(count)
output.array.copyInto(
destination = array,
destinationOffset = this.position,
startIndex = 0,
endIndex = count
)
this.position += count
}
fun writeInt(intValue: Int) {
ensureCapacity(4)
for (i in 3 downTo 0) {
array[position++] = (intValue shr i * 8).toByte()
}
}
fun writeLong(longValue: Long) {
ensureCapacity(8)
for (i in 7 downTo 0) {
array[position++] = (longValue shr i * 8).toByte()
}
}
fun encodeVarint32(value: Int) {
// Fast-path: unrolled loop for single byte
ensureCapacity(5)
if (value and 0x7F.inv() == 0) {
array[position++] = value.toByte()
return
}
val length = varIntLength(value.toLong())
encodeVarint(value.toLong(), length)
}
fun encodeVarint64(value: Long) {
val length = varIntLength(value)
ensureCapacity(length + 1)
encodeVarint(value, length)
}
private fun encodeVarint(value: Long, length: Int) {
var current = value
for (i in 0 until length) {
array[position + i] = ((current and 0x7F) or 0x80).toByte()
current = current ushr 7
}
array[position + length] = current.toByte()
position += length + 1
}
private fun varIntLength(value: Long): Int {
return VAR_INT_LENGTHS[value.countLeadingZeroBits()]
}
}
| apache-2.0 | d5ef86558971cc362304e9efa16b06b8 | 28.534483 | 119 | 0.565528 | 4.583278 | false | false | false | false |
scorsero/scorsero-client-android | app/src/androidTest/java/io/github/dmi3coder/scorsero/score/ScoreCreationControllerTest.kt | 1 | 3715 | package io.github.dmi3coder.scorsero.score
import org.junit.Assert.*
import org.hamcrest.CoreMatchers.instanceOf
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.not
import android.support.test.runner.lifecycle.Stage.RESUMED
import android.support.test.InstrumentationRegistry.getInstrumentation
import android.app.Activity
import android.support.test.espresso.Espresso.*
import android.support.test.espresso.matcher.ViewMatchers.*
import android.support.test.espresso.action.ViewActions.*
import android.support.test.espresso.assertion.ViewAssertions
import android.support.test.espresso.matcher.ViewMatchers
import android.support.test.filters.LargeTest
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import android.support.test.runner.lifecycle.ActivityLifecycleMonitorRegistry
import android.view.KeyEvent
import android.view.View
import android.widget.ImageButton
import android.widget.Toolbar
import io.github.dmi3coder.scorsero.MainActivity
import io.github.dmi3coder.scorsero.R
import io.github.dmi3coder.scorsero.R.id
import io.github.dmi3coder.scorsero.data.Score
import io.github.dmi3coder.scorsero.main.MainController
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.notNullValue
import org.hamcrest.Matcher
import org.joda.time.DateTime
import org.junit.After
import org.junit.Assert
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Created by dim3coder on 2:54 PM 8/18/17.
*/
@RunWith(AndroidJUnit4::class)
class ScoreCreationControllerTest {
@JvmField
@Rule val mActivityTestRule = ActivityTestRule<MainActivity>(MainActivity::class.java)
@Before fun setUp() {}
@Test
fun mainScreen_longTapOnFab_openScoreCreationScreen() {
onView(withId(R.id.main_starter_fab)).perform(longClick())
val creationController = getOperationController()
Assert.assertThat(creationController.javaClass.simpleName,
`is`(equalTo(ScoreCreationController::class.java.simpleName)))
}
@Test
fun creationController_tapOnFab_CreateScoreAndOpenMainScreen() {
mainScreen_longTapOnFab_openScoreCreationScreen()
val controller = getOperationController()
assertThat(controller.operationScore, `is`(notNullValue()))
var scoreData = Score()
scoreData.title = "Creation score ${Math.random()}"
controller.setScore(scoreData)
onView(withId(R.id.creation_fab)).perform(click())
val textView = onView(
CoreMatchers.allOf(withId(id.title), withText(scoreData.title), isDisplayed()))
textView.check(ViewAssertions.matches(withText(scoreData.title)))
}
@Test
fun creationController_setScore_uiChanged() {
mainScreen_longTapOnFab_openScoreCreationScreen()
val controller = getOperationController()
assertThat(controller.operationScore, `is`(notNullValue()))
var scoreData = Score()
scoreData.title = "Creation score ${Math.random()}"
scoreData.description = "Creation description ${Math.random()}"
scoreData.priority = 2
scoreData.creationDate = DateTime.now().plusDays(1).toDate().time
scoreData.completed = false
controller.setScore(scoreData)
onView(allOf(withId(R.id.field_value), withText(scoreData.title), isDisplayed())).check(ViewAssertions.matches(ViewMatchers.withText(scoreData.title)))
}
fun getOperationController(): ScoreCreationController = mActivityTestRule.activity.router!!
.backstack.last().controller() as ScoreCreationController
@After fun tearDown() {}
} | gpl-3.0 | bbfeb7a71da7d27be1d870a246f0bb84 | 36.16 | 155 | 0.795424 | 4.183559 | false | true | false | false |
Kotlin/kotlinx.serialization | benchmark/src/jmh/kotlin/kotlinx/benchmarks/json/TwitterFeedStreamBenchmark.kt | 1 | 2641 | package kotlinx.benchmarks.json
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import kotlinx.benchmarks.model.MacroTwitterFeed
import kotlinx.benchmarks.model.MicroTwitterFeed
import kotlinx.serialization.json.*
import org.openjdk.jmh.annotations.*
import java.io.*
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.TimeUnit
import kotlin.io.path.deleteIfExists
import kotlin.io.path.outputStream
@Warmup(iterations = 7, time = 1)
@Measurement(iterations = 7, time = 1)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(2)
open class TwitterFeedStreamBenchmark {
val resource = TwitterFeedBenchmark::class.java.getResource("/twitter_macro.json")!!
val bytes = resource.readBytes()
private val twitter = Json.decodeFromString(MacroTwitterFeed.serializer(), resource.readText())
private val jsonIgnoreUnknwn = Json { ignoreUnknownKeys = true }
private val objectMapper: ObjectMapper =
jacksonObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
private val inputStream: InputStream
get() = ByteArrayInputStream(bytes)
private val outputStream: OutputStream
get() = ByteArrayOutputStream()
@Benchmark
fun encodeTwitterWriteText(): OutputStream {
return outputStream.use {
it.bufferedWriter().write(Json.encodeToString(MacroTwitterFeed.serializer(), twitter))
it
}
}
@Benchmark
fun encodeTwitterWriteStream(): OutputStream {
return outputStream.use {
Json.encodeToStream(MacroTwitterFeed.serializer(), twitter, it)
it
}
}
@Benchmark
fun encodeTwitterJacksonStream(): OutputStream {
return outputStream.use {
objectMapper.writeValue(it, twitter)
it
}
}
@Benchmark
fun decodeMicroTwitterReadText(): MicroTwitterFeed {
return inputStream.use {
jsonIgnoreUnknwn.decodeFromString(MicroTwitterFeed.serializer(), it.bufferedReader().readText())
}
}
@Benchmark
fun decodeMicroTwitterStream(): MicroTwitterFeed {
return inputStream.use {
jsonIgnoreUnknwn.decodeFromStream(MicroTwitterFeed.serializer(), it.buffered())
}
}
@Benchmark
fun decodeMicroTwitterJacksonStream(): MicroTwitterFeed {
return inputStream.use {
objectMapper.readValue(it, MicroTwitterFeed::class.java)
}
}
}
| apache-2.0 | d23fc6f1a4569bd831193c914db5a81e | 31.207317 | 108 | 0.715259 | 4.775769 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/effect/entity/LanternEntityEffectCollectionBuilder.kt | 1 | 2134 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.effect.entity
import com.google.common.collect.HashMultimap
import com.google.common.collect.Multimap
class LanternEntityEffectCollectionBuilder : EntityEffectCollection.Builder {
private val effects: Multimap<EntityEffectType, EntityEffect> = HashMultimap.create()
override fun add(effectType: EntityEffectType, entityEffect: EntityEffect): EntityEffectCollection.Builder = apply {
this.effects.put(effectType, entityEffect)
}
override fun addAll(entries: Map<EntityEffectType, EntityEffect>): EntityEffectCollection.Builder = apply {
for ((key, value) in entries)
this.effects.put(key, value)
}
override fun replaceOrAdd(effectType: EntityEffectType, effectToReplace: Class<out EntityEffect>, entityEffect: EntityEffect):
EntityEffectCollection.Builder = apply {
val effects = this.effects[effectType]
effects.removeIf { obj: EntityEffect? -> effectToReplace.isInstance(obj) }
effects.add(entityEffect)
}
override fun reset(effectType: EntityEffectType): EntityEffectCollection.Builder = apply {
this.effects.removeAll(effectType)
}
override fun removeIf(effectType: EntityEffectType, predicate: (EntityEffect) -> Boolean): EntityEffectCollection.Builder = apply {
this.effects[effectType].removeIf(predicate)
}
override fun build(): EntityEffectCollection = LanternEntityEffectCollection(HashMultimap.create(this.effects))
override fun from(value: EntityEffectCollection): EntityEffectCollection.Builder = apply {
this.effects.clear()
this.effects.putAll((value as LanternEntityEffectCollection).effects)
}
override fun reset(): EntityEffectCollection.Builder = apply {
this.effects.clear()
}
} | mit | bad8cf10f9d48903b45fecd42297eda1 | 38.537037 | 135 | 0.73477 | 4.50211 | false | false | false | false |
SerCeMan/franky | franky-intellij/src/main/kotlin/me/serce/franky/jvm/JVMAttachService.kt | 1 | 4139 | package me.serce.franky.jvm
import com.intellij.openapi.components.ServiceManager
import com.sun.tools.attach.VirtualMachine
import com.sun.tools.attach.VirtualMachineDescriptor
import me.serce.franky.FrankyComponent
import me.serce.franky.Protocol.Request.RequestType.START_PROFILING
import me.serce.franky.Protocol.Request.RequestType.STOP_PROFILING
import me.serce.franky.util.Loggable
import me.serce.franky.util.ensureLibattach
import me.serce.franky.util.logger
import rx.Observable
import rx.schedulers.Schedulers
import java.lang.RuntimeException
import java.nio.file.Files
import java.nio.file.StandardCopyOption.REPLACE_EXISTING
import kotlin.concurrent.thread
data class AttachableJVM(val id: String, val name: String) : Comparable<AttachableJVM> {
override fun compareTo(other: AttachableJVM) = id.compareTo(other.id)
}
class JVMAttachService(val jvmRemoteService: JVMRemoteService, val frankyComponent: FrankyComponent) {
companion object : Loggable {
val LOG = logger()
fun getInstance() = ServiceManager.getService(JVMAttachService::class.java)
}
fun attachableJVMs(): List<AttachableJVM> = VirtualMachine.list().map { jvm: VirtualMachineDescriptor ->
AttachableJVM(jvm.id(), jvm.displayName())
}
fun connect(jvm: AttachableJVM): Observable<JVMSession> {
val channelObs = jvmRemoteService.init(jvm.id.toInt())
return Observable
.fromCallable {
try {
ensureLibattach()
VirtualMachine.attach(jvm.id)
} catch (e: Throwable) {
if (e is UnsatisfiedLinkError) {
throw RuntimeException("Unable connect VM. Please add libattach.so library to libpath", e)
}
throw RuntimeException("Unable to connect to ${jvm.id}", e)
}
}
.doOnNext { vm ->
val pid = vm.id()
thread(isDaemon = true, name = "VM Attach Thread pid=$pid") {
LOG.info("Attaching Franky JVM agent to pid=$pid")
try {
val frankyPath = Files.createTempFile("libfrankyagent_tmp", ".so").apply {
toFile().deleteOnExit()
}
val frankyResource = FrankyComponent::class.java.classLoader.getResource("libfrankyagent.so").openStream()
Files.copy(frankyResource, frankyPath, REPLACE_EXISTING)
vm.loadAgentPath(frankyPath.toAbsolutePath().toString(), "${frankyComponent.FRANKY_PORT}")
} catch (t: Throwable) {
LOG.error("JVM connection had crashed", t)
}
LOG.info("Franky JVM agent detached from pid=$pid")
}
}
.zipWith(channelObs, { removeVm, vm -> Pair(vm, removeVm) })
.subscribeOn(Schedulers.io())
.map { p -> JVMSession(p.first, p.second) }
}
}
//fun main(args: Array<String>) {
// val vm = VirtualMachine.attach("25034")
// thread(isDaemon = true, name = "VM Attach Thread pid=${vm.id()}") {
// vm.loadAgentPath("/home/serce/git/franky/lib/libfrankyagent.so", "$FRANKY_PORT")
// }
// readLine()
//}
class JVMSession(private val remoteJVM: JVMRemoteInstance,
private val vm: VirtualMachine) : AutoCloseable, Loggable {
private var isRunning = false
private val LOG = logger()
fun startProfiling() {
LOG.info("Starting profiling session ${vm.id()}")
remoteJVM.send(START_PROFILING)
isRunning = true
}
fun stopProfiling() {
LOG.info("Stopping profiling session ${vm.id()}")
remoteJVM.send(STOP_PROFILING)
isRunning = false
}
fun profilingResult() = remoteJVM.response
override fun close() {
LOG.info("Closing JVM session")
vm.detach()
remoteJVM.close()
}
}
| apache-2.0 | 4946d8e1ac9efdb7faacf0d41e9f07d5 | 38.798077 | 134 | 0.597246 | 4.417289 | false | false | false | false |
if710/if710.github.io | 2019-10-02/SystemServices/app/src/main/java/br/ufpe/cin/android/systemservices/location/MapActivity.kt | 1 | 1428 | package br.ufpe.cin.android.systemservices.location
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import br.ufpe.cin.android.systemservices.R
import com.google.android.gms.maps.*
class MapActivity : FragmentActivity(), OnMapReadyCallback {
private var latitude: Double = 0.toDouble()
private var longitude: Double = 0.toDouble()
//nao estou checando que tem acesso ao play services como no caso de FusedLocation...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map)
val i = intent
latitude = i.getDoubleExtra(LAT_KEY, -8.047)
longitude = i.getDoubleExtra(LON_KEY, -34.876)
val mapa = supportFragmentManager.findFragmentById(R.id.mapa) as SupportMapFragment
mapa.getMapAsync(this)
}
override fun onMapReady(googleMap: GoogleMap) {
val location = LatLng(latitude, longitude)
googleMap.addMarker(MarkerOptions().position(location).title("Marcador!"))
googleMap.moveCamera(CameraUpdateFactory.newLatLng(location))
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15f))
}
companion object {
val LAT_KEY = "latitude"
val LON_KEY = "longitude"
}
}
| mit | 13bf59594716fc98147c84f8f458652c | 31.454545 | 91 | 0.723389 | 4.175439 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/scm/GitSCMExtension.kt | 1 | 3570 | package net.nemerosa.ontrack.extension.git.scm
import net.nemerosa.ontrack.extension.git.GitExtensionFeature
import net.nemerosa.ontrack.extension.git.property.GitBranchConfigurationProperty
import net.nemerosa.ontrack.extension.git.property.GitBranchConfigurationPropertyType
import net.nemerosa.ontrack.extension.git.property.GitProjectConfigurationProperty
import net.nemerosa.ontrack.extension.git.property.GitProjectConfigurationPropertyType
import net.nemerosa.ontrack.extension.scm.service.SCM
import net.nemerosa.ontrack.extension.scm.service.SCMExtension
import net.nemerosa.ontrack.extension.scm.service.SCMPullRequest
import net.nemerosa.ontrack.extension.support.AbstractExtension
import net.nemerosa.ontrack.model.structure.Branch
import net.nemerosa.ontrack.model.structure.Project
import net.nemerosa.ontrack.model.structure.PropertyService
import org.springframework.stereotype.Component
/**
* Implementation of the [SCMExtension] for a Git project.
*
* WARNING: most of the operations are NOT possible.
*/
@Component
class GitSCMExtension(
extensionFeature: GitExtensionFeature,
private val propertyService: PropertyService,
) : AbstractExtension(extensionFeature), SCMExtension {
override fun getSCM(project: Project): SCM? {
val property: GitProjectConfigurationProperty? =
propertyService.getProperty(project, GitProjectConfigurationPropertyType::class.java).value
return property?.run {
GitSCM(
project,
// property,
)
}
}
private inner class GitSCM(
private val project: Project,
// private val property: GitProjectConfigurationProperty,
) : SCM {
override val repositoryURI: String
get() = unsupported("repositoryURI")
override val repositoryHtmlURL: String
get() = unsupported("repositoryHtmlURL")
override val repository: String
get() = unsupported("repository")
override fun getSCMBranch(branch: Branch): String? {
checkProject(branch.project)
val branchProperty: GitBranchConfigurationProperty? =
propertyService.getProperty(branch, GitBranchConfigurationPropertyType::class.java).value
return branchProperty?.branch
}
override fun createBranch(sourceBranch: String, newBranch: String): String {
unsupported("createBranch")
}
override fun download(scmBranch: String, path: String, retryOnNotFound: Boolean): ByteArray? {
unsupported("download")
}
override fun upload(scmBranch: String, commit: String, path: String, content: ByteArray) {
unsupported("upload")
}
override fun createPR(
from: String,
to: String,
title: String,
description: String,
autoApproval: Boolean,
remoteAutoMerge: Boolean,
): SCMPullRequest {
unsupported("createPR")
}
private fun checkProject(other: Project) {
check(other.id == project.id) {
"An SCM service can be used only for its project."
}
}
private fun unsupported(operation: String): Nothing =
throw IllegalStateException(
"""
Operation [$operation] not supported by the Git SCM.
The GitSCM will be removed in version 5 on Ontrack.
""".trimIndent()
)
}
} | mit | 2e21a8b2f645ea8fdc1f2457e0564369 | 34.71 | 105 | 0.666947 | 5.144092 | false | true | false | false |
nemerosa/ontrack | ontrack-service/src/main/java/net/nemerosa/ontrack/service/labels/LabelManagementServiceImpl.kt | 1 | 2884 | package net.nemerosa.ontrack.service.labels
import net.nemerosa.ontrack.model.Ack
import net.nemerosa.ontrack.model.labels.*
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.repository.LabelRecord
import net.nemerosa.ontrack.repository.LabelRepository
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
class LabelManagementServiceImpl(
private val labelRepository: LabelRepository,
private val labelProviderService: LabelProviderService,
private val securityService: SecurityService
) : LabelManagementService {
override val labels: List<Label>
get() = labelRepository.labels
.filter { isComputedByOK(it) }
.map { it.toLabel() }
override fun findLabels(category: String?, name: String?): List<Label> {
return labelRepository.findLabels(category, name)
.filter { isComputedByOK(it) }
.map { it.toLabel() }
}
private fun isComputedByOK(record: LabelRecord): Boolean {
val computedBy = record.computedBy
return computedBy == null || (labelProviderService.getLabelProvider(computedBy)?.isEnabled ?: false)
}
override fun newLabel(form: LabelForm): Label {
securityService.checkGlobalFunction(LabelManagement::class.java)
form.validate()
return labelRepository.newLabel(form).toLabel()
}
override fun findLabelById(labelId: Int): Label? =
labelRepository.findLabelById(labelId)?.toLabel()
override fun getLabel(labelId: Int): Label =
labelRepository.getLabel(labelId).toLabel()
override fun updateLabel(labelId: Int, form: LabelForm): Label {
securityService.checkGlobalFunction(LabelManagement::class.java)
form.validate()
val label = getLabel(labelId)
if (label.computedBy != null) {
throw LabelNotEditableException(label)
} else {
return labelRepository.updateLabel(labelId, form).toLabel()
}
}
override fun deleteLabel(labelId: Int): Ack {
securityService.checkGlobalFunction(LabelManagement::class.java)
val label = getLabel(labelId)
if (label.computedBy != null) {
throw LabelNotEditableException(label)
} else {
return labelRepository.deleteLabel(labelId)
}
}
private fun LabelRecord.toLabel() =
Label(
id = id,
category = category,
name = name,
description = description,
color = color,
computedBy = computedBy
?.let { id -> labelProviderService.getLabelProvider(id) }
?.description
)
}
| mit | c514bb0e39804a45539255d76e2b964e | 35.05 | 108 | 0.644591 | 4.904762 | false | false | false | false |
jraska/github-client | core-android-api/src/main/java/com/jraska/github/client/core/android/Activity.kt | 1 | 543 | package com.jraska.github.client.core.android
import android.app.Activity
import android.net.Uri
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
fun Activity.inputUrl(): HttpUrl {
val inputUri = intent.data ?: throw IllegalArgumentException("No uri provided")
return replaceNoHttpScheme(inputUri)
.toString()
.toHttpUrl()
}
private fun replaceNoHttpScheme(uri: Uri): Uri {
if (uri.scheme == "http" || uri.scheme == "https") {
return uri
}
return uri.buildUpon()
.scheme("https")
.build()
}
| apache-2.0 | 578216ebf48f44ef6c573dacf89f18f6 | 21.625 | 81 | 0.71639 | 3.693878 | false | false | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/view/gallery/GalleryPage.kt | 1 | 5727 | package com.emogoth.android.phone.mimi.view.gallery
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ProgressBar
import com.emogoth.android.phone.mimi.BuildConfig
import com.emogoth.android.phone.mimi.util.DownloadItem
import com.emogoth.android.phone.mimi.util.DownloadListener
import com.emogoth.android.phone.mimi.util.MimiPrefs
import com.emogoth.android.phone.mimi.viewmodel.GalleryItem
import com.emogoth.android.phone.mimi.viewmodel.GalleryViewModel
import java.io.File
@SuppressLint("ViewConstructor") // This custom view should not be instantiated in xml
abstract class GalleryPage(context: Context, private val viewModel: GalleryViewModel) : FrameLayout(context), DownloadListener {
companion object {
val LOG_TAG: String = GalleryPage::class.java.simpleName
const val MAX_RETRIES = 5
}
var postId: Long = -1
protected var downloadComplete = false
protected var pageSelected = false
protected var loaded = false
private var childView: View? = null
private var progressView: ProgressBar? = null
private var progressViewID = View.generateViewId()
private var progress: Int = 0
set(value) {
field = value
if (value in 0..100) {
progressView?.progress = field
}
}
private var retryCount = 0
init {
id = View.generateViewId()
val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
params.gravity = Gravity.CENTER
layoutParams = params
val v = ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal)
val progressParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER)
progressParams.gravity = Gravity.CENTER
v.id = progressViewID
v.layoutParams = progressParams
v.max = 100
v.setPadding(10, 0, 10, 0)
progressView = v
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (findViewById<ProgressBar>(progressViewID) == null) {
addView(progressView)
}
if (downloadComplete && !loaded) {
onComplete()
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
loaded = false
}
protected var downloadItem = DownloadItem.empty()
val localFile: File
get() {
return downloadItem.file
}
fun bind(item: GalleryItem) {
onViewBind()
if (item != GalleryItem.empty()) {
postId = item.id
downloadComplete = false
downloadItem = viewModel.addDownloadListener(item.id, this)
progressView?.progress = 0
progressView?.visibility = View.VISIBLE
childView?.visibility = View.INVISIBLE
} else {
downloadComplete = true
progressView?.visibility = View.GONE
childView?.visibility = View.VISIBLE
}
}
protected fun addMainChildView(child: View) {
if (progressView != null) {
val v = progressView
v?.visibility = View.GONE
}
val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
params.gravity = Gravity.CENTER
child.layoutParams = params
child.setOnClickListener {
if (context is Activity && MimiPrefs.closeGalleryOnClick(context)) {
val activity: Activity = context as Activity
activity.finish()
}
}
addView(child)
childView = child
}
protected fun retryDownload(): Boolean {
if (retryCount < MAX_RETRIES) {
retryCount++
viewModel.retryDownload(downloadItem)
return true
}
return false
}
override fun onBytesReceived(progress: Int) {
this.progress = progress
}
override fun onComplete() {
if (BuildConfig.DEBUG) {
Log.d("GalleryPage", "onComplete called: ${downloadItem.file.absolutePath}")
}
if (!downloadItem.file.exists()) {
Log.w("GalleryPage", "onComplete called, but file does not exist: ${downloadItem.file.absolutePath}")
Log.w("ImagePage", "onComplete called, but file does not exist: \n" +
"${downloadItem.file.absolutePath} \n" +
"${downloadItem.url} \n" +
"${downloadItem.thumbUrl} \n" +
"${downloadItem.id}")
if (retryCount < MAX_RETRIES) {
retryCount++
viewModel.retryDownload(downloadItem)
}
}
downloadComplete = true
progressView?.visibility = View.GONE
childView?.visibility = View.VISIBLE
}
override fun onError(t: Throwable) {
downloadComplete = true
Log.e(LOG_TAG, "Error downloading file", t)
}
abstract fun onViewBind()
open fun onPageSelectedChange(selected: Boolean) {
pageSelected = selected
if (downloadComplete) {
progressView?.visibility = View.GONE
childView?.visibility = View.VISIBLE
} else {
progressView?.visibility = View.VISIBLE
childView?.visibility = View.INVISIBLE
}
}
open fun fullScreen(enabled: Boolean = true) {
}
} | apache-2.0 | a32ee9d7b6d81767a746081af8328067 | 29.147368 | 143 | 0.628601 | 4.882353 | false | false | false | false |
AngrySoundTech/CouponCodes3 | mods/canary/src/main/kotlin/tech/feldman/couponcodes/canary/database/CanaryDataAccess.kt | 2 | 2445 | /**
* The MIT License
* Copyright (c) 2015 Nicholas Feldman (AngrySoundTech)
* <p/>
* 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:
* <p/>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p/>
* 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.
*/
package tech.feldman.couponcodes.canary.database
import net.canarymod.database.Column
import net.canarymod.database.Column.DataType
import net.canarymod.database.DataAccess
class CanaryDataAccess : DataAccess("canary_coupon_object") {
@Column(columnName = "name", dataType = DataType.STRING)
lateinit var couponName: String
@Column(columnName = "ctype", dataType = DataType.STRING)
lateinit var ctype: String
@Column(columnName = "usetimes", dataType = DataType.INTEGER)
var usetimes: Int = 0
@Column(columnName = "usedplayers", dataType = DataType.STRING)
lateinit var usedplayers: String
@Column(columnName = "ids", dataType = DataType.STRING)
lateinit var ids: String
@Column(columnName = "money", dataType = DataType.INTEGER)
var money: Int = 0
@Column(columnName = "groupname", dataType = DataType.STRING)
lateinit var groupname: String
@Column(columnName = "timeuse", dataType = DataType.INTEGER)
var timeuse: Int = 0
@Column(columnName = "xp", dataType = DataType.INTEGER)
var xp: Int = 0
@Column(columnName = "command", dataType = DataType.STRING)
lateinit var command: String
@Override
override fun getInstance(): DataAccess {
return CanaryDataAccess()
}
}
| mit | 2d05b453d094ea3e60266a6fe06772dc | 41.155172 | 80 | 0.731697 | 4.252174 | false | false | false | false |
stoman/competitive-programming | problems/2021adventofcode17a/submissions/accepted/Stefan.kt | 2 | 653 | import java.util.*
import kotlin.math.absoluteValue
fun main() {
val s = Scanner(System.`in`).useDelimiter("""=|\.\.|,|\s|\n""")
s.next() // target
s.next() // area:
s.next() // x=
s.nextInt() // xMin
s.nextInt() // xMax
s.next() // ,
s.next() // y=
val yMin = s.nextInt()
val yMax = s.nextInt()
var ret = -1
for (i in 0..yMin.absoluteValue + 1) {
var sim = 0
var yVelocity = i
var maxHeight = sim
while (sim >= yMin) {
if (sim <= yMax) {
ret = ret.coerceAtLeast(maxHeight)
}
sim += yVelocity
maxHeight = maxHeight.coerceAtLeast(sim)
yVelocity--
}
}
println(ret)
}
| mit | 33046cb94a3137bd65a8d406097a6aab | 20.064516 | 65 | 0.543645 | 3.281407 | false | false | false | false |
soywiz/korge | korge/src/commonTest/kotlin/com/soywiz/korge/input/component/MouseComponentTest.kt | 1 | 1714 | package com.soywiz.korge.input.component
import com.soywiz.korge.input.*
import com.soywiz.korge.tests.*
import com.soywiz.korge.view.*
import com.soywiz.korim.bitmap.*
import com.soywiz.korim.color.*
import kotlin.test.*
class MouseComponentTest : ViewsForTesting() {
@Test
fun name() = viewsTest {
val log = arrayListOf<String>()
val tex = Bitmap32(16, 16)
val image = Image(tex)
views.stage += image
image.onOver { log += "onOver" }
image.onOut { log += "onOut" }
image.onClick { log += "onClick" }
image.onDown { log += "onDown" }
image.onUp { log += "onUp" }
image.onUpOutside { log += "onUpOutside" }
image.onMove { log += "onMove" }
mouseMoveTo(8.0, 8.0)
assertEquals("onOver", log.joinToString(","))
mouseMoveTo(20.0, 20.0)
assertEquals("onOver,onOut", log.joinToString(","))
mouseMoveTo(8.0, 8.0)
mouseDown()
assertEquals("onOver,onOut,onOver,onDown", log.joinToString(","))
mouseMoveTo(10.0, 10.0)
assertEquals("onOver,onOut,onOver,onDown,onMove", log.joinToString(","))
mouseMoveTo(50.0, 50.0)
assertEquals("onOver,onOut,onOver,onDown,onMove,onOut", log.joinToString(","))
mouseUp()
assertEquals("onOver,onOut,onOver,onDown,onMove,onOut,onUpOutside", log.joinToString(","))
}
@Test
fun test2() = viewsTest {
val log = arrayListOf<String>()
fixedSizeContainer(100, 100) {
solidRect(50, 50, Colors.RED) {
onClick { log += "rect" }
}
onClick { log += "container" }
}
mouseMoveAndClickTo(80, 80)
assertEquals("container", log.joinToString(","))
mouseMoveAndClickTo(45, 45)
assertEquals("container,rect", log.joinToString(","))
}
}
| apache-2.0 | 6266d6e7cfa0f96d77c7272ae5da6ef3 | 30.163636 | 92 | 0.644107 | 3.227872 | false | true | false | false |
apixandru/intellij-community | plugins/settings-repository/src/actions/CommitToIcsAction.kt | 16 | 6238 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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 org.jetbrains.settingsRepository.actions
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.StorageScheme
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.actions.CommonCheckinFilesAction
import com.intellij.openapi.vcs.actions.VcsContext
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.CommitExecutor
import com.intellij.openapi.vcs.checkin.BeforeCheckinDialogHandler
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.project.stateStore
import com.intellij.util.SmartList
import org.jetbrains.settingsRepository.CommitToIcsDialog
import org.jetbrains.settingsRepository.ProjectId
import org.jetbrains.settingsRepository.icsManager
import org.jetbrains.settingsRepository.icsMessage
import java.util.*
class CommitToIcsAction : CommonCheckinFilesAction() {
class IcsBeforeCommitDialogHandler : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
return CheckinHandler.DUMMY
}
override fun createSystemReadyHandler(project: Project): BeforeCheckinDialogHandler? {
return BEFORE_CHECKIN_DIALOG_HANDLER
}
companion object {
private val BEFORE_CHECKIN_DIALOG_HANDLER = object : BeforeCheckinDialogHandler() {
override fun beforeCommitDialogShown(project: Project, changes: List<Change>, executors: Iterable<CommitExecutor>, showVcsCommit: Boolean): Boolean {
val collectConsumer = ProjectChangeCollectConsumer(project)
collectProjectChanges(changes, collectConsumer)
showDialog(project, collectConsumer, null)
return true
}
}
}
}
override fun getActionName(dataContext: VcsContext) = icsMessage("action.CommitToIcs.text")
override fun isApplicableRoot(file: VirtualFile, status: FileStatus, dataContext: VcsContext): Boolean {
val project = dataContext.project
return project is ProjectEx && project.stateStore.storageScheme == StorageScheme.DIRECTORY_BASED && super.isApplicableRoot(file, status, dataContext) && !file.isDirectory && isProjectConfigFile(file, dataContext.project!!)
}
override fun prepareRootsForCommit(roots: Array<FilePath>, project: Project) = roots
override fun performCheckIn(context: VcsContext, project: Project, roots: Array<out FilePath>) {
val projectId = getProjectId(project) ?: return
val changes = context.selectedChanges
val collectConsumer = ProjectChangeCollectConsumer(project)
if (changes != null && changes.isNotEmpty()) {
for (change in changes) {
collectConsumer.consume(change)
}
}
else {
val manager = ChangeListManager.getInstance(project)
for (path in getRoots(context)) {
collectProjectChanges(manager.getChangesIn(path), collectConsumer)
}
}
showDialog(project, collectConsumer, projectId)
}
}
private class ProjectChangeCollectConsumer(private val project: Project) {
private var projectChanges: MutableList<Change>? = null
fun consume(change: Change) {
if (isProjectConfigFile(change.virtualFile, project)) {
if (projectChanges == null) {
projectChanges = SmartList<Change>()
}
projectChanges!!.add(change)
}
}
fun getResult() = if (projectChanges == null) listOf<Change>() else projectChanges!!
fun hasResult() = projectChanges != null
}
private fun getProjectId(project: Project): String? {
val projectId = ServiceManager.getService<ProjectId>(project, ProjectId::class.java)!!
if (projectId.uid == null) {
if (icsManager.settings.doNoAskMapProject ||
MessageDialogBuilder.yesNo("Settings Server Project Mapping", "Project is not mapped on Settings Server. Would you like to map?").project(project).doNotAsk(object : DialogWrapper.DoNotAskOption.Adapter() {
override fun isSelectedByDefault(): Boolean {
return true
}
override fun rememberChoice(isSelected: Boolean, exitCode: Int) {
icsManager.settings.doNoAskMapProject = isSelected
}
}).show() == Messages.YES) {
projectId.uid = UUID.randomUUID().toString()
}
}
return projectId.uid
}
private fun showDialog(project: Project, collectConsumer: ProjectChangeCollectConsumer, projectId: String?) {
if (!collectConsumer.hasResult()) {
return
}
var effectiveProjectId = projectId
if (effectiveProjectId == null) {
effectiveProjectId = getProjectId(project)
if (effectiveProjectId == null) {
return
}
}
CommitToIcsDialog(project, effectiveProjectId, collectConsumer.getResult()).show()
}
private fun collectProjectChanges(changes: Collection<Change>, collectConsumer: ProjectChangeCollectConsumer) {
for (change in changes) {
collectConsumer.consume(change)
}
}
private fun isProjectConfigFile(file: VirtualFile?, project: Project): Boolean {
if (file == null) {
return false
}
return FileUtil.isAncestor(project.basePath!!, file.path, true)
}
| apache-2.0 | 2d38e574ce0c331f701f3fd5778f4e49 | 37.506173 | 226 | 0.758256 | 4.648286 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/SharedDecksDownloadFragment.kt | 1 | 19550 | /****************************************************************************************
* *
* Copyright (c) 2021 Shridhar Goel <[email protected]> *
* *
* This program 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/>. *
****************************************************************************************/
package com.ichi2.anki
import android.app.DownloadManager
import android.content.*
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.CookieManager
import android.webkit.URLUtil
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import com.afollestad.materialdialogs.MaterialDialog
import com.ichi2.anki.SharedDecksActivity.Companion.DOWNLOAD_FILE
import com.ichi2.utils.ImportUtils
import timber.log.Timber
import java.io.File
import java.net.URLConnection
import kotlin.math.abs
/**
* Used when a download is captured from AnkiWeb shared decks WebView.
* Only for downloads started via SharedDecksActivity.
*
* Only one download is supported at a time, since importing multiple decks
* simultaneously is not supported.
*/
class SharedDecksDownloadFragment : Fragment() {
private var mDownloadId: Long = 0
private var mFileName: String? = null
private var mHandler: Handler = Handler(Looper.getMainLooper())
private var mIsProgressCheckerRunning = false
private lateinit var mCancelButton: Button
private lateinit var mTryAgainButton: Button
private lateinit var mImportDeckButton: Button
private lateinit var mDownloadPercentageText: TextView
private lateinit var mDownloadProgressBar: ProgressBar
private lateinit var mCheckNetworkInfoText: TextView
/**
* Android's DownloadManager - Used here to manage the functionality of downloading decks, one
* at a time. Responsible for enqueuing a download and generating the corresponding download ID,
* removing a download from the queue and providing cursor using a query related to the download ID.
* Since only one download is supported at a time, the DownloadManager's queue is expected to
* have a single request at a time.
*/
private lateinit var mDownloadManager: DownloadManager
var isDownloadInProgress = false
private var mDownloadCancelConfirmationDialog: MaterialDialog? = null
companion object {
const val DOWNLOAD_PROGRESS_CHECK_DELAY = 100L
const val DOWNLOAD_STARTED_PROGRESS_PERCENTAGE = "0"
const val DOWNLOAD_COMPLETED_PROGRESS_PERCENTAGE = "100"
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_shared_decks_download, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mDownloadPercentageText = view.findViewById(R.id.download_percentage)
mDownloadProgressBar = view.findViewById(R.id.download_progress)
mCancelButton = view.findViewById(R.id.cancel_shared_decks_download)
mImportDeckButton = view.findViewById(R.id.import_shared_deck_button)
mTryAgainButton = view.findViewById(R.id.try_again_deck_download)
mCheckNetworkInfoText = view.findViewById(R.id.check_network_info_text)
val fileToBeDownloaded = arguments?.getSerializable(DOWNLOAD_FILE) as DownloadFile
mDownloadManager = (activity as SharedDecksActivity).downloadManager
downloadFile(fileToBeDownloaded)
mCancelButton.setOnClickListener {
Timber.i("Cancel download button clicked which would lead to showing of confirmation dialog")
showCancelConfirmationDialog()
}
mImportDeckButton.setOnClickListener {
Timber.i("Import deck button clicked")
openDownloadedDeck(context)
}
mTryAgainButton.setOnClickListener {
Timber.i("Try again button clicked, retry downloading of deck")
mDownloadManager.remove(mDownloadId)
downloadFile(fileToBeDownloaded)
mCancelButton.visibility = View.VISIBLE
mTryAgainButton.visibility = View.GONE
}
}
/**
* Register broadcast receiver for listening to download completion.
* Set the request for downloading a deck, enqueue it in DownloadManager, store download ID and
* file name, mark download to be in progress, set the title of the download screen and start
* the download progress checker.
*/
private fun downloadFile(fileToBeDownloaded: DownloadFile) {
// Register broadcast receiver for download completion.
Timber.d("Registering broadcast receiver for download completion")
activity?.registerReceiver(mOnComplete, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
val currentFileName = URLUtil.guessFileName(
fileToBeDownloaded.url, fileToBeDownloaded.contentDisposition,
fileToBeDownloaded.mimeType
)
val downloadRequest = generateDeckDownloadRequest(fileToBeDownloaded, currentFileName)
// Store unique download ID to be used when onReceive() of BroadcastReceiver gets executed.
mDownloadId = mDownloadManager.enqueue(downloadRequest)
mFileName = currentFileName
isDownloadInProgress = true
Timber.d("Download ID -> $mDownloadId")
Timber.d("File name -> $mFileName")
view?.findViewById<TextView>(R.id.downloading_title)?.text = getString(R.string.downloading_file, mFileName)
startDownloadProgressChecker()
}
private fun generateDeckDownloadRequest(fileToBeDownloaded: DownloadFile, currentFileName: String): DownloadManager.Request {
val request: DownloadManager.Request = DownloadManager.Request(Uri.parse(fileToBeDownloaded.url))
request.setMimeType(fileToBeDownloaded.mimeType)
val cookies = CookieManager.getInstance().getCookie(fileToBeDownloaded.url)
request.addRequestHeader("Cookie", cookies)
request.addRequestHeader("User-Agent", fileToBeDownloaded.userAgent)
request.setTitle(currentFileName)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, currentFileName)
return request
}
/**
* Registered in downloadFile() method.
* When onReceive() is called, open the deck file in AnkiDroid to import it.
*/
private var mOnComplete: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Timber.i("Download might be complete now, verify and continue with import")
fun verifyDeckIsImportable() {
if (mFileName == null) {
// Send ACRA report
AnkiDroidApp.sendExceptionReport(
"File name is null",
"SharedDecksDownloadFragment::verifyDeckIsImportable"
)
return
}
// Return if mDownloadId does not match with the ID of the completed download.
if (mDownloadId != intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0)) {
Timber.w(
"Download ID did not match with the ID of the completed download. " +
"Download completion related to some other download might have been received. " +
"Deck download might still be going on, when it completes then the method would be called again."
)
// Send ACRA report
AnkiDroidApp.sendExceptionReport(
"Download ID does not match with the ID of the completed download",
"SharedDecksDownloadFragment::verifyDeckIsImportable"
)
return
}
stopDownloadProgressChecker()
// Halt execution if file doesn't have extension as 'apkg' or 'colpkg'
if (!ImportUtils.isFileAValidDeck(mFileName)) {
Timber.i("File does not have 'apkg' or 'colpkg' extension, abort the deck opening task")
checkDownloadStatusAndUnregisterReceiver(isSuccessful = false, isInvalidDeckFile = true)
return
}
val query = DownloadManager.Query()
query.setFilterById(mDownloadId)
val cursor = mDownloadManager.query(query)
cursor.use {
// Return if cursor is empty.
if (!it.moveToFirst()) {
Timber.i("Empty cursor, cannot continue further with success check and deck import")
checkDownloadStatusAndUnregisterReceiver(isSuccessful = false)
return
}
val columnIndex: Int = it.getColumnIndex(DownloadManager.COLUMN_STATUS)
// Return if download was not successful.
if (it.getInt(columnIndex) != DownloadManager.STATUS_SUCCESSFUL) {
Timber.i("Download could not be successful, update UI and unregister receiver")
Timber.d("Status code -> ${it.getInt(columnIndex)}")
checkDownloadStatusAndUnregisterReceiver(isSuccessful = false)
return
}
}
}
try {
verifyDeckIsImportable()
} catch (exception: Exception) {
Timber.w(exception)
checkDownloadStatusAndUnregisterReceiver(isSuccessful = false)
return
}
if (isVisible) {
// Setting these since progress checker can stop before progress is updated to represent 100%
mDownloadPercentageText.text = getString(R.string.percentage, DOWNLOAD_COMPLETED_PROGRESS_PERCENTAGE)
mDownloadProgressBar.progress = DOWNLOAD_COMPLETED_PROGRESS_PERCENTAGE.toInt()
// Remove cancel button and show import deck button
mCancelButton.visibility = View.GONE
mImportDeckButton.visibility = View.VISIBLE
}
Timber.i("Opening downloaded deck for import")
openDownloadedDeck(context)
Timber.d("Checking download status and unregistering receiver")
checkDownloadStatusAndUnregisterReceiver(isSuccessful = true)
}
}
/**
* Unregister the mOnComplete broadcast receiver.
*/
private fun unregisterReceiver() {
Timber.d("Unregistering receiver")
try {
activity?.unregisterReceiver(mOnComplete)
} catch (exception: IllegalArgumentException) {
// This might throw an exception in cases where the receiver is already in unregistered state.
// Log the exception in such cases, there is nothing else to do.
Timber.w(exception)
return
}
}
/**
* Check download progress and update status at intervals of 0.1 second.
*/
private val mDownloadProgressChecker: Runnable by lazy {
object : Runnable {
override fun run() {
checkDownloadProgress()
// Keep checking download progress at intervals of 0.1 second.
mHandler.postDelayed(this, DOWNLOAD_PROGRESS_CHECK_DELAY)
}
}
}
/**
* Start checking for download progress.
*/
private fun startDownloadProgressChecker() {
Timber.d("Starting download progress checker")
mDownloadProgressChecker.run()
mIsProgressCheckerRunning = true
mDownloadPercentageText.text = getString(R.string.percentage, DOWNLOAD_STARTED_PROGRESS_PERCENTAGE)
mDownloadProgressBar.progress = DOWNLOAD_STARTED_PROGRESS_PERCENTAGE.toInt()
}
/**
* Stop checking for download progress.
*/
private fun stopDownloadProgressChecker() {
Timber.d("Stopping download progress checker")
mHandler.removeCallbacks(mDownloadProgressChecker)
mIsProgressCheckerRunning = false
}
/**
* Checks download progress and sets the current progress in ProgressBar.
*/
private fun checkDownloadProgress() {
val query = DownloadManager.Query()
query.setFilterById(mDownloadId)
val cursor = mDownloadManager.query(query)
cursor.use {
// Return if cursor is empty.
if (!it.moveToFirst()) {
return
}
// Calculate download progress and display it in the ProgressBar.
val downloadedBytes = it.getLong(it.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
val totalBytes = it.getInt(it.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
// Taking absolute value to prevent case of -0.0 % being shown.
val downloadProgress: Float = abs(downloadedBytes * 1f / totalBytes * 100)
val downloadProgressIntValue = downloadProgress.toInt()
val percentageValue = if (downloadProgressIntValue == 0 || downloadProgressIntValue == 100) {
// Show 0 % and 100 % instead of 0.0 % and 100.0 %
downloadProgressIntValue.toString()
} else {
// Show download progress percentage up to 1 decimal place.
"%.1f".format(downloadProgress)
}
mDownloadPercentageText.text = getString(R.string.percentage, percentageValue)
mDownloadProgressBar.progress = downloadProgress.toInt()
val columnIndexForStatus = it.getColumnIndex(DownloadManager.COLUMN_STATUS)
val columnIndexForReason = it.getColumnIndex(DownloadManager.COLUMN_REASON)
if (columnIndexForStatus == -1) {
Timber.w("Column for status does not exist")
return
}
if (columnIndexForReason == -1) {
Timber.w("Column for reason does not exist")
return
}
// Display message if download is waiting for network connection
if (it.getInt(columnIndexForStatus) == DownloadManager.STATUS_PAUSED &&
it.getInt(columnIndexForReason) == DownloadManager.PAUSED_WAITING_FOR_NETWORK
) {
mCheckNetworkInfoText.visibility = View.VISIBLE
} else {
mCheckNetworkInfoText.visibility = View.GONE
}
}
}
/**
* Open the downloaded deck using 'mFileName'.
*/
private fun openDownloadedDeck(context: Context?) {
val mimeType = URLConnection.guessContentTypeFromName(mFileName)
val fileIntent = Intent(context, IntentHandler::class.java)
fileIntent.action = Intent.ACTION_VIEW
val fileUri = context?.let {
FileProvider.getUriForFile(
it,
it.applicationContext?.packageName + ".apkgfileprovider",
File(it.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), mFileName.toString())
)
}
Timber.d("File URI -> $fileUri")
fileIntent.setDataAndType(fileUri, mimeType)
fileIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
try {
context?.startActivity(fileIntent)
} catch (e: ActivityNotFoundException) {
UIUtils.showThemedToast(context, R.string.something_wrong, false)
Timber.w(e)
}
}
/**
* Handle download error scenarios.
*
* If there are any pending downloads, continue with them.
* Else, set mIsPreviousDownloadOngoing as false and unregister mOnComplete broadcast receiver.
*/
private fun checkDownloadStatusAndUnregisterReceiver(isSuccessful: Boolean, isInvalidDeckFile: Boolean = false) {
if (isVisible && !isSuccessful) {
if (isInvalidDeckFile) {
Timber.i("File is not a valid deck, hence return from the download screen")
UIUtils.showThemedToast(activity, R.string.import_log_no_apkg, false)
// Go back if file is not a deck and cannot be imported
activity?.onBackPressed()
} else {
Timber.i("Download failed, update UI and provide option to retry")
UIUtils.showThemedToast(activity, R.string.something_wrong, false)
// Update UI if download could not be successful
mTryAgainButton.visibility = View.VISIBLE
mCancelButton.visibility = View.GONE
mDownloadPercentageText.text = getString(R.string.download_failed)
mDownloadProgressBar.progress = DOWNLOAD_STARTED_PROGRESS_PERCENTAGE.toInt()
}
}
unregisterReceiver()
isDownloadInProgress = false
// If the cancel confirmation dialog is being shown and the download is no longer in progress, then remove the dialog.
removeCancelConfirmationDialog()
}
fun showCancelConfirmationDialog() {
mDownloadCancelConfirmationDialog = context?.let {
MaterialDialog.Builder(it)
.title(R.string.cancel_download_question_title)
.positiveText(R.string.dialog_cancel)
.negativeText(R.string.dialog_continue)
.onPositive { _, _ ->
mDownloadManager.remove(mDownloadId)
unregisterReceiver()
isDownloadInProgress = false
activity?.onBackPressed()
}
.onNegative { dialog, _ ->
dialog.dismiss()
}
.show()
}
}
private fun removeCancelConfirmationDialog() {
mDownloadCancelConfirmationDialog?.dismiss()
}
}
| gpl-3.0 | 8f91efbeb1c10f0ae565e549b6ac2992 | 42.444444 | 129 | 0.622967 | 5.48541 | false | false | false | false |
rmnn/compiler | src/main/kotlin/ru/dageev/compiler/bytecodegeneration/method/MethodGenerator.kt | 1 | 2054 | package ru.dageev.compiler.bytecodegeneration.method
import jdk.internal.org.objectweb.asm.ClassWriter
import jdk.internal.org.objectweb.asm.Opcodes
import ru.dageev.compiler.bytecodegeneration.statement.StatementGenerator
import ru.dageev.compiler.domain.ClassesContext
import ru.dageev.compiler.domain.declaration.MethodDeclaration
import ru.dageev.compiler.domain.node.statement.Block
import ru.dageev.compiler.domain.scope.MethodSignature
import ru.dageev.compiler.domain.type.PrimitiveType
import ru.dageev.compiler.parser.helper.getMainMethodSignature
import ru.dageev.compiler.parser.matcher.MethodSignatureMatcher
/**
* Created by dageev
* on 11/26/16.
*/
class MethodGenerator(val classesContext: ClassesContext, val classWriter: ClassWriter, val forMainClass: Boolean = false) : AbstractMethodGenerator() {
fun generate(method: MethodDeclaration) {
val block = method.statement as Block
val (access, descriptor) = if (forMainClass) {
Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC to
if (isMainMethod(method.methodSignature)) getMainMethodDescriptor()
else method.methodSignature.getDescriptor()
} else {
method.methodSignature.accessModifier.opCode to method.methodSignature.getDescriptor()
}
val methodVisitor = classWriter.visitMethod(access, method.methodSignature.name, descriptor, null, null)
methodVisitor.visitCode()
val statementGenerator = StatementGenerator(block.scope, classesContext, methodVisitor)
block.accept(statementGenerator)
appendReturnIfNotExists(method, block, statementGenerator)
methodVisitor.visitMaxs(-1, -1)
methodVisitor.visitEnd()
}
fun getMainMethodDescriptor(): String {
val parametersDescriptor = "([Ljava/lang/String;)"
return parametersDescriptor + PrimitiveType.VOID.getDescriptor()
}
fun isMainMethod(methodSignature: MethodSignature) = MethodSignatureMatcher().matches(methodSignature, getMainMethodSignature())
} | apache-2.0 | b029ce9814909d00035f6e1c9b0bf684 | 42.723404 | 152 | 0.755112 | 4.765661 | false | false | false | false |
jpeddicord/speedofsound | src/net/codechunk/speedofsound/util/BluetoothDevicePreference.kt | 1 | 4472 | package net.codechunk.speedofsound.util
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.preference.DialogPreference
import android.preference.PreferenceManager
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.ArrayAdapter
import android.widget.ListView
import net.codechunk.speedofsound.R
import java.util.*
/**
* A preference dialog listing saved and paired Bluetooth devices.
*/
class BluetoothDevicePreference(context: Context, attrs: AttributeSet) : DialogPreference(context, attrs) {
private var value: Set<String>? = null
private var view: View? = null
private val adapterDevices = ArrayList<PrettyBluetoothDevice>()
private val persistedDevices: Set<String>
get() = PreferenceManager.getDefaultSharedPreferences(context)
.getStringSet(key, HashSet())!!
/**
* Get a set of checked devices from this dialog's ListView.
*/
/**
* Set the checked devices in the displayed ListView.
*/
private var checkedDevices: Set<String>
get() {
val list = this.view!!.findViewById<View>(R.id.bluetooth_preference_listview) as ListView
val devices = HashSet<String>()
val checked = list.checkedItemPositions
val size = list.adapter.count
for (i in 0 until size) {
if (!checked.get(i)) {
continue
}
val device = this.adapterDevices[i]
devices.add(device.address)
}
return devices
}
set(devices) {
val list = this.view!!.findViewById<View>(R.id.bluetooth_preference_listview) as ListView
val size = list.adapter.count
for (i in 0 until size) {
if (devices.contains(this.adapterDevices[i].address)) {
list.setItemChecked(i, true)
}
}
}
override fun onSetInitialValue(restorePersistedValue: Boolean, defaultValue: Any?) {
if (restorePersistedValue) {
this.value = persistedDevices
} else {
this.value = HashSet()
persistDevices(this.value!!)
}
}
override fun onCreateDialogView(): View {
super.onCreateDialogView()
// reload persisted values (onSetInitialValue only called for first init)
this.value = persistedDevices
// inflate it all
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
this.view = inflater.inflate(R.layout.bluetooth_preference_dialog, null)
// get our paired music bluetooth devices
this.adapterDevices.clear()
val adapter = BluetoothAdapter.getDefaultAdapter()
if (adapter != null) {
val deviceSet = adapter.bondedDevices
for (bluetoothDevice in deviceSet) {
this.adapterDevices.add(PrettyBluetoothDevice(bluetoothDevice))
}
}
// add them to the list
val list = this.view!!.findViewById<View>(R.id.bluetooth_preference_listview) as ListView
list.choiceMode = ListView.CHOICE_MODE_MULTIPLE
val listAdapter = ArrayAdapter(context, android.R.layout.simple_list_item_multiple_choice, this.adapterDevices)
list.adapter = listAdapter
checkedDevices = this.value!!
return this.view!!
}
public override fun onDialogClosed(positiveResult: Boolean) {
super.onDialogClosed(positiveResult)
if (!positiveResult) {
return
}
if (shouldPersist()) {
persistDevices(checkedDevices)
}
notifyChanged()
}
private fun persistDevices(items: Set<String>) {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
val editor = prefs.edit()
editor.putStringSet(key, items)
editor.apply()
}
/**
* Bluetooth device with a nice toString().
*/
private inner class PrettyBluetoothDevice internal constructor(private val device: BluetoothDevice) {
val address: String
get() = this.device.address
override fun toString(): String {
return this.device.name
}
}
companion object {
const val KEY = "enable_bluetooth_devices"
}
}
| gpl-2.0 | 20a90e929e9455d483baa61783670713 | 30.272727 | 119 | 0.636181 | 4.963374 | false | false | false | false |
mctoyama/PixelClient | src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/client/StateRunning07UpdateActor.kt | 1 | 1154 | package org.pixelndice.table.pixelclient.connection.lobby.client
import org.apache.logging.log4j.LogManager
import org.pixelndice.table.pixelclient.ApplicationBus
import org.pixelndice.table.pixelclient.currentCampaign
import org.pixelndice.table.pixelclient.ds.resource.Actor
import org.pixelndice.table.pixelprotocol.Protobuf
private val logger = LogManager.getLogger(StateRunning07UpdateActor::class.java)
class StateRunning07UpdateActor: State {
override fun process(ctx: Context) {
val packet = ctx.channel.packet
if( packet != null ){
if( packet.payloadCase == Protobuf.Packet.PayloadCase.UPDATEACTOR){
val actor = currentCampaign.searchGameResource(packet.updateActor.id) as Actor
actor.updateFromProtobuf(packet.updateActor)
ApplicationBus.post(ApplicationBus.UpdateActorFromLobby(actor.id))
logger.debug("Updated Actor ${packet.updateActor}")
}else{
logger.error("Expecting UpdateActor, instead received: $packet. IP: ${ctx.channel.address}")
}
ctx.state = StateRunning()
}
}
} | bsd-2-clause | 90128825ff670aeba9a2c5c1ded6ff43 | 36.258065 | 108 | 0.704506 | 4.543307 | false | false | false | false |
panpf/sketch | sketch/src/main/java/com/github/panpf/sketch/decode/internal/BaseAnimatedImageDrawableDecoder.kt | 1 | 6786 | /*
* Copyright (C) 2022 panpf <[email protected]>
*
* 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 com.github.panpf.sketch.decode.internal
import android.graphics.ImageDecoder
import android.graphics.drawable.AnimatedImageDrawable
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.annotation.WorkerThread
import androidx.exifinterface.media.ExifInterface
import com.github.panpf.sketch.datasource.AssetDataSource
import com.github.panpf.sketch.datasource.ByteArrayDataSource
import com.github.panpf.sketch.datasource.ContentDataSource
import com.github.panpf.sketch.datasource.DataSource
import com.github.panpf.sketch.datasource.ResourceDataSource
import com.github.panpf.sketch.decode.DrawableDecodeResult
import com.github.panpf.sketch.decode.DrawableDecoder
import com.github.panpf.sketch.decode.ImageInfo
import com.github.panpf.sketch.drawable.SketchAnimatableDrawable
import com.github.panpf.sketch.drawable.internal.ScaledAnimatedImageDrawable
import com.github.panpf.sketch.request.ANIMATION_REPEAT_INFINITE
import com.github.panpf.sketch.request.animatable2CompatCallbackOf
import com.github.panpf.sketch.request.animatedTransformation
import com.github.panpf.sketch.request.animationEndCallback
import com.github.panpf.sketch.request.animationStartCallback
import com.github.panpf.sketch.request.internal.RequestContext
import com.github.panpf.sketch.request.repeatCount
import com.github.panpf.sketch.transform.asPostProcessor
import com.github.panpf.sketch.util.Size
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.nio.ByteBuffer
/**
* Only the following attributes are supported:
*
* resize.size
*
* resize.precision: It is always LESS_PIXELS
*
* colorSpace
*
* repeatCount
*
* animatedTransformation
*
* onAnimationStart
*
* onAnimationEnd
*/
@RequiresApi(Build.VERSION_CODES.P)
abstract class BaseAnimatedImageDrawableDecoder(
private val requestContext: RequestContext,
private val dataSource: DataSource,
) : DrawableDecoder {
@WorkerThread
override suspend fun decode(): DrawableDecodeResult {
val request = requestContext.request
val source = when (dataSource) {
is AssetDataSource -> {
ImageDecoder.createSource(request.context.assets, dataSource.assetFileName)
}
is ResourceDataSource -> {
ImageDecoder.createSource(dataSource.resources, dataSource.drawableId)
}
is ContentDataSource -> {
ImageDecoder.createSource(request.context.contentResolver, dataSource.contentUri)
}
is ByteArrayDataSource -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
ImageDecoder.createSource(dataSource.data)
} else {
ImageDecoder.createSource(ByteBuffer.wrap(dataSource.data))
}
}
else -> {
// Currently running on a limited number of IO contexts, so this warning can be ignored
@Suppress("BlockingMethodInNonBlockingContext")
ImageDecoder.createSource(dataSource.file())
}
}
var imageInfo: ImageInfo? = null
var inSampleSize = 1
var imageDecoder: ImageDecoder? = null
val drawable = try {
// Currently running on a limited number of IO contexts, so this warning can be ignored
@Suppress("BlockingMethodInNonBlockingContext")
ImageDecoder.decodeDrawable(source) { decoder, info, _ ->
imageDecoder = decoder
imageInfo = ImageInfo(
info.size.width,
info.size.height,
info.mimeType,
ExifInterface.ORIENTATION_UNDEFINED
)
val resizeSize = requestContext.resizeSize
inSampleSize = calculateSampleSize(
imageSize = Size(info.size.width, info.size.height),
targetSize = Size(resizeSize.width, resizeSize.height)
)
decoder.setTargetSampleSize(inSampleSize)
request.colorSpace?.let {
decoder.setTargetColorSpace(it)
}
// Set the animated transformation to be applied on each frame.
decoder.postProcessor = request.animatedTransformation?.asPostProcessor()
}
} finally {
imageDecoder?.close()
}
if (drawable !is AnimatedImageDrawable) {
throw Exception("Only support AnimatedImageDrawable")
}
drawable.repeatCount = request.repeatCount
?.takeIf { it != ANIMATION_REPEAT_INFINITE }
?: AnimatedImageDrawable.REPEAT_INFINITE
val transformedList =
if (inSampleSize != 1) listOf(createInSampledTransformed(inSampleSize)) else null
val animatableDrawable = SketchAnimatableDrawable(
// AnimatedImageDrawable cannot be scaled using bounds, which will be exposed in the ResizeDrawable
// Use ScaledAnimatedImageDrawable package solution to this it
animatableDrawable = ScaledAnimatedImageDrawable(drawable),
imageUri = request.uriString,
requestKey = requestContext.key,
requestCacheKey = requestContext.cacheKey,
imageInfo = imageInfo!!,
dataFrom = dataSource.dataFrom,
transformedList = transformedList,
extras = null,
).apply {
val onStart = request.animationStartCallback
val onEnd = request.animationEndCallback
if (onStart != null || onEnd != null) {
withContext(Dispatchers.Main) {
registerAnimationCallback(animatable2CompatCallbackOf(onStart, onEnd))
}
}
}
return DrawableDecodeResult(
drawable = animatableDrawable,
imageInfo = animatableDrawable.imageInfo,
dataFrom = animatableDrawable.dataFrom,
transformedList = animatableDrawable.transformedList,
extras = animatableDrawable.extras,
)
}
} | apache-2.0 | 8a8bca6a629afb6579e07cb41285fc00 | 40.133333 | 111 | 0.67374 | 5.25639 | false | false | false | false |
JosephCatrambone/ReBUILD | core/src/io/xoana/rebuild/Maths.kt | 1 | 13942 | package io.xoana.rebuild
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.math.Vector3
/**
* Created by Jo on 2017-07-09.
*/
class Vec(var x:Float=0f, var y:Float=0f, var z:Float=0f, var w:Float=0f) {
// libGDX Interop section.
constructor(v2: Vector2):this(v2.x, v2.y, 0f, 0f)
constructor(v3: Vector3):this(v3.x, v3.y, v3.z, 0f)
fun toGDXVector2(): Vector2 = Vector2(this.x, this.y)
fun toGDXVector3(): Vector3 = Vector3(this.x, this.y, this.z)
// End libGDX interop section
val isZero:Boolean
get():Boolean = x==0f && y==0f && z==0f && w==0f
val squaredMagnitude:Float
get():Float = this.dot(this)
val magnitude:Float
get():Float = Math.sqrt(this.squaredMagnitude.toDouble()).toFloat()
var data:FloatArray
get() = floatArrayOf(x, y, z, w)
set(value:FloatArray) {
this.x = value.getOrElse(0, {_ -> 0f})
this.y = value.getOrElse(1, {_ -> 0f})
this.z = value.getOrElse(2, {_ -> 0f})
this.w = value.getOrElse(3, {_ -> 0f})
}
operator fun plus(value:Float):Vec = Vec(this.x+value, this.y+value, this.z+value, this.w+value)
operator fun minus(value:Float):Vec = Vec(this.x-value, this.y-value, this.z-value, this.w-value)
operator fun times(value:Float):Vec = Vec(this.x*value, this.y*value, this.z*value, this.w*value)
operator fun div(value:Float):Vec = Vec(this.x/value, this.y/value, this.z/value, this.w/value)
operator fun plus(other:Vec):Vec = Vec(this.x+other.x, this.y+other.y, this.z+other.z, this.w+other.w)
operator fun minus(other:Vec):Vec = Vec(this.x-other.x, this.y-other.y, this.z-other.z, this.w-other.w)
operator fun times(other:Vec):Vec = Vec(this.x*other.x, this.y*other.y, this.z*other.z, this.w*other.w)
operator fun div(other:Vec):Vec = Vec(this.x/other.x, this.y/other.y, this.z/other.z, this.w/other.w) // TODO: This probably shouldn't exist because of the default zeros.
fun sum():Float {
return x+y+z+w
}
fun dot(other:Vec):Float {
return (this * other).sum()
}
// Perform the cross product with this as a vector2
fun cross2(other:Vec):Float = x*other.y - y*other.x
fun cross3(other:Vec):Vec {
return Vec(
this.y*other.z - this.z*other.y,
this.x*other.z - this.z*other.x,
this.x*other.y - this.y*other.x
)
// (2,3,4) (x) (5,6,7) -> (-3, 6, -3)
}
fun normalized():Vec {
// elements / sqrt(sum(elem ^2))
val mag = this.magnitude
// If we have no magnitude, just return a zero vec.
if(mag == 0f) {
TODO("Unhandled case: Normalizing zero-length vector")
}
return Vec(x/mag, y/mag, z/mag, w/mag)
}
fun normalize() {
val mag = this.magnitude
if(mag == 0f) { TODO() }
x /= mag
y /= mag
z /= mag
w /= mag
}
fun distanceSquared(other:Vec): Float {
val delta = this - other
return delta.x*delta.x + delta.y*delta.y + delta.z*delta.z + delta.w*delta.w
}
fun project(other:Vec): Vec {
// Project this vector onto the other.
// (A dot norm(b)) * norm(b)
// or
// (a dot b) / (b dot b) * b
val bNorm = other.normalized()
return bNorm * this.dot(bNorm)
}
}
class Line(val start:Vec, val end:Vec) {
/***
*
*/
fun intersection2D(other:Line, epsilon:Float = 1e-8f): Vec? {
// Begin with line-line intersection.
val determinant = ((start.x-end.x)*(other.start.y-other.end.y))-((start.y-end.y)*(other.start.x-other.end.x))
if(Math.abs(determinant.toDouble()).toFloat() < epsilon) {
return null;
}
val candidatePoint = Vec(
((start.x*end.y - start.y*end.x)*(other.start.x-other.end.x))-((start.x-end.x)*(other.start.x*other.end.y - other.start.y*other.end.x)),
((start.x*end.y - start.y*end.x)*(other.start.y-other.end.y))-((start.y-end.y)*(other.start.x*other.end.y - other.start.y*other.end.x))
)/determinant
// If the lines are infinite, we're done. No more work.
return candidatePoint
}
fun segmentIntersection2D(other:Line): Vec? {
val a = this.start
val b = this.end
val c = other.start
val d = other.end
val r = b-a
val s = d-c
val rxs = r.cross2(s)
val t:Float = (c-a).cross2(s)/rxs
val u:Float = (c-a).cross2(r)/rxs
if(t < 0 || t > 1 || u < 0 || u > 1) {
return null;
}
return a + r*t
}
fun shortestConnectingSegment(other:Line, epsilon:Float=1e-6f): Line? {
// Returns the smallest line segment between two lines in N-dimensional space.
// This can be thought of as 'intersection' in some sense if len < epsilon.
// Ported from Paul Bourke's algorithm.
// The line from L12 to L34 is Lab.
// Lab = Pa -> Pb
// L12 = P1 -> P2
// L34 = P3 -> P4
// Pa = P1 + m(P2-P1) // Pa is on L12
// Pb = P3 + n(P4-P3) // Pb is on L34
// Want to minimize ||Pb - Pa||^2
// Therefore: minimize ||P3 + n(P4-P3) - P1 + m(P2-P1)||^2
// Side note: shortest line between the two has to be perpendicular to both, meaning (Pa - Pb) dot (P2 - P1) = 0 AND (Pa - Pb) dot (P4 - P3) = 0.
val p1 = this.start
val p2 = this.end
val p3 = other.start
val p4 = other.end
val p13 = p1 - p3
val p43 = p4 - p3
val p21 = p2 - p1
if(p43.squaredMagnitude < epsilon || p21.squaredMagnitude < epsilon) {
return null
}
val d1343 = p13.dot(p43)
val d4321 = p43.dot(p21)
val d1321 = p13.dot(p21)
val d4343 = p43.dot(p43)
val d2121 = p21.dot(p21)
val denominator = d2121*d4343 - d4321*d4321
if(denominator < epsilon) {
return null
}
val numerator = d1343 * d4321 - d1321 * d4343
val m = numerator/denominator
val n = (d1343 + (d4321 * m)) / d4343
val pa = p1 + (p21*m)
val pb = p3 + (p43*n)
return Line(pa, pb)
}
fun pointOnLine(pt:Vec, epsilon:Float = 1e-6f):Boolean {
// Is this point a solution to this line?
if(epsilon == 0f) {
// THIS IS A BAD IDEA! NUMERICAL PRECISION IS A FACTOR!
// p1 + t*(p2-p1) = pt?
// Just solve for t, and if the value is between 0 and 1, it's on the line.
// t*(p2-p1) = pt - p1
// t = (pt - p1)/(p2-p1)
// Unfortunately, we've gotta' do this component-wise.
val tX = (pt.x - start.x) / (end.x - start.x)
if (tX < 0 || tX > 1) {
return false
}
val tY = (pt.y - start.y) / (end.y - start.y)
if (tY < 0 || tY > 1) {
return false
}
return true
} else {
TODO("Bugfix")
return ((Math.abs(((end.y-start.y)*pt.x - (end.x-start.x)*pt.y + end.x*start.y - end.y*start.x).toDouble()))/Math.sqrt(((end.x-start.x)*(end.x-start.x) + (end.y-start.y)*(end.y-start.y)).toDouble()).toFloat()) < epsilon
}
}
}
class AABB(val x:Float, val y:Float, val w:Float, val h:Float) {
val center = Vec(x+(w/2), y+(h/2))
fun overlaps(other:AABB):Boolean {
// This Right < Other Left
if(x+w < other.x) {
return false
}
// thisTop < otherBottom
if(y+h < other.y) {
return false
}
// thisLeft > otherRight
if(x > other.x+other.w) {
return false
}
// thisBottom > otherTop
if(y > other.y+other.h) {
return false
}
return true
}
fun pointInside(otherX:Float, otherY:Float):Boolean {
return otherX > this.x && otherX < (this.x+this.w) && otherY > this.y && otherY < (this.y+this.h)
}
// Returns the smallest vector required to push the other AABB out of this one.
// NOTE: Assumes that these AABBs overlap.
fun getPushForce(other:AABB): Vec {
// For each axis, calculate the overlap and keep the smallest one.
val otherCenter = other.center
val thisCenter = this.center
val zeroOverlapX = this.w/2 + other.w/2 // Sum of half-widths.
val dx = otherCenter.x - thisCenter.x
val forceX = zeroOverlapX - Math.abs(dx) // If we apply forceX to the other object, it will bring it to this one's surface.
val zeroOverlapY = this.h/2 + other.h/2
val dy = otherCenter.y - thisCenter.y
val forceY = zeroOverlapY - Math.abs(dy)
if(Math.abs(forceX) < Math.abs(forceY)) {
return Vec(Math.copySign(forceX, dx))
} else {
return Vec(0f, Math.copySign(forceY, dy))
}
}
}
class Triangle(val a:Vec, val b:Vec, val c:Vec) {
fun intersection(line:Line, lineSegment:Boolean=false, planeIntersection:Boolean=false, epsilon:Float=1e-6f): Vec? {
/*
If the line doesn't intersect the triangle, returns null.
If planeIntersection is true, will return where the line intersects the plane instead of just the triangle.
If lineSegment is true, will return where the line intersects the plane or, if the point is not on the line, returns null.
Let N be the normal of the triangle as determined by the ab (cross) ac.
If then a point Q on the plane satisfies the equation N dot (Q-a) = 0. (?)
Substitute: N dot (P1 + u(P2-P1)) = N dot P3
u = N dot (a - P1) / N dot (P2 - P1)
*/
val r = b-a
val s = c-a
val normal = r.cross3(s)
val numerator = normal.dot(a - line.start)
val denominator = normal.dot(line.end - line.start)
if(Math.abs(denominator) < epsilon) {
return null
}
val t = numerator / denominator
if(lineSegment && (t < 0.0f || t > 1.0f)) {
return null // There is an intersection, but it's not on the line.
}
// Get the point.
val p = line.start + (line.end-line.start)*t
// If we care only about the plane, can return here.
if(planeIntersection) {
return p
}
// Check to see if the point is inside the triangle.
var alpha = r.dot(r)
var beta = r.dot(s)
var gamma = beta
var delta = s.dot(s)
val invDeterminant = alpha*delta - gamma*beta
if(Math.abs(invDeterminant) < epsilon) {
return null
}
val determinant = 1.0f / invDeterminant
alpha *= determinant
beta *= determinant
gamma *= determinant
delta *= determinant
// 2x3 matrix.
val mRow0 = (r * delta) + (s * -beta)
val mRow1 = (r * -gamma) + (s * alpha)
val u = mRow0.dot(p - a)
val v = mRow1.dot(p - a)
if(u >= 0 && v >= 0 && u <= 1 && v <= 1 && u+v <= 1) {
return p
} else {
return null
}
}
fun pointInTriangle2D(p:Vec):Boolean {
/*
// Any point p where [B-A] cross [p-A] does not point in the same direction as [B-A] cross [C-A] isn't inside the triangle.
val pPrime = p-a
val q = b-a
val r = c-a
if((q.cross2(pPrime) >= 0) != (q.cross2(r) >= 0)) {
return false // Can't be
}
// One more check now. Need to verify it's inside the other sides, too.
val qPrime = p-b
val s = a-b
val t = c-b
val qpos = s.cross2(qPrime)
val dpos = s.cross2(t)
return (qpos >= 0) == (dpos >= 0)
*/
// Barycentric coordinate version from Realtime Collision Detection.
// Compute vectors
val v0 = c-a
val v1 = b-a
val v2 = p-a
// Compute dot products
val dot00 = v0.dot(v0)
val dot01 = v0.dot(v1)
val dot02 = v0.dot(v2)
val dot11 = v1.dot(v1)
val dot12 = v1.dot(v2)
// Compute barycentric coordinates
val denom = (dot00 * dot11 - dot01 * dot01)
if(denom == 0f) { // degenerate.
return false
}
val invDenom = 1 / denom
val u = (dot11 * dot02 - dot01 * dot12) * invDenom
val v = (dot00 * dot12 - dot01 * dot02) * invDenom
// Check if point is in triangle
return (u >= 0) && (v >= 0) && (u + v < 1)
}
}
class Polygon(val points:List<Vec>) {
fun pointInside(pt:Vec): Boolean {
TODO()
}
fun splitAtPoints(p1:Vec, p2:Vec, vararg innerPoints:Vec): Pair<Polygon, Polygon> {
// Split the polygon with a fracture starting from p1 and running to p2. Two polygons will be returned.
// If innerPoints are returned, they will be included in both polygons between the fracture points.
// Both p1 and p2 will be present in both sections.
// Go around the points and find the indices of the cut.
var p1Index=-1
var p1Distance = Float.MAX_VALUE
var p2Index=-1
var p2Distance = Float.MAX_VALUE
for(i in 0 until points.size) {
// Get the distance from this point to p1.
val distToP1 = p1.distanceSquared(points[i])
val distToP2 = p2.distanceSquared(points[i])
if(distToP1 < p1Distance) {
p1Index = i
p1Distance = distToP1
}
if(distToP2 < p2Distance) {
p2Index = i
p2Distance = distToP2
}
}
// Make sure that p1 comes first.
if(p2Index < p1Index) {
val temp = p1Index
p1Index = p2Index
p2Index = temp
}
// If we have no internal points, we can just return the two new poligons.
if(innerPoints.isEmpty()) {
val leftPoints = points.filterIndexed{ i,v -> i <= p1Index || i >= p2Index }
val rightPoints = points.filterIndexed{ i,v -> i >= p1Index && i <= p2Index }
return Pair(Polygon(leftPoints), Polygon(rightPoints))
} else {
// There are two ways to assemble the halfs.
// If the first point in the innerPoint list is closer to the start p1 and the end point is closer to p2, keep straight. Otherwise flip the inner list.
// p1 ------------------------- p2
// innerpt1 -------- innerp2
val p1ToSplitHeadDistance = points[p1Index].distanceSquared(innerPoints.first())
val p1ToSplitTailDistance = points[p1Index].distanceSquared(innerPoints.last())
val p2ToSplitHeadDistance = points[p2Index].distanceSquared(innerPoints.first())
val p2ToSplitTailDistance = points[p2Index].distanceSquared(innerPoints.last())
if(p1ToSplitHeadDistance < p2ToSplitHeadDistance && p2ToSplitTailDistance < p1ToSplitTailDistance) {
// We should take the points in order.
val leftPoints = points.filterIndexed{ i,v -> i <= p1Index }.plus(innerPoints).plus(points.filterIndexed{ i,v -> i >= p2Index })
val rightPoints = innerPoints.reversed().plus(points.filterIndexed{i,v -> i >= p1Index && i <= p2Index})
return Pair(Polygon(leftPoints), Polygon(rightPoints))
} else if(p1ToSplitHeadDistance > p2ToSplitHeadDistance && p2ToSplitTailDistance > p1ToSplitTailDistance) {
// We should take the points reversed.
val leftPoints = points.filterIndexed{ i,v -> i <= p1Index }.plus(innerPoints.reversed()).plus(points.filterIndexed{ i,v -> i >= p2Index })
val rightPoints = innerPoints.toList().plus(points.filterIndexed{i,v -> i >= p1Index && i <= p2Index})
return Pair(Polygon(leftPoints), Polygon(rightPoints))
} else {
// It's not clear which way they should rotate.
throw Exception("Ambiguous split direction. Polygon can't figure out how to match up the divide.")
}
}
}
}
| mit | 93cef05013f24c3d1bbc2266d89962fb | 31.124424 | 222 | 0.64424 | 2.680638 | false | false | false | false |
peterLaurence/TrekAdvisor | app/src/main/java/com/peterlaurence/trekme/ui/mapcreate/views/GoogleMapWmtsViewFragment.kt | 1 | 16240 | package com.peterlaurence.trekme.ui.mapcreate.views
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.*
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import com.peterlaurence.mapview.MapView
import com.peterlaurence.mapview.MapViewConfiguration
import com.peterlaurence.mapview.api.addMarker
import com.peterlaurence.mapview.api.moveMarker
import com.peterlaurence.trekme.R
import com.peterlaurence.trekme.core.map.TileStreamProvider
import com.peterlaurence.trekme.core.mapsource.MapSource
import com.peterlaurence.trekme.core.mapsource.MapSourceBundle
import com.peterlaurence.trekme.core.projection.MercatorProjection
import com.peterlaurence.trekme.core.providers.bitmap.*
import com.peterlaurence.trekme.core.providers.layers.IgnLayers
import com.peterlaurence.trekme.service.event.DownloadServiceStatusEvent
import com.peterlaurence.trekme.ui.LocationProviderHolder
import com.peterlaurence.trekme.ui.dialogs.SelectDialog
import com.peterlaurence.trekme.ui.mapcreate.components.Area
import com.peterlaurence.trekme.ui.mapcreate.components.AreaLayer
import com.peterlaurence.trekme.ui.mapcreate.components.AreaListener
import com.peterlaurence.trekme.ui.mapcreate.events.MapSourceSettingsEvent
import com.peterlaurence.trekme.ui.mapcreate.views.components.PositionMarker
import com.peterlaurence.trekme.ui.mapcreate.views.events.LayerSelectEvent
import com.peterlaurence.trekme.viewmodel.common.Location
import com.peterlaurence.trekme.viewmodel.common.LocationProvider
import com.peterlaurence.trekme.viewmodel.common.LocationViewModel
import com.peterlaurence.trekme.viewmodel.common.tileviewcompat.toMapViewTileStreamProvider
import com.peterlaurence.trekme.viewmodel.mapcreate.GoogleMapWmtsViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
/**
* Displays Google Maps - compatible tile matrix sets.
* For example :
*
* [IGN WMTS](https://geoservices.ign.fr/documentation/geoservices/wmts.html). A `GetCapabilities`
* request reveals that each level is square area. Here is an example for level 18 :
* ```
* <TileMatrix>
* <ows:Identifier>18</ows:Identifier>
* <ScaleDenominator>2132.7295838497840572</ScaleDenominator>
* <TopLeftCorner>
* -20037508.3427892476320267 20037508.3427892476320267
* </TopLeftCorner>
* <TileWidth>256</TileWidth>
* <TileHeight>256</TileHeight>
* <MatrixWidth>262144</MatrixWidth>
* <MatrixHeight>262144</MatrixHeight>
* </TileMatrix>
* ```
* This level correspond to a 256 * 262144 = 67108864 px wide and height area.
* The `TopLeftCorner` corner contains the WebMercator coordinates. The bottom right corner has
* implicitly the opposite coordinates.
* **Beware** that this "level 18" is actually the 19th level (matrix set starts at 0).
*
* The same settings can be seen at [USGS WMTS](https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/WMTS/1.0.0/WMTSCapabilities.xml)
* for the "GoogleMapsCompatible" TileMatrixSet (and not the "default028mm" one).
*
* @author peterLaurence on 11/05/18
*/
class GoogleMapWmtsViewFragment : Fragment() {
private lateinit var mapSource: MapSource
private lateinit var rootView: ConstraintLayout
private lateinit var mapView: MapView
private lateinit var areaLayer: AreaLayer
private lateinit var locationProvider: LocationProvider
private lateinit var positionMarker: PositionMarker
private lateinit var wmtsWarning: TextView
private lateinit var wmtsWarningLink: TextView
private lateinit var navigateToIgnCredentialsBtn: Button
private lateinit var fabSave: FloatingActionButton
private val projection = MercatorProjection()
private val viewModel: GoogleMapWmtsViewModel by activityViewModels()
private val locationViewModel: LocationViewModel by activityViewModels()
private lateinit var area: Area
/* Size of level 18 */
private val mapSize = 67108864
private val highestLevel = 18
private val tileSize = 256
private val x0 = -20037508.3427892476320267
private val y0 = -x0
private val x1 = -x0
private val y1 = x0
companion object {
private const val ARG_MAP_SOURCE = "mapSource"
@JvmStatic
fun newInstance(mapSource: MapSourceBundle): GoogleMapWmtsViewFragment {
val fragment = GoogleMapWmtsViewFragment()
val args = Bundle()
args.putParcelable(ARG_MAP_SOURCE, mapSource)
fragment.arguments = args
return fragment
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is LocationProviderHolder) {
locationProvider = context.locationProvider
} else {
throw RuntimeException("$context must implement LocationProviderHolder")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mapSource = arguments?.getParcelable<MapSourceBundle>(ARG_MAP_SOURCE)?.mapSource
?: MapSource.OPEN_STREET_MAP
locationViewModel.setLocationProvider(locationProvider)
locationViewModel.getLocationLiveData().observe(this, Observer<Location> {
it?.let {
onLocationReceived(it)
}
})
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
rootView =
inflater.inflate(R.layout.fragment_wmts_view, container, false) as ConstraintLayout
return rootView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
wmtsWarning = view.findViewById(R.id.fragmentWmtWarning)
fabSave = view.findViewById(R.id.fabSave)
fabSave.setOnClickListener { validateArea() }
wmtsWarningLink = view.findViewById(R.id.fragmentWmtWarningLink)
wmtsWarningLink.movementMethod = LinkMovementMethod.getInstance()
/**
* If there is something wrong with IGN credentials, a special button helps to go directly
* to the credentials editing fragment.
*/
navigateToIgnCredentialsBtn = view.findViewById(R.id.fragmentWmtsNagivateToIgnCredentials)
navigateToIgnCredentialsBtn.setOnClickListener {
EventBus.getDefault().post(MapSourceSettingsEvent(MapSource.IGN))
}
configure()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
/* Hide the app title */
val actionBar = (activity as AppCompatActivity).supportActionBar
actionBar?.setDisplayShowTitleEnabled(false)
/* Clear the existing action menu */
menu.clear()
/* Fill the new one */
inflater.inflate(R.menu.menu_fragment_map_create, menu)
/* Only show the layer menu for IGN France for instance */
val layerMenu = menu.findItem(R.id.map_layer_menu_id)
layerMenu.isVisible = when (mapSource) {
MapSource.IGN -> true
else -> false
}
super.onCreateOptionsMenu(menu, inflater)
}
@SuppressLint("RestrictedApi")
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.map_area_widget_id -> {
if (this::areaLayer.isInitialized) {
areaLayer.detach()
}
addAreaLayer()
fabSave.visibility = View.VISIBLE
}
R.id.map_layer_menu_id -> {
val event = LayerSelectEvent(arrayListOf())
val title = getString(R.string.ign_select_layer_title)
val values = IgnLayers.values().map { it.publicName }
val layerPublicName = viewModel.getLayerPublicNameForSource(mapSource)
val layerSelectDialog =
SelectDialog.newInstance(title, values, layerPublicName, event)
layerSelectDialog.show(
requireActivity().supportFragmentManager,
"SelectDialog-${event.javaClass.canonicalName}"
)
}
}
return super.onOptionsItemSelected(item)
}
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
override fun onResume() {
super.onResume()
startLocationUpdates()
}
override fun onPause() {
super.onPause()
stopLocationUpdates()
}
override fun onStop() {
EventBus.getDefault().unregister(this)
super.onStop()
}
private fun startLocationUpdates() {
locationViewModel.startLocationUpdates()
}
private fun stopLocationUpdates() {
locationViewModel.stopLocationUpdates()
}
/**
* Confirm to the user that the download started.
*/
@Subscribe
fun onDownloadServiceStatus(e: DownloadServiceStatusEvent) {
if (e.started) {
view?.let {
val snackBar = Snackbar.make(it, R.string.download_confirm, Snackbar.LENGTH_SHORT)
snackBar.show()
}
}
}
@Subscribe
fun onLayerDefined(e: LayerSelectEvent) {
/* Update the layer preference */
viewModel.setLayerPublicNameForSource(mapSource, e.getSelection())
/* The re-create the mapview */
removeMapView()
configure()
}
private fun configure() = lifecycleScope.launch {
/* 0- TODO: Show an infinite scrollbar to the user until all operations below are done */
/* 1- Create the TileStreamProvider */
val streamProvider = viewModel.createTileStreamProvider(mapSource)
if (streamProvider == null) {
showWarningMessage()
return@launch
}
/* 2- Configure the mapView only if the test succeeds */
val checkResult = checkTileAccessibility(streamProvider)
try {
if (!checkResult) {
showWarningMessage()
return@launch
} else {
addMapView(streamProvider)
hideWarningMessage()
}
} catch (e: IllegalStateException) {
/* Since this can happen anytime during the lifecycle of this fragment, we should be
* resilient and discard this error */
}
/* 3- Scroll to the init position if there is one pre-configured */
viewModel.getScaleAndScrollInitConfig(mapSource)?.also {
/* At this point the mapView should be initialized, but we never know.. */
if (::mapView.isInitialized) {
mapView.scale = it.scale
mapView.scrollTo(it.scrollX, it.scrollY)
}
}
}
/**
* Simple check whether we are able to download tiles or not.
*/
private suspend fun checkTileAccessibility(tileStreamProvider: TileStreamProvider): Boolean = withContext(Dispatchers.IO) {
when (mapSource) {
MapSource.IGN -> {
try {
checkIgnProvider(tileStreamProvider)
} catch (e: Exception) {
false
}
}
MapSource.IGN_SPAIN -> checkIgnSpainProvider(tileStreamProvider)
MapSource.USGS -> checkUSGSProvider(tileStreamProvider)
MapSource.OPEN_STREET_MAP -> checkOSMProvider(tileStreamProvider)
MapSource.SWISS_TOPO -> checkSwissTopoProvider(tileStreamProvider)
}
}
private fun showWarningMessage() {
wmtsWarning.visibility = View.VISIBLE
wmtsWarningLink.visibility = View.VISIBLE
if (mapSource == MapSource.IGN) {
navigateToIgnCredentialsBtn.visibility = View.VISIBLE
wmtsWarning.text = getText(R.string.mapcreate_warning_ign)
} else {
wmtsWarning.text = getText(R.string.mapcreate_warning_others)
}
}
private fun hideWarningMessage() {
wmtsWarning.visibility = View.GONE
navigateToIgnCredentialsBtn.visibility = View.GONE
wmtsWarningLink.visibility = View.GONE
}
private fun addMapView(tileStreamProvider: TileStreamProvider) {
val context = this.context ?: return
val mapView = MapView(context)
val config = MapViewConfiguration(
19, mapSize, mapSize, tileSize,
tileStreamProvider.toMapViewTileStreamProvider()
).setWorkerCount(16)
/* Particular case of OSM Maps, limit concurrency while fetching tiles to avoid being banned */
if (mapSource == MapSource.OPEN_STREET_MAP) {
config.setWorkerCount(2)
}
mapView.configure(config)
/* Map calibration */
mapView.defineBounds(x0, y0, x1, y1)
/* Position marker */
positionMarker = PositionMarker(context)
mapView.addMarker(positionMarker, 0.0, 0.0, -0.5f, -0.5f)
/* Add the view */
setMapView(mapView)
}
private fun setMapView(mapView: MapView) {
this.mapView = mapView
this.mapView.id = R.id.tileview_ign_id
this.mapView.isSaveEnabled = true
val params = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
)
rootView.addView(mapView, 0, params)
}
private fun removeMapView() {
rootView.removeViewAt(0)
}
private fun addAreaLayer() {
if (!::mapView.isInitialized) return
view?.post {
areaLayer = AreaLayer(requireContext(), object : AreaListener {
override fun areaChanged(area: Area) {
[email protected] = area
}
override fun hideArea() {
}
})
areaLayer.attachTo(mapView)
}
}
/**
* Called when the user validates his area by clicking on the floating action button.
*/
private fun validateArea() {
if (this::area.isInitialized) {
val fm = activity?.supportFragmentManager
if (fm != null) {
mapSource.let {
val wmtsLevelsDialog = if (it == MapSource.IGN) {
WmtsLevelsDialogIgn.newInstance(area, MapSourceBundle(it))
} else {
WmtsLevelsDialog.newInstance(area, MapSourceBundle(it))
}
wmtsLevelsDialog.show(fm, "fragment")
}
}
}
}
private fun onLocationReceived(location: Location) {
/* If there is no MapView, no need to go further */
if (!::mapView.isInitialized) {
return
}
/* A Projection is always defined in this case */
lifecycleScope.launch {
val projectedValues = withContext(Dispatchers.Default) {
projection.doProjection(location.latitude, location.longitude)
}
if (projectedValues != null) {
updatePosition(projectedValues[0], projectedValues[1])
}
}
}
/**
* Update the position on the map.
*
* @param x the projected X coordinate
* @param y the projected Y coordinate
*/
private fun updatePosition(x: Double, y: Double) {
if (::positionMarker.isInitialized) {
mapView.moveMarker(positionMarker, x, y)
}
}
}
| gpl-3.0 | 27a1d2dbf9137c33213ac27cb10b1824 | 34.692308 | 152 | 0.657328 | 4.723677 | false | false | false | false |
Madzi/owide | src/main/kotlin/owide/language/Stream.kt | 1 | 249 | package owide.language
class Stream(val text: String) {
private var pos = 0
fun reset() { pos = 0 }
fun eof(): Boolean = pos >= text.length
fun next(): Char = text[pos++]
fun nextWord(): String = TODO("Not implemented yet")
} | apache-2.0 | 0b84dd758d15025ffda7d95fa1b32eba | 19.833333 | 56 | 0.610442 | 3.661765 | false | false | false | false |
donglua/GithubContributionsWidget | app/src/main/kotlin/org/droiders/githubwidget/WidgetConfigActivity.kt | 1 | 3716 | package org.droiders.githubwidget
import android.app.ProgressDialog
import android.appwidget.AppWidgetManager
import android.content.*
import android.databinding.DataBindingUtil
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.crashlytics.android.Crashlytics
import io.fabric.sdk.android.Fabric
import org.droiders.githubwidget.contributions.ContributionsContract
import org.droiders.githubwidget.contributions.ContributionsModel
import org.droiders.githubwidget.contributions.ContributionsPresenter
import org.droiders.githubwidget.data.DBHelper
import org.droiders.githubwidget.data.DBHelper.Companion.TABLE_NAME
import org.droiders.githubwidget.data.Contributions
import org.droiders.githubwidget.databinding.ActivityWidgetConfigBinding
/**
* Created by donglua on 2016/12/27.
*/
class WidgetConfigActivity : AppCompatActivity(), ContributionsContract.View {
private lateinit var mPresenter: ContributionsContract.Presenter
private var mProgressDialog: ProgressDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Fabric.with(this, Crashlytics())
val binding = DataBindingUtil.setContentView<ActivityWidgetConfigBinding>(this,
R.layout.activity_widget_config)
val model = ContributionsModel()
val name = model.getUserName(this)
binding.etUserName.setText(name)
binding.etUserName.setSelection(name.length)
mPresenter = ContributionsPresenter(this, model)
binding.buttonUpdate.setOnClickListener {
val userName = binding.etUserName.text.toString()
if (userName.isEmpty()) {
showToast("User Name Can't Be Blank ~")
return@setOnClickListener
}
model.saveUserName(this, userName)
mPresenter.initUserContributions(userName)
showProcessing()
}
}
override fun showAppWidget(list: List<Contributions>) {
val uri = Uri.parse("content://${applicationInfo.packageName}.provider/$TABLE_NAME")
list.forEach {
val values = ContentValues()
values.put(DBHelper.COLUMN_COLOR, it.color)
values.put(DBHelper.COLUMN_DATA_COUNT, it.dataCount)
values.put(DBHelper.COLUMN_DATE, it.day)
contentResolver.insert(uri, values)
}
updateWidgetList()
dismissProcessing()
finish()
}
private fun updateWidgetList() {
val name = ComponentName(this, ContributionsWidgetProvider::class.java)
val widgetIds = AppWidgetManager.getInstance(this).getAppWidgetIds(name)
val updateWidgetListIntent = Intent(this, ContributionsWidgetProvider::class.java)
updateWidgetListIntent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
updateWidgetListIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIds)
updateWidgetListIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetIds.last())
sendBroadcast(updateWidgetListIntent)
setResult(RESULT_OK, updateWidgetListIntent)
}
override fun showFailure(message: String?) {
runOnUiThread {
if (message != null) showToast(message)
}
}
override fun onDestroy() {
dismissProcessing()
super.onDestroy()
}
fun showProcessing() {
mProgressDialog = ProgressDialog(this)
mProgressDialog?.setMessage("loading...")
mProgressDialog?.setProgressStyle(ProgressDialog.STYLE_SPINNER)
mProgressDialog?.show()
}
fun dismissProcessing() {
mProgressDialog?.dismiss()
}
}
| apache-2.0 | b0983a382e6a70178b14af21d668c1da | 33.407407 | 94 | 0.710441 | 4.84485 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/navigation/goto/RsTargetElementEvaluator.kt | 2 | 3374 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.navigation.goto
import com.intellij.codeInsight.TargetElementEvaluatorEx2
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.util.BitUtil
import org.rust.lang.core.macros.findExpansionElements
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.ref.*
import org.rust.lang.core.types.ty.TyAdt
import org.rust.lang.core.types.type
class RsTargetElementEvaluator : TargetElementEvaluatorEx2() {
/**
* Allows to intercept platform calls to [PsiReference.resolve]
*
* Note that if this method returns null, it means
* "use default logic", i.e. call `ref.resolve()`
*/
override fun getElementByReference(ref: PsiReference, flags: Int): PsiElement? {
if (ref !is RsReference) return null
// prefer pattern binding to its target if element name is accepted
if (ref is RsPatBindingReferenceImpl && BitUtil.isSet(flags, TargetElementUtil.ELEMENT_NAME_ACCEPTED)) {
return ref.element
}
if (ref is RsPathReference) {
ref.tryResolveTypeAliasToImpl()?.let {
return it
}
}
// Filter invocations from CtrlMouseHandler (see RsQuickNavigationInfoTest)
// and leave invocations from GotoDeclarationAction only.
if (!RsGoToDeclarationRunningService.getInstance().isGoToDeclarationAction) return null
return tryResolveToDeriveMetaItem(ref)
}
private fun tryResolveToDeriveMetaItem(ref: PsiReference): PsiElement? {
val target = ref.resolve() as? RsAbstractable ?: return null
val trait = (target.owner as? RsAbstractableOwner.Trait)?.trait ?: return null
val item = when (val element = ref.element) {
is RsPath -> element.path?.reference?.deepResolve() as? RsStructOrEnumItemElement
else -> {
val receiver = when (element) {
is RsMethodCall -> element.parentDotExpr.expr.type
is RsBinaryOp -> (element.parent as? RsBinaryExpr)?.left?.type
else -> return null
}
(receiver as? TyAdt)?.item
}
}
return item?.derivedTraitsToMetaItems?.get(trait)
}
/**
* Used to get parent named element when [element] is a name identifier
*
* Note that if this method returns null, it means "use default logic"
*/
override fun getNamedElement(element: PsiElement): PsiElement? {
// This hack enables some actions (e.g. "find usages") when the [element] is inside a macro
// call and this element expands to name identifier of some named element.
val elementType = element.elementType
if (elementType == RsElementTypes.IDENTIFIER || elementType == RsElementTypes.QUOTE_IDENTIFIER) {
val delegate = element.findExpansionElements()?.firstOrNull() ?: return null
val delegateParent = delegate.parent
if (delegateParent is RsNameIdentifierOwner && delegateParent.nameIdentifier == delegate) {
return delegateParent
}
}
return null
}
}
| mit | ad68402b554213d6ea887ef8c87e571a | 38.694118 | 112 | 0.663308 | 4.705718 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/config/NamedObjectMap.kt | 1 | 5570 | /*
Copyright 2017-2020 Charles Korn.
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 batect.config
import com.charleskorn.kaml.Location
import com.charleskorn.kaml.YamlInput
import kotlinx.serialization.CompositeDecoder
import kotlinx.serialization.Decoder
import kotlinx.serialization.Encoder
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialDescriptor
import kotlinx.serialization.internal.StringSerializer
import kotlinx.serialization.map
abstract class NamedObjectMap<E>(contentName: String, contents: Iterable<E>) : Map<String, E>, Set<E> {
init {
val duplicates = contents
.groupBy { nameFor(it) }
.filter { it.value.size > 1 }
.map { it.key }
if (duplicates.isNotEmpty()) {
throw IllegalArgumentException("Cannot create a ${this.javaClass.simpleName} where a $contentName name is used more than once. Duplicated $contentName names: ${duplicates.joinToString(", ")}")
}
}
private val implementation: Map<String, E> = contents.associateBy { nameFor(it) }
// Map members
override val entries: Set<Map.Entry<String, E>>
get() = implementation.entries
override val keys: Set<String>
get() = implementation.keys
override val values: Collection<E>
get() = implementation.values
override val size: Int
get() = implementation.size
override fun containsKey(key: String): Boolean = implementation.containsKey(key)
override fun containsValue(value: E): Boolean = implementation.containsValue(value)
override fun get(key: String): E? = implementation[key]
override fun isEmpty(): Boolean = implementation.isEmpty()
override fun contains(element: E): Boolean = containsValue(element)
override fun containsAll(elements: Collection<E>): Boolean = values.containsAll(elements)
override fun iterator(): Iterator<E> = values.iterator()
abstract fun nameFor(value: E): String
override fun equals(other: Any?): Boolean = implementation == other
override fun hashCode(): Int = implementation.hashCode()
}
abstract class NamedObjectMapSerializer<TCollection : Iterable<TElement>, TElement>(val elementSerializer: KSerializer<TElement>) {
val keySerializer = StringSerializer
// We can't just declare the value of this here due to https://github.com/Kotlin/kotlinx.serialization/issues/315#issuecomment-460015206
abstract val descriptor: SerialDescriptor
fun deserialize(decoder: Decoder): TCollection {
val input = decoder.beginStructure(descriptor)
return read(input).also { input.endStructure(descriptor) }
}
private fun read(input: CompositeDecoder): TCollection {
val size = input.decodeCollectionSize(descriptor)
while (true) {
when (val index = input.decodeElementIndex(descriptor)) {
CompositeDecoder.READ_ALL -> return readAll(input, size)
else -> return readUntilDone(input, index)
}
}
}
private fun readAll(input: CompositeDecoder, size: Int): TCollection {
val soFar = mutableSetOf<TElement>()
for (currentIndex in 0..size) {
soFar.add(readSingle(input, currentIndex, false))
}
return createCollection(soFar)
}
private fun readUntilDone(input: CompositeDecoder, firstIndex: Int): TCollection {
var currentIndex = firstIndex
val soFar = mutableSetOf<TElement>()
while (currentIndex != CompositeDecoder.READ_DONE) {
soFar.add(readSingle(input, currentIndex, true))
currentIndex = input.decodeElementIndex(descriptor)
}
return createCollection(soFar)
}
private fun readSingle(input: CompositeDecoder, index: Int, checkIndex: Boolean): TElement {
val nameLocation = (input as YamlInput).getCurrentLocation()
val name = input.decodeSerializableElement(descriptor, index, keySerializer)
validateName(name, nameLocation)
val valueIndex = if (checkIndex) {
input.decodeElementIndex(descriptor)
} else {
index + 1
}
val unnamed = input.decodeSerializableElement(descriptor, valueIndex, elementSerializer)
return addName(name, unnamed)
}
@Suppress("UNUSED_PARAMETER")
fun serialize(encoder: Encoder, obj: TCollection) {
val output = encoder.beginCollection(descriptor, obj.count())
obj.forEachIndexed { index, element ->
output.encodeSerializableElement(descriptor, 2*index, keySerializer, getName(element))
output.encodeSerializableElement(descriptor, 2*index + 1, elementSerializer, element)
}
output.endStructure(descriptor)
}
open fun validateName(name: String, location: Location) {}
protected abstract fun addName(name: String, element: TElement): TElement
protected abstract fun createCollection(elements: Set<TElement>): TCollection
protected abstract fun getName(element: TElement): String
}
| apache-2.0 | fac8b1e39176c3714e98fdb3d2146a4d | 36.133333 | 204 | 0.698923 | 4.768836 | false | false | false | false |
rickgit/Test | app_kotlin/src/main/java/edu/ptu/java/app_kotlin/databinding/UserBindable.kt | 1 | 574 | package edu.ptu.java.app_kotlin.databinding
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import androidx.databinding.library.baseAdapters.BR
class UserBindable(): BaseObservable() {
@Bindable
var name = "初始化数据"
set(value) {
field = value
notifyPropertyChanged(BR.name)
}
@Bindable
var url = "https://tse1-mm.cn.bing.net/th/id/OIP.BW54Wc2X6zBd8PyKkXgDqgHaHa?pid=Api&rs=1"
set(value) {
field = value
notifyPropertyChanged(BR.url)
}
} | apache-2.0 | 66c764c8ecd1eb2d688ba23800d85f19 | 27.25 | 93 | 0.657801 | 3.63871 | false | false | false | false |
michael71/LanbahnPanel | app/src/main/java/de/blankedv/lanbahnpanel/elements/SensorElement.kt | 1 | 3042 | package de.blankedv.lanbahnpanel.elements
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Rect
import android.util.Log
import de.blankedv.lanbahnpanel.util.LanbahnBitmaps.bitmaps
import de.blankedv.lanbahnpanel.util.LPaints.linePaintDarkYellowDash
import de.blankedv.lanbahnpanel.util.LPaints.linePaintGrayDash
import de.blankedv.lanbahnpanel.util.LPaints.linePaintRedDash
import de.blankedv.lanbahnpanel.model.*
class SensorElement : ActivePanelElement {
constructor() : super() {}
// check bit0 for "OCCUPIED"
fun isOccupied() : Boolean {
if (state == STATE_UNKNOWN) return false
return ((state and 0x01) != 0) // bit0 is set
}
override fun getSensitiveRect(): Rect {
if (x2 == INVALID_INT) { // dot type sensor
return Rect(x - RASTER / 5, y - RASTER / 7, x + RASTER / 5, y + RASTER / 7)
} else { // line type sensor
return Rect((x + x2) / 2 - RASTER / 5, (y + y2) / 2 - RASTER / 7, (x + x2) / 2 + RASTER / 5,
(y + y2) / 2 + RASTER / 7)
}
}
override fun doDraw(canvas: Canvas) {
if (x2 != INVALID_INT) { // draw dashed line as sensor
// read data from central station and set red/gray dashed line accordingly
if (isOccupied()) {
canvas.drawLine((x * prescale).toFloat(), (y * prescale).toFloat(), (x2 * prescale).toFloat(), (y2 * prescale).toFloat(), linePaintRedDash)
if ((train != INVALID_INT) && ( !prefs.getBoolean(KEY_DRAW_ADR2, false))){
// draw train number on sensor
doDrawTrainNumber(canvas)
}
} else {
if (inRoute) {
canvas.drawLine((x * prescale).toFloat(), (y * prescale).toFloat(), (x2 * prescale).toFloat(), (y2 * prescale).toFloat(), linePaintDarkYellowDash)
} else {
canvas.drawLine((x * prescale).toFloat(), (y * prescale).toFloat(), (x2 * prescale).toFloat(), (y2 * prescale).toFloat(), linePaintGrayDash)
}
}
} else {
// draw lamp type of sensor s_on.png etc
// "inRoute is ignored in this case
val h: Int
val w: Int
val bm: Bitmap?
val bmName = StringBuilder("sensor")
if (isOccupied()) {
bmName.append("_on")
} else {
bmName.append("_off")
}
bm = bitmaps[bmName.toString()]
if (bm == null) {
Log.e(TAG,
"error, bitmap not found with name=" + bmName.toString())
} else {
h = bm.height / 2
w = bm.width / 2
canvas.drawBitmap(bm, (x * prescale - w).toFloat(), (y * prescale - h).toFloat(), null) // center
// bitmap
}
}
if (prefs.getBoolean(KEY_DRAW_ADR2, false))
doDrawAddresses(canvas)
}
}
| gpl-3.0 | 3d2f02afbb1eeadcf392c780c29693fd | 37.025 | 166 | 0.539776 | 3.981675 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/timeline/meta/Timeline.kt | 1 | 41402 | /*
* Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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 org.andstatus.app.timeline.meta
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.provider.BaseColumns
import org.andstatus.app.IntentExtra
import org.andstatus.app.account.MyAccount
import org.andstatus.app.actor.ActorsScreenType
import org.andstatus.app.context.MyContext
import org.andstatus.app.context.MyContextEmpty
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.data.ContentValuesUtils
import org.andstatus.app.data.DbUtils
import org.andstatus.app.data.MatchedUri
import org.andstatus.app.data.MyQuery
import org.andstatus.app.data.ParsedUri
import org.andstatus.app.data.SqlWhere
import org.andstatus.app.database.table.TimelineTable
import org.andstatus.app.net.social.Actor
import org.andstatus.app.origin.Origin
import org.andstatus.app.os.AsyncUtil
import org.andstatus.app.service.CommandResult
import org.andstatus.app.timeline.ListScope
import org.andstatus.app.util.BundleUtils
import org.andstatus.app.util.CollectionsUtil
import org.andstatus.app.util.IsEmpty
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.MyStringBuilder
import org.andstatus.app.util.RelativeTime
import org.andstatus.app.util.StringUtil
import org.andstatus.app.util.TriState
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
/**
* @author [email protected]
*/
class Timeline : Comparable<Timeline?>, IsEmpty {
val myContext: MyContext
@Volatile
private var id: Long = 0
val timelineType: TimelineType
/** "Authenticated User" used to retrieve/post to... this Timeline */
val myAccountToSync: MyAccount
/** An Actor as a parameter of this timeline.
* This may be the same as the Authenticated User ([.myAccountToSync])
* or some other User e.g. to get a list of messages by some other person/user of the Social Network
*/
val actor: Actor
/** The Social Network of this timeline. Some timelines don't depend on
* an Authenticated User ([.myAccountToSync]), e.g. [TimelineType.PUBLIC] - this
* timeline may be fetched by any authenticated user of this Social Network */
private val origin: Origin
/** Pre-fetched string to be used to present in UI */
private var actorInTimeline: String = ""
/** This may be used e.g. to search [TimelineType.PUBLIC] timeline */
private val searchQuery: String
/** The timeline combines messages from all accounts
* or from Social Networks, e.g. Search in all Social Networks */
val isCombined: Boolean
/** If this timeline can be synced */
private val isSyncable: Boolean
/** If this timeline can be synced automatically */
private val isSyncableAutomatically: Boolean
/** Is it possible to sync this timeline via usage of one or more (child, not combined...)
* timelines for individual accounts */
private val isSyncableForAccounts: Boolean
/** Is it possible to sync this timeline via usage of one or more (child, not combined...)
* timelines for individual Social networks */
private val isSyncableForOrigins: Boolean
/** If the timeline is synced automatically */
@Volatile
private var isSyncedAutomatically = false
/** If the timeline should be shown in a Timeline selector */
@Volatile
private var isDisplayedInSelector: DisplayedInSelector = DisplayedInSelector.NEVER
/** Used for sorting timelines in a selector */
@Volatile
private var selectorOrder: Long = 0
/** When this timeline was last time successfully synced */
private val syncSucceededDate: AtomicLong = AtomicLong()
/** When last sync error occurred */
private val syncFailedDate: AtomicLong = AtomicLong()
/** Error message at [.syncFailedDate] */
@Volatile
private var errorMessage: String? = ""
/** Number of successful sync operations: "Synced [.syncedTimesCount] times" */
private val syncedTimesCount: AtomicLong = AtomicLong()
/** Number of failed sync operations */
private val syncFailedTimesCount: AtomicLong = AtomicLong()
private val downloadedItemsCount: AtomicLong = AtomicLong()
private val newItemsCount: AtomicLong = AtomicLong()
private val countSince: AtomicLong = AtomicLong(System.currentTimeMillis())
/** Accumulated numbers for statistics. They are reset by a user's request */
private val syncedTimesCountTotal: AtomicLong = AtomicLong()
private val syncFailedTimesCountTotal: AtomicLong = AtomicLong()
private val downloadedItemsCountTotal: AtomicLong = AtomicLong()
private val newItemsCountTotal: AtomicLong = AtomicLong()
/** Timeline position of the youngest ever downloaded message */
@Volatile
private var youngestPosition = ""
/** Date of the item corresponding to the [.youngestPosition] */
@Volatile
private var youngestItemDate: Long = 0
/** Last date when youngest items of this timeline were successfully synced
* (even if there were no new item at that time).
* It may be used to calculate when it will be time for the next automatic update
*/
@Volatile
private var youngestSyncedDate: Long = 0
/** Timeline position of the oldest ever downloaded message */
@Volatile
private var oldestPosition = ""
/** Date of the item corresponding to the [.oldestPosition] */
@Volatile
private var oldestItemDate: Long = 0
/** Last date when oldest items of this timeline were successfully synced
* (even if there were no new item at that time).
* It may be used to calculate when it will be time for the next automatic update
*/
@Volatile
private var oldestSyncedDate: Long = 0
/** Position of the timeline, which a User viewed */
@Volatile
private var visibleItemId: Long = 0
@Volatile
private var visibleY = 0
@Volatile
private var visibleOldestDate: Long = 0
@Volatile
private var changed = true
@Volatile
private var lastChangedDate: Long = 0
private constructor() {
myContext = MyContextEmpty.EMPTY
timelineType = TimelineType.UNKNOWN
myAccountToSync = MyAccount.EMPTY
actor = Actor.EMPTY
origin = Origin.EMPTY
searchQuery = ""
isCombined = calcIsCombined(timelineType, origin)
isSyncable = false
isSyncableAutomatically = false
isSyncableForAccounts = false
isSyncableForOrigins = false
}
internal constructor(myContext: MyContext, id: Long, timelineType: TimelineType,
actor: Actor, origin: Origin, searchQuery: String?, selectorOrder: Long) {
Objects.requireNonNull(timelineType)
Objects.requireNonNull(actor)
Objects.requireNonNull(origin)
this.myContext = myContext
this.id = id
this.actor = fixedActor(timelineType, actor)
this.origin = fixedOrigin(timelineType, origin)
myAccountToSync = calcAccountToSync(myContext, timelineType, this.origin, this.actor)
this.searchQuery = StringUtil.optNotEmpty(searchQuery).orElse("")
isCombined = calcIsCombined(timelineType, this.origin)
this.timelineType = fixedTimelineType(timelineType)
isSyncable = calcIsSyncable(myAccountToSync)
isSyncableAutomatically = isSyncable && myAccountToSync.isSyncedAutomatically
isSyncableForAccounts = calcIsSyncableForAccounts(myContext)
isSyncableForOrigins = calcIsSyncableForOrigins(myContext)
this.selectorOrder = selectorOrder
}
fun getDefaultSelectorOrder(): Long {
return (timelineType.ordinal + 1L) * 2 + if (isCombined) 1 else 0
}
private fun calcIsSyncable(myAccountToSync: MyAccount): Boolean {
return (!isCombined && timelineType.isSyncable()
&& myAccountToSync.isValidAndSucceeded()
&& myAccountToSync.origin.originType.isTimelineTypeSyncable(timelineType))
}
private fun calcIsSyncableForAccounts(myContext: MyContext): Boolean {
return isCombined &&
timelineType.isSyncable() && timelineType.canBeCombinedForMyAccounts() &&
myContext.accounts.getFirstSucceeded().isValidAndSucceeded()
}
private fun calcIsSyncableForOrigins(myContext: MyContext): Boolean {
return isCombined &&
timelineType.isSyncable() && timelineType.canBeCombinedForOrigins() &&
myContext.accounts.getFirstSucceeded().isValidAndSucceeded()
}
private fun calcIsCombined(timelineType: TimelineType, origin: Origin): Boolean {
return if (timelineType.isAtOrigin()) origin.isEmpty else actor.isEmpty
}
private fun calcAccountToSync(myContext: MyContext, timelineType: TimelineType, origin: Origin, actor: Actor): MyAccount {
return if (timelineType.isAtOrigin() && origin.nonEmpty)
myContext.accounts.getFirstPreferablySucceededForOrigin(origin)
else myContext.accounts.toSyncThatActor(actor)
}
private fun fixedActor(timelineType: TimelineType, actor: Actor): Actor {
return if (timelineType.isForUser()) actor else Actor.EMPTY
}
private fun fixedOrigin(timelineType: TimelineType, origin: Origin): Origin {
return if (timelineType.isAtOrigin()) origin else Origin.EMPTY
}
private fun fixedTimelineType(timelineType: TimelineType): TimelineType {
return if (isCombined || (if (timelineType.isAtOrigin()) origin.isValid
else actor.nonEmpty)) timelineTypeFixEverything(timelineType) else TimelineType.UNKNOWN
}
private fun timelineTypeFixEverything(timelineType: TimelineType): TimelineType {
return when (timelineType) {
TimelineType.EVERYTHING,
TimelineType.SEARCH -> if (hasSearchQuery()) TimelineType.SEARCH else TimelineType.EVERYTHING
else -> timelineType
}
}
override operator fun compareTo(other: Timeline?): Int {
if (other == null) return 1
val result = CollectionsUtil.compareCheckbox(checkBoxDisplayedInSelector(), other.checkBoxDisplayedInSelector())
return if (result != 0) {
result
} else getSelectorOrder().compareTo(other.getSelectorOrder())
}
fun toContentValues(values: ContentValues) {
ContentValuesUtils.putNotZero(values, BaseColumns._ID, id)
values.put(TimelineTable.TIMELINE_TYPE, timelineType.save())
values.put(TimelineTable.ACTOR_ID, actor.actorId)
values.put(TimelineTable.ACTOR_IN_TIMELINE, actorInTimeline)
values.put(TimelineTable.ORIGIN_ID, origin.id)
values.put(TimelineTable.SEARCH_QUERY, searchQuery)
values.put(TimelineTable.IS_SYNCED_AUTOMATICALLY, isSyncedAutomatically)
values.put(TimelineTable.DISPLAYED_IN_SELECTOR, isDisplayedInSelector.save())
values.put(TimelineTable.SELECTOR_ORDER, selectorOrder)
values.put(TimelineTable.SYNC_SUCCEEDED_DATE, syncSucceededDate.get())
values.put(TimelineTable.SYNC_FAILED_DATE, syncFailedDate.get())
values.put(TimelineTable.ERROR_MESSAGE, errorMessage)
values.put(TimelineTable.SYNCED_TIMES_COUNT, syncedTimesCount.get())
values.put(TimelineTable.SYNC_FAILED_TIMES_COUNT, syncFailedTimesCount.get())
values.put(TimelineTable.DOWNLOADED_ITEMS_COUNT, downloadedItemsCount.get())
values.put(TimelineTable.NEW_ITEMS_COUNT, newItemsCount.get())
values.put(TimelineTable.COUNT_SINCE, countSince.get())
values.put(TimelineTable.SYNCED_TIMES_COUNT_TOTAL, syncedTimesCountTotal.get())
values.put(TimelineTable.SYNC_FAILED_TIMES_COUNT_TOTAL, syncFailedTimesCountTotal.get())
values.put(TimelineTable.DOWNLOADED_ITEMS_COUNT_TOTAL, downloadedItemsCountTotal.get())
values.put(TimelineTable.NEW_ITEMS_COUNT_TOTAL, newItemsCountTotal.get())
values.put(TimelineTable.YOUNGEST_POSITION, youngestPosition)
values.put(TimelineTable.YOUNGEST_ITEM_DATE, youngestItemDate)
values.put(TimelineTable.YOUNGEST_SYNCED_DATE, youngestSyncedDate)
values.put(TimelineTable.OLDEST_POSITION, oldestPosition)
values.put(TimelineTable.OLDEST_ITEM_DATE, oldestItemDate)
values.put(TimelineTable.OLDEST_SYNCED_DATE, oldestSyncedDate)
values.put(TimelineTable.VISIBLE_ITEM_ID, visibleItemId)
values.put(TimelineTable.VISIBLE_Y, visibleY)
values.put(TimelineTable.VISIBLE_OLDEST_DATE, visibleOldestDate)
if (lastChangedDate > 0) values.put(TimelineTable.LAST_CHANGED_DATE, lastChangedDate)
}
fun fromSearch(myContext: MyContext, globalSearch: Boolean): Timeline {
return if (globalSearch) myContext.timelines.get(TimelineType.SEARCH, actor, origin, searchQuery) else this
}
fun fromIsCombined(myContext: MyContext, isCombinedNew: Boolean): Timeline =
if (isCombined == isCombinedNew || !isCombined && timelineType.isForUser() && !timelineType.isAtOrigin()
&& actor.user.isMyUser != TriState.TRUE
) this
else myContext.timelines.get(
timelineType,
if (isCombinedNew) Actor.EMPTY else myContext.accounts.currentAccount.actor,
if (isCombinedNew) Origin.EMPTY else myContext.accounts.currentAccount.origin,
searchQuery
)
fun fromMyAccount(myContext: MyContext, myAccountNew: MyAccount): Timeline =
if (isCombined || myAccountToSync == myAccountNew || timelineType.isForUser() &&
!timelineType.isAtOrigin() && actor.user.isMyUser != TriState.TRUE
) this
else myContext.timelines.get(
timelineType,
myAccountNew.actor,
myAccountNew.origin, searchQuery
)
override val isEmpty: Boolean
get() {
return timelineType == TimelineType.UNKNOWN
}
fun isValid(): Boolean {
return timelineType != TimelineType.UNKNOWN
}
fun getId(): Long {
return id
}
fun getOrigin(): Origin {
return origin
}
fun preferredOrigin(): Origin {
return if (origin.nonEmpty) origin else if (actor.nonEmpty) actor.toHomeOrigin().origin else myContext.accounts.currentAccount.origin
}
fun checkBoxDisplayedInSelector(): Boolean {
return isDisplayedInSelector != DisplayedInSelector.NEVER
}
fun isDisplayedInSelector(): DisplayedInSelector {
return isDisplayedInSelector
}
fun setDisplayedInSelector(displayedInSelector: DisplayedInSelector) {
if (isDisplayedInSelector != displayedInSelector) {
isDisplayedInSelector = displayedInSelector
setChanged()
}
}
fun getSelectorOrder(): Long {
return selectorOrder
}
fun setSelectorOrder(selectorOrder: Long) {
if (this.selectorOrder != selectorOrder) {
setChanged()
this.selectorOrder = selectorOrder
}
}
fun save(myContext: MyContext): Timeline {
if (AsyncUtil.isUiThread) return this
if (needToLoadActorInTimeline()) {
setChanged()
}
if (timelineType.isPersistable() && (id == 0L || changed) && myContext.isReady) {
val isNew = id == 0L
if (isNew) {
val duplicatedId = findDuplicateInDatabase(myContext)
if (duplicatedId != 0L) {
MyLog.i(this, "Found duplicating timeline, id=$duplicatedId for $this")
return myContext.timelines.fromId(duplicatedId)
}
if (isAddedByDefault()) {
setDisplayedInSelector(DisplayedInSelector.IN_CONTEXT)
setSyncedAutomatically(timelineType.isSyncedAutomaticallyByDefault())
}
}
if (selectorOrder == 0L) {
selectorOrder = getDefaultSelectorOrder()
}
saveInternal(myContext)
if (isNew && id != 0L) {
return myContext.timelines.fromId(id)
}
}
return this
}
private fun findDuplicateInDatabase(myContext: MyContext): Long {
val where = SqlWhere()
where.append(TimelineTable.TIMELINE_TYPE + "='" + timelineType.save() + "'")
where.append(TimelineTable.ORIGIN_ID + "=" + origin.id)
where.append(TimelineTable.ACTOR_ID + "=" + actor.actorId)
where.append(TimelineTable.SEARCH_QUERY + "='" + searchQuery + "'")
return MyQuery.conditionToLongColumnValue(
myContext.database,
"findDuplicateInDatabase",
TimelineTable.TABLE_NAME,
BaseColumns._ID,
where.getCondition())
}
private fun saveInternal(myContext: MyContext): Long {
if (needToLoadActorInTimeline()) {
actorInTimeline = MyQuery.actorIdToName(myContext, actor.actorId, MyPreferences.getActorInTimeline())
}
val contentValues = ContentValues()
toContentValues(contentValues)
if (myContext.isTestRun) {
MyLog.v(this) { "Saving $this" }
}
if (getId() == 0L) {
DbUtils.addRowWithRetry(myContext, TimelineTable.TABLE_NAME, contentValues, 3)
.onSuccess { idAdded: Long ->
id = idAdded
changed = false
}
} else {
DbUtils.updateRowWithRetry(myContext, TimelineTable.TABLE_NAME, getId(), contentValues, 3)
.onSuccess { changed = false }
}
return getId()
}
private fun needToLoadActorInTimeline(): Boolean {
return (actor.nonEmpty
&& StringUtil.isEmptyOrTemp(actorInTimeline)
&& actor.user.isMyUser.untrue)
}
fun delete(myContext: MyContext) {
if (isRequired() && myContext.timelines.stream().noneMatch { that: Timeline -> duplicates(that) }) {
MyLog.d(this, "Cannot delete required timeline: $this")
return
}
val db = myContext.database
if (db == null) {
MyLog.d(this, "delete; Database is unavailable")
} else {
val sql = "DELETE FROM " + TimelineTable.TABLE_NAME + " WHERE _ID=" + getId()
db.execSQL(sql)
MyLog.v(this) { "Timeline deleted: $this" }
}
}
fun isAddedByDefault(): Boolean {
if (isRequired()) return true
if (isCombined || !isValid() || hasSearchQuery()) return false
return if (timelineType.isAtOrigin()) {
(TimelineType.getDefaultOriginTimelineTypes().contains(timelineType)
&& (origin.originType.isTimelineTypeSyncable(timelineType)
|| timelineType == TimelineType.EVERYTHING))
} else {
actor.user.isMyUser.isTrue && actor.getDefaultMyAccountTimelineTypes().contains(timelineType)
}
}
/** Required timeline cannot be deleted */
fun isRequired(): Boolean {
return isCombined && timelineType.isCombinedRequired() && !hasSearchQuery()
}
override fun toString(): String {
val builder = MyStringBuilder()
if (timelineType.isAtOrigin()) {
builder.withComma(if (origin.isValid) origin.name else "(all origins)")
}
if (timelineType.isForUser()) {
if (actor.isEmpty) {
builder.withComma("(all accounts)")
} else if (actor.user.isMyUser.isTrue && myAccountToSync.isValid) {
builder.withComma("account", myAccountToSync.getAccountName())
if (myAccountToSync.origin != origin && origin.isValid) {
builder.withComma("origin", origin.name)
}
} else {
builder.withComma(actor.user.toString())
}
}
if (timelineType != TimelineType.UNKNOWN) {
builder.withComma("type", timelineType.save())
}
if (actorInTimeline.isNotEmpty()) {
builder.withCommaQuoted("actor", actorInTimeline, true)
} else if (actor.nonEmpty) {
builder.withComma("actor$actor")
}
if (hasSearchQuery()) {
builder.withCommaQuoted("search", getSearchQuery(), true)
}
if (id != 0L) {
builder.withComma("id", id)
}
if (!isSyncable()) {
builder.withComma("not syncable")
}
return builder.toKeyValue("Timeline")
}
fun positionsToString(): String {
val builder = StringBuilder()
builder.append("TimelinePositions{")
if (youngestSyncedDate > RelativeTime.SOME_TIME_AGO) {
builder.append("synced at " + Date(youngestSyncedDate).toString())
builder.append(", pos:" + getYoungestPosition())
}
if (oldestSyncedDate > RelativeTime.SOME_TIME_AGO) {
builder.append("older synced at " + Date(oldestSyncedDate).toString())
builder.append(", pos:" + getOldestPosition())
}
builder.append('}')
return builder.toString()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other !is Timeline) return false
if (timelineType != other.timelineType) return false
if (id != 0L || other.id != 0L) {
return id == other.id
}
if (origin != other.origin) return false
return if (actor != other.actor) false else StringUtil.equalsNotEmpty(searchQuery, other.searchQuery)
}
fun duplicates(that: Timeline): Boolean {
if (equals(that)) return false
if (id > 0 && id < that.id) return false
if (timelineType != that.timelineType) return false
if (origin != that.origin) return false
return if (!actor.isSame(that.actor)) false else StringUtil.equalsNotEmpty(searchQuery, that.searchQuery)
}
override fun hashCode(): Int {
var result = timelineType.hashCode()
if (id != 0L) result = 31 * result + java.lang.Long.hashCode(id)
result = 31 * result + origin.hashCode()
result = 31 * result + actor.hashCode()
if (searchQuery.isNotEmpty()) result = 31 * result + searchQuery.hashCode()
return result
}
fun getActorId(): Long {
return actor.actorId
}
fun hasSearchQuery(): Boolean {
return getSearchQuery().isNotEmpty()
}
fun getSearchQuery(): String {
return searchQuery
}
fun toBundle(bundle: Bundle) {
BundleUtils.putNotZero(bundle, IntentExtra.TIMELINE_ID, id)
if (timelineType != TimelineType.UNKNOWN) {
bundle.putString(IntentExtra.TIMELINE_TYPE.key, timelineType.save())
}
BundleUtils.putNotZero(bundle, IntentExtra.ORIGIN_ID, origin.id)
BundleUtils.putNotZero(bundle, IntentExtra.ACTOR_ID, actor.actorId)
BundleUtils.putNotEmpty(bundle, IntentExtra.SEARCH_QUERY, searchQuery)
}
/**
* @return true if it's time to auto update this timeline
*/
fun isTimeToAutoSync(): Boolean {
if (System.currentTimeMillis() - getLastSyncedDate() < MIN_RETRY_PERIOD_MS) {
return false
}
val syncFrequencyMs = myAccountToSync.getEffectiveSyncFrequencyMillis()
// This correction needs to take into account
// that we stored time when sync ended, and not when Android initiated the sync.
val correctionForExecutionTime = syncFrequencyMs / 10
val passedMs = System.currentTimeMillis() - getLastSyncedDate()
val blnOut = passedMs > syncFrequencyMs - correctionForExecutionTime
MyLog.v(this) {
"It's time to auto update " + this +
". " +
TimeUnit.MILLISECONDS.toMinutes(passedMs) +
" minutes passed."
}
return blnOut
}
fun forgetPositionsAndDates() {
if (youngestPosition.isNotEmpty()) {
youngestPosition = ""
setChanged()
}
if (youngestItemDate > 0) {
youngestItemDate = 0
setChanged()
}
if (youngestSyncedDate > 0) {
youngestSyncedDate = 0
setChanged()
}
if (oldestPosition.isNotEmpty()) {
oldestPosition = ""
setChanged()
}
if (oldestItemDate > 0) {
oldestItemDate = 0
setChanged()
}
if (oldestSyncedDate > 0) {
oldestSyncedDate = 0
setChanged()
}
setSyncSucceededDate(0)
if (syncFailedDate.get() > 0) {
syncFailedDate.set(0)
setChanged()
}
}
fun onNewMsg(newDate: Long, youngerPosition: String?, olderPosition: String?) {
if (newDate <= RelativeTime.SOME_TIME_AGO) return
if (!youngerPosition.isNullOrEmpty() && (youngestItemDate < newDate ||
youngestItemDate == newDate && StringUtil.isNewFilledValue(youngestPosition, youngerPosition))) {
youngestItemDate = newDate
youngestPosition = youngerPosition
setChanged()
}
if (!olderPosition.isNullOrEmpty() && (oldestItemDate <= RelativeTime.SOME_TIME_AGO || oldestItemDate > newDate ||
oldestItemDate == newDate && StringUtil.isNewFilledValue(oldestPosition, olderPosition))) {
oldestItemDate = newDate
oldestPosition = olderPosition
setChanged()
}
}
fun getYoungestPosition(): String {
return youngestPosition
}
fun getYoungestItemDate(): Long {
return youngestItemDate
}
fun getYoungestSyncedDate(): Long {
return youngestSyncedDate
}
fun setYoungestSyncedDate(newDate: Long) {
if (newDate > RelativeTime.SOME_TIME_AGO && youngestSyncedDate < newDate) {
youngestSyncedDate = newDate
setChanged()
}
}
fun getOldestItemDate(): Long {
return oldestItemDate
}
fun getOldestPosition(): String {
return oldestPosition
}
fun getOldestSyncedDate(): Long {
return oldestSyncedDate
}
fun setOldestSyncedDate(newDate: Long) {
if (newDate > RelativeTime.SOME_TIME_AGO && (oldestSyncedDate <= RelativeTime.SOME_TIME_AGO || oldestSyncedDate > newDate)) {
oldestSyncedDate = newDate
setChanged()
}
}
fun getVisibleItemId(): Long {
return visibleItemId
}
fun setVisibleItemId(visibleItemId: Long) {
if (this.visibleItemId != visibleItemId) {
setChanged()
this.visibleItemId = visibleItemId
}
}
fun getVisibleY(): Int {
return visibleY
}
fun setVisibleY(visibleY: Int) {
if (this.visibleY != visibleY) {
setChanged()
this.visibleY = visibleY
}
}
fun getVisibleOldestDate(): Long {
return visibleOldestDate
}
fun setVisibleOldestDate(visibleOldestDate: Long) {
if (this.visibleOldestDate != visibleOldestDate) {
setChanged()
this.visibleOldestDate = visibleOldestDate
}
}
fun isSyncedAutomatically(): Boolean {
return isSyncedAutomatically
}
fun setSyncedAutomatically(isSyncedAutomatically: Boolean) {
if (this.isSyncedAutomatically != isSyncedAutomatically && isSyncableAutomatically()) {
this.isSyncedAutomatically = isSyncedAutomatically
setChanged()
}
}
fun isChanged(): Boolean {
return changed
}
fun cloneForAccount(myContext: MyContext, ma: MyAccount): Timeline {
return myContext.timelines.get(0, timelineType, ma.actor, Origin.EMPTY, getSearchQuery())
}
fun cloneForOrigin(myContext: MyContext, origin: Origin): Timeline {
return myContext.timelines.get(0, timelineType, Actor.EMPTY, origin, getSearchQuery())
}
fun onSyncEnded(myContext: MyContext, result: CommandResult) {
onSyncEnded(result).save(myContext)
myContext.timelines.stream()
.filter { obj: Timeline -> obj.isSyncable() }
.filter { timeline: Timeline -> isSyncedSimultaneously(timeline) }
.forEach { timeline: Timeline -> timeline.onSyncedSimultaneously(this).save(myContext) }
}
private fun onSyncedSimultaneously(other: Timeline): Timeline {
if (setIfLess(syncFailedDate, other.syncFailedDate)) {
errorMessage = other.errorMessage
}
setIfLess(syncFailedTimesCount, other.syncFailedTimesCount)
setIfLess(syncFailedTimesCountTotal, other.syncFailedTimesCountTotal)
setIfLess(syncSucceededDate, other.syncSucceededDate)
setIfLess(syncedTimesCount, other.syncedTimesCount)
setIfLess(syncedTimesCountTotal, other.syncedTimesCountTotal)
setIfLess(newItemsCount, other.newItemsCount)
setIfLess(newItemsCountTotal, other.newItemsCountTotal)
setIfLess(downloadedItemsCount, other.downloadedItemsCount)
setIfLess(downloadedItemsCountTotal, other.downloadedItemsCountTotal)
onNewMsg(other.youngestItemDate, other.youngestPosition, "")
onNewMsg(other.oldestItemDate, "", other.oldestPosition)
setYoungestSyncedDate(other.youngestSyncedDate)
setOldestSyncedDate(other.oldestSyncedDate)
return this
}
private fun isSyncedSimultaneously(timeline: Timeline): Boolean {
return (this != timeline &&
!timeline.isCombined &&
timelineType.connectionApiRoutine == timeline.timelineType.connectionApiRoutine &&
searchQuery == timeline.searchQuery &&
myAccountToSync == timeline.myAccountToSync &&
actor == timeline.actor &&
origin == timeline.origin)
}
private fun onSyncEnded(result: CommandResult): Timeline {
if (result.hasError()) {
syncFailedDate.set(System.currentTimeMillis())
if (result.getMessage().isNotEmpty()) {
errorMessage = result.getMessage()
}
syncFailedTimesCount.incrementAndGet()
syncFailedTimesCountTotal.incrementAndGet()
} else {
syncSucceededDate.set(System.currentTimeMillis())
syncedTimesCount.incrementAndGet()
syncedTimesCountTotal.incrementAndGet()
}
if (result.getNewCount() > 0) {
newItemsCount.addAndGet(result.getNewCount())
newItemsCountTotal.addAndGet(result.getNewCount())
}
if (result.getDownloadedCount() > 0) {
downloadedItemsCount.addAndGet(result.getDownloadedCount())
downloadedItemsCountTotal.addAndGet(result.getDownloadedCount())
}
setChanged()
return this
}
fun getSyncSucceededDate(): Long {
return syncSucceededDate.get()
}
fun setSyncSucceededDate(syncSucceededDate: Long) {
if (this.syncSucceededDate.get() != syncSucceededDate) {
this.syncSucceededDate.set(syncSucceededDate)
setChanged()
}
}
fun isSynableSomehow(): Boolean {
return isSyncable || isSyncableForOrigins() || isSyncableForAccounts()
}
fun isSyncable(): Boolean {
return isSyncable
}
fun isSyncableAutomatically(): Boolean {
return isSyncableAutomatically
}
fun isSyncableForAccounts(): Boolean {
return isSyncableForAccounts
}
fun isSyncableForOrigins(): Boolean {
return isSyncableForOrigins
}
fun isSyncedByOtherUser(): Boolean {
return actor.isEmpty || myAccountToSync.actor.notSameUser(actor)
}
fun getDownloadedItemsCount(isTotal: Boolean): Long {
return if (isTotal) downloadedItemsCountTotal.get() else downloadedItemsCount.get()
}
fun getNewItemsCount(isTotal: Boolean): Long {
return if (isTotal) newItemsCountTotal.get() else newItemsCount.get()
}
fun getSyncedTimesCount(isTotal: Boolean): Long {
return if (isTotal) syncedTimesCountTotal.get() else syncedTimesCount.get()
}
fun getSyncFailedDate(): Long {
return syncFailedDate.get()
}
fun getSyncFailedTimesCount(isTotal: Boolean): Long {
return if (isTotal) syncFailedTimesCountTotal.get() else syncFailedTimesCount.get()
}
fun getErrorMessage(): String? {
return errorMessage
}
fun getLastSyncedDate(): Long {
return java.lang.Long.max(getSyncSucceededDate(), getSyncFailedDate())
}
fun getActorInTimeline(): String {
return if (actorInTimeline.isEmpty()) {
if (needToLoadActorInTimeline()) {
"..."
} else {
actor.user.getKnownAs()
}
} else {
actorInTimeline
}
}
fun resetCounters(all: Boolean) {
if (all) {
syncFailedTimesCountTotal.set(0)
syncedTimesCountTotal.set(0)
downloadedItemsCountTotal.set(0)
newItemsCountTotal.set(0)
}
errorMessage = ""
syncFailedTimesCount.set(0)
syncedTimesCount.set(0)
downloadedItemsCount.set(0)
newItemsCount.set(0)
countSince.set(System.currentTimeMillis())
changed = true
}
fun getCountSince(): Long {
return countSince.get()
}
fun getUri(): Uri {
return MatchedUri.getTimelineUri(this)
}
fun getClickUri(): Uri {
return Uri.parse("content://" + TIMELINE_CLICK_HOST + getUri().getEncodedPath())
}
private fun setChanged() {
changed = true
lastChangedDate = System.currentTimeMillis()
}
fun getLastChangedDate(): Long {
return lastChangedDate
}
fun match(isForSelector: Boolean, isTimelineCombined: TriState, timelineType: TimelineType,
actor: Actor, origin: Origin): Boolean {
if (isForSelector && isDisplayedInSelector() == DisplayedInSelector.ALWAYS) {
return true
} else if (isForSelector && isDisplayedInSelector() == DisplayedInSelector.NEVER) {
return false
} else if (timelineType != TimelineType.UNKNOWN && timelineType != this.timelineType) {
return false
} else if (isTimelineCombined == TriState.TRUE) {
return isCombined
} else if (isTimelineCombined == TriState.FALSE && isCombined) {
return false
} else if (timelineType == TimelineType.UNKNOWN || timelineType.scope == ListScope.ACTOR_AT_ORIGIN) {
return ((actor.actorId == 0L || actor.actorId == getActorId())
&& (origin.isEmpty || origin == getOrigin()))
} else if (timelineType.isAtOrigin()) {
return origin.isEmpty || origin == getOrigin()
}
return actor.actorId == 0L || actor.actorId == getActorId()
}
fun hasActorProfile(): Boolean {
return !isCombined && actor.nonEmpty && timelineType.hasActorProfile()
}
fun orElse(aDefault: Timeline): Timeline {
return if (isEmpty) aDefault else this
}
companion object {
val EMPTY: Timeline = Timeline()
private val MIN_RETRY_PERIOD_MS = TimeUnit.SECONDS.toMillis(30)
const val TIMELINE_CLICK_HOST: String = "timeline.app.andstatus.org"
fun fromCursor(myContext: MyContext, cursor: Cursor): Timeline {
val timeline = Timeline(
myContext,
DbUtils.getLong(cursor, BaseColumns._ID),
TimelineType.load(DbUtils.getString(cursor, TimelineTable.TIMELINE_TYPE)),
Actor.load(myContext, DbUtils.getLong(cursor, TimelineTable.ACTOR_ID)),
myContext.origins.fromId(DbUtils.getLong(cursor, TimelineTable.ORIGIN_ID)),
DbUtils.getString(cursor, TimelineTable.SEARCH_QUERY),
DbUtils.getLong(cursor, TimelineTable.SELECTOR_ORDER))
timeline.changed = false
timeline.actorInTimeline = DbUtils.getString(cursor, TimelineTable.ACTOR_IN_TIMELINE)
timeline.setSyncedAutomatically(DbUtils.getBoolean(cursor, TimelineTable.IS_SYNCED_AUTOMATICALLY))
timeline.isDisplayedInSelector = DisplayedInSelector.load(DbUtils.getString(cursor, TimelineTable.DISPLAYED_IN_SELECTOR))
timeline.syncSucceededDate.set(DbUtils.getLong(cursor, TimelineTable.SYNC_SUCCEEDED_DATE))
timeline.syncFailedDate.set(DbUtils.getLong(cursor, TimelineTable.SYNC_FAILED_DATE))
timeline.errorMessage = DbUtils.getString(cursor, TimelineTable.ERROR_MESSAGE)
timeline.syncedTimesCount.set(DbUtils.getLong(cursor, TimelineTable.SYNCED_TIMES_COUNT))
timeline.syncFailedTimesCount.set(DbUtils.getLong(cursor, TimelineTable.SYNC_FAILED_TIMES_COUNT))
timeline.downloadedItemsCount.set(DbUtils.getLong(cursor, TimelineTable.DOWNLOADED_ITEMS_COUNT))
timeline.newItemsCount.set(DbUtils.getLong(cursor, TimelineTable.NEW_ITEMS_COUNT))
timeline.countSince.set(DbUtils.getLong(cursor, TimelineTable.COUNT_SINCE))
timeline.syncedTimesCountTotal.set(DbUtils.getLong(cursor, TimelineTable.SYNCED_TIMES_COUNT_TOTAL))
timeline.syncFailedTimesCountTotal.set(DbUtils.getLong(cursor, TimelineTable.SYNC_FAILED_TIMES_COUNT_TOTAL))
timeline.downloadedItemsCountTotal.set(DbUtils.getLong(cursor, TimelineTable.DOWNLOADED_ITEMS_COUNT_TOTAL))
timeline.newItemsCountTotal.set(DbUtils.getLong(cursor, TimelineTable.NEW_ITEMS_COUNT_TOTAL))
timeline.youngestPosition = DbUtils.getString(cursor, TimelineTable.YOUNGEST_POSITION)
timeline.youngestItemDate = DbUtils.getLong(cursor, TimelineTable.YOUNGEST_ITEM_DATE)
timeline.youngestSyncedDate = DbUtils.getLong(cursor, TimelineTable.YOUNGEST_SYNCED_DATE)
timeline.oldestPosition = DbUtils.getString(cursor, TimelineTable.OLDEST_POSITION)
timeline.oldestItemDate = DbUtils.getLong(cursor, TimelineTable.OLDEST_ITEM_DATE)
timeline.oldestSyncedDate = DbUtils.getLong(cursor, TimelineTable.OLDEST_SYNCED_DATE)
timeline.visibleItemId = DbUtils.getLong(cursor, TimelineTable.VISIBLE_ITEM_ID)
timeline.visibleY = DbUtils.getInt(cursor, TimelineTable.VISIBLE_Y)
timeline.visibleOldestDate = DbUtils.getLong(cursor, TimelineTable.VISIBLE_OLDEST_DATE)
timeline.lastChangedDate = DbUtils.getLong(cursor, TimelineTable.LAST_CHANGED_DATE)
return timeline
}
fun fromBundle(myContext: MyContext, bundle: Bundle?): Timeline {
if (bundle == null) return EMPTY
val timeline = myContext.timelines.fromId(bundle.getLong(IntentExtra.TIMELINE_ID.key))
return if (timeline.nonEmpty) timeline
else myContext.timelines[TimelineType.load(bundle.getString(IntentExtra.TIMELINE_TYPE.key)),
Actor.load(myContext, bundle.getLong(IntentExtra.ACTOR_ID.key)),
myContext.origins.fromId(BundleUtils.fromBundle(bundle, IntentExtra.ORIGIN_ID)),
BundleUtils.getString(bundle, IntentExtra.SEARCH_QUERY)]
}
fun fromParsedUri(myContext: MyContext, parsedUri: ParsedUri, searchQueryIn: String?): Timeline {
val timeline = myContext.timelines[parsedUri.getTimelineType(), Actor.load(myContext,
parsedUri.getActorId()), parsedUri.getOrigin(myContext),
if (searchQueryIn.isNullOrEmpty()) parsedUri.searchQuery else searchQueryIn]
if (timeline.timelineType == TimelineType.UNKNOWN && parsedUri.getActorsScreenType() == ActorsScreenType.UNKNOWN) {
MyLog.w(Timeline::class.java, "fromParsedUri; uri:" + parsedUri.getUri() + "; " + timeline)
}
return timeline
}
fun fromId(myContext: MyContext, id: Long): Timeline {
return if (id == 0L) EMPTY else MyQuery.get(myContext,
"SELECT * FROM " + TimelineTable.TABLE_NAME + " WHERE " + BaseColumns._ID + "=" + id
) { cursor: Cursor -> fromCursor(myContext, cursor) }.stream().findFirst().orElse(EMPTY)
}
private fun setIfLess(value: AtomicLong, other: AtomicLong): Boolean {
if (value.get() < other.get()) {
value.set(other.get())
return true
}
return false
}
}
}
| apache-2.0 | c3b182d296a30fd198b8bb28cf219824 | 38.96332 | 141 | 0.653109 | 4.716564 | false | false | false | false |
TUWien/DocScan | app/src/main/java/at/ac/tuwien/caa/docscan/ui/segmentation/ImageUtils.kt | 1 | 8922 | /*
* Copyright 2019 Google LLC
*
* 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
*
* https://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 at.ac.tuwien.caa.docscan.ui.segmentation
import android.graphics.*
import androidx.exifinterface.media.ExifInterface
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* Collection of image reading and manipulation utilities in the form of static functions.
* TODO: Most of this functions are duplicated.
*/
abstract class ImageUtils {
companion object {
/**
* Helper function used to convert an EXIF orientation enum into a transformation matrix
* that can be applied to a bitmap.
*
* @param orientation - One of the constants from [ExifInterface]
*/
private fun decodeExifOrientation(orientation: Int): Matrix {
val matrix = Matrix()
// Apply transformation corresponding to declared EXIF orientation
when (orientation) {
ExifInterface.ORIENTATION_NORMAL, ExifInterface.ORIENTATION_UNDEFINED -> Unit
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90F)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180F)
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270F)
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.postScale(-1F, 1F)
ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.postScale(1F, -1F)
ExifInterface.ORIENTATION_TRANSPOSE -> {
matrix.postScale(-1F, 1F)
matrix.postRotate(270F)
}
ExifInterface.ORIENTATION_TRANSVERSE -> {
matrix.postScale(-1F, 1F)
matrix.postRotate(90F)
}
// Error out if the EXIF orientation is invalid
else -> throw IllegalArgumentException("Invalid orientation: $orientation")
}
// Return the resulting matrix
return matrix
}
/**
* sets the Exif orientation of an image.
* this method is used to fix the exit of pictures taken by the camera
*
* @param filePath - The image file to change
* @param value - the orientation of the file
*/
fun setExifOrientation(
filePath: String,
value: String
) {
val exif = ExifInterface(filePath)
exif.setAttribute(
ExifInterface.TAG_ORIENTATION, value
)
exif.saveAttributes()
}
/** Transforms rotation and mirroring information into one of the [ExifInterface] constants */
fun computeExifOrientation(rotationDegrees: Int, mirrored: Boolean) = when {
rotationDegrees == 0 && !mirrored -> ExifInterface.ORIENTATION_NORMAL
rotationDegrees == 0 && mirrored -> ExifInterface.ORIENTATION_FLIP_HORIZONTAL
rotationDegrees == 180 && !mirrored -> ExifInterface.ORIENTATION_ROTATE_180
rotationDegrees == 180 && mirrored -> ExifInterface.ORIENTATION_FLIP_VERTICAL
rotationDegrees == 270 && mirrored -> ExifInterface.ORIENTATION_TRANSVERSE
rotationDegrees == 90 && !mirrored -> ExifInterface.ORIENTATION_ROTATE_90
rotationDegrees == 90 && mirrored -> ExifInterface.ORIENTATION_TRANSPOSE
rotationDegrees == 270 && mirrored -> ExifInterface.ORIENTATION_ROTATE_270
rotationDegrees == 270 && !mirrored -> ExifInterface.ORIENTATION_TRANSVERSE
else -> ExifInterface.ORIENTATION_UNDEFINED
}
/**
* Decode a bitmap from a file and apply the transformations described in its EXIF data
*
* @param file - The image file to be read using [BitmapFactory.decodeFile]
*/
fun decodeBitmap(file: File): Bitmap {
// First, decode EXIF data and retrieve transformation matrix
val exif = ExifInterface(file.absolutePath)
val transformation =
decodeExifOrientation(
exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_ROTATE_90
)
)
// Read bitmap using factory methods, and transform it using EXIF data
val options = BitmapFactory.Options()
val bitmap = BitmapFactory.decodeFile(file.absolutePath, options)
return Bitmap.createBitmap(
BitmapFactory.decodeFile(file.absolutePath),
0, 0, bitmap.width, bitmap.height, transformation, true
)
}
fun scaleBitmapAndKeepRatio(
targetBmp: Bitmap,
reqHeightInPixels: Int,
reqWidthInPixels: Int
): Bitmap {
if (targetBmp.height == reqHeightInPixels && targetBmp.width == reqWidthInPixels) {
return targetBmp
}
val matrix = Matrix()
matrix.setRectToRect(
RectF(
0f, 0f,
targetBmp.height.toFloat(),
targetBmp.width.toFloat()
),
RectF(
0f, 0f,
reqHeightInPixels.toFloat(),
reqWidthInPixels.toFloat()
),
Matrix.ScaleToFit.CENTER
)
val scaled = Bitmap.createBitmap(
targetBmp,
0,
0,
targetBmp.width,
targetBmp.height,
matrix,
true
)
val background =
Bitmap.createBitmap(reqWidthInPixels, reqHeightInPixels, Bitmap.Config.ARGB_8888)
val canvas = Canvas(background)
// apply black background
canvas.drawColor(Color.BLACK);
// val newScaled = if(scaled.width > reqWidthInPixels){
// Bitmap.createScaledBitmap(scaled)
// }else if(scaled.height > reqHeightInPixels){
//
// }
var left = 0F
var top = 0F
if (scaled.height < background.height) {
left = 0F
top = (background.height / 2F) - (scaled.height / 2F)
}
if (scaled.width < background.width) {
left = (background.width / 2F) - (scaled.width / 2F)
top = 0F
}
canvas.drawBitmap(scaled, left, top, null)
return background
}
/**
* Pre-Conditions:
* - width and height of [bitmap] both equals to [size]
*
* @return a byte buffer holding the quantized (uint8) image of [bitmap]
*/
fun bitmapToByteBuffer(
bitmap: Bitmap,
size: Int
): ByteBuffer {
// alloc
val inputImage = ByteBuffer.allocateDirect(1 * size * size * 3)
inputImage.order(ByteOrder.nativeOrder())
inputImage.rewind()
val intValues = IntArray(size * size)
bitmap.getPixels(intValues, 0, size, 0, 0, size, size)
var pixel = 0
for (y in 0 until size) {
for (x in 0 until size) {
val value = intValues[pixel++]
inputImage.put((value shr 16 and 0xFF).toByte())
inputImage.put((value shr 8 and 0xFF).toByte())
inputImage.put((value and 0xFF).toByte())
}
}
inputImage.rewind()
return inputImage
}
fun convertByteBufferMaskToBitmap(
tensorOutputBufferuint32: ByteBuffer,
size: Int,
colors: IntArray
): Bitmap {
val maskBitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
tensorOutputBufferuint32.rewind()
// loop through all pixels
for (y in 0 until size) {
for (x in 0 until size) {
// get class prediction for value
val value = tensorOutputBufferuint32.getInt((y * size + x) * 4)
val color = colors[value]
maskBitmap.setPixel(x, y, color)
}
}
return maskBitmap
}
}
}
| lgpl-3.0 | 940fa8e8799e10960ece6b093176fb38 | 36.805085 | 102 | 0.561982 | 5.294955 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/orders/dto/OrdersSubscription.kt | 1 | 3579 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.orders.dto
import com.google.gson.annotations.SerializedName
import kotlin.Boolean
import kotlin.Int
import kotlin.String
/**
* @param createTime - Date of creation in Unixtime
* @param id - Subscription ID
* @param itemId - Subscription order item
* @param period - Subscription period
* @param periodStartTime - Date of last period start in Unixtime
* @param price - Subscription price
* @param status - Subscription status
* @param updateTime - Date of last change in Unixtime
* @param cancelReason - Cancel reason
* @param nextBillTime - Date of next bill in Unixtime
* @param expireTime - Subscription expiration time in Unixtime
* @param pendingCancel - Pending cancel state
* @param title - Subscription name
* @param appId - Subscription's application id
* @param applicationName - Subscription's application name
* @param photoUrl - Item photo image url
* @param testMode - Is test subscription
* @param trialExpireTime - Date of trial expire in Unixtime
*/
data class OrdersSubscription(
@SerializedName("create_time")
val createTime: Int,
@SerializedName("id")
val id: Int,
@SerializedName("item_id")
val itemId: String,
@SerializedName("period")
val period: Int,
@SerializedName("period_start_time")
val periodStartTime: Int,
@SerializedName("price")
val price: Int,
@SerializedName("status")
val status: String,
@SerializedName("update_time")
val updateTime: Int,
@SerializedName("cancel_reason")
val cancelReason: String? = null,
@SerializedName("next_bill_time")
val nextBillTime: Int? = null,
@SerializedName("expire_time")
val expireTime: Int? = null,
@SerializedName("pending_cancel")
val pendingCancel: Boolean? = null,
@SerializedName("title")
val title: String? = null,
@SerializedName("app_id")
val appId: Int? = null,
@SerializedName("application_name")
val applicationName: String? = null,
@SerializedName("photo_url")
val photoUrl: String? = null,
@SerializedName("test_mode")
val testMode: Boolean? = null,
@SerializedName("trial_expire_time")
val trialExpireTime: Int? = null
)
| mit | 4162f2d6c0a6b4ba79a780174bdd83ec | 37.902174 | 81 | 0.69321 | 4.434944 | false | false | false | false |
Etik-Tak/backend | src/main/kotlin/dk/etiktak/backend/model/infosource/InfoSource.kt | 1 | 2879 | // Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, 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 conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not 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 OWNER 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.
/**
* Represents a info source that can be referenced by recommendations.
*/
package dk.etiktak.backend.model.infosource
import dk.etiktak.backend.model.BaseModel
import org.springframework.format.annotation.DateTimeFormat
import java.util.*
import javax.persistence.*
import javax.validation.constraints.NotNull
@Entity(name = "info_sources")
class InfoSource : BaseModel() {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "infosource_id")
var id: Long = 0
@Column(name = "uuid", nullable = false, unique = true)
var uuid: String = ""
@Column(name = "name", nullable = true)
var name: String? = null
@NotNull
@OneToMany(mappedBy = "infoSource", fetch = FetchType.LAZY)
var domains: MutableList<InfoSourceDomain> = ArrayList()
@NotNull
@OneToMany(mappedBy = "infoSource", fetch = FetchType.LAZY)
var infoSourceReferences: MutableList<InfoSourceReference> = ArrayList()
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
var creationTime = Date()
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
var modificationTime = Date()
@PreUpdate
fun preUpdate() {
modificationTime = Date()
}
@PrePersist
fun prePersist() {
val now = Date()
creationTime = now
modificationTime = now
}
}
| bsd-3-clause | baa09178184c55711225dfe2f4bd0e00 | 35.443038 | 83 | 0.728031 | 4.429231 | false | false | false | false |
campos20/tnoodle | webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/pdf/util/StringUtil.kt | 1 | 1857 | package org.worldcubeassociation.tnoodle.server.webscrambles.pdf.util
import java.security.SecureRandom
import kotlin.math.ceil
object StringUtil {
private const val INVALID_CHARS = "\\/:*?\"<>|"
// Excludes ambiguous characters: 0/O, 1/I
private const val PASSCODE_DIGIT_SET = "23456789abcdefghijkmnpqrstuvwxyz"
private const val PASSCODE_NUM_CHARS = 8
fun padTurnsUniformly(scramble: String, padding: String): String {
val maxTurnLength = scramble.split("\\s+".toRegex()).map { it.length }.maxOrNull() ?: 0
val lines = scramble.split("\\n".toRegex()).dropLastWhile { it.isEmpty() }
return lines.joinToString("\n") { line ->
val lineTurns = line.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }
lineTurns.joinToString(" ") { turn ->
// TODO - this is a disgusting hack for sq1. We don't pad the /
// turns because they're guaranteed to occur as every other turn,
// so stuff will line up nicely without padding them. I don't know
// what a good general solution to this problem is.
val missingPad = maxTurnLength - turn.length
val repetitions = ceil(missingPad.toDouble() / padding.length)
val actualPadding = padding.repeat(repetitions.toInt()).takeUnless { turn == "/" }
turn + actualPadding.orEmpty()
}
}
}
fun String.toFileSafeString() = filter { it !in INVALID_CHARS }
fun List<String>.stripNewlines() = map { it.replace("\n", " ") }
fun randomPasscode(): String {
val secureRandom = SecureRandom()
return 0.until(PASSCODE_NUM_CHARS)
.map { secureRandom.nextInt(PASSCODE_DIGIT_SET.length) }
.map { PASSCODE_DIGIT_SET[it] }
.joinToString("")
}
}
| gpl-3.0 | 17b141f276d60e16476950635cd69c52 | 38.510638 | 98 | 0.613355 | 4.359155 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/helpers/MainNavigationController.kt | 1 | 2180 | package com.habitrpg.android.habitica.helpers
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.navigation.NavController
import androidx.navigation.NavDeepLinkRequest
import androidx.navigation.NavDirections
import java.lang.ref.WeakReference
import java.util.Date
import kotlin.math.abs
object MainNavigationController {
var lastNavigation: Date? = null
private var controllerReference: WeakReference<NavController>? = null
private val navController: NavController?
get() { return controllerReference?.get() }
val isReady: Boolean
get() = controllerReference?.get() != null
fun setup(navController: NavController) {
this.controllerReference = WeakReference(navController)
}
fun navigate(transactionId: Int, args: Bundle? = null) {
if (abs((lastNavigation?.time ?: 0) - Date().time) > 500) {
lastNavigation = Date()
try {
navController?.navigate(transactionId, args)
} catch (e: IllegalArgumentException) {
Log.e("Main Navigation", e.localizedMessage ?: "")
} catch (error: Exception) {
Log.e("Main Navigation", error.localizedMessage ?: "")
}
}
}
fun navigate(directions: NavDirections) {
if (abs((lastNavigation?.time ?: 0) - Date().time) > 500) {
lastNavigation = Date()
try {
navController?.navigate(directions)
} catch (_: IllegalArgumentException) {}
}
}
fun navigate(uriString: String) {
val uri = Uri.parse(uriString)
navigate(uri)
}
fun navigate(uri: Uri) {
if (navController?.graph?.hasDeepLink(uri) == true) {
navController?.navigate(uri)
}
}
fun navigate(request: NavDeepLinkRequest) {
if (navController?.graph?.hasDeepLink(request) == true) {
navController?.navigate(request)
}
}
fun handle(deeplink: Intent) {
navController?.handleDeepLink(deeplink)
}
fun navigateBack() {
navController?.navigateUp()
}
}
| gpl-3.0 | e4e22ef4829b6826c489ad11838bdeff | 28.066667 | 73 | 0.627523 | 4.759825 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/streak/notification/StreakNotificationDelegate.kt | 1 | 8239 | package org.stepik.android.view.streak.notification
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.core.app.TaskStackBuilder
import org.stepic.droid.R
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.core.ScreenManager
import org.stepic.droid.notifications.NotificationBroadcastReceiver
import org.stepic.droid.preferences.SharedPreferenceHelper
import org.stepic.droid.util.AppConstants
import org.stepic.droid.util.DateTimeHelper
import org.stepic.droid.util.StepikUtil
import org.stepik.android.domain.user_activity.repository.UserActivityRepository
import org.stepik.android.view.notification.NotificationDelegate
import org.stepik.android.view.notification.StepikNotificationManager
import org.stepik.android.view.notification.helpers.NotificationHelper
import java.util.Calendar
import javax.inject.Inject
class StreakNotificationDelegate
@Inject
constructor(
private val context: Context,
private val analytic: Analytic,
private val userActivityRepository: UserActivityRepository,
private val screenManager: ScreenManager,
private val sharedPreferenceHelper: SharedPreferenceHelper,
private val notificationHelper: NotificationHelper,
stepikNotificationManager: StepikNotificationManager
) : NotificationDelegate("show_streak_notification", stepikNotificationManager) {
companion object {
private const val STREAK_NOTIFICATION_ID = 3214L
}
override fun onNeedShowNotification() {
if (sharedPreferenceHelper.isStreakNotificationEnabled) {
scheduleStreakNotification()
val numberOfStreakNotifications = sharedPreferenceHelper.numberOfStreakNotifications
if (numberOfStreakNotifications < AppConstants.MAX_NUMBER_OF_NOTIFICATION_STREAK) {
try {
val pins: ArrayList<Long> = userActivityRepository.getUserActivities(sharedPreferenceHelper.profile?.id ?: throw Exception("User is not auth"))
.blockingGet()
.firstOrNull()
?.pins!!
val (currentStreak, isSolvedToday) = StepikUtil.getCurrentStreakExtended(pins)
if (currentStreak <= 0) {
analytic.reportEvent(Analytic.Streak.GET_ZERO_STREAK_NOTIFICATION)
showNotificationWithoutStreakInfo(Analytic.Streak.NotificationType.zero)
} else {
// if current streak is > 0 -> streaks works! -> continue send it
// it will reset before sending, after sending it will be incremented
sharedPreferenceHelper.resetNumberOfStreakNotifications()
val bundle = Bundle()
if (isSolvedToday) {
showNotificationStreakImprovement(currentStreak)
bundle.putString(Analytic.Streak.NOTIFICATION_TYPE_PARAM, Analytic.Streak.NotificationType.solvedToday.name)
} else {
showNotificationWithStreakCallToAction(currentStreak)
bundle.putString(Analytic.Streak.NOTIFICATION_TYPE_PARAM, Analytic.Streak.NotificationType.notSolvedToday.name)
}
analytic.reportEvent(Analytic.Streak.GET_NON_ZERO_STREAK_NOTIFICATION, bundle)
}
} catch (exception: Exception) {
// no internet || cant get streaks -> show some notification without streak information.
analytic.reportEvent(Analytic.Streak.GET_NO_INTERNET_NOTIFICATION)
showNotificationWithoutStreakInfo(Analytic.Streak.NotificationType.noInternet)
return
} finally {
sharedPreferenceHelper.incrementNumberOfNotifications()
}
} else {
// too many ignored notifications about streaks
streakNotificationNumberIsOverflow()
}
}
}
fun scheduleStreakNotification() {
if (sharedPreferenceHelper.isStreakNotificationEnabled) {
// plan new alarm
val hour = sharedPreferenceHelper.timeNotificationCode
val now = DateTimeHelper.nowUtc()
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, hour)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)
var nextNotificationMillis = calendar.timeInMillis
if (nextNotificationMillis < now) {
nextNotificationMillis += AppConstants.MILLIS_IN_24HOURS
}
scheduleNotificationAt(nextNotificationMillis)
}
}
private fun showNotificationStreakImprovement(currentStreak: Int) {
val message = context.resources.getString(R.string.streak_notification_message_improvement, currentStreak)
showNotificationStreakBase(message, Analytic.Streak.NotificationType.solvedToday)
}
private fun showNotificationWithStreakCallToAction(currentStreak: Int) {
val message = context.resources.getQuantityString(R.plurals.streak_notification_message_call_to_action, currentStreak, currentStreak)
showNotificationStreakBase(message, Analytic.Streak.NotificationType.notSolvedToday)
}
private fun showNotificationWithoutStreakInfo(notificationType: Analytic.Streak.NotificationType) {
val message = context.resources.getString(R.string.streak_notification_empty_number)
showNotificationStreakBase(message, notificationType)
}
private fun showNotificationStreakBase(message: String, notificationType: Analytic.Streak.NotificationType) {
val taskBuilder: TaskStackBuilder = getStreakNotificationTaskBuilder(notificationType)
val notification = notificationHelper.makeSimpleNotificationBuilder(stepikNotification = null,
justText = message,
taskBuilder = taskBuilder,
title = context.getString(R.string.time_to_learn_notification_title),
deleteIntent = getDeleteIntentForStreaks(), id = STREAK_NOTIFICATION_ID
)
showNotification(STREAK_NOTIFICATION_ID, notification.build())
}
private fun getStreakNotificationTaskBuilder(notificationType: Analytic.Streak.NotificationType): TaskStackBuilder {
val taskBuilder: TaskStackBuilder = TaskStackBuilder.create(context)
val myCoursesIntent = screenManager.getMyCoursesIntent(context)
myCoursesIntent.action = AppConstants.OPEN_NOTIFICATION_FROM_STREAK
myCoursesIntent.putExtra(Analytic.Streak.NOTIFICATION_TYPE_PARAM, notificationType)
taskBuilder.addNextIntent(myCoursesIntent)
return taskBuilder
}
private fun streakNotificationNumberIsOverflow() {
sharedPreferenceHelper.isStreakNotificationEnabled = false
val taskBuilder: TaskStackBuilder = TaskStackBuilder.create(context)
val profileIntent = screenManager.getProfileIntent(context)
// taskBuilder.addParentStack(ProfileActivity::class.java)
taskBuilder.addParentStack(org.stepik.android.view.profile.ui.activity.ProfileActivity::class.java)
taskBuilder.addNextIntent(profileIntent)
val message = context.getString(R.string.streak_notification_not_working)
val notification = notificationHelper.makeSimpleNotificationBuilder(stepikNotification = null,
justText = message,
taskBuilder = taskBuilder,
title = context.getString(R.string.time_to_learn_notification_title), id = STREAK_NOTIFICATION_ID
)
showNotification(STREAK_NOTIFICATION_ID, notification.build())
}
private fun getDeleteIntentForStreaks(): PendingIntent {
val deleteIntent = Intent(context, NotificationBroadcastReceiver::class.java)
deleteIntent.action = AppConstants.NOTIFICATION_CANCELED_STREAK
return PendingIntent.getBroadcast(context, 0, deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT)
}
} | apache-2.0 | e006b038248249503d6cef8889c40134 | 51.151899 | 163 | 0.700085 | 5.445473 | false | false | false | false |
modmuss50/Fluxed-Redstone | src/main/kotlin/me/modmuss50/fr/network/FRNetworkHandler.kt | 1 | 3926 | package me.modmuss50.fr.network
import ic2.api.energy.EnergyNet
import ic2.api.energy.tile.IEnergyAcceptor
import ic2.api.energy.tile.IEnergyEmitter
import io.netty.buffer.ByteBuf
import me.modmuss50.fr.FluxedRedstone
import me.modmuss50.fr.mutlipart.IC2Interface
import net.minecraft.client.Minecraft
import net.minecraft.util.EnumFacing
import net.minecraft.util.math.BlockPos
import net.minecraftforge.fml.common.network.NetworkRegistry
import net.minecraftforge.fml.common.network.simpleimpl.IMessage
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext
import net.minecraftforge.fml.relauncher.Side
class FRNetworkHandler {
companion object {
val instance = NetworkRegistry.INSTANCE.newSimpleChannel("fluxedredstone")
}
fun registerPackets() {
instance.registerMessage(RequestIC2MessageHandler::class.java, MsgRequestIC2Map::class.java, 0, Side.SERVER)
instance.registerMessage(RespIC2MapHandler::class.java, MsgRespIC2Map::class.java, 1, Side.CLIENT)
}
class MsgRequestIC2Map() : IMessage {
var id = 0
lateinit var origin: BlockPos
constructor(id: Int, origin: BlockPos) : this() {
this.id = id
this.origin = origin
}
override fun fromBytes(buf: ByteBuf?) {
id = buf!!.readInt()
origin = BlockPos(buf.readInt(), buf.readInt(), buf.readInt())
}
override fun toBytes(buf: ByteBuf?) {
buf!!.writeInt(id)
buf.writeInt(origin.x)
buf.writeInt(origin.y)
buf.writeInt(origin.z)
}
}
// Sent to designate the block to the given face of the origin should be connected to.
// Server --> Client
class MsgRespIC2Map() : IMessage {
var id = 0
lateinit var machine: EnumFacing // The face relative to the origin on which the machine resides
constructor(id: Int, machine: EnumFacing) : this() {
this.id = id
this.machine = machine
}
override fun fromBytes(buf: ByteBuf?) {
id = buf!!.readInt()
machine = EnumFacing.VALUES[buf.readUnsignedByte().toInt()]
}
override fun toBytes(buf: ByteBuf?) {
buf!!.writeInt(id)
buf.writeByte(machine.ordinal)
}
}
class RequestIC2MessageHandler : IMessageHandler<MsgRequestIC2Map, IMessage> {
override fun onMessage(message: MsgRequestIC2Map?, ctx: MessageContext?): IMessage? {
val world = ctx!!.serverHandler.playerEntity.serverWorld
world.addScheduledTask {
for (rel in EnumFacing.VALUES) {
val tile = world.getTileEntity(message!!.origin.offset(rel))
if (tile != null) {
val etile = EnergyNet.instance.getTile(world, message.origin.offset(rel))
if (FluxedRedstone.ic2Interface.connectable(etile, rel.opposite)) {
instance.sendTo(MsgRespIC2Map(message.id, rel), ctx.serverHandler.playerEntity)
}
}
}
}
return null
}
}
class RespIC2MapHandler : IMessageHandler<MsgRespIC2Map, IMessage> {
override fun onMessage(message: MsgRespIC2Map?, ctx: MessageContext?): IMessage? {
Minecraft.getMinecraft().addScheduledTask {
val pipe = FluxedRedstone.ic2Interface.waiting[message!!.id]
if (pipe != null) {
if (!pipe.ic2ConnectionCache.contains(message.machine)) {
pipe.ic2ConnectionCache.add(message.machine)
pipe.checkConnections() // Don't cause an infinite loop
}
}
}
return null
}
}
} | mit | b0bff797ae39030c2374e2812c219c1a | 36.759615 | 116 | 0.620224 | 4.421171 | false | false | false | false |
MrSugarCaney/DirtyArrows | src/main/kotlin/nl/sugcube/dirtyarrows/bow/BowAbility.kt | 1 | 15090 | package nl.sugcube.dirtyarrows.bow
import nl.sugcube.dirtyarrows.Broadcast
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.util.*
import org.bukkit.GameMode
import org.bukkit.Location
import org.bukkit.Sound
import org.bukkit.configuration.file.FileConfiguration
import org.bukkit.entity.Arrow
import org.bukkit.entity.Entity
import org.bukkit.entity.LivingEntity
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.entity.ProjectileHitEvent
import org.bukkit.event.entity.ProjectileLaunchEvent
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.ItemStack
import java.util.concurrent.ConcurrentHashMap
/**
* Base for all bow abilities.
*
* * Override [effect] to execute a repeating scheduled effect every [handleEveryNTicks] ticks.
* * Override [particle] to show a particle on every applicable site.
* * Override [land] to handle when arrows shot with this bow land.
* * Override [launch] for behaviour when the player shoots arrows.
*
* The implementing class should keep track of relevant entities/other data itself.
*
* @author SugarCaney
*/
abstract class BowAbility(
/**
* The main DA plugin instance.
*/
protected val plugin: DirtyArrows,
/**
* Corresponding [DefaultBow] enum type.
*/
val type: BowType,
/**
* Must handle the effects of this ability every `handleEveryNTicks` ticks.
*/
val handleEveryNTicks: Int = 20,
/**
* Whether the bow can be used in protected regions.
*/
val canShootInProtectedRegions: Boolean = false,
/**
* How many blocks around the region the protection should still count.
* Example: bigger for the nuclear bow than for the clucky bow.
*/
val protectionRange: Double = 5.0,
/**
* What items are required for a single use.
*/
costRequirements: List<ItemStack> = emptyList(),
/**
* Whether to remove the arrow when it hit.
*/
val removeArrow: Boolean = true,
/**
* Short human readable description of the bow's effects.
*/
val description: String = ""
) : Listener, Runnable {
/**
* What items are required for a single use.
*/
var costRequirements: List<ItemStack> = costRequirements
protected set
/**
* Keeps track of the amount of ticks that have passed.
*/
protected var tickCounter = 0
private set
/**
* Set containing all arrows that have been shot with this bow.
*/
protected val arrows: MutableSet<Arrow> = HashSet()
/**
* The plugin's configuration.
*/
protected val config: FileConfiguration = plugin.config
/**
* The configuration node of the bow.
*/
protected val node = type.node
/**
* How many milliseconds of cooldown the ability has.
*/
private val cooldownTime = config.getInt("$node.cooldown").toLong()
/**
* Whether to play a sound when the recharge time expires.
*/
private val playSoundWhenRecharged = config.getBoolean("play-sound-when-charged")
/**
* Maps each player to the unix time they used this bow ability (millis).
* When a player is contained in this map, the cooldown period is active.
* When an ability has no cooldown, this map is always empty.
* Gets accessed from the scheduler (run) and the event thread (projectilel launch event) hence concurrent.
*/
private val cooldownMap = ConcurrentHashMap<Player, Long>()
/**
* Maps each entity to the items that were consumed latest by the ability.
*/
private val mostRecentItemsConsumed = HashMap<Entity, List<ItemStack>>()
/**
* Get the items that were consumed on last use.
*/
val Entity.lastConsumedItems: List<ItemStack>
get() = mostRecentItemsConsumed[this] ?: emptyList()
/**
* Executes a repeating scheduled effect every [handleEveryNTicks] ticks.
*/
open fun effect() = Unit
/**
* Shows a single particle effect on every applicable instance.
*/
open fun particle(tickNumber: Int) = Unit
/**
* Handles when a player shoots an arrow with this bow.
*
* @param player
* The player that launched the arrow.
* @param arrow
* The launched arrow.
* @param event
* The corresponding [ProjectileLaunchEvent].
*/
open fun launch(player: Player, arrow: Arrow, event: ProjectileLaunchEvent) = Unit
/**
* Executes whenever an arrow with this abilities lands.
* Only arrows that are shot with this bow, or are registered in [arrow] will get a [land] event.
* The arrow is removed from [arrow] when the arrow landed.
*
* @param arrow
* The arrow that has landed.
* @param player
* The player that shot the arrow.
* @param event
* The event that fired when the arrow landed.
*/
open fun land(arrow: Arrow, player: Player, event: ProjectileHitEvent) = Unit
override fun run() {
tickCounter++
// Only execute the effect every [handleEveryNTicks] ticks.
if (tickCounter % handleEveryNTicks == 0) {
effect()
}
// Show particles every tick.
if (plugin.config.getBoolean("show-particles")) {
particle(tickCounter)
}
removeExpiredCooldowns()
}
/**
* Removes all cooldown periods when they have expired.
*/
private fun removeExpiredCooldowns() {
val now = System.currentTimeMillis()
cooldownMap.entries.removeIf { (player, usedTime) ->
val toRemove = now - usedTime >= cooldownTime
if (toRemove) {
player.playSound(player.location, Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 10f, 1f)
}
toRemove
}
}
@EventHandler(priority = EventPriority.NORMAL)
fun eventHandlerProjectileHit(event: ProjectileHitEvent) {
val arrow = event.entity as? Arrow ?: return
val player = arrow.shooter as? Player ?: return
// Only hit arrows that are linked to this ability.
if (arrow in arrows) {
// Remove arrow beforehand, as per documentation of [land]
unregisterArrow(arrow)
// Only apply effects when the arrow does not land in a protected region.
// Give back the items if it is in a protected region as they have been removed upon launch.
if (arrow.location.isInProtectedRegion(player)) {
player.reimburseBowItems()
} else {
land(arrow, player, event)
if (removeArrow) {
arrow.remove()
}
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
fun eventHandlerLaunchProjectile(event: ProjectileLaunchEvent) {
val arrow = event.entity as? Arrow ?: return
val player = arrow.shooter as? Player ?: return
// Check if the bow can be used.
if (player.isDirtyArrowsActivated().not()) return
if (player.hasBowInHand().not()) return
if (player.hasPermission().not()) return
if (player.inCooldownPeriod()) return
if (canShootInProtectedRegions.not() && player.location.isInProtectedRegion(player)) return
if (player.meetsResourceRequirements().not()) return
// Set cooldown.
if (cooldownTime > 0) {
cooldownMap[player] = System.currentTimeMillis()
}
// All is fine, handle event.
arrows.add(arrow)
player.consumeBowItems()
launch(player, arrow, event)
}
/**
* Checks if Dirty Arrows is activated for this player.
*
* @return `true` if DA is activated, `false` if not.
*/
protected fun Player.isDirtyArrowsActivated(): Boolean {
return plugin.activationManager.isActivatedFor(this)
}
/**
* Checks if the player has the correct bow in their hand.
*
* @return `true` if the player has a bow in their hand, `false` otherwise.
*/
protected fun Player.hasBowInHand(): Boolean {
val expectedName = bowName()
return itemInMainHand.itemName == expectedName || itemInOffHand.itemName == expectedName
}
/**
* Checks if the player has the right permissions to use this bow.
*
* @param showError
* Whether to show an error if the player has no permission.
* @return `true` when the player has permission to use this bow, `false` otherwise.
*/
protected fun Player.hasPermission(showError: Boolean = true): Boolean {
val hasPermission = hasPermission([email protected])
if (showError && hasPermission.not()) {
player?.sendMessage(Broadcast.NO_BOW_PERMISSION.format(bowName()))
}
return hasPermission
}
/**
* Checks if the ability is in cooldown.
*
* @param showError
* Whether to show an error if the ability is in cooldown.
* @return `true` when the player is in cooldown, `false` otherwise.
*/
protected fun Player.inCooldownPeriod(showError: Boolean = true): Boolean {
val cooldown = player?.let { isOnCooldown(it) } ?: false
if (cooldown && showError) {
val timeLeft = cooldownTimeLeft() / 1000.0
val bowName = config.getString([email protected])?.applyColours()
player?.sendMessage(Broadcast.COOLDOWN.format(timeLeft, bowName))
}
return cooldown
}
/**
* Checks if the location is inside a protected region.
*
* @param entity
* The entity that shot the arrow.
* @param showError
* Whether to show an error to the player when they are in a protected region.
* @return `true` when the player is in a protected region, `false` otherwise.
*/
protected fun Location.isInProtectedRegion(entity: LivingEntity?, showError: Boolean = true): Boolean {
val inRegion = plugin.regionManager.isWithinARegionMargin(this, protectionRange) != null
if (showError && inRegion && canShootInProtectedRegions.not()) {
entity?.sendMessage(Broadcast.DISABLED_IN_PROTECTED_REGION.format(bowName()))
}
return inRegion
}
/**
* Checks whether the given player has all resources required to use this bow.
*
* @param showError
* Whether to show an error to the player when they don't meet
* @return `true` if the player meets the cost requirements, `false` if they don't.
*/
protected fun Player.meetsResourceRequirements(showError: Boolean = true): Boolean {
val survival = gameMode == GameMode.SURVIVAL || gameMode == GameMode.ADVENTURE
val meetsRequirements = survival.not() || costRequirements.all {
inventory.checkForItem(it)
}
if (showError && meetsRequirements.not()) {
sendMessage(Broadcast.NOT_ENOUGH_RESOURCES.format(costRequirements.joinToString(", ") {
"${it.type.name.toLowerCase()} (x${it.amount})"
}))
}
return meetsRequirements
}
/**
* Checks if the inventory contains the required item.
*/
open fun Inventory.checkForItem(itemStack: ItemStack) = containsAtLeastInlcudingData(itemStack)
/**
* Get the colour applied bow name of the bow of this ability.
*/
fun bowName() = plugin.config.getString([email protected])?.applyColours()
?: error("No bow name found in configuration for ${[email protected]}")
/**
* Whether the given player has the ability on cooldown.
*
* @param player
* The player to check for.
* @return `true` if the player has the ability on cooldown, `false` otherwise.
*/
fun isOnCooldown(player: Player) = cooldownMap.containsKey(player)
/**
* Looks up how many milliseconds of cooldown the given player has left for this ability.
*/
protected fun Player.cooldownTimeLeft(): Long {
if (isOnCooldown(this).not()) return 0
val usedTime = cooldownMap.getOrDefault(this, 0L)
return cooldownTime - (System.currentTimeMillis() - usedTime)
}
/**
* Registers that the given arrow is shot by this bow.
*
* @return `true` if the arrow has been added, `false` if the arrow is already registered.
*/
protected open fun registerArrow(arrow: Arrow) = arrows.add(arrow)
/**
* Unregisters the arrow.
*
* @return `true` if the arrow has been successfully removed; `false` if it was not present.
*/
protected open fun unregisterArrow(arrow: Arrow) = arrows.remove(arrow)
/**
* Removes all resources from the player's inventory that are required for 1 use.
*/
@Suppress("DEPRECATION")
protected open fun Player.consumeBowItems() {
val recentlyRemoved = ArrayList<ItemStack>(costRequirements.size)
costRequirements.forEach { item ->
// Find the item with the correct material. removeItem won't work when the item has
// item data.
val eligibleItem = inventory.asSequence()
.filterNotNull()
.firstOrNull { it.type == item.type && it.amount >= item.amount && it.data?.data == item.data?.data }
?: return@forEach
val toRemove = eligibleItem.clone().apply {
amount = item.amount
}
if (gameMode != GameMode.CREATIVE) {
inventory.removeIncludingData(toRemove)
}
recentlyRemoved.add(toRemove)
}
mostRecentItemsConsumed[this] = recentlyRemoved
}
/**
* Removes the given entity from the cost requirements cache.
* Effectively clearing the consumption cache for the entity.
*/
fun removeFromCostRequirementsCache(entity: Entity) = mostRecentItemsConsumed.remove(entity)
/**
* Gives back all resources from the player's inventory that are required for 1 use.
*/
protected open fun Player.reimburseBowItems() {
if (player != null && player!!.gameMode != GameMode.CREATIVE) {
costRequirements.forEach {
inventory.addItem(it)
}
}
}
/**
* Get the item of the bow that the player is holding (with this ability).
*
* @return The applicable bow item, or `null` when the player does not hold a bow.
*/
protected fun Player.bowItem(): ItemStack? {
val bowName = bowName()
return if (itemInMainHand.itemName == bowName) {
itemInMainHand
} else if (itemInOffHand.itemName == bowName) {
itemInOffHand
} else null
}
} | gpl-3.0 | 78ac39e748c9dec3b33b7b06839b917f | 32.836323 | 121 | 0.628032 | 4.637369 | false | false | false | false |
Adventech/sabbath-school-android-2 | common/design-compose/src/main/kotlin/app/ss/design/compose/extensions/surface/Surface.kt | 1 | 1999 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* 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.
*/
package app.ss.design.compose.extensions.surface
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import app.ss.design.compose.theme.SsTheme
@Composable
fun ThemeSurface(
darkTheme: Boolean = false,
content: @Composable () -> Unit
) {
SsTheme(darkTheme = darkTheme) {
Surface(content = content)
}
}
@Composable
fun BottomSheetSurface(content: @Composable () -> Unit) {
SsTheme {
Surface(
modifier = Modifier.fillMaxSize(),
shape = RoundedCornerShape(
topStart = 16.dp,
topEnd = 16.dp
),
content = content
)
}
}
| mit | c8c7349d5b1fdf59ecd1fab50b08ff5d | 35.345455 | 80 | 0.722361 | 4.452116 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/ui/item/AbstractItem.kt | 1 | 733 | package com.sjn.stamp.ui.item
import android.content.Context
import eu.davidea.flexibleadapter.items.AbstractFlexibleItem
import eu.davidea.viewholders.FlexibleViewHolder
abstract class AbstractItem<VH : FlexibleViewHolder> internal constructor(var id: String) : AbstractFlexibleItem<VH>() {
abstract val title: String
abstract val subtitle: String
override fun equals(other: Any?): Boolean {
if (other is AbstractItem<*>) {
val inItem = other as AbstractItem<*>?
return this.id == inItem?.id
}
return false
}
override fun hashCode(): Int = id.hashCode()
override fun toString(): String = "id=$id, title=$title"
open fun delete(context: Context) {}
} | apache-2.0 | 3e86ac50d786a383f3ebc18bc89e3dab | 28.36 | 120 | 0.687585 | 4.496933 | false | false | false | false |
Saketme/JRAW | docs/src/main/kotlin/net/dean/jraw/docs/PageCompiler.kt | 2 | 2363 | package net.dean.jraw.docs
import java.io.File
class PageCompiler(private val linkGenerator: DocLinkGenerator, private val codeSamples: List<CodeSampleRef>) {
private val _unusedSamples: MutableList<CodeSampleRef> = ArrayList(codeSamples)
val unusedSamples: List<CodeSampleRef>
get() = _unusedSamples
fun compile(file: File): List<String> = compile(file.readLines())
fun compile(text: List<String>): List<String> {
return text.map {
// Map each line to a list of lines. This is necessary since compiling a sample will produce multiple lines
when {
// Only one sample supported per line
sampleRegex.matches(it.trim()) -> {
val result = sampleRegex.find(it)!!
val sampleName = result.groupValues[1]
val sample = codeSamples.firstOrNull { it.name == sampleName } ?:
throw IllegalArgumentException("No code sample named '$sampleName'")
_unusedSamples.remove(sample)
val lines: MutableList<String> = ArrayList(sample.content)
// Use GitHub flavored Markdown for code
lines.add(0, "```java")
lines.add("```")
lines
}
// Multiple links are supported on one line
linkRegex.containsMatchIn(it) -> {
val replaced = linkRegex.replace(it) { match ->
// groupValues[0] is the input string
val name = match.groupValues[1]
val clazz = ProjectTypeFinder.from(name)
?: throw IllegalArgumentException("No JRAW type with (simple) name $name")
val link = linkGenerator.generate(clazz)
"[${clazz.simpleName}]($link)"
}
listOf(replaced)
}
else -> listOf(it)
}
}.flatten() // Flatten the List<List<String>> into a List<String>
}
companion object {
// https://regexr.com/3goec
private val sampleRegex = Regex("\\{\\{ ?(\\w+\\.\\w+) ?}}")
// https://regexr.com/3gto2
private val linkRegex = Regex("\\[\\[@((?:\\w+\\.)*\\w+)]]")
}
}
| mit | d1910e5a940116c71b66ef76f55f0e80 | 39.050847 | 119 | 0.525603 | 4.912682 | false | false | false | false |
JohnnyShieh/Gank | app/src/main/kotlin/com/johnny/gank/main/TodayGankFragment.kt | 1 | 7657 | package com.johnny.gank.main
/*
* Copyright (C) 2016 Johnny Shieh Open Source Project
*
* 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.
*/
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.app.ActivityOptionsCompat
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.johnny.gank.R
import com.johnny.gank.base.BaseFragment
import com.johnny.gank.network.GankService
import com.johnny.gank.model.GankType
import com.johnny.gank.model.response.DayData
import com.johnny.gank.model.ui.GankGirlImageItem
import com.johnny.gank.model.ui.GankHeaderItem
import com.johnny.gank.model.ui.GankItem
import com.johnny.gank.model.ui.GankNormalItem
import com.johnny.gank.model.StatName
import com.johnny.gank.adapter.GankListAdapter
import com.johnny.rxflux.RxFlux
import com.johnny.rxflux.Store
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_refresh_recycler.*
import org.koin.android.ext.android.inject
import org.koin.android.viewmodel.ext.android.viewModel
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
/**
* @author Johnny Shieh ([email protected])
* @version 1.0
*/
class TodayGankFragment : BaseFragment(),
SwipeRefreshLayout.OnRefreshListener {
companion object {
const val TAG = "TodayGankFragment"
}
val mStore: TodayGankStore by viewModel()
val mActionCreator: TodayGankActionCreator by inject()
private lateinit var mAdapter: GankListAdapter
override var statPageName = StatName.PAGE_TODAY
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_refresh_recycler, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
refresh_layout.setColorSchemeResources(
R.color.colorPrimary,
R.color.colorPrimaryDark,
R.color.colorAccent
)
refresh_layout.setOnRefreshListener(this)
recycler_view.layoutManager = LinearLayoutManager(activity)
recycler_view.setHasFixedSize(true)
mAdapter = GankListAdapter(this)
mAdapter.onItemClickListener = object : GankListAdapter.OnItemClickListener {
override fun onClickNormalItem(view: View, normalItem: GankNormalItem) {
if (!normalItem.gank.url.isEmpty()) {
WebviewActivity.openUrl(activity!!, normalItem.gank.url, normalItem.gank.desc)
}
}
override fun onClickGirlItem(view: View, girlImageItem: GankGirlImageItem) {
if (girlImageItem.imgUrl.isNotEmpty()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.transitionName = girlImageItem.imgUrl
}
startActivity(
PictureActivity.newIntent(
activity!!,
girlImageItem.imgUrl,
girlImageItem.publishedAt
)
)
}
}
}
recycler_view.adapter = mAdapter
refresh_layout.post {
refresh_layout.isRefreshing = true
refreshData()
}
mStore.refreshFinish.observe(this, Observer {
refresh_layout.isRefreshing = false
})
mStore.items.observe(this, Observer {
mAdapter.swapData(it)
})
}
private fun refreshData() {
mActionCreator.getTodayGank(mStore)
}
override fun onRefresh() {
refreshData()
}
}
private val GET_TODAY_GANK = RxFlux.newActionType<List<GankItem>>("today_gank_page_get_today_gank")
class TodayGankActionCreator(private val gankService: GankService) {
private var requesting = false
@SuppressLint("CheckResult")
fun getTodayGank(store: Store) {
if (requesting) {
return
}
requesting = true
gankService.getTodayGank()
.map { getGankList(it) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ gankList ->
requesting = false
RxFlux.postAction(GET_TODAY_GANK, store, gankList)
}, { throwable ->
requesting = false
RxFlux.postAction(GET_TODAY_GANK, store, throwable)
})
}
private fun getGankList(dayData: DayData?): List<GankItem> {
if (null == dayData) {
return arrayListOf()
}
val gankList = ArrayList<GankItem>(10)
if (dayData.results.welfareList.isNotEmpty()) {
gankList.add(GankGirlImageItem.newImageItem(dayData.results.welfareList[0]))
}
if (dayData.results.androidList.isNotEmpty()) {
gankList.add(GankHeaderItem(GankType.ANDROID))
gankList.addAll(GankNormalItem.newGankList(dayData.results.androidList))
}
if (dayData.results.iosList.isNotEmpty()) {
gankList.add(GankHeaderItem(GankType.IOS))
gankList.addAll(GankNormalItem.newGankList(dayData.results.iosList))
}
if (dayData.results.frontEndList.isNotEmpty()) {
gankList.add(GankHeaderItem(GankType.FRONTEND))
gankList.addAll(GankNormalItem.newGankList(dayData.results.frontEndList))
}
if (dayData.results.extraList.isNotEmpty()) {
gankList.add(GankHeaderItem(GankType.EXTRA))
gankList.addAll(GankNormalItem.newGankList(dayData.results.extraList))
}
if (dayData.results.casualList.isNotEmpty()) {
gankList.add(GankHeaderItem(GankType.CASUAL))
gankList.addAll(GankNormalItem.newGankList(dayData.results.casualList))
}
if (dayData.results.appList.isNotEmpty()) {
gankList.add(GankHeaderItem(GankType.APP))
gankList.addAll(GankNormalItem.newGankList(dayData.results.appList))
}
if (dayData.results.videoList.isNotEmpty()) {
gankList.add(GankHeaderItem(GankType.VIDEO))
gankList.addAll(GankNormalItem.newGankList(dayData.results.videoList))
}
return gankList
}
}
class TodayGankStore : Store() {
val refreshFinish = MutableLiveData<Unit>()
val items = MutableLiveData<List<GankItem>>()
init {
register(
GET_TODAY_GANK,
{ value ->
refreshFinish.value = Unit
items.value = value
},
{
refreshFinish.value = Unit
}
)
}
}
| apache-2.0 | f78394c199209b9d4340b0ca4f1d8dcd | 33.96347 | 99 | 0.655087 | 4.514741 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ExtractDeclarationFromCurrentFileIntention.kt | 1 | 7146 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations
import com.intellij.codeInsight.actions.OptimizeImportsProcessor
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.codeInsight.navigation.NavigationUtil
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.util.CommonRefactoringUtil
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.moveCaret
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.refactoring.createKotlinFile
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.MoveKotlinTopLevelDeclarationsDialog
import org.jetbrains.kotlin.idea.refactoring.showWithTransaction
import org.jetbrains.kotlin.idea.util.application.invokeLater
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.resolve.source.getPsi
private const val TIMEOUT_FOR_IMPORT_OPTIMIZING_MS: Long = 700L
class ExtractDeclarationFromCurrentFileIntention : SelfTargetingRangeIntention<KtClassOrObject>(
KtClassOrObject::class.java,
KotlinBundle.lazyMessage("intention.extract.declarations.from.file.text")
), LowPriorityAction {
private fun KtClassOrObject.tryGetExtraClassesToMove(): List<KtNamedDeclaration>? {
val descriptor = resolveToDescriptorIfAny() ?: return null
if (descriptor.getSuperClassNotAny()?.modality == Modality.SEALED) return null
return descriptor.sealedSubclasses
.mapNotNull { it.source.getPsi() as? KtNamedDeclaration }
.filterNot { isAncestor(it) }
}
override fun applicabilityRange(element: KtClassOrObject): TextRange? {
element.name ?: return null
if (element.parent !is KtFile) return null
if (element.hasModifier(KtTokens.PRIVATE_KEYWORD)) return null
if (element.containingKtFile.run { declarations.size == 1 || containingDirectory === null }) return null
val extraClassesToMove = element.tryGetExtraClassesToMove() ?: return null
val startOffset = when (element) {
is KtClass -> element.startOffset
is KtObjectDeclaration -> element.getObjectKeyword()?.startOffset
else -> return null
} ?: return null
val endOffset = element.nameIdentifier?.endOffset ?: return null
setTextGetter(
KotlinBundle.lazyMessage(
"intention.extract.declarations.from.file.text.details",
element.name.toString(),
extraClassesToMove.size
)
)
return TextRange(startOffset, endOffset)
}
override fun startInWriteAction() = false
override fun applyTo(element: KtClassOrObject, editor: Editor?) {
requireNotNull(editor) { "This intention requires an editor" }
val file = element.containingKtFile
val project = file.project
val originalOffset = editor.caretModel.offset - element.startOffset
val directory = file.containingDirectory ?: return
val packageName = file.packageFqName
val targetFileName = "${element.name}.kt"
val targetFile = directory.findFile(targetFileName)
if (targetFile !== null) {
if (isUnitTestMode()) {
throw CommonRefactoringUtil.RefactoringErrorHintException(RefactoringBundle.message("file.already.exist", targetFileName))
}
// If automatic move is not possible, fall back to full-fledged Move Declarations refactoring
runFullFledgedMoveRefactoring(project, element, packageName, directory, targetFile, file)
return
}
val moveTarget = KotlinMoveTargetForDeferredFile(packageName, directory.virtualFile) {
createKotlinFile(targetFileName, directory, packageName.asString())
}
val moveSource = element.tryGetExtraClassesToMove()
?.let { additionalElements ->
MoveSource(additionalElements.toMutableList().also { it.add(0, element) })
}
?: MoveSource(element)
val moveCallBack = MoveCallback {
val newFile = directory.findFile(targetFileName) as KtFile
val newDeclaration = newFile.declarations.first()
NavigationUtil.activateFileWithPsiElement(newFile)
FileEditorManager.getInstance(project).selectedTextEditor?.moveCaret(newDeclaration.startOffset + originalOffset)
runBlocking { withTimeoutOrNull(TIMEOUT_FOR_IMPORT_OPTIMIZING_MS) { OptimizeImportsProcessor(project, file).run() } }
}
val descriptor = MoveDeclarationsDescriptor(
project,
moveSource,
moveTarget,
MoveDeclarationsDelegate.TopLevel,
searchInCommentsAndStrings = false,
searchInNonCode = false,
moveCallback = moveCallBack
)
MoveKotlinDeclarationsProcessor(descriptor).run()
}
private fun runFullFledgedMoveRefactoring(
project: Project,
element: KtClassOrObject,
packageName: FqName,
directory: PsiDirectory,
targetFile: PsiFile?,
file: KtFile
) {
invokeLater {
val callBack = MoveCallback {
runBlocking {
withTimeoutOrNull(TIMEOUT_FOR_IMPORT_OPTIMIZING_MS) {
OptimizeImportsProcessor(project, file).run()
}
}
}
MoveKotlinTopLevelDeclarationsDialog(
project,
setOf(element),
packageName.asString(),
directory,
targetFile as? KtFile,
/* freezeTargets */ false,
/* moveToPackage = */ true,
/* searchInComments = */ true,
/* searchForTextOccurrences = */ true,
/* deleteEmptySourceFiles = */ true,
/* moveMppDeclarations = */ false,
callBack
).showWithTransaction()
}
}
} | apache-2.0 | 7e008e3bbfa4c95622e1d0796f33f5e9 | 42.054217 | 158 | 0.695214 | 5.397281 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-7/app/src/main/java/dev/mfazio/pennydrop/data/PennyDropDatabase.kt | 4 | 1535 | package dev.mfazio.pennydrop.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.sqlite.db.SupportSQLiteDatabase
import dev.mfazio.pennydrop.game.AI
import dev.mfazio.pennydrop.types.Player
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@Database(
entities = [Game::class, Player::class, GameStatus::class],
version = 1
)
@TypeConverters(Converters::class)
abstract class PennyDropDatabase : RoomDatabase() {
abstract fun pennyDropDao(): PennyDropDao
companion object {
@Volatile
private var instance: PennyDropDatabase? = null
fun getDatabase(
context: Context,
scope: CoroutineScope
): PennyDropDatabase =
instance ?: synchronized(this) {
val instance = Room.databaseBuilder(
context,
PennyDropDatabase::class.java,
"PennyDropDatabase"
).addCallback(object : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
scope.launch {
instance?.pennyDropDao()?.insertPlayers(AI.basicAI.map(AI::toPlayer))
}
}
}).build()
this.instance = instance
instance
}
}
} | apache-2.0 | b0a41ad9ba8c07893d93b4edc8da018b | 30.346939 | 97 | 0.60456 | 5.133779 | false | false | false | false |
Turbo87/intellij-emberjs | src/main/kotlin/com/emberjs/hbs/HbsModuleReference.kt | 1 | 1650 | package com.emberjs.hbs
import com.emberjs.index.EmberNameIndex
import com.emberjs.lookup.EmberLookupElementBuilder
import com.emberjs.resolver.EmberName
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementResolveResult.createResults
import com.intellij.psi.PsiManager
import com.intellij.psi.PsiPolyVariantReferenceBase
import com.intellij.psi.ResolveResult
import com.intellij.psi.search.ProjectScope
open class HbsModuleReference(element: PsiElement, val moduleType: String) :
PsiPolyVariantReferenceBase<PsiElement>(element, TextRange(0, element.textLength), true) {
val project = element.project
private val scope = ProjectScope.getAllScope(project)
private val psiManager: PsiManager by lazy { PsiManager.getInstance(project) }
open fun matches(module: EmberName) =
module.type == moduleType && module.name == value
override fun multiResolve(incompleteCode: Boolean): Array<out ResolveResult> {
// Collect all components from the index
return EmberNameIndex.getFilteredFiles(scope) { matches(it) }
// Convert search results for LookupElements
.mapNotNull { psiManager.findFile(it) }
.let(::createResults)
}
override fun getVariants(): Array<out Any?> {
// Collect all components from the index
return EmberNameIndex.getFilteredProjectKeys(scope) { it.type == moduleType }
// Convert search results for LookupElements
.map { EmberLookupElementBuilder.create(it, dots = false) }
.toTypedArray()
}
}
| apache-2.0 | 4035ff27f149f64f6673f220e33540ff | 40.25 | 98 | 0.72303 | 4.94012 | false | false | false | false |
RMHSProgrammingClub/Bot-Game | kotlin/src/main/kotlin/com/n9mtq4/botclient/ControllableBot.kt | 1 | 9397 | package com.n9mtq4.botclient
import com.n9mtq4.botclient.world.Block
import com.n9mtq4.botclient.world.BlockType
import com.n9mtq4.botclient.world.Bot
import com.n9mtq4.botclient.world.Flag
import com.n9mtq4.botclient.world.WorldObject
import org.json.simple.JSONArray
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
import java.util.ArrayList
/**
* A bot that you can control.
* These are received when you call game.waitForTurn
* Not technically a part of the world.
*
* Created by will on 11/24/15 at 3:16 PM.
*
* @author Will "n9Mtq4" Bresnahan
*
* @property health the health of the bot
* @property vision an array of what the bot can see
*
* @param x The x position
* @param y the y position
* @param angle The angle in degrees
* @param health The health
* @param actionPoints The number of action points the bot has
* @param vision An array of [WorldObject]s that you can see
*/
class ControllableBot(uid: Int, x: Int, y: Int, angle: Int, val health: Int, actionPoints: Int, mana: Int, val vision: ArrayList<WorldObject>) : WorldObject {
/**
* The UID of the bot
* returns -1 if the server doesn't have support
* */
val uid = uid
get() {
if (field == -1) System.err.println("[WARNING]: BotServer doesn't have UID, returning -1")
return field
}
/**
* The x pos of the bot
* */
override var x = x
private set
/**
* The y pos of the bot
* */
override var y = y
private set
/**
* The angle in degrees of the bot
* */
var angle = angle
private set
/**
* The number of action points the bot has
* */
var actionPoints = actionPoints
private set
/**
* The amount of mana the bot has
* */
var mana = mana
private set
/**
* A list of all the actions that
* will/did happen this turn
* */
internal val turnLog: ArrayList<String>
/**
* Constructor for [ControllableBot]
* All it does is creates a blank [ArrayList]
* for the turn actions
* */
init {
this.turnLog = arrayListOf()
}
/**
* Moves the bot in the x or y direction
* Remember: negative y is up, and positive is down!
*
* @param x the x value to move (-1, 0, or 1)
* @param y the y value to move (-1, 0, or 1)
* @return this bot, (a build method)
* @throws NotEnoughActionPointsException if you can't perform the action
* */
@Throws(NotEnoughActionPointsException::class)
fun move(x: Int, y: Int): ControllableBot {
// check if in bounds
assertTrue(x in -1..1, "x must be within -1 and 1")
assertTrue(y in -1..1, "y must be within -1 and 1")
// make sure that the bot can move
assertActionPoints(calcMoveCost(x, y), actionPoints, "move")
actionPoints -= calcMoveCost(x, y) // client side tracking of action points
turnLog("MOVE $x $y") // add the movement to this turn's actions
// update client copy
this.x += x
this.y += y
return this
}
/**
* Calculates the action point cost of
* moving
* */
fun calcMoveCost(x: Int, y: Int) = MOVEMENT_COST
/**
* Turns the bot [angle] degrees.
*
* @param angle The angle to turn in degrees
* @return this bot, (a build method)
* @throws NotEnoughActionPointsException if you can't perform the action
* */
@Throws(NotEnoughActionPointsException::class)
fun turn(angle: Int): ControllableBot {
// make sure the angle is in bounds
assertTrue(angle in -360..360, "angle must be between -360 and 360")
// make sure the bot can turn
assertActionPoints(calcTurnCost(angle), actionPoints, "turn")
actionPoints -= calcTurnCost(angle) // client side tracking of action points
turnLog("TURN $angle") // add the turn to this turn's actions
// update local copy
this.angle += angle
return this
}
/**
* Calculates the action point cost of
* turning
* */
fun calcTurnCost(angle: Int) = Math.abs(Math.ceil((angle / TURN_COST).toDouble())).toInt()
/**
* Shoots a projectile from the bot.
* Uses the current angle for the shooting
*
* @return this bot, (a build method)
* @throws NotEnoughActionPointsException if you can't perform the action
* */
@Throws(NotEnoughActionPointsException::class)
fun shoot(): ControllableBot {
// make sure the bot can shoot
assertActionPoints(calcShootCost(), actionPoints, "shoot")
actionPoints -= calcShootCost() // client side tracking of action points
turnLog("SHOOT") // add the shooting to this turn's actions
return this
}
/**
* Calculates the action point cost of
* shooting
* */
fun calcShootCost() = SHOOT_COST
/**
* Spawns a new bot for your team off ([x], [y]) of
* your bot's current position.
*
* @param x the delta x pos of the new bot
* @param y the delta y pos of the new bot
* @return this bot, (a build method)
* @throws NotEnoughManaPointsException if you can't perform the action
* */
@Throws(NotEnoughActionPointsException::class)
fun spawnBot(x: Int, y: Int): ControllableBot {
// check if in bounds
assertTrue(x in -1..1, "x must be within -1 and 1")
assertTrue(y in -1..1, "y must be within -1 and 1")
// make sure the bot can spawn another bot
// assertManaPoints(calcSpawnCostAp(x, y), mana, "spawn")
assertActionManaPoints(calcSpawnCostAp(x, y), actionPoints, calcSpawnCostMana(x, y), mana, "spawn")
actionPoints -= calcSpawnCostAp(x, y) // client side tracking of action points
mana -= calcSpawnCostMana(x, y)
turnLog("SPAWN $x $y") // add the spawning to this turn's actions
return this
}
/**
* Calculates the action point cost of
* spawning another bot
* */
fun calcSpawnCostAp(x: Int, y: Int) = SPAWN_COST
/**
* Calculates the mana point cost of
* spawning another bot
* */
fun calcSpawnCostMana(x: Int, y: Int) = SPAWN_MANA_COST
/**
* Places a new block right at the [x] and [y] off of you.
*
* @param x the delta x pos of the block
* @param y the delta y pos of the block
* @return this bot, (a build method)
* @throws NotEnoughManaPointsException if you can't perform the action
* */
@Throws(NotEnoughManaPointsException::class)
fun placeBlock(x: Int, y: Int): ControllableBot {
// check if in bounds
assertTrue(x in -1..1, "x must be within -1 and 1")
assertTrue(y in -1..1, "y must be within -1 and 1")
// make sure the bot can spawn another bot
// assertManaPoints(calcPlaceBlock(), mana, "place")
assertActionManaPoints(calcPlaceBlockCostAp(x, y), actionPoints, calcPlaceBlockCostMana(x, y), mana, "place")
actionPoints -= calcPlaceBlockCostAp(x, y) // client side tracking of action points
mana -= calcPlaceBlockCostMana(x, y)
turnLog("PLACE $x $y") // add the spawning to this turn's actions
return this
}
/**
* Calculates the action point cost of
* placing a block
* */
fun calcPlaceBlockCostAp(x: Int, y: Int) = PLACE_COST
/**
* Calculates the mana point cost of
* placing a bot
* */
fun calcPlaceBlockCostMana(x: Int, y: Int) = PLACE_MANA_COST
/**
* Adds a command onto this turn's actions
* */
private fun turnLog(msg: String) {
turnLog.add(msg)
}
/**
* Contains the buildBot method
* */
companion object {
/**
* Creates a [ControllableBot] from the data provided from
* [Game.readAndMakeBot]
*
* @param data some pre-parsed data from [Game.readAndMakeBot]
* @return A [ControllableBot] created from the given data
* */
@JvmName("buildBot")
internal fun buildBot(data: String): ControllableBot {
// initialize the json parsing
// val jsonString = data.joinToString("\n")
val parser = JSONParser()
val json: JSONObject = parser.parse(data) as JSONObject
// parse the things for the bot
val uid = ((json["uid"] ?: -1L) as Long).toInt() // bot id is -1 if server doesn't have support
val x = (json["x"] as Long).toInt()
val y = (json["y"] as Long).toInt()
val angle = (json["angle"] as Long).toInt()
val health = (json["health"] as Long).toInt()
val actionPoints = (json["ap"] as Long).toInt()
val mana = (json["mana"] as Long).toInt()
// start vision parsing
val visionJson = json["vision"] as JSONArray
val vision = ArrayList<WorldObject>()
visionJson.map { it as JSONObject }.forEach {
// stuff everything has
val type = it["type"] as String
val vx = (it["x"] as Long).toInt()
val vy = (it["y"] as Long).toInt()
// stuff only some things have
if (type.equals("bot", true)) {
// bots have a team, angle, and health
val vteam = (it["team"] as Long).toInt()
val vangle = (it["angle"] as Long).toInt()
val vhealth = (it["health"] as Long).toInt()
vision.add(Bot(vx, vy, vangle, vhealth, vteam))
}else if (type.equals("block", true)) {
// blocks have health
val vhealth = (it["health"] as Long).toInt()
vision.add(Block(vx, vy, vhealth, true, BlockType.BLOCK))
}else if (type.equals("wall", true)) {
// walls are generic
vision.add(Block(vx, vy, 100, false, BlockType.WALL))
}else if (type.equals("flag", true)) {
// flags have a team
val vteam = (it["team"] as Long).toInt()
vision.add(Flag(vx, vy, vteam))
}else {
// throw IOException("Error reading vision data:\n$data")
throw ClientNetworkException("Error reading vision", "vision data", data)
}
}
return ControllableBot(uid, x, y, angle, health, actionPoints, mana, vision)
}
}
}
| mit | 99c8ebf08ae1ee21b41b2c86fb9e28db | 27.219219 | 158 | 0.660849 | 3.240345 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/compiler-plugins/parcelize/common/src/org/jetbrains/kotlin/idea/compilerPlugin/parcelize/ParcelizeUltraLightClassModifierExtension.kt | 2 | 4102 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.compilerPlugin.parcelize
import com.intellij.psi.PsiVariable
import com.intellij.psi.impl.light.LightFieldBuilder
import org.jetbrains.kotlin.asJava.UltraLightClassModifierExtension
import org.jetbrains.kotlin.asJava.builder.LightMemberOrigin
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtUltraLightClass
import org.jetbrains.kotlin.asJava.classes.createGeneratedMethodFromDescriptor
import org.jetbrains.kotlin.asJava.elements.KtLightField
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.parcelize.ParcelizeSyntheticComponent
import org.jetbrains.kotlin.parcelize.serializers.ParcelizeExtensionBase
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.util.isAnnotated
import org.jetbrains.kotlin.util.isOrdinaryClass
class ParcelizeUltraLightClassModifierExtension : ParcelizeExtensionBase, UltraLightClassModifierExtension {
private fun tryGetParcelizeClass(declaration: KtDeclaration, descriptor: Lazy<DeclarationDescriptor?>): ClassDescriptor? {
if (!declaration.isOrdinaryClass || !declaration.isAnnotated) {
return null
}
val module = declaration.module
if (module == null || !ParcelizeAvailability.isAvailable(module)) {
return null
}
val descriptorValue = descriptor.value ?: return null
val parcelizeClass = (descriptorValue as? ClassDescriptor) ?: descriptorValue.containingDeclaration as? ClassDescriptor
if (parcelizeClass == null || !parcelizeClass.isParcelizeClassDescriptor) {
return null
}
return parcelizeClass
}
override fun interceptFieldsBuilding(
declaration: KtDeclaration,
descriptor: Lazy<DeclarationDescriptor?>,
containingDeclaration: KtUltraLightClass,
fieldsList: MutableList<KtLightField>
) {
val parcelizeClass = tryGetParcelizeClass(declaration, descriptor) ?: return
if (parcelizeClass.hasCreatorField()) return
val creatorType = "android.os.Parcelable.Creator<${parcelizeClass.fqNameSafe.asString()}>"
val field = object: LightFieldBuilder("CREATOR", creatorType, containingDeclaration), KtLightField {
override val kotlinOrigin: KtDeclaration? get() = null
override val lightMemberOrigin: LightMemberOrigin? get() = null
override fun computeConstantValue(visitedVars: MutableSet<PsiVariable>?): Any? = null
override fun getContainingClass(): KtLightClass = containingDeclaration
}.also {
it.setModifiers("public", "static", "final")
}
fieldsList.add(field)
}
override fun interceptMethodsBuilding(
declaration: KtDeclaration,
descriptor: Lazy<DeclarationDescriptor?>,
containingDeclaration: KtUltraLightClass,
methodsList: MutableList<KtLightMethod>
) {
val parcelizeClass = tryGetParcelizeClass(declaration, descriptor) ?: return
with(parcelizeClass) {
if (hasSyntheticDescribeContents()) {
findFunction(ParcelizeSyntheticComponent.ComponentKind.DESCRIBE_CONTENTS)?.let {
methodsList.add(
containingDeclaration.createGeneratedMethodFromDescriptor(it)
)
}
}
if (hasSyntheticWriteToParcel()) {
findFunction(ParcelizeSyntheticComponent.ComponentKind.WRITE_TO_PARCEL)?.let {
methodsList.add(
containingDeclaration.createGeneratedMethodFromDescriptor(it)
)
}
}
}
}
} | apache-2.0 | 30f4da75889914165538e7ea1a156645 | 42.648936 | 127 | 0.716236 | 5.327273 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database-tests/src/main/kotlin/entities/AddressNoPartition.kt | 1 | 943 | package entities
import com.onyx.persistence.ManagedEntity
import com.onyx.persistence.annotations.*
import com.onyx.persistence.annotations.values.CascadePolicy
import com.onyx.persistence.annotations.values.FetchPolicy
import com.onyx.persistence.annotations.values.IdentifierGenerator
import com.onyx.persistence.annotations.values.RelationshipType
/**
* Created by Tim Osborn on 3/17/17.
*/
@Entity
class AddressNoPartition : ManagedEntity() {
@Identifier(generator = IdentifierGenerator.SEQUENCE)
@Attribute
var id: Long? = null
@Attribute(nullable = false)
var street: String? = null
@Attribute(nullable = false)
var houseNr: Int = 0
@Suppress("UNUSED")
@Relationship(type = RelationshipType.ONE_TO_MANY, inverseClass = PersonNoPartition::class, inverse = "address", cascadePolicy = CascadePolicy.ALL, fetchPolicy = FetchPolicy.LAZY)
var occupants: MutableList<PersonNoPartition>? = null
}
| agpl-3.0 | 652a05b0b4eb2454f7992ea52edf02c3 | 32.678571 | 183 | 0.767762 | 4.209821 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Util.kt | 4 | 1861 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.j2k.ast
import org.jetbrains.kotlin.j2k.CodeBuilder
fun CodeBuilder.appendWithPrefix(element: Element, prefix: String): CodeBuilder = if (!element.isEmpty) this append prefix append element else this
fun CodeBuilder.appendWithSuffix(element: Element, suffix: String): CodeBuilder = if (!element.isEmpty) this append element append suffix else this
fun CodeBuilder.appendOperand(expression: Expression, operand: Expression, parenthesisForSamePrecedence: Boolean = false): CodeBuilder {
val parentPrecedence = expression.precedence() ?: throw IllegalArgumentException("Unknown precedence for $expression")
val operandPrecedence = operand.precedence()
val needParenthesis = operandPrecedence != null &&
(parentPrecedence < operandPrecedence || parentPrecedence == operandPrecedence && parenthesisForSamePrecedence)
if (needParenthesis) append("(")
append(operand)
if (needParenthesis) append(")")
return this
}
fun Element.wrapToBlockIfRequired(): Element = when (this) {
is AssignmentExpression -> if (isMultiAssignment()) Block.of(this).assignNoPrototype() else this
else -> this
}
private fun Expression.precedence(): Int? {
return when (this) {
is QualifiedExpression, is MethodCallExpression, is ArrayAccessExpression, is PostfixExpression, is BangBangExpression, is StarExpression -> 0
is PrefixExpression -> 1
is TypeCastExpression -> 2
is BinaryExpression -> op.precedence
is RangeExpression, is UntilExpression, is DownToExpression -> 5
is IsOperator -> 8
is IfStatement -> 13
is AssignmentExpression -> 14
else -> null
}
}
| apache-2.0 | 78442b8ea806541ada08a58f3785b254 | 38.595745 | 158 | 0.734551 | 4.975936 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/rebase/log/squash/GitSquashLogAction.kt | 5 | 2390 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.rebase.log.squash
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.vcs.log.VcsCommitMetadata
import git4idea.i18n.GitBundle
import git4idea.rebase.log.*
internal class GitSquashLogAction : GitMultipleCommitEditingAction() {
override fun update(e: AnActionEvent, commitEditingData: MultipleCommitEditingData) {
if (commitEditingData.selection.size < 2) {
e.presentation.isEnabledAndVisible = false
}
}
override fun actionPerformedAfterChecks(commitEditingData: MultipleCommitEditingData) {
val selectedCommitDetails = getOrLoadDetails(commitEditingData.project, commitEditingData.logData, commitEditingData.selection)
val dialog = GitNewCommitMessageActionDialog(
commitEditingData,
originMessage = selectedCommitDetails.joinToString("\n".repeat(3)) { it.fullMessage },
title = GitBundle.message("rebase.log.squash.new.message.dialog.title"),
dialogLabel = GitBundle.message("rebase.log.squash.new.message.dialog.label")
)
dialog.show { newMessage ->
squashInBackground(commitEditingData, selectedCommitDetails, newMessage)
}
}
private fun squashInBackground(
commitEditingData: MultipleCommitEditingData,
selectedCommitsDetails: List<VcsCommitMetadata>,
newMessage: String
) {
object : Task.Backgroundable(commitEditingData.project, GitBundle.message("rebase.log.squash.progress.indicator.title")) {
override fun run(indicator: ProgressIndicator) {
val operationResult = GitSquashOperation(commitEditingData.repository).execute(selectedCommitsDetails, newMessage)
if (operationResult is GitCommitEditingOperationResult.Complete) {
operationResult.notifySuccess(
GitBundle.message("rebase.log.squash.success.notification.title"),
GitBundle.message("rebase.log.squash.undo.progress.title"),
GitBundle.message("rebase.log.squash.undo.impossible.title"),
GitBundle.message("rebase.log.squash.undo.failed.title")
)
}
}
}.queue()
}
override fun getFailureTitle() = GitBundle.message("rebase.log.squash.action.failure.title")
} | apache-2.0 | f9ff9f1153959d309ceefcea514928b5 | 44.980769 | 131 | 0.757741 | 4.484053 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/navigation/EdgeNavigation.kt | 2 | 815 | package eu.kanade.tachiyomi.ui.reader.viewer.navigation
import android.graphics.RectF
import eu.kanade.tachiyomi.ui.reader.viewer.ViewerNavigation
/**
* Visualization of default state without any inversion
* +---+---+---+
* | N | N | N | P: Previous
* +---+---+---+
* | N | M | N | M: Menu
* +---+---+---+
* | N | P | N | N: Next
* +---+---+---+
*/
class EdgeNavigation : ViewerNavigation() {
override var regions: List<Region> = listOf(
Region(
rectF = RectF(0f, 0f, 0.33f, 1f),
type = NavigationRegion.NEXT
),
Region(
rectF = RectF(0.33f, 0.66f, 0.66f, 1f),
type = NavigationRegion.PREV
),
Region(
rectF = RectF(0.66f, 0f, 1f, 1f),
type = NavigationRegion.NEXT
),
)
}
| apache-2.0 | 886cc847f0de0d99b7adcae7d8ae4cd5 | 24.46875 | 60 | 0.520245 | 3.468085 | false | false | false | false |
Fantast/project-euler | src/main/euler/solved/Task_540.kt | 1 | 1520 | package solved
import tasks.AbstractTask
import tasks.Tester
import utils.log.Logger
import utils.sieves.FactorizationSieve
//Answer : 500000000002845
class Task_540 : AbstractTask() {
val LIM = 3141592653589793L
val LIM2 = LIM / 2
val sqLIM = Math.sqrt(LIM.toDouble()).toInt()
var factors: LongArray = LongArray(20)
var factorsCount = 0
override fun solving() {
val sieve = FactorizationSieve(sqLIM)
var res = 0L;
var m = 1L;
while (m <= sqLIM) {
progress1000000(m);
val maxn = min(
m - 1,
LIM2 / m,
Math.sqrt((LIM - m * m).toDouble()).toLong()
)
if (maxn > 0) {
factorsCount = sieve.primeFactors(m.toInt(), factors)
if (m % 2 == 0L) {
res += phi(maxn, factorsCount)
} else {
res += phi(maxn / 2, factorsCount)
}
}
++m;
}
println(res)
}
//http://projecteuclid.org/euclid.ijm/1255455259
fun phi(x: Long, v: Int): Long {
if (v == 0) {
return x
}
if (x == 0L) {
return 0L
}
return phi(x, v - 1) - phi(x / factors[v - 1], v - 1)
}
companion object {
@JvmStatic fun main(args: Array<String>) {
Logger.init("default.log")
Tester.test(Task_540())
Logger.close()
}
}
}
| mit | 0db4f5ec605a33cb2c05bbdd8d6ded39 | 23.126984 | 69 | 0.471711 | 3.734644 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/opus/src/templates/kotlin/opus/OpusEncTypes.kt | 4 | 2064 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opus
import org.lwjgl.generator.*
val OggOpusComments = "OggOpusComments".opaque
val OggOpusEnc = "OggOpusEnc".opaque
val ope_write_func = Module.OPUS.callback {
intb(
"OPEWriteFunc",
"Called for writing a page.",
opaque_p("user_data", "user-defined data passed to the callback"),
unsigned_char.const.p("ptr", "buffer to be written"),
AutoSize("ptr")..opus_int32("len", "number of bytes to be written"),
nativeType = "ope_write_func",
returnDoc = "error code; {@code 0: success}, {@code 1: failure}"
) {
documentation = "Instances of this interface may be set to the ##OpusEncCallbacks."
}
}
val ope_close_func = Module.OPUS.callback {
int(
"OPECloseFunc",
"Called for closing a stream.",
opaque_p("user_data", "user-defined data passed to the callback"),
nativeType = "ope_close_func",
returnDoc = "error code; {@code 0: success}, {@code 1: failure}"
) {
documentation = "Instances of this interface may be set to the ##OpusEncCallbacks."
}
}
val ope_packet_func = Module.OPUS.callback {
void(
"OPEPacketFunc",
"Called on every packet encoded (including header).",
opaque_p("user_data", "user-defined data passed to the callback"),
unsigned_char.const.p("packet_ptr", "packet data"),
AutoSize("packet_ptr")..opus_int32("packet_len", "number of bytes in the packet"),
opus_uint32("flags", "optional flags (none defined for now so zero)"),
nativeType = "ope_packet_func"
) {
documentation = "Instances of this interface may be set with #SET_PACKET_CALLBACK_REQUEST."
}
}
val OpusEncCallbacks = struct(Module.OPUS, "OpusEncCallbacks") {
documentation = "Callback functions for accessing the stream."
ope_write_func("write", "callback for writing to the stream")
ope_close_func("close", "callback for closing the stream")
}
| bsd-3-clause | 67deb87088774397e4c43e7c3fed10dc | 30.753846 | 99 | 0.643411 | 3.773309 | false | false | false | false |
Frederikam/FredBoat | FredBoat/src/main/java/fredboat/command/admin/EvalCommand.kt | 1 | 6873 | /*
* MIT License
*
* Copyright (c) 2017 Frederik Ar. Mikkelsen
*
* 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.
*
*/
package fredboat.command.admin
import fredboat.commandmeta.abs.Command
import fredboat.commandmeta.abs.CommandContext
import fredboat.commandmeta.abs.ICommandRestricted
import fredboat.definitions.PermissionLevel
import fredboat.main.Launcher
import fredboat.messaging.internal.Context
import fredboat.util.TextUtils
import lavalink.client.player.LavalinkPlayer
import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationContext
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
class EvalCommand(
private val springContext: () -> ApplicationContext,
name: String,
vararg aliases: String
) : Command(name, *aliases), ICommandRestricted {
companion object {
private val log = LoggerFactory.getLogger(EvalCommand::class.java)
}
private var lastTask: Future<*>? = null
override val minimumPerms: PermissionLevel
get() = PermissionLevel.BOT_OWNER
override suspend fun invoke(context: CommandContext) {
val started = System.currentTimeMillis()
val engine: ScriptEngine = ScriptEngineManager().getEngineByName("nashorn")
engine.eval("var imports = new JavaImporter(java.io, java.lang, java.util);")
var source = context.rawArgs
if (context.hasArguments() && (context.args[0] == "-k" || context.args[0] == "kill")) {
if (this.lastTask != null) {
if (this.lastTask!!.isDone || this.lastTask!!.isCancelled) {
context.reply("Task isn't running.")
} else {
this.lastTask!!.cancel(true)
context.reply("Task killed.")
}
} else {
context.reply("No task found to kill.")
}
return
}
context.sendTyping()
val timeOut: Int
if (context.args.size > 1 && (context.args[0] == "-t" || context.args[0] == "timeout")) {
timeOut = Integer.parseInt(context.args[1])
source = source.replaceFirst(context.args[0].toRegex(), "")
source = source.replaceFirst(context.args[1].toRegex(), "")
} else
timeOut = -1
val finalSource = source.trim { it <= ' ' }
context.apply {
engine.put("sentinel", guild.sentinel)
engine.put("channel", textChannel)
engine.put("tc", textChannel)
val player = Launcher.botController.playerRegistry.getOrCreate(guild)
engine.put("player", player)
engine.put("players", Launcher.botController.playerRegistry)
engine.put("link", (player.player as LavalinkPlayer?)?.link)
engine.put("lavalink", player.lavalink)
engine.put("vc", player.currentVoiceChannel)
engine.put("author", member)
engine.put("invoker", member)
engine.put("bot", guild.selfMember)
engine.put("member", guild.selfMember)
engine.put("message", msg)
engine.put("guild", guild)
engine.put("pm", Launcher.botController.audioPlayerManager)
engine.put("context", context)
engine.put("spring", springContext.invoke())
}
val service = Executors.newScheduledThreadPool(1) { r -> Thread(r, "Eval comm execution") }
val future = service.submit {
val out: Any?
try {
out = engine.eval(
"(function() {"
+ "with (imports) {\n" + finalSource + "\n}"
+ "})();")
} catch (ex: Exception) {
context.reply(String.format("`%s`\n\n`%sms`",
ex.message, System.currentTimeMillis() - started))
log.info("Error occurred in eval", ex)
return@submit
}
val outputS: String
outputS = when {
out == null -> ":ok_hand::skin-tone-3:"
out.toString().contains("\n") -> "\nEval: " + TextUtils.asCodeBlock(out.toString())
else -> "\nEval: `" + out.toString() + "`"
}
context.reply(String.format("```java\n%s```\n%s\n`%sms`",
finalSource, outputS, System.currentTimeMillis() - started))
}
this.lastTask = future
val script = object : Thread("Eval comm waiter") {
override fun run() {
try {
if (timeOut > -1) {
future.get(timeOut.toLong(), TimeUnit.SECONDS)
}
} catch (ex: TimeoutException) {
future.cancel(true)
context.reply("Task exceeded time limit of $timeOut seconds.")
} catch (ex: Exception) {
context.reply(String.format("`%s`\n\n`%sms`",
ex.message, System.currentTimeMillis() - started))
}
}
}
script.start()
}
override fun help(context: Context): String {
return ("{0}{1} [-t seconds | -k] <javascript-code>\n#Run the provided javascript code with the Nashorn engine."
+ " By default no timeout is set for the task, set a timeout by passing `-t` as the first argument and"
+ " the amount of seconds to wait for the task to finish as the second argument."
+ " Run with `-k` or `kill` as first argument to stop the last submitted eval task if it's still ongoing.")
}
}
| mit | 0724b8963f82d1e1a16aea1a4a2bf572 | 39.429412 | 123 | 0.599593 | 4.572854 | false | false | false | false |
mdanielwork/intellij-community | platform/vcs-log/graph/src/com/intellij/vcs/log/graph/utils/DfsUtil.kt | 1 | 3886 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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 com.intellij.vcs.log.graph.utils
import com.intellij.openapi.util.Ref
import com.intellij.util.containers.IntStack
import com.intellij.vcs.log.graph.api.LiteLinearGraph
import com.intellij.vcs.log.graph.utils.impl.BitSetFlags
object Dfs {
interface NodeVisitor {
fun enterNode(node: Int, previousNode: Int, travelDirection: Boolean)
fun exitNode(node: Int)
}
object NextNode {
const val NODE_NOT_FOUND = -1
const val EXIT = -10
}
}
/*
* Depth-first walk for a graph. For each node, walks both into upward and downward siblings.
* Tries to preserve direction of travel: when a node is entered from up-sibling, goes to the down-siblings first.
* Then goes to the other up-siblings.
* And when a node is entered from down-sibling, goes to the up-siblings first.
* Then goes to the other down-siblings.
* When a node is entered the first time, enterNode is called.
* When a all the siblings of the node are visited, exitNode is called.
*/
fun LiteLinearGraph.walk(start: Int, visitor: Dfs.NodeVisitor) {
val visited = BitSetFlags(nodesCount(), false)
val stack = IntStack()
stack.push(start) // commit + direction of travel
outer@ while (!stack.empty()) {
val currentNode = stack.peek()
val down = isDown(stack)
if (!visited.get(currentNode)) {
visited.set(currentNode, true)
visitor.enterNode(currentNode, getPreviousNode(stack), down)
}
for (nextNode in getNodes(currentNode, if (down) LiteLinearGraph.NodeFilter.DOWN else LiteLinearGraph.NodeFilter.UP)) {
if (!visited.get(nextNode)) {
stack.push(nextNode)
continue@outer
}
}
for (nextNode in getNodes(currentNode, if (down) LiteLinearGraph.NodeFilter.UP else LiteLinearGraph.NodeFilter.DOWN)) {
if (!visited.get(nextNode)) {
stack.push(nextNode)
continue@outer
}
}
visitor.exitNode(currentNode)
stack.pop()
}
}
private fun getPreviousNode(stack: IntStack): Int {
return if (stack.size() < 2) {
Dfs.NextNode.NODE_NOT_FOUND
}
else stack.get(stack.size() - 2)
}
private fun isDown(stack: IntStack): Boolean {
val currentNode = stack.peek()
val previousNode = getPreviousNode(stack)
if (previousNode == Dfs.NextNode.NODE_NOT_FOUND) return true
return previousNode < currentNode
}
fun LiteLinearGraph.isAncestor(lowerNode: Int, upperNode: Int): Boolean {
val visited = BitSetFlags(nodesCount(), false)
val result = Ref.create(false)
walk(lowerNode) { currentNode ->
visited.set(currentNode, true)
if (currentNode == upperNode) {
result.set(true)
return@walk Dfs.NextNode.EXIT
}
if (currentNode > upperNode) {
for (nextNode in getNodes(currentNode, LiteLinearGraph.NodeFilter.UP)) {
if (!visited.get(nextNode)) {
return@walk nextNode
}
}
}
Dfs.NextNode.NODE_NOT_FOUND
}
return result.get()
}
fun walk(startRowIndex: Int, nextNodeFun: (Int) -> Int) {
val stack = IntStack()
stack.push(startRowIndex)
while (!stack.empty()) {
val nextNode = nextNodeFun(stack.peek())
if (nextNode == Dfs.NextNode.EXIT) return
if (nextNode != Dfs.NextNode.NODE_NOT_FOUND) {
stack.push(nextNode)
}
else {
stack.pop()
}
}
stack.clear()
}
| apache-2.0 | b5efd8b7c4dd69f2c9a4ce3739c66391 | 28.439394 | 123 | 0.692229 | 3.708015 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/assistance/CodeFormatLesson.kt | 5 | 2730 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.learn.lesson.general.assistance
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.editor.impl.EditorComponentImpl
import training.dsl.LessonContext
import training.dsl.LessonSample
import training.dsl.LessonUtil
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.dsl.restoreAfterStateBecomeFalse
import training.learn.LessonsBundle
import training.learn.course.KLesson
class CodeFormatLesson(private val sample: LessonSample, private val optimizeImports: Boolean) :
KLesson("CodeAssistance.CodeFormatting", LessonsBundle.message("code.format.lesson.name")) {
override val lessonContent: LessonContext.() -> Unit = {
prepareSample(sample)
val properties = PropertiesComponent.getInstance()
prepareRuntimeTask {
properties.setValue("LayoutCode.optimizeImports", false)
}
actionTask("ReformatCode") {
restoreIfModifiedOrMoved(sample)
LessonsBundle.message("code.format.reformat.selection", action(it))
}
prepareRuntimeTask {
editor.selectionModel.removeSelection()
}
task("ReformatCode") {
text(LessonsBundle.message("code.format.reformat.file", action(it)))
trigger(it) { editor.selectionModel.selectedText == null }
test {
actions(it)
}
}
if (optimizeImports) {
task("ShowReformatFileDialog") {
text(LessonsBundle.message("code.format.show.reformat.file.dialog", action(it)))
triggerStart(it)
test {
actions(it)
}
}
task {
val runButtonText = CodeInsightBundle.message("reformat.code.accept.button.text")
val optimizeImportsActionText = CodeInsightBundle.message("process.optimize.imports")
text(LessonsBundle.message("code.format.optimize.imports", strong(optimizeImportsActionText), strong(runButtonText)))
stateCheck {
focusOwner is EditorComponentImpl && properties.getBoolean("LayoutCode.optimizeImports")
}
restoreAfterStateBecomeFalse {
focusOwner is EditorComponentImpl
}
test(waitEditorToBeReady = false) {
properties.setValue("LayoutCode.optimizeImports", true)
ideFrame {
button("Run").click()
}
}
}
}
}
override val suitableTips = listOf("LayoutCode")
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("code.format.help.link"),
LessonUtil.getHelpLink("configuring-code-style.html")),
)
} | apache-2.0 | 99f662aec59ab967381d2a76ae5f1284 | 34.012821 | 140 | 0.710989 | 4.797891 | false | false | false | false |
dahlstrom-g/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/XmlReader.kt | 1 | 36236 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("XmlReader")
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty", "ReplacePutWithAssignment", "ReplaceGetOrSet")
package com.intellij.ide.plugins
import com.intellij.openapi.components.ComponentConfig
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.ExtensionPointDescriptor
import com.intellij.openapi.extensions.LoadingOrder
import com.intellij.openapi.extensions.PluginId
import com.intellij.util.lang.ZipFilePool
import com.intellij.util.messages.ListenerDescriptor
import com.intellij.util.xml.dom.NoOpXmlInterner
import com.intellij.util.xml.dom.XmlInterner
import com.intellij.util.xml.dom.createNonCoalescingXmlStreamReader
import com.intellij.util.xml.dom.readXmlAsModel
import org.codehaus.stax2.XMLStreamReader2
import org.codehaus.stax2.typed.TypedXMLStreamException
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.io.InputStream
import java.text.ParseException
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*
import javax.xml.stream.XMLStreamConstants
import javax.xml.stream.XMLStreamException
import javax.xml.stream.XMLStreamReader
import javax.xml.stream.events.XMLEvent
@Internal const val PACKAGE_ATTRIBUTE = "package"
@Internal const val IMPLEMENTATION_DETAIL_ATTRIBUTE = "implementation-detail"
@Internal const val ON_DEMAND_ATTRIBUTE = "on-demand"
private const val defaultXPointerValue = "xpointer(/idea-plugin/*)"
/**
* Do not use [java.io.BufferedInputStream] - buffer is used internally already.
*/
fun readModuleDescriptor(input: InputStream,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
readInto: RawPluginDescriptor?,
locationSource: String?): RawPluginDescriptor {
return readModuleDescriptor(reader = createNonCoalescingXmlStreamReader(input, locationSource),
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
readInto = readInto)
}
fun readModuleDescriptor(input: ByteArray,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
readInto: RawPluginDescriptor?,
locationSource: String?): RawPluginDescriptor {
return readModuleDescriptor(reader = createNonCoalescingXmlStreamReader(input, locationSource),
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
readInto = readInto)
}
internal fun readModuleDescriptor(reader: XMLStreamReader2,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
readInto: RawPluginDescriptor?): RawPluginDescriptor {
try {
if (reader.eventType != XMLStreamConstants.START_DOCUMENT) {
throw XMLStreamException("State ${XMLStreamConstants.START_DOCUMENT} is expected, " +
"but current state is ${getEventTypeString(reader.eventType)}", reader.location)
}
val descriptor = readInto ?: RawPluginDescriptor()
@Suppress("ControlFlowWithEmptyBody")
while (reader.next() != XMLStreamConstants.START_ELEMENT) {
}
if (!reader.isStartElement) {
return descriptor
}
readRootAttributes(reader, descriptor)
reader.consumeChildElements { localName ->
readRootElementChild(reader = reader,
descriptor = descriptor,
readContext = readContext,
localName = localName,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase)
assert(reader.isEndElement)
}
return descriptor
}
finally {
reader.closeCompletely()
}
}
@TestOnly
fun readModuleDescriptorForTest(input: ByteArray): RawPluginDescriptor {
return readModuleDescriptor(
input = input,
readContext = object : ReadModuleContext {
override val interner = NoOpXmlInterner
override val isMissingIncludeIgnored
get() = false
},
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
dataLoader = object : DataLoader {
override val pool: ZipFilePool? = null
override fun load(path: String) = throw UnsupportedOperationException()
override fun toString() = ""
},
includeBase = null,
readInto = null,
locationSource = null,
)
}
private fun readRootAttributes(reader: XMLStreamReader2, descriptor: RawPluginDescriptor) {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
PACKAGE_ATTRIBUTE -> descriptor.`package` = getNullifiedAttributeValue(reader, i)
"url" -> descriptor.url = getNullifiedAttributeValue(reader, i)
"use-idea-classloader" -> descriptor.isUseIdeaClassLoader = reader.getAttributeAsBoolean(i)
"allow-bundled-update" -> descriptor.isBundledUpdateAllowed = reader.getAttributeAsBoolean(i)
IMPLEMENTATION_DETAIL_ATTRIBUTE -> descriptor.implementationDetail = reader.getAttributeAsBoolean(i)
ON_DEMAND_ATTRIBUTE -> descriptor.onDemand = reader.getAttributeAsBoolean(i)
"require-restart" -> descriptor.isRestartRequired = reader.getAttributeAsBoolean(i)
"version" -> {
// internalVersionString - why it is not used, but just checked?
getNullifiedAttributeValue(reader, i)?.let {
try {
it.toInt()
}
catch (e: NumberFormatException) {
LOG.error("Cannot parse version: $it'", e)
}
}
}
}
}
}
/**
* Keep in sync with KotlinPluginUtil.KNOWN_KOTLIN_PLUGIN_IDS
*/
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog", "SSBasedInspection")
private val KNOWN_KOTLIN_PLUGIN_IDS = HashSet(Arrays.asList(
"org.jetbrains.kotlin",
"com.intellij.appcode.kmm",
"org.jetbrains.kotlin.native.appcode"
))
private fun readRootElementChild(reader: XMLStreamReader2,
descriptor: RawPluginDescriptor,
localName: String,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?) {
when (localName) {
"id" -> {
if (descriptor.id == null) {
descriptor.id = getNullifiedContent(reader)
}
else if (!KNOWN_KOTLIN_PLUGIN_IDS.contains(descriptor.id) && descriptor.id != "com.intellij") {
// no warn and no redefinition for kotlin - compiler.xml is a known issue
LOG.warn("id redefinition (${reader.locationInfo.location})")
descriptor.id = getNullifiedContent(reader)
}
else {
reader.skipElement()
}
}
"name" -> descriptor.name = getNullifiedContent(reader)
"category" -> descriptor.category = getNullifiedContent(reader)
"version" -> {
// kotlin includes compiler.xml that due to some reasons duplicates version
if (descriptor.version == null || !KNOWN_KOTLIN_PLUGIN_IDS.contains(descriptor.id)) {
descriptor.version = getNullifiedContent(reader)
}
else {
reader.skipElement()
}
}
"description" -> descriptor.description = getNullifiedContent(reader)
"change-notes" -> descriptor.changeNotes = getNullifiedContent(reader)
"resource-bundle" -> descriptor.resourceBundleBaseName = getNullifiedContent(reader)
"product-descriptor" -> readProduct(reader, descriptor)
"module" -> {
findAttributeValue(reader, "value")?.let { moduleName ->
var modules = descriptor.modules
if (modules == null) {
descriptor.modules = Collections.singletonList(PluginId.getId(moduleName))
}
else {
if (modules.size == 1) {
val singleton = modules
modules = ArrayList(4)
modules.addAll(singleton)
descriptor.modules = modules
}
modules.add(PluginId.getId(moduleName))
}
}
reader.skipElement()
}
"idea-version" -> {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"since-build" -> descriptor.sinceBuild = getNullifiedAttributeValue(reader, i)
"until-build" -> descriptor.untilBuild = getNullifiedAttributeValue(reader, i)
}
}
reader.skipElement()
}
"vendor" -> {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"email" -> descriptor.vendorEmail = getNullifiedAttributeValue(reader, i)
"url" -> descriptor.vendorUrl = getNullifiedAttributeValue(reader, i)
}
}
descriptor.vendor = getNullifiedContent(reader)
}
"incompatible-with" -> {
getNullifiedContent(reader)?.let {
var list = descriptor.incompatibilities
if (list == null) {
list = ArrayList()
descriptor.incompatibilities = list
}
list.add(PluginId.getId(it))
}
}
"application-components" -> readComponents(reader, descriptor.appContainerDescriptor)
"project-components" -> readComponents(reader, descriptor.projectContainerDescriptor)
"module-components" -> readComponents(reader, descriptor.moduleContainerDescriptor)
"applicationListeners" -> readListeners(reader, descriptor.appContainerDescriptor)
"projectListeners" -> readListeners(reader, descriptor.projectContainerDescriptor)
"extensions" -> readExtensions(reader, descriptor, readContext.interner)
"extensionPoints" -> readExtensionPoints(reader = reader,
descriptor = descriptor,
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase)
"content" -> readContent(reader = reader,
descriptor = descriptor,
readContext = readContext)
"dependencies" -> readDependencies(reader = reader, descriptor = descriptor, readContext = readContext)
"depends" -> readOldDepends(reader, descriptor)
"actions" -> readActions(descriptor, reader, readContext)
"include" -> readInclude(reader = reader,
readInto = descriptor,
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
allowedPointer = defaultXPointerValue)
"helpset" -> {
// deprecated and not used element
reader.skipElement()
}
"locale" -> {
// not used in descriptor
reader.skipElement()
}
else -> {
LOG.error("Unknown element: $localName")
reader.skipElement()
}
}
if (!reader.isEndElement) {
throw XMLStreamException("Unexpected state (" +
"expected=END_ELEMENT, " +
"actual=${getEventTypeString(reader.eventType)}, " +
"lastProcessedElement=$localName" +
")", reader.location)
}
}
private fun readActions(descriptor: RawPluginDescriptor, reader: XMLStreamReader2, readContext: ReadModuleContext) {
var actionElements = descriptor.actions
if (actionElements == null) {
actionElements = ArrayList()
descriptor.actions = actionElements
}
val resourceBundle = findAttributeValue(reader, "resource-bundle")
reader.consumeChildElements { elementName ->
if (checkXInclude(elementName, reader)) {
return@consumeChildElements
}
actionElements.add(RawPluginDescriptor.ActionDescriptor(
name = elementName,
element = readXmlAsModel(reader = reader, rootName = elementName, interner = readContext.interner),
resourceBundle = resourceBundle,
))
}
}
private fun readOldDepends(reader: XMLStreamReader2, descriptor: RawPluginDescriptor) {
var isOptional = false
var configFile: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"optional" -> isOptional = reader.getAttributeAsBoolean(i)
"config-file" -> configFile = reader.getAttributeValue(i)
}
}
val dependencyIdString = getNullifiedContent(reader) ?: return
var depends = descriptor.depends
if (depends == null) {
depends = ArrayList()
descriptor.depends = depends
}
depends.add(PluginDependency(pluginId = PluginId.getId(dependencyIdString), configFile = configFile, isOptional = isOptional))
}
private fun readExtensions(reader: XMLStreamReader2, descriptor: RawPluginDescriptor, interner: XmlInterner) {
val ns = findAttributeValue(reader, "defaultExtensionNs")
reader.consumeChildElements { elementName ->
if (checkXInclude(elementName, reader)) {
return@consumeChildElements
}
var implementation: String? = null
var os: ExtensionDescriptor.Os? = null
var qualifiedExtensionPointName: String? = null
var order = LoadingOrder.ANY
var orderId: String? = null
var hasExtraAttributes = false
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"implementation" -> implementation = reader.getAttributeValue(i)
"implementationClass" -> {
// deprecated attribute
implementation = reader.getAttributeValue(i)
}
"os" -> os = readOs(reader.getAttributeValue(i))
"id" -> orderId = getNullifiedAttributeValue(reader, i)
"order" -> order = readOrder(reader.getAttributeValue(i))
"point" -> qualifiedExtensionPointName = getNullifiedAttributeValue(reader, i)
else -> hasExtraAttributes = true
}
}
if (qualifiedExtensionPointName == null) {
qualifiedExtensionPointName = interner.name("${ns ?: reader.namespaceURI}.${elementName}")
}
val containerDescriptor: ContainerDescriptor
when (qualifiedExtensionPointName) {
"com.intellij.applicationService" -> containerDescriptor = descriptor.appContainerDescriptor
"com.intellij.projectService" -> containerDescriptor = descriptor.projectContainerDescriptor
"com.intellij.moduleService" -> containerDescriptor = descriptor.moduleContainerDescriptor
else -> {
// bean EP can use id / implementation attributes for own bean class
// - that's why we have to create XmlElement even if all attributes are common
val element = if (qualifiedExtensionPointName == "com.intellij.postStartupActivity") {
reader.skipElement()
null
}
else {
readXmlAsModel(reader = reader, rootName = null, interner = interner).takeIf {
!it.children.isEmpty() || !it.attributes.keys.isEmpty()
}
}
var map = descriptor.epNameToExtensions
if (map == null) {
map = HashMap()
descriptor.epNameToExtensions = map
}
val extensionDescriptor = ExtensionDescriptor(implementation, os, orderId, order, element, hasExtraAttributes)
val list = map.get(qualifiedExtensionPointName)
if (list == null) {
map.put(qualifiedExtensionPointName, Collections.singletonList(extensionDescriptor))
}
else if (list.size == 1) {
val l = ArrayList<ExtensionDescriptor>(4)
l.add(list.get(0))
l.add(extensionDescriptor)
map.put(qualifiedExtensionPointName, l)
}
else {
list.add(extensionDescriptor)
}
assert(reader.isEndElement)
return@consumeChildElements
}
}
containerDescriptor.addService(readServiceDescriptor(reader, os))
reader.skipElement()
}
}
private fun readOrder(orderAttr: String?): LoadingOrder {
return when (orderAttr) {
null -> LoadingOrder.ANY
LoadingOrder.FIRST_STR -> LoadingOrder.FIRST
LoadingOrder.LAST_STR -> LoadingOrder.LAST
else -> LoadingOrder(orderAttr)
}
}
private fun checkXInclude(elementName: String, reader: XMLStreamReader2): Boolean {
if (elementName == "include" && reader.namespaceURI == "http://www.w3.org/2001/XInclude") {
LOG.error("`include` is supported only on a root level (${reader.location})")
reader.skipElement()
return true
}
return false
}
@Suppress("DuplicatedCode")
private fun readExtensionPoints(reader: XMLStreamReader2,
descriptor: RawPluginDescriptor,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?) {
reader.consumeChildElements { elementName ->
if (elementName != "extensionPoint") {
if (elementName == "include" && reader.namespaceURI == "http://www.w3.org/2001/XInclude") {
val partial = RawPluginDescriptor()
readInclude(reader = reader,
readInto = partial,
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
allowedPointer = "xpointer(/idea-plugin/extensionPoints/*)")
LOG.warn("`include` is supported only on a root level (${reader.location})")
applyPartialContainer(partial, descriptor) { it.appContainerDescriptor }
applyPartialContainer(partial, descriptor) { it.projectContainerDescriptor }
applyPartialContainer(partial, descriptor) { it.moduleContainerDescriptor }
}
else {
LOG.error("Unknown element: $elementName (${reader.location})")
reader.skipElement()
}
return@consumeChildElements
}
var area: String? = null
var qualifiedName: String? = null
var name: String? = null
var beanClass: String? = null
var `interface`: String? = null
var isDynamic = false
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"area" -> area = getNullifiedAttributeValue(reader, i)
"qualifiedName" -> qualifiedName = reader.getAttributeValue(i)
"name" -> name = getNullifiedAttributeValue(reader, i)
"beanClass" -> beanClass = getNullifiedAttributeValue(reader, i)
"interface" -> `interface` = getNullifiedAttributeValue(reader, i)
"dynamic" -> isDynamic = reader.getAttributeAsBoolean(i)
}
}
if (beanClass == null && `interface` == null) {
throw RuntimeException("Neither beanClass nor interface attribute is specified for extension point at ${reader.location}")
}
if (beanClass != null && `interface` != null) {
throw RuntimeException("Both beanClass and interface attributes are specified for extension point at ${reader.location}")
}
reader.skipElement()
val containerDescriptor = when (area) {
null -> descriptor.appContainerDescriptor
"IDEA_PROJECT" -> descriptor.projectContainerDescriptor
"IDEA_MODULE" -> descriptor.moduleContainerDescriptor
else -> {
LOG.error("Unknown area: $area")
return@consumeChildElements
}
}
var result = containerDescriptor.extensionPoints
if (result == null) {
result = ArrayList()
containerDescriptor.extensionPoints = result
}
result.add(ExtensionPointDescriptor(
name = qualifiedName ?: name ?: throw RuntimeException("`name` attribute not specified for extension point at ${reader.location}"),
isNameQualified = qualifiedName != null,
className = `interface` ?: beanClass!!,
isBean = `interface` == null,
isDynamic = isDynamic
))
}
}
private inline fun applyPartialContainer(from: RawPluginDescriptor,
to: RawPluginDescriptor,
crossinline extractor: (RawPluginDescriptor) -> ContainerDescriptor) {
extractor(from).extensionPoints?.let {
val toContainer = extractor(to)
if (toContainer.extensionPoints == null) {
toContainer.extensionPoints = it
}
else {
toContainer.extensionPoints!!.addAll(it)
}
}
}
@Suppress("DuplicatedCode")
private fun readServiceDescriptor(reader: XMLStreamReader2, os: ExtensionDescriptor.Os?): ServiceDescriptor {
var serviceInterface: String? = null
var serviceImplementation: String? = null
var testServiceImplementation: String? = null
var headlessImplementation: String? = null
var configurationSchemaKey: String? = null
var overrides = false
var preload = ServiceDescriptor.PreloadMode.FALSE
var client: ServiceDescriptor.ClientKind? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"serviceInterface" -> serviceInterface = getNullifiedAttributeValue(reader, i)
"serviceImplementation" -> serviceImplementation = getNullifiedAttributeValue(reader, i)
"testServiceImplementation" -> testServiceImplementation = getNullifiedAttributeValue(reader, i)
"headlessImplementation" -> headlessImplementation = getNullifiedAttributeValue(reader, i)
"configurationSchemaKey" -> configurationSchemaKey = reader.getAttributeValue(i)
"overrides" -> overrides = reader.getAttributeAsBoolean(i)
"preload" -> {
when (reader.getAttributeValue(i)) {
"true" -> preload = ServiceDescriptor.PreloadMode.TRUE
"await" -> preload = ServiceDescriptor.PreloadMode.AWAIT
"notHeadless" -> preload = ServiceDescriptor.PreloadMode.NOT_HEADLESS
"notLightEdit" -> preload = ServiceDescriptor.PreloadMode.NOT_LIGHT_EDIT
else -> LOG.error("Unknown preload mode value ${reader.getAttributeValue(i)} at ${reader.location}")
}
}
"client" -> {
when (reader.getAttributeValue(i)) {
"all" -> client = ServiceDescriptor.ClientKind.ALL
"local" -> client = ServiceDescriptor.ClientKind.LOCAL
"guest" -> client = ServiceDescriptor.ClientKind.GUEST
else -> LOG.error("Unknown client value: ${reader.getAttributeValue(i)} at ${reader.location}")
}
}
}
}
return ServiceDescriptor(serviceInterface, serviceImplementation, testServiceImplementation, headlessImplementation,
overrides, configurationSchemaKey, preload, client, os)
}
private fun readProduct(reader: XMLStreamReader2, descriptor: RawPluginDescriptor) {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"code" -> descriptor.productCode = getNullifiedAttributeValue(reader, i)
"release-date" -> descriptor.releaseDate = parseReleaseDate(reader.getAttributeValue(i))
"release-version" -> {
try {
descriptor.releaseVersion = reader.getAttributeAsInt(i)
}
catch (e: TypedXMLStreamException) {
descriptor.releaseVersion = 0
}
}
"optional" -> descriptor.isLicenseOptional = reader.getAttributeAsBoolean(i)
}
}
reader.skipElement()
}
private fun readComponents(reader: XMLStreamReader2, containerDescriptor: ContainerDescriptor) {
val result = containerDescriptor.getComponentListToAdd()
reader.consumeChildElements("component") {
var isApplicableForDefaultProject = false
var interfaceClass: String? = null
var implementationClass: String? = null
var headlessImplementationClass: String? = null
var os: ExtensionDescriptor.Os? = null
var overrides = false
var options: MutableMap<String, String?>? = null
reader.consumeChildElements { elementName ->
when (elementName) {
"skipForDefaultProject" -> {
val value = reader.elementText
if (!value.isEmpty() && value.equals("false", ignoreCase = true)) {
isApplicableForDefaultProject = true
}
}
"loadForDefaultProject" -> {
val value = reader.elementText
isApplicableForDefaultProject = value.isEmpty() || value.equals("true", ignoreCase = true)
}
"interface-class" -> interfaceClass = getNullifiedContent(reader)
// empty value must be supported
"implementation-class" -> implementationClass = getNullifiedContent(reader)
// empty value must be supported
"headless-implementation-class" -> headlessImplementationClass = reader.elementText
"option" -> {
var name: String? = null
var value: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"name" -> name = getNullifiedAttributeValue(reader, i)
"value" -> value = getNullifiedAttributeValue(reader, i)
}
}
reader.skipElement()
if (name != null && value != null) {
when {
name == "os" -> os = readOs(value)
name == "overrides" -> overrides = value.toBoolean()
options == null -> {
options = Collections.singletonMap(name, value)
}
else -> {
if (options!!.size == 1) {
options = HashMap(options)
}
options!!.put(name, value)
}
}
}
}
else -> reader.skipElement()
}
assert(reader.isEndElement)
}
assert(reader.isEndElement)
result.add(ComponentConfig(interfaceClass, implementationClass, headlessImplementationClass, isApplicableForDefaultProject,
os, overrides, options))
}
}
private fun readContent(reader: XMLStreamReader2,
descriptor: RawPluginDescriptor,
readContext: ReadModuleContext) {
var items = descriptor.contentModules
if (items == null) {
items = ArrayList()
descriptor.contentModules = items
}
reader.consumeChildElements { elementName ->
when (elementName) {
"module" -> {
var name: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"name" -> name = readContext.interner.name(reader.getAttributeValue(i))
}
}
if (name.isNullOrEmpty()) {
throw RuntimeException("Name is not specified at ${reader.location}")
}
var configFile: String? = null
val index = name.lastIndexOf('/')
if (index != -1) {
configFile = "${name.substring(0, index)}.${name.substring(index + 1)}.xml"
}
items.add(PluginContentDescriptor.ModuleItem(name = name, configFile = configFile))
}
else -> throw RuntimeException("Unknown content item type: $elementName")
}
reader.skipElement()
}
assert(reader.isEndElement)
}
private fun readDependencies(reader: XMLStreamReader2, descriptor: RawPluginDescriptor, readContext: ReadModuleContext) {
var modules: MutableList<ModuleDependenciesDescriptor.ModuleReference>? = null
var plugins: MutableList<ModuleDependenciesDescriptor.PluginReference>? = null
reader.consumeChildElements { elementName ->
when (elementName) {
"module" -> {
var name: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"name" -> name = readContext.interner.name(reader.getAttributeValue(i))
}
}
if (modules == null) {
modules = ArrayList()
}
modules!!.add(ModuleDependenciesDescriptor.ModuleReference(name!!))
}
"plugin" -> {
var id: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"id" -> id = readContext.interner.name(reader.getAttributeValue(i))
}
}
if (plugins == null) {
plugins = ArrayList()
}
plugins!!.add(ModuleDependenciesDescriptor.PluginReference(PluginId.getId(id!!)))
}
else -> throw RuntimeException("Unknown content item type: ${elementName}")
}
reader.skipElement()
}
descriptor.dependencies = ModuleDependenciesDescriptor(modules ?: Collections.emptyList(), plugins ?: Collections.emptyList())
assert(reader.isEndElement)
}
private fun findAttributeValue(reader: XMLStreamReader2, name: String): String? {
for (i in 0 until reader.attributeCount) {
if (reader.getAttributeLocalName(i) == name) {
return getNullifiedAttributeValue(reader, i)
}
}
return null
}
private fun getNullifiedContent(reader: XMLStreamReader2): String? = reader.elementText.takeIf { !it.isEmpty() }
private fun getNullifiedAttributeValue(reader: XMLStreamReader2, i: Int) = reader.getAttributeValue(i).takeIf { !it.isEmpty() }
interface ReadModuleContext {
val interner: XmlInterner
val isMissingIncludeIgnored: Boolean
}
private fun readInclude(reader: XMLStreamReader2,
readInto: RawPluginDescriptor,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
allowedPointer: String) {
var path: String? = null
var pointer: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"href" -> path = getNullifiedAttributeValue(reader, i)
"xpointer" -> pointer = reader.getAttributeValue(i)?.takeIf { !it.isEmpty() && it != allowedPointer }
else -> throw RuntimeException("Unknown attribute ${reader.getAttributeLocalName(i)} (${reader.location})")
}
}
if (pointer != null) {
throw RuntimeException("Attribute `xpointer` is not supported anymore (xpointer=$pointer, location=${reader.location})")
}
if (path == null) {
throw RuntimeException("Missing `href` attribute (${reader.location})")
}
var isOptional = false
reader.consumeChildElements("fallback") {
isOptional = true
reader.skipElement()
}
var readError: IOException? = null
val read = try {
pathResolver.loadXIncludeReference(dataLoader = dataLoader,
base = includeBase,
relativePath = path,
readContext = readContext,
readInto = readInto)
}
catch (e: IOException) {
readError = e
false
}
if (read || isOptional) {
return
}
if (readContext.isMissingIncludeIgnored) {
LOG.info("$path include ignored (dataLoader=$dataLoader)", readError)
return
}
else {
throw RuntimeException("Cannot resolve $path (dataLoader=$dataLoader)", readError)
}
}
private var dateTimeFormatter: DateTimeFormatter? = null
private val LOG: Logger
get() = PluginManagerCore.getLogger()
private fun parseReleaseDate(dateString: String): LocalDate? {
if (dateString.isEmpty() || dateString == "__DATE__") {
return null
}
var formatter = dateTimeFormatter
if (formatter == null) {
formatter = DateTimeFormatter.ofPattern("yyyyMMdd", Locale.US)
dateTimeFormatter = formatter
}
try {
return LocalDate.parse(dateString, formatter)
}
catch (e: ParseException) {
LOG.error("Cannot parse release date", e)
}
return null
}
private fun readListeners(reader: XMLStreamReader2, containerDescriptor: ContainerDescriptor) {
var result = containerDescriptor.listeners
if (result == null) {
result = ArrayList()
containerDescriptor.listeners = result
}
reader.consumeChildElements("listener") {
var os: ExtensionDescriptor.Os? = null
var listenerClassName: String? = null
var topicClassName: String? = null
var activeInTestMode = true
var activeInHeadlessMode = true
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"os" -> os = readOs(reader.getAttributeValue(i))
"class" -> listenerClassName = getNullifiedAttributeValue(reader, i)
"topic" -> topicClassName = getNullifiedAttributeValue(reader, i)
"activeInTestMode" -> activeInTestMode = reader.getAttributeAsBoolean(i)
"activeInHeadlessMode" -> activeInHeadlessMode = reader.getAttributeAsBoolean(i)
}
}
if (listenerClassName == null || topicClassName == null) {
LOG.error("Listener descriptor is not correct as ${reader.location}")
}
else {
result.add(ListenerDescriptor(os, listenerClassName, topicClassName, activeInTestMode, activeInHeadlessMode))
}
reader.skipElement()
}
assert(reader.isEndElement)
}
private fun readOs(value: String): ExtensionDescriptor.Os {
return when (value) {
"mac" -> ExtensionDescriptor.Os.mac
"linux" -> ExtensionDescriptor.Os.linux
"windows" -> ExtensionDescriptor.Os.windows
"unix" -> ExtensionDescriptor.Os.unix
"freebsd" -> ExtensionDescriptor.Os.freebsd
else -> throw IllegalArgumentException("Unknown OS: $value")
}
}
private inline fun XMLStreamReader.consumeChildElements(crossinline consumer: (name: String) -> Unit) {
// cursor must be at the start of parent element
assert(isStartElement)
var depth = 1
while (true) {
when (next()) {
XMLStreamConstants.START_ELEMENT -> {
depth++
consumer(localName)
assert(isEndElement)
depth--
}
XMLStreamConstants.END_ELEMENT -> {
if (depth != 1) {
throw IllegalStateException("Expected depth: 1")
}
return
}
XMLStreamConstants.CDATA,
XMLStreamConstants.SPACE,
XMLStreamConstants.CHARACTERS,
XMLStreamConstants.ENTITY_REFERENCE,
XMLStreamConstants.COMMENT,
XMLStreamConstants.PROCESSING_INSTRUCTION -> {
// ignore
}
else -> throw XMLStreamException("Unexpected state: ${getEventTypeString(eventType)}", location)
}
}
}
private inline fun XMLStreamReader2.consumeChildElements(name: String, crossinline consumer: () -> Unit) {
consumeChildElements {
if (name == it) {
consumer()
assert(isEndElement)
}
else {
skipElement()
}
}
}
private fun getEventTypeString(eventType: Int): String {
return when (eventType) {
XMLEvent.START_ELEMENT -> "START_ELEMENT"
XMLEvent.END_ELEMENT -> "END_ELEMENT"
XMLEvent.PROCESSING_INSTRUCTION -> "PROCESSING_INSTRUCTION"
XMLEvent.CHARACTERS -> "CHARACTERS"
XMLEvent.COMMENT -> "COMMENT"
XMLEvent.START_DOCUMENT -> "START_DOCUMENT"
XMLEvent.END_DOCUMENT -> "END_DOCUMENT"
XMLEvent.ENTITY_REFERENCE -> "ENTITY_REFERENCE"
XMLEvent.ATTRIBUTE -> "ATTRIBUTE"
XMLEvent.DTD -> "DTD"
XMLEvent.CDATA -> "CDATA"
XMLEvent.SPACE -> "SPACE"
else -> "UNKNOWN_EVENT_TYPE, $eventType"
}
} | apache-2.0 | b4cebeaf41c939336043a6303633d285 | 36.707596 | 137 | 0.643862 | 4.933424 | false | false | false | false |
subhalaxmin/Programming-Kotlin | Chapter07/src/main/kotlin/com/packt/chapter2/return.kt | 4 | 795 | package com.packt.chapter2
import com.sun.org.apache.xml.internal.security.Init
fun addTwoNumbers(a: Int, b: Int): Int {
return a + b
}
fun largestNumber(a: Int, b: Int, c: Int): Int {
fun largest(a: Int, b: Int): Int {
if (a > b) return a
else return b
}
return largest(largest(a, b), largest(b, c))
}
fun printLessThanTwo() {
val list = listOf(1, 2, 3, 4)
list.forEach(fun(x) {
if (x < 2) println(x)
else return
})
println("This line will still execute")
}
fun printUntilStop1() {
val list = listOf("a", "b", "stop", "c")
list.forEach stop@ {
if (it == "stop") return@stop
else println(it)
}
}
fun printUntilStop2() {
val list = listOf("a", "b", "stop", "c")
list.forEach {
if (it == "stop") return@forEach
else println(it)
}
} | mit | 34a6fbf79c9ea11cf476ebe1c2223ce2 | 18.9 | 52 | 0.601258 | 2.829181 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/KindsResolverProcessor.kt | 1 | 2119 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.processors
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.ProcessorWithHints
import com.intellij.util.containers.enumMapOf
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.util.elementInfo
import org.jetbrains.plugins.groovy.lang.resolve.*
open class KindsResolverProcessor(
protected val name: String,
protected val place: PsiElement,
protected val kinds: Set<GroovyResolveKind>
) : ProcessorWithHints(),
NameHint,
GroovyResolveKind.Hint {
init {
@Suppress("LeakingThis") hint(NameHint.KEY, this)
@Suppress("LeakingThis") hint(GroovyResolveKind.HINT_KEY, this)
}
final override fun getName(state: ResolveState): String? = name
final override fun shouldProcess(kind: GroovyResolveKind): Boolean = kind in kinds
private val candidates = enumMapOf<GroovyResolveKind, GroovyResolveResult>()
final override fun execute(element: PsiElement, state: ResolveState): Boolean {
if (element !is PsiNamedElement) return true
require(element.isValid) {
"Invalid element. ${elementInfo(element)}"
}
val elementName = getName(state, element)
if (name != elementName) return true
val kind = getResolveKind(element)
if (kind == null) {
log.warn("Unknown kind. ${elementInfo(element)}")
}
else if (kind !in kinds) {
if (state[sorryCannotKnowElementKind] != true) {
log.error("Unneeded kind: $kind. ${elementInfo(element)}")
}
}
else if (kind !in candidates) {
candidates[kind] = BaseGroovyResolveResult(element, place, state)
}
return true
}
fun getCandidate(kind: GroovyResolveKind): GroovyResolveResult? = candidates[kind]
fun getAllCandidates(): List<GroovyResolveResult> = candidates.values.toList()
}
| apache-2.0 | e57b07beb4bf109506d01eb102bc8c64 | 34.316667 | 140 | 0.741387 | 4.306911 | false | false | false | false |
algra/pact-jvm | pact-jvm-model/src/main/kotlin/au/com/dius/pact/model/PactReader.kt | 1 | 4100 | package au.com.dius.pact.model
import au.com.dius.pact.provider.broker.PactBrokerClient
import au.com.dius.pact.provider.broker.com.github.kittinunf.result.Result
import au.com.dius.pact.util.HttpClientUtils
import au.com.dius.pact.util.HttpClientUtils.isJsonResponse
import com.google.gson.JsonElement
import com.google.gson.JsonParser
import groovy.json.JsonSlurper
import mu.KotlinLogging
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.methods.HttpGet
import org.apache.http.entity.ContentType
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import java.net.URI
import java.net.URL
private val logger = KotlinLogging.logger {}
private val ACCEPT_JSON = mutableMapOf("requestProperties" to mutableMapOf("Accept" to "application/json"))
data class InvalidHttpResponseException(override val message: String) : RuntimeException(message)
fun loadPactFromUrl(source: UrlPactSource, options: Map<String, Any>, http: CloseableHttpClient?): Pair<Any, PactSource> {
return when (source) {
is BrokerUrlSource -> {
val brokerClient = PactBrokerClient(source.pactBrokerUrl, options)
val pactResponse = brokerClient.fetchPact(source.url)
pactResponse.pactFile to source.copy(attributes = pactResponse.links, options = options)
}
else -> if (options.containsKey("authentication")) {
val jsonResource = fetchJsonResource(http!!, options, source)
when (jsonResource) {
is Result.Success -> jsonResource.value
is Result.Failure -> throw jsonResource.error
}
} else {
JsonSlurper().parse(URL(source.url), ACCEPT_JSON) to source
}
}
}
fun fetchJsonResource(http: CloseableHttpClient, options: Map<String, Any>, source: UrlPactSource):
Result<Pair<JsonElement, UrlPactSource>, Exception> {
return Result.of {
val httpGet = HttpGet(HttpClientUtils.buildUrl("", source.url, true))
httpGet.addHeader("Content-Type", "application/json")
httpGet.addHeader("Accept", "application/hal+json, application/json")
val response = http.execute(httpGet)
if (response.statusLine.statusCode < 300) {
val contentType = ContentType.getOrDefault(response.entity)
if (isJsonResponse(contentType)) {
return@of JsonParser().parse(EntityUtils.toString(response.entity)) to source
} else {
throw InvalidHttpResponseException("Expected a JSON response, but got '$contentType'")
}
} else {
when (response.statusLine.statusCode) {
404 -> throw InvalidHttpResponseException("No JSON document found at source '$source'")
else -> throw InvalidHttpResponseException("Request to source '$source' failed with response " +
"'${response.statusLine}'")
}
}
}
}
fun newHttpClient(baseUrl: String, options: Map<String, Any>): CloseableHttpClient {
val builder = HttpClients.custom().useSystemProperties()
if (options["authentication"] is List<*>) {
val authentication = options["authentication"] as List<*>
val scheme = authentication.first().toString().toLowerCase()
when (scheme) {
"basic" -> {
if (authentication.size > 2) {
val credsProvider = BasicCredentialsProvider()
val uri = URI(baseUrl)
credsProvider.setCredentials(AuthScope(uri.host, uri.port),
UsernamePasswordCredentials(authentication[1].toString(), authentication[2].toString()))
builder.setDefaultCredentialsProvider(credsProvider)
} else {
logger.warn { "Basic authentication requires a username and password, ignoring." }
}
}
else -> logger.warn { "Only supports basic authentication, got '$scheme', ignoring." }
}
} else if (options.containsKey("authentication")) {
logger.warn { "Authentication options needs to be a list of values, got '${options["authentication"]}', ignoring." }
}
return builder.build()
}
| apache-2.0 | 594a4de8f5d2eb7c9c381b64b742c5a5 | 41.268041 | 122 | 0.722927 | 4.34322 | false | false | false | false |
google/intellij-community | plugins/kotlin/code-insight/intentions-shared/src/org/jetbrains/kotlin/idea/codeInsight/intentions/shared/AddBracesToAllBranchesIntention.kt | 3 | 3378 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight.intentions.shared
import com.intellij.openapi.editor.Editor
import com.intellij.util.containers.addIfNotNull
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.psi.*
internal class AddBracesToAllBranchesIntention : SelfTargetingIntention<KtExpression>(
KtExpression::class.java,
KotlinBundle.lazyMessage("add.braces.to.all.branches")
) {
override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean {
val targetIfOrWhenExpression = targetIfOrWhenExpression(element) ?: return false
if (targetIfOrWhenExpression.targetBranchExpressions().isEmpty()) return false
when (targetIfOrWhenExpression) {
is KtIfExpression -> setTextGetter(KotlinBundle.lazyMessage("add.braces.to.if.all.statements"))
is KtWhenExpression -> setTextGetter(KotlinBundle.lazyMessage("add.braces.to.when.all.entries"))
}
return true
}
override fun applyTo(element: KtExpression, editor: Editor?) {
val targetIfOrWhenExpression = targetIfOrWhenExpression(element) ?: return
targetIfOrWhenExpression.targetBranchExpressions().forEach {
AddBracesIntention.addBraces(targetIfOrWhenExpression, it)
}
}
private fun KtExpression.targetBranchExpressions(): List<KtExpression> {
val branchExpressions = allBranchExpressions()
if (branchExpressions.size <= 1) return emptyList()
return branchExpressions.filter { it !is KtBlockExpression }
}
companion object {
fun targetIfOrWhenExpression(element: KtExpression): KtExpression? {
return when (element) {
is KtIfExpression -> {
var target = element
while (true) {
val container = target.parent as? KtContainerNodeForControlStructureBody ?: break
val parent = container.parent as? KtIfExpression ?: break
if (parent.`else` != target) break
target = parent
}
target
}
is KtWhenExpression -> element
is KtBlockExpression -> (element.parent.parent as? KtExpression)?.let { targetIfOrWhenExpression(it) }
else -> null
}
}
fun KtExpression.allBranchExpressions(): List<KtExpression> = when (this) {
is KtIfExpression -> {
val branchExpressions = mutableListOf<KtExpression>()
fun collect(ifExpression: KtIfExpression) {
branchExpressions.addIfNotNull(ifExpression.then)
when (val elseExpression = ifExpression.`else`) {
is KtIfExpression -> collect(elseExpression)
else -> branchExpressions.addIfNotNull(elseExpression)
}
}
collect(this)
branchExpressions
}
is KtWhenExpression -> entries.mapNotNull { it.expression }
else -> emptyList()
}
}
}
| apache-2.0 | ae409f7cd908212c78142bc9ee525c24 | 44.648649 | 120 | 0.636175 | 5.519608 | false | false | false | false |
google/intellij-community | python/python-terminal/src/com/jetbrains/python/sdk/PyVirtualEnvTerminalCustomizer.kt | 2 | 6528 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.python.packaging.PyCondaPackageService
import com.jetbrains.python.run.findActivateScript
import com.jetbrains.python.sdk.flavors.CondaEnvSdkFlavor
import org.jetbrains.plugins.terminal.LocalTerminalCustomizer
import org.jetbrains.plugins.terminal.TerminalOptionsProvider
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
import javax.swing.JCheckBox
import kotlin.io.path.Path
import kotlin.io.path.exists
import kotlin.io.path.isExecutable
import kotlin.io.path.name
class PyVirtualEnvTerminalCustomizer : LocalTerminalCustomizer() {
private fun generateCommandForPowerShell(sdk: Sdk, sdkHomePath: VirtualFile): Array<out String>? {
// TODO: This should be migrated to Targets API: each target provides terminal
if ((sdk.sdkAdditionalData as? PythonSdkAdditionalData)?.flavor is CondaEnvSdkFlavor) {
// Activate conda
val condaPath = PyCondaPackageService.getCondaExecutable(sdk.homePath)?.let { Path(it) }
val condaActivationCommand: String
if (condaPath != null && condaPath.exists() && condaPath.isExecutable()) {
condaActivationCommand = getCondaActivationCommand(condaPath, sdkHomePath)
}
else {
logger<PyVirtualEnvTerminalCustomizer>().warn("Can't find $condaPath, will not activate conda")
condaActivationCommand = PyTerminalBundle.message("powershell.conda.not.activated", "conda")
}
return arrayOf("powershell.exe", "-NoExit", "-Command", condaActivationCommand)
}
// Activate convenient virtualenv
val virtualEnvProfile = sdkHomePath.parent.findChild("activate.ps1") ?: return null
return if (virtualEnvProfile.exists()) arrayOf("powershell.exe", "-NoExit", "-File", virtualEnvProfile.path) else null
}
/**
*``conda init`` installs conda activation hook into user profile
* We run this hook manually because we can't ask user to install hook and restart terminal
* In case of failure we ask user to run "conda init" manually
*/
private fun getCondaActivationCommand(condaPath: Path, sdkHomePath: VirtualFile): String {
// ' are in "Write-Host"
val errorMessage = PyTerminalBundle.message("powershell.conda.not.activated", condaPath).replace('\'', '"')
// No need to escape path: conda can't have spaces
return """
$condaPath shell.powershell hook | Out-String | Invoke-Expression ;
try { conda activate ${sdkHomePath.parent.path} } catch { Write-Host('$errorMessage') }
""".trim()
}
override fun customizeCommandAndEnvironment(project: Project,
workingDirectory: String?,
command: Array<out String>,
envs: MutableMap<String, String>): Array<out String> {
var sdk: Sdk? = null
if (workingDirectory != null) {
sdk = PySdkUtil.findSdkForDirectory(project, Paths.get(workingDirectory), false)
}
if (sdk != null &&
(PythonSdkUtil.isVirtualEnv(sdk) || PythonSdkUtil.isConda(sdk)) &&
PyVirtualEnvTerminalSettings.getInstance(project).virtualEnvActivate) {
// in case of virtualenv sdk on unix we activate virtualenv
val sdkHomePath = sdk.homeDirectory
if (sdkHomePath != null && command.isNotEmpty()) {
val shellPath = command[0]
if (Path(shellPath).name == "powershell.exe") {
return generateCommandForPowerShell(sdk, sdkHomePath) ?: command
}
if (isShellIntegrationAvailable(shellPath)) { //fish shell works only for virtualenv and not for conda
//for bash we pass activate script to jediterm shell integration (see jediterm-bash.in) to source it there
//TODO: fix conda for fish
findActivateScript(sdkHomePath.path, shellPath)?.let { activate ->
envs.put("JEDITERM_SOURCE", activate.first)
envs.put("JEDITERM_SOURCE_ARGS", activate.second ?: "")
}
}
else {
//for other shells we read envs from activate script by the default shell and pass them to the process
envs.putAll(PySdkUtil.activateVirtualEnv(sdk))
}
}
}
return command
}
private fun isShellIntegrationAvailable(shellPath: String): Boolean {
if (TerminalOptionsProvider.instance.shellIntegration) {
val shellName = File(shellPath).name
return shellName == "bash" || (SystemInfo.isMac && shellName == "sh") || shellName == "zsh" || shellName == "fish"
}
return false
}
override fun getConfigurable(project: Project): UnnamedConfigurable = object : UnnamedConfigurable {
val settings = PyVirtualEnvTerminalSettings.getInstance(project)
var myCheckbox: JCheckBox = JCheckBox(PyTerminalBundle.message("activate.virtualenv.checkbox.text"))
override fun createComponent() = myCheckbox
override fun isModified() = myCheckbox.isSelected != settings.virtualEnvActivate
override fun apply() {
settings.virtualEnvActivate = myCheckbox.isSelected
}
override fun reset() {
myCheckbox.isSelected = settings.virtualEnvActivate
}
}
}
class SettingsState {
var virtualEnvActivate: Boolean = true
}
@State(name = "PyVirtualEnvTerminalCustomizer", storages = [(Storage("python-terminal.xml"))])
class PyVirtualEnvTerminalSettings : PersistentStateComponent<SettingsState> {
var myState: SettingsState = SettingsState()
var virtualEnvActivate: Boolean
get() = myState.virtualEnvActivate
set(value) {
myState.virtualEnvActivate = value
}
override fun getState(): SettingsState = myState
override fun loadState(state: SettingsState) {
myState.virtualEnvActivate = state.virtualEnvActivate
}
companion object {
fun getInstance(project: Project): PyVirtualEnvTerminalSettings {
return project.getService(PyVirtualEnvTerminalSettings::class.java)
}
}
}
| apache-2.0 | ff1f9e42b22ac46fec3ba4eb974ae9ff | 39.04908 | 140 | 0.712929 | 4.706561 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/remote/personal_deadlines/mapper/DeadlinesMapper.kt | 2 | 1817 | package org.stepik.android.remote.personal_deadlines.mapper
import com.google.gson.GsonBuilder
import org.stepic.droid.jsonHelpers.adapters.UTCDateAdapter
import org.stepic.droid.web.storage.model.StorageRecord
import org.stepic.droid.web.storage.model.StorageRecordWrapped
import org.stepik.android.data.personal_deadlines.getKindOfRecord
import org.stepik.android.domain.personal_deadlines.model.DeadlinesWrapper
import org.stepik.android.remote.remote_storage.model.StorageRequest
import org.stepik.android.remote.remote_storage.model.StorageResponse
import java.util.Date
import javax.inject.Inject
class DeadlinesMapper
@Inject
constructor() {
private val gson = GsonBuilder()
.registerTypeAdapter(Date::class.java, UTCDateAdapter())
.create()
fun mapToStorageRequest(deadlines: DeadlinesWrapper, recordId: Long? = null): StorageRequest =
StorageRequest(
StorageRecordWrapped(
id = recordId,
kind = getKindOfRecord(deadlines.course),
data = gson.toJsonTree(deadlines)
)
)
fun mapToStorageRequest(record: StorageRecord<DeadlinesWrapper>): StorageRequest =
StorageRequest(record.wrap(gson))
fun mapToStorageRecord(response: StorageResponse): StorageRecord<DeadlinesWrapper>? =
response
.records
.firstOrNull()
?.let(::unwrapStorageRecord)
fun mapToStorageRecordList(response: StorageResponse): List<StorageRecord<DeadlinesWrapper>> =
response
.records
.mapNotNull(::unwrapStorageRecord)
private fun unwrapStorageRecord(record: StorageRecordWrapped): StorageRecord<DeadlinesWrapper>? =
record
.unwrap<DeadlinesWrapper>(gson)
.takeIf { it.data.deadlines != null }
} | apache-2.0 | 000846cd503722a5429aee90e9460cdc | 36.875 | 101 | 0.718767 | 4.744125 | false | false | false | false |
ursjoss/sipamato | core/core-web/src/main/java/ch/difty/scipamato/core/web/paper/jasper/summary/PaperSummary.kt | 2 | 948 | package ch.difty.scipamato.core.web.paper.jasper.summary
import ch.difty.scipamato.core.entity.Paper
import ch.difty.scipamato.core.web.paper.jasper.CoreShortFieldConcatenator
import ch.difty.scipamato.core.web.paper.jasper.PaperSummaryCommon
import ch.difty.scipamato.core.web.paper.jasper.ReportHeaderFields
import ch.difty.scipamato.core.web.paper.jasper.na
/**
* DTO to feed the PaperSummaryDataSource
*/
class PaperSummary(
p: Paper,
shortFieldConcatenator: CoreShortFieldConcatenator,
rhf: ReportHeaderFields,
) : PaperSummaryCommon(p, shortFieldConcatenator, rhf) {
val population: String = na(shortFieldConcatenator.populationFrom(p, rhf))
val result: String = na(shortFieldConcatenator.resultFrom(p, rhf))
val populationLabel: String = na(rhf.populationLabel, population)
val resultLabel: String = na(rhf.resultLabel, result)
companion object {
private const val serialVersionUID = 1L
}
}
| gpl-3.0 | d999164d5922a127f8b49a9391a3de3e | 35.461538 | 78 | 0.777426 | 3.618321 | false | false | false | false |
allotria/intellij-community | build/launch/src/com/intellij/tools/launch/DockerLauncher.kt | 3 | 9785 | package com.intellij.tools.launch
import com.intellij.openapi.util.SystemInfo
import com.intellij.tools.launch.Launcher.affixIO
import com.sun.security.auth.module.UnixSystem
import org.apache.log4j.Logger
import java.io.File
import java.nio.file.Files
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.math.pow
class DockerLauncher(private val paths: PathsProvider, private val options: DockerLauncherOptions) {
companion object {
private val logger = Logger.getLogger(DockerLauncher::class.java)
private val random = Random()
}
private val UBUNTU_18_04_WITH_USER_TEMPLATE = "ubuntu-18-04-docker-launcher"
fun assertCanRun() = dockerInfo()
fun runInContainer(cmd: List<String>): Process {
// we try to make everything the same as on the host folder, e.g. UID, paths
val username = System.getProperty("user.name")
val uid = UnixSystem().uid.toString()
val userHomePath = File(System.getProperty("user.home"))
// e.g. ~/.m2/ will be /mnt/cache/.m2 on TC
fun File.pathNotResolvingSymlinks() = this.absoluteFile.normalize().path
if (!userHomePath.exists()) error("Home directory ${userHomePath.pathNotResolvingSymlinks()} of user=$username, uid=$uid does not exist")
val imageName = "$UBUNTU_18_04_WITH_USER_TEMPLATE-user-$username-uid-$uid"
val buildArgs = mapOf(
"USER_NAME" to username,
"USER_ID" to UnixSystem().uid.toString(),
"USER_HOME" to userHomePath.pathNotResolvingSymlinks()
)
dockerBuild(imageName, buildArgs)
val containerIdFile = File.createTempFile("cwm.docker.cid", "")
fun MutableList<String>.addVolume(volume: File, isWritable: Boolean) {
fun volumeParameter(volume: String, isWritable: Boolean) = "--volume=$volume:$volume:${if (isWritable) "rw" else "ro"}"
val canonical = volume.canonicalPath
this.add(volumeParameter(canonical, isWritable))
// there's no consistency as to whether symlinks are resolved in user code, so we'll try our best and provide both
val notResolvingSymlinks = volume.pathNotResolvingSymlinks()
if (canonical != notResolvingSymlinks)
this.add(volumeParameter(notResolvingSymlinks, isWritable))
}
fun MutableList<String>.addReadonly(volume: File) = addVolume(volume, false)
fun MutableList<String>.addWriteable(volume: File) = addVolume(volume, true)
val dockerCmd = mutableListOf(
"docker",
"run",
// for network configuration (e.g. default gateway)
"--cap-add=NET_ADMIN",
"--cidfile",
containerIdFile.pathNotResolvingSymlinks(),
// -u=USER_NAME will throw if user does not exist, but -u=UID will not
"--user=$username"
)
val containerName = if (options.containerName != null)
"${options.containerName}-${System.nanoTime()}".let {
dockerCmd.add("--name=$it")
it
}
else null
// **** RW ****
val writeable = listOf(paths.logFolder,
paths.configFolder,
paths.systemFolder,
paths.outputRootFolder, // classpath index making a lot of noise
paths.ultimateRootFolder.resolve("platform/cwm-tests/general/data"), // classpath index making a lot of noise in stderr
paths.communityRootFolder.resolve("build/download")) // quiche lib
// docker can create these under root, so we create them ourselves
writeable.forEach {
Files.createDirectories(it.toPath())
dockerCmd.addWriteable(it)
}
// **** RO ****
dockerCmd.addReadonly(paths.javaHomeFolder)
// jars
dockerCmd.addReadonly(paths.communityBinFolder)
dockerCmd.addReadonly(paths.communityRootFolder.resolve("lib"))
dockerCmd.addReadonly(paths.ultimateRootFolder.resolve("lib"))
dockerCmd.addReadonly(paths.ultimateRootFolder.resolve("plugins"))
dockerCmd.addReadonly(paths.ultimateRootFolder.resolve("contrib"))
// a lot of jars in classpaths, /plugins, /xml, so we'll just mount the whole root
dockerCmd.addReadonly(paths.communityRootFolder)
// main jar itself
dockerCmd.addReadonly(paths.launcherFolder)
// ~/.m2
dockerCmd.addReadonly(paths.mavenRepositoryFolder)
// quiche
dockerCmd.addReadonly(paths.ultimateRootFolder.resolve(".idea"))
// user-provided volumes
paths.dockerVolumesToWritable.forEach { (volume, isWriteable) -> dockerCmd.addVolume(volume, isWriteable) }
options.exposedPorts.forEach {
dockerCmd.add("-p")
dockerCmd.add("127.0.0.1:$it:$it")
}
options.environment.forEach {
dockerCmd.add("--env")
dockerCmd.add("${it.key}=${it.value}")
}
if (options.network != DockerNetwork.AUTO) {
dockerCmd.addAll(listOf(
"--network", options.network.name,
"--ip", options.network.IPv4Address
))
}
dockerCmd.add(imageName)
logger.info(dockerCmd.joinToString("\n"))
// docker will still have a route for all subnet packets to go through the host, this only affects anything not in the subnet
val ipRouteBash = if (options.network != DockerNetwork.AUTO && options.network.defaultGatewayIPv4Address != null) "sudo ip route change default via ${options.network.defaultGatewayIPv4Address}" else null
if (options.runBashBeforeJava != null || ipRouteBash != null) {
dockerCmd.add("/bin/bash")
dockerCmd.add("-c")
val cmdHttpLinkSomewhatEscaped = cmd.joinToString(" ").replace("&", "\\&")
var entrypointBash = ""
if (ipRouteBash != null)
entrypointBash += "$ipRouteBash && "
if (options.runBashBeforeJava != null)
entrypointBash += "${options.runBashBeforeJava} && "
dockerCmd.add("$entrypointBash$cmdHttpLinkSomewhatEscaped")
}
else {
dockerCmd.addAll(cmd)
}
if (containerIdFile.exists())
assert(containerIdFile.delete())
val containerIdPath = containerIdFile.pathNotResolvingSymlinks()
val dockerRunPb = ProcessBuilder(dockerCmd)
dockerRunPb.affixIO(options.redirectOutputIntoParentProcess, paths.logFolder)
val dockerRun = dockerRunPb.start()
val readableCmd = dockerRunPb.command().joinToString(" ")
logger.info("Docker run cmd=$readableCmd")
logger.info("Started docker run, waiting for container ID at ${containerIdPath}")
// using WatchService is overkill here
for (i in 1..5) {
if (!dockerRun.isAlive) error("docker run exited with code ${dockerRun.exitValue()}")
if (containerIdFile.exists() && containerIdFile.length() > 0) {
logger.info("Container ID file with non-zero length detected at ${containerIdPath}")
break;
}
val sleepMillis = 100L * 2.0.pow(i).toLong()
logger.info("No container ID in file ${containerIdPath} yet, sleeping for $sleepMillis")
Thread.sleep(sleepMillis)
}
val containerId = containerIdFile.readText()
if (containerId.isEmpty()) error { "Started container ID must not be empty" }
logger.info("Container ID=$containerId")
if (containerName != null) {
fun isInDockerPs() = runCmd(1, TimeUnit.MINUTES, true, paths.tempFolder, true, "docker", "ps").count { it.contains(containerName) } > 0
for (i in 1..5) {
if (!dockerRun.isAlive) error("docker run exited with code ${dockerRun.exitValue()}")
if (isInDockerPs()) {
logger.info("Container with name $containerName detected in docker ps output")
break;
}
val sleepMillis = 100L * 2.0.pow(i).toLong()
logger.info("No container with name $containerName in docker ps output, sleeping for $sleepMillis")
Thread.sleep(sleepMillis)
}
}
return dockerRun
}
private fun dockerInfo() = runCmd(1, TimeUnit.MINUTES, false, paths.tempFolder, false, "docker", "info")
private fun dockerKill(containerId: String) = runCmd(1, TimeUnit.MINUTES, false, paths.tempFolder,false, "docker", "kill", containerId)
private fun dockerBuild(tag: String, buildArgs: Map<String, String>) {
val dockerBuildCmd = listOf("docker", "build", "-t", tag).toMutableList()
buildArgs.forEach {
dockerBuildCmd.add("--build-arg")
dockerBuildCmd.add("${it.key}=${it.value}")
}
dockerBuildCmd.add(".")
runCmd(10,
TimeUnit.MINUTES,
true,
paths.communityRootFolder.resolve("build/launch/src/com/intellij/tools/launch"),
false,
*dockerBuildCmd.toTypedArray())
}
private fun runCmd(timeout: Long, unit: TimeUnit, assertSuccess: Boolean, workDir: File, captureStdout: Boolean = false, vararg cmd: String): List<String> {
if (!SystemInfo.isLinux)
error("We are heavily relaying on paths being the same everywhere and may use networks, so only Linux can be used as a host system.")
val processBuilder = ProcessBuilder(*cmd)
processBuilder.directory(workDir)
val stdoutFile = File.createTempFile(cmd[0], "out")
@Suppress("SSBasedInspection")
stdoutFile.deleteOnExit()
if (!captureStdout)
processBuilder.affixIO(options.redirectOutputIntoParentProcess, paths.logFolder)
else
processBuilder.redirectOutput(stdoutFile)
val readableCmd = cmd.joinToString(" ", prefix = "'", postfix = "'")
logger.info(readableCmd)
val process = processBuilder.start()
try {
if (!process.waitFor(timeout, unit))
error("${cmd[0]} failed to exit under required timeout of $timeout $unit, will destroy it")
if (assertSuccess)
if (process.exitValue() != 0) error("${cmd[0]} exited with non-zero exit code ${process.exitValue()}. Full commandline: ${cmd.joinToString(" ")}")
} finally {
process.destroy()
}
return stdoutFile.readLines()
}
} | apache-2.0 | bd230a945e552eee6567dce472c1d98e | 35.789474 | 207 | 0.676137 | 4.126951 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerExImpl.kt | 1 | 18355 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.project.impl
import com.intellij.conversion.ConversionResult
import com.intellij.conversion.ConversionService
import com.intellij.diagnostic.ActivityCategory
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.diagnostic.runMainActivity
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.AppLifecycleListener
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.impl.setTrusted
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.ide.startup.impl.StartupManagerImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.StorageScheme
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.getProjectDataPathRoot
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.platform.PlatformProjectOpenProcessor
import com.intellij.project.ProjectStoreOwner
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.projectImport.ProjectOpenedCallback
import com.intellij.serviceContainer.processProjectComponents
import com.intellij.ui.GuiUtils
import com.intellij.ui.IdeUICustomization
import com.intellij.util.io.delete
import org.jetbrains.annotations.ApiStatus
import java.awt.event.InvocationEvent
import java.io.IOException
import java.nio.file.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import java.util.function.BiFunction
@ApiStatus.Internal
open class ProjectManagerExImpl : ProjectManagerImpl() {
final override fun createProject(name: String?, path: String): Project? {
return newProject(toCanonicalName(path), OpenProjectTask(isNewProject = true, runConfigurators = false, projectName = name))
}
final override fun newProject(projectName: String?, path: String, useDefaultProjectAsTemplate: Boolean, isDummy: Boolean): Project? {
return newProject(toCanonicalName(path), OpenProjectTask(isNewProject = true,
useDefaultProjectAsTemplate = useDefaultProjectAsTemplate,
projectName = projectName))
}
final override fun loadAndOpenProject(originalFilePath: String): Project? {
return openProject(toCanonicalName(originalFilePath), OpenProjectTask())
}
final override fun openProject(projectStoreBaseDir: Path, options: OpenProjectTask): Project? {
return openProjectAsync(projectStoreBaseDir, options).get(30, TimeUnit.MINUTES)
}
final override fun openProjectAsync(projectStoreBaseDir: Path, options: OpenProjectTask): CompletableFuture<Project?> {
val app = ApplicationManager.getApplication()
if (LOG.isDebugEnabled && !app.isUnitTestMode) {
LOG.debug("open project: $options", Exception())
}
if (options.project != null && isProjectOpened(options.project)) {
return CompletableFuture.completedFuture(null)
}
val activity = StartUpMeasurer.startMainActivity("project opening preparation")
if (!options.forceOpenInNewFrame) {
val openProjects = openProjects
if (!openProjects.isNullOrEmpty()) {
var projectToClose = options.projectToClose
if (projectToClose == null) {
// if several projects are opened, ask to reuse not last opened project frame, but last focused (to avoid focus switching)
val lastFocusedFrame = IdeFocusManager.getGlobalInstance().lastFocusedFrame
projectToClose = lastFocusedFrame?.project
if (projectToClose == null || projectToClose is LightEditCompatible) {
projectToClose = openProjects[openProjects.size - 1]
}
}
// this null assertion is required to overcome bug in new version of KT compiler: KT-40034
@Suppress("UNNECESSARY_NOT_NULL_ASSERTION")
if (checkExistingProjectOnOpen(projectToClose!!, options.callback, projectStoreBaseDir, this)) {
return CompletableFuture.completedFuture(null)
}
}
}
val frameAllocator = if (app.isHeadlessEnvironment) ProjectFrameAllocator(options) else ProjectUiFrameAllocator(options, projectStoreBaseDir)
val disableAutoSaveToken = SaveAndSyncHandler.getInstance().disableAutoSave()
return frameAllocator.run {
activity.end()
val result: PrepareProjectResult
if (options.project == null) {
result = prepareProject(options, projectStoreBaseDir) ?: return@run null
}
else {
result = PrepareProjectResult(options.project, null)
}
val project = result.project
if (!addToOpened(project)) {
return@run null
}
frameAllocator.projectLoaded(project)
try {
openProject(project, ProgressManager.getInstance().progressIndicator, isRunStartUpActivitiesEnabled(project))
}
catch (e: ProcessCanceledException) {
app.invokeAndWait { closeProject(project, /* saveProject = */false, /* dispose = */true, /* checkCanClose = */false) }
app.messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed()
return@run null
}
frameAllocator.projectOpened(project)
result
}
.handle(BiFunction { result, error ->
disableAutoSaveToken.finish()
if (error != null) {
throw error
}
if (result == null) {
frameAllocator.projectNotLoaded(error = null)
if (options.showWelcomeScreen) {
WelcomeFrame.showIfNoProjectOpened()
}
return@BiFunction null
}
val project = result.project
if (options.callback != null) {
options.callback!!.projectOpened(project, result.module ?: ModuleManager.getInstance(project).modules[0])
}
project
})
}
override fun openProject(project: Project): Boolean {
val store = if (project is ProjectStoreOwner) (project as ProjectStoreOwner).componentStore else null
if (store != null) {
val projectFilePath = if (store.storageScheme == StorageScheme.DIRECTORY_BASED) store.directoryStorePath!! else store.projectFilePath
for (p in openProjects) {
if (ProjectUtil.isSameProject(projectFilePath, p)) {
GuiUtils.invokeLaterIfNeeded({ ProjectUtil.focusProjectWindow(p, false) }, ModalityState.NON_MODAL)
return false
}
}
}
return doOpenProject(project)
}
@ApiStatus.Internal
private fun doOpenProject(project: Project): Boolean {
if (!addToOpened(project)) {
return false
}
val app = ApplicationManager.getApplication()
if (!app.isUnitTestMode && app.isDispatchThread) {
LOG.warn("Do not open project in EDT")
}
try {
openProject(project, ProgressManager.getInstance().progressIndicator, isRunStartUpActivitiesEnabled(project))
}
catch (e: ProcessCanceledException) {
app.invokeAndWait { closeProject(project, /* saveProject = */false, /* dispose = */true, /* checkCanClose = */false) }
app.messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed()
if (!app.isUnitTestMode) {
WelcomeFrame.showIfNoProjectOpened()
}
return false
}
return true
}
override fun newProject(projectFile: Path, options: OpenProjectTask): Project? {
removeProjectConfigurationAndCaches(projectFile)
val project = instantiateProject(projectFile, options)
try {
val template = if (options.useDefaultProjectAsTemplate) defaultProject else null
initProject(projectFile, project, options.isRefreshVfsNeeded, options.preloadServices, template,
ProgressManager.getInstance().progressIndicator)
project.setTrusted(true)
return project
}
catch (t: Throwable) {
handleErrorOnNewProject(t)
return null
}
}
protected open fun handleErrorOnNewProject(t: Throwable) {
LOG.warn(t)
try {
val errorMessage = message(t)
ApplicationManager.getApplication().invokeAndWait {
Messages.showErrorDialog(errorMessage, ProjectBundle.message("project.load.default.error"))
}
}
catch (e: NoClassDefFoundError) {
// error icon not loaded
LOG.info(e)
}
}
protected open fun instantiateProject(projectStoreBaseDir: Path, options: OpenProjectTask): ProjectImpl {
val activity = StartUpMeasurer.startMainActivity("project instantiation")
val project = ProjectExImpl(projectStoreBaseDir, options.projectName)
activity.end()
options.beforeInit?.invoke(project)
return project
}
private fun prepareProject(options: OpenProjectTask, projectStoreBaseDir: Path): PrepareProjectResult? {
val project: Project?
val indicator = ProgressManager.getInstance().progressIndicator
if (options.isNewProject) {
removeProjectConfigurationAndCaches(projectStoreBaseDir)
project = instantiateProject(projectStoreBaseDir, options)
val template = if (options.useDefaultProjectAsTemplate) defaultProject else null
initProject(projectStoreBaseDir, project, options.isRefreshVfsNeeded, options.preloadServices, template, indicator)
}
else {
var conversionResult: ConversionResult? = null
if (options.runConversionBeforeOpen) {
val conversionService = ConversionService.getInstance()
if (conversionService != null) {
indicator?.text = IdeUICustomization.getInstance().projectMessage("progress.text.project.checking.configuration")
conversionResult = runMainActivity("project conversion") {
conversionService.convert(projectStoreBaseDir)
}
if (conversionResult.openingIsCanceled()) {
return null
}
indicator?.text = ""
}
}
project = instantiateProject(projectStoreBaseDir, options)
// template as null here because it is not a new project
initProject(projectStoreBaseDir, project, options.isRefreshVfsNeeded, options.preloadServices, null, indicator)
if (conversionResult != null && !conversionResult.conversionNotNeeded()) {
StartupManager.getInstance(project).runAfterOpened {
conversionResult.postStartupActivity(project)
}
}
}
@Suppress("UNNECESSARY_NOT_NULL_ASSERTION")
if (options.beforeOpen != null && !options.beforeOpen!!(project)) {
return null
}
if (options.runConfigurators && (options.isNewProject || ModuleManager.getInstance(project).modules.isEmpty())) {
val module = PlatformProjectOpenProcessor.runDirectoryProjectConfigurators(projectStoreBaseDir, project,
options.isProjectCreatedWithWizard)
options.preparedToOpen?.invoke(module)
return PrepareProjectResult(project, module)
}
else {
return PrepareProjectResult(project, module = null)
}
}
protected open fun isRunStartUpActivitiesEnabled(project: Project): Boolean = true
}
@NlsSafe
private fun message(e: Throwable): String {
var message = e.message ?: e.localizedMessage
if (message != null) {
return message
}
message = e.toString()
val causeMessage = message(e.cause ?: return message)
return "$message (cause: $causeMessage)"
}
private fun checkExistingProjectOnOpen(projectToClose: Project,
callback: ProjectOpenedCallback?,
projectDir: Path?,
projectManager: ProjectManagerExImpl): Boolean {
val result = CompletableFuture<Boolean>()
val settings = GeneralSettings.getInstance()
val isValidProject = projectDir != null && ProjectUtil.isValidProjectPath(projectDir)
ApplicationManager.getApplication().invokeAndWait{
try {
if (projectDir != null && ProjectAttachProcessor.canAttachToProject() &&
(!isValidProject || settings.confirmOpenNewProject == GeneralSettings.OPEN_PROJECT_ASK)) {
val exitCode = ProjectUtil.confirmOpenOrAttachProject()
if (exitCode == -1) {
result.complete(true)
return@invokeAndWait
}
else if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
if (!projectManager.closeAndDispose(projectToClose)) {
result.complete(true)
return@invokeAndWait
}
}
else if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH) {
if (PlatformProjectOpenProcessor.attachToProject(projectToClose, projectDir, callback)) {
result.complete(true)
return@invokeAndWait
}
}
// process all pending events that can interrupt focus flow
// todo this can be removed after taming the focus beast
IdeEventQueue.getInstance().flushQueue()
}
else {
val exitCode = ProjectUtil.confirmOpenNewProject(false)
if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
if (!projectManager.closeAndDispose(projectToClose)) {
result.complete(true)
return@invokeAndWait
}
}
else if (exitCode != GeneralSettings.OPEN_PROJECT_NEW_WINDOW) {
// not in a new window
result.complete(true)
return@invokeAndWait
}
}
result.complete(false)
} catch (err: Throwable) {
result.completeExceptionally(err)
}
}
return result.get()
}
private fun openProject(project: Project, indicator: ProgressIndicator?, runStartUpActivities: Boolean) {
val waitEdtActivity = StartUpMeasurer.startMainActivity("placing calling projectOpened on event queue")
if (indicator != null) {
indicator.text = if (ApplicationManager.getApplication().isInternal) "Waiting on event queue..." // NON-NLS (internal mode)
else ProjectBundle.message("project.preparing.workspace")
indicator.isIndeterminate = true
}
ApplicationManager.getApplication().invokeAndWait {
waitEdtActivity.end()
if (indicator != null && ApplicationManager.getApplication().isInternal) {
indicator.text = "Running project opened tasks..." // NON-NLS (internal mode)
}
ProjectManagerImpl.LOG.debug("projectOpened")
LifecycleUsageTriggerCollector.onProjectOpened(project)
val activity = StartUpMeasurer.startMainActivity("project opened callbacks")
ApplicationManager.getApplication().messageBus.syncPublisher(ProjectManager.TOPIC).projectOpened(project)
// https://jetbrains.slack.com/archives/C5E8K7FL4/p1495015043685628
// projectOpened in the project components is called _after_ message bus event projectOpened for ages
// old behavior is preserved for now (smooth transition, to not break all), but this order is not logical,
// because ProjectComponent.projectOpened it is part of project initialization contract, but message bus projectOpened it is just an event
// (and, so, should be called after project initialization)
processProjectComponents(project.picoContainer) { component, pluginDescriptor ->
StartupManagerImpl.runActivity {
val componentActivity = StartUpMeasurer.startActivity(component.javaClass.name, ActivityCategory.PROJECT_OPEN_HANDLER,
pluginDescriptor.pluginId.idString)
component.projectOpened()
componentActivity.end()
}
}
activity.end()
ProjectImpl.ourClassesAreLoaded = true
}
if (runStartUpActivities) {
(StartupManager.getInstance(project) as StartupManagerImpl).projectOpened(indicator)
}
}
// allow `invokeAndWait` inside startup activities
internal fun waitAndProcessInvocationEventsInIdeEventQueue(startupManager: StartupManagerImpl) {
val eventQueue = IdeEventQueue.getInstance()
while (true) {
// getNextEvent() will block until an event has been posted by another thread, so,
// peekEvent() is used to check that there is already some event in the queue
if (eventQueue.peekEvent() == null) {
if (startupManager.postStartupActivityPassed()) {
break
}
else {
continue
}
}
val event = eventQueue.nextEvent
if (event is InvocationEvent) {
eventQueue.dispatchEvent(event)
}
}
}
private data class PrepareProjectResult(val project: Project, val module: Module?)
private fun toCanonicalName(filePath: String): Path {
val file = Paths.get(filePath)
try {
if (SystemInfoRt.isWindows && FileUtil.containsWindowsShortName(filePath)) {
return file.toRealPath(LinkOption.NOFOLLOW_LINKS)
}
}
catch (e: InvalidPathException) {
}
catch (e: IOException) {
// OK. File does not yet exist, so its canonical path will be equal to its original path.
}
return file
}
private fun removeProjectConfigurationAndCaches(projectFile: Path) {
try {
if (Files.isRegularFile(projectFile)) {
Files.deleteIfExists(projectFile)
}
else {
Files.newDirectoryStream(projectFile.resolve(Project.DIRECTORY_STORE_FOLDER)).use { directoryStream ->
for (file in directoryStream) {
file!!.delete()
}
}
}
}
catch (ignored: IOException) {
}
try {
getProjectDataPathRoot(projectFile).delete()
}
catch (ignored: IOException) {
}
}
| apache-2.0 | 7a02b6797eed30e7ca622ab9869ce31b | 39.076419 | 145 | 0.709235 | 5.247284 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/completion/editconfig/EditConfigCompletionContributor.kt | 1 | 4138 | package com.aemtools.completion.editconfig
import com.aemtools.common.constant.const
import com.aemtools.completion.model.editconfig.XmlAttributeDefinition
import com.aemtools.common.util.findParentByType
import com.aemtools.service.ServiceFacade
import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.codeInsight.completion.XmlAttributeInsertHandler
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.impl.source.xml.XmlTagImpl
import com.intellij.psi.xml.XmlAttribute
import com.intellij.psi.xml.XmlTag
import com.intellij.psi.xml.XmlToken
import com.intellij.util.ProcessingContext
/**
* @author Dmytro_Troynikov
*/
class EditConfigCompletionContributor : CompletionContributor {
constructor() {
extend(CompletionType.BASIC, PlatformPatterns.psiElement(), EditConfigCompletionProvider())
}
}
private class EditConfigCompletionProvider : CompletionProvider<CompletionParameters>() {
private val editConfigRepository = ServiceFacade.getEditConfigRepository()
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext,
result: CompletionResultSet) {
if (!accept(parameters)) {
return
}
val currentElement = parameters.position as XmlToken
val currentPositionType = extractCurrentPositionType(currentElement)
val variantsGenerator = variantsProviders.get(currentPositionType) ?: return
result.addAllElements(variantsGenerator(parameters, currentElement))
}
private val variantsForName: (CompletionParameters, XmlToken) -> List<LookupElement> = { _, token ->
val tag = token.findParentByType(XmlTag::class.java)
val tagDefinition = editConfigRepository.getTagDefinitionByName((tag as XmlTagImpl).name)
val tagAttributes = tag.attributes.map { it.name }
val attributes = tagDefinition.attributes.filter { !tagAttributes.contains(it.name) }
attributes.map {
LookupElementBuilder.create(it.name).withInsertHandler(
XmlAttributeInsertHandler()
)
}
}
private val variantsForValue: (CompletionParameters, XmlToken) -> List<LookupElement> = { _, token ->
val tag = token.findParentByType(XmlTag::class.java)
val tagDefinition = editConfigRepository.getTagDefinitionByName((tag as XmlTagImpl).name)
val attributeName = (token.findParentByType(XmlAttribute::class.java) as XmlAttribute).name
val attributeDefinition: XmlAttributeDefinition? = tagDefinition.attributes.find { it.name == attributeName }
attributeDefinition?.values.orEmpty().map { LookupElementBuilder.create(it) }
}
private val variantsForTagName: (CompletionParameters, XmlToken) -> List<LookupElement> = { _, token ->
val parentTag = token.findParentByType(XmlTag::class.java)
?.findParentByType(XmlTag::class.java)
val tagDefinition = editConfigRepository.getTagDefinitionByName(
(parentTag as XmlTagImpl).name)
tagDefinition.childNodes.map {
LookupElementBuilder.create(it)
}
}
private fun extractCurrentPositionType(token: XmlToken): String {
val currentPositionType = token.tokenType.toString()
if (currentPositionType == const.xml.XML_ATTRIBUTE_NAME &&
(token.findParentByType(XmlTag::class.java) as XmlTagImpl).name.contains(
const.IDEA_STRING_CARET_PLACEHOLDER)) {
return const.xml.XML_TAG_NAME
}
return currentPositionType
}
private fun accept(parameters: CompletionParameters): Boolean {
return const.CQ_EDITCONFIG_XML == parameters.originalFile.name
}
private val variantsProviders = mapOf(
const.xml.XML_ATTRIBUTE_NAME to variantsForName,
const.xml.XML_ATTRIBUTE_VALUE to variantsForValue,
const.xml.XML_TAG_NAME to variantsForTagName
)
}
| gpl-3.0 | 891f4cf39009c7b20ffa6b97e95abcad | 37.672897 | 113 | 0.774045 | 4.856808 | false | true | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/fragment/ReceiveFragment.kt | 1 | 7574 | /*
* Copyright (C) 2021 Veli Tasalı
*
* This program 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 2
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.fragment
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import androidx.navigation.fragment.findNavController
import androidx.transition.TransitionManager
import com.genonbeta.android.framework.io.DocumentFile
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.databinding.LayoutReceiveBinding
import org.monora.uprotocol.client.android.protocol.closeQuietly
import org.monora.uprotocol.client.android.util.CommonErrors
import org.monora.uprotocol.client.android.viewmodel.ClientPickerViewModel
import org.monora.uprotocol.client.android.viewmodel.FilesViewModel
import org.monora.uprotocol.client.android.viewmodel.content.SenderClientContentViewModel
import org.monora.uprotocol.core.CommunicationBridge
import org.monora.uprotocol.core.TransportSeat
import org.monora.uprotocol.core.protocol.Client
import org.monora.uprotocol.core.protocol.Direction
import org.monora.uprotocol.core.protocol.communication.CommunicationException
import javax.inject.Inject
@AndroidEntryPoint
class ReceiveFragment : Fragment(R.layout.layout_receive) {
private val clientPickerViewModel: ClientPickerViewModel by activityViewModels()
private val filesViewModel: FilesViewModel by viewModels()
private val receiverViewModel: ReceiverViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = LayoutReceiveBinding.bind(view)
binding.button.setOnClickListener {
findNavController().navigate(ReceiveFragmentDirections.pickClient())
}
binding.changeStorageButton.setOnClickListener {
findNavController().navigate(ReceiveFragmentDirections.actionReceiveFragmentToFilePickerFragment())
}
binding.webShareButton.setOnClickListener {
findNavController().navigate(ReceiveFragmentDirections.actionReceiveFragmentToWebShareLauncherFragment3())
}
binding.storageFolderText.text = filesViewModel.appDirectory.getName()
setFragmentResultListener(FilePickerFragment.RESULT_FILE_PICKED) { _, bundle ->
val file = bundle.getParcelable<DocumentFile?>(
FilePickerFragment.EXTRA_DOCUMENT_FILE
) ?: return@setFragmentResultListener
filesViewModel.appDirectory = file
binding.storageFolderText.text = filesViewModel.appDirectory.getName()
}
clientPickerViewModel.bridge.observe(viewLifecycleOwner) { bridge ->
receiverViewModel.consume(bridge)
}
clientPickerViewModel.registerForTransferRequests(viewLifecycleOwner) { transfer, _ ->
findNavController().navigate(
ReceiveFragmentDirections.actionReceiveFragmentToNavTransferDetails(transfer)
)
}
receiverViewModel.state.observe(viewLifecycleOwner) {
when (it) {
is GuidanceRequestState.InProgress -> {
binding.statusText.text = getString(R.string.starting)
}
is GuidanceRequestState.Success -> {
binding.statusText.text = getString(R.string.sender_accepted)
}
is GuidanceRequestState.Finishing -> {
binding.statusText.text = getString(R.string.sender_finishing)
}
is GuidanceRequestState.Error -> {
binding.statusText.text = if (it.exception is NotExpectingException) {
getString(R.string.sender_not_expecting, it.client?.clientNickname)
} else {
CommonErrors.messageOf(requireContext(), it.exception)
}
}
}
if (it.isInProgress) {
binding.progressBar.show()
} else {
binding.progressBar.hide()
}
val isError = it is GuidanceRequestState.Error
val alpha = if (isError) 0.5f else 1.0f
binding.image.alpha = alpha
binding.text.isEnabled = !isError
binding.warningIcon.visibility = if(isError) View.VISIBLE else View.GONE
binding.button.isEnabled = !it.isInProgress
binding.viewModel = SenderClientContentViewModel(it.client)
binding.executePendingBindings()
}
}
}
@HiltViewModel
class ReceiverViewModel @Inject internal constructor(
private val transportSeat: TransportSeat,
) : ViewModel() {
private val _state = MutableLiveData<GuidanceRequestState>()
val state = liveData {
emitSource(_state)
}
fun consume(bridge: CommunicationBridge) {
_state.postValue(GuidanceRequestState.InProgress)
viewModelScope.launch(Dispatchers.IO) {
try {
val guidanceResult = bridge.requestGuidance(Direction.Incoming)
if (guidanceResult.result) {
_state.postValue(GuidanceRequestState.Success(bridge.remoteClient))
bridge.proceed(transportSeat, guidanceResult)
_state.postValue(GuidanceRequestState.Finishing(bridge.remoteClient))
} else {
throw NotExpectingException(bridge.remoteClient)
}
} catch (e: Exception) {
bridge.closeQuietly()
_state.postValue(GuidanceRequestState.Error(bridge.remoteClient, e))
}
}
}
}
sealed class GuidanceRequestState(val client: Client? = null, val isInProgress: Boolean = false) {
object InProgress : GuidanceRequestState(isInProgress = true)
class Success(client: Client) : GuidanceRequestState(client, true)
class Finishing(client: Client) : GuidanceRequestState(client, false)
class Error(client: Client, val exception: Exception) : GuidanceRequestState(client)
}
class NotExpectingException(client: Client) : CommunicationException(client)
| gpl-2.0 | 27d2b8ba78212132dd7f6bf5d5ee3ea9 | 40.157609 | 118 | 0.705401 | 5.035239 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.