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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vhromada/Catalog
|
web/src/main/kotlin/com/github/vhromada/catalog/web/mapper/impl/SeasonMapperImpl.kt
|
1
|
1290
|
package com.github.vhromada.catalog.web.mapper.impl
import com.github.vhromada.catalog.web.connector.entity.ChangeSeasonRequest
import com.github.vhromada.catalog.web.connector.entity.Season
import com.github.vhromada.catalog.web.fo.SeasonFO
import com.github.vhromada.catalog.web.mapper.SeasonMapper
import org.springframework.stereotype.Component
/**
* A class represents implementation of mapper for seasons.
*
* @author Vladimir Hromada
*/
@Component("seasonMapper")
class SeasonMapperImpl : SeasonMapper {
override fun map(source: Season): SeasonFO {
return SeasonFO(
uuid = source.uuid,
number = source.number.toString(),
startYear = source.startYear.toString(),
endYear = source.endYear.toString(),
language = source.language,
subtitles = source.subtitles,
note = source.note
)
}
override fun mapRequest(source: SeasonFO): ChangeSeasonRequest {
return ChangeSeasonRequest(
number = source.number!!.toInt(),
startYear = source.startYear!!.toInt(),
endYear = source.endYear!!.toInt(),
language = source.language!!,
subtitles = source.subtitles!!,
note = source.note
)
}
}
|
mit
|
b1705a43fe9c2cb35eab0b336df4b78b
| 31.25 | 75 | 0.65814 | 4.558304 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/testUtils.kt
|
1
|
4713
|
// 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.idea.test
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import com.intellij.util.indexing.IndexingFlag
import com.intellij.util.indexing.UnindexedFilesUpdater
import com.intellij.util.ui.UIUtil
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.base.plugin.KotlinPluginKind
import org.jetbrains.kotlin.idea.base.plugin.checkKotlinPluginKind
import org.jetbrains.kotlin.idea.caches.project.LibraryModificationTracker
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.idea.base.test.KotlinRoot
import java.io.File
@JvmField
val IDEA_TEST_DATA_DIR = File(KotlinRoot.DIR, "idea/tests/testData")
fun KtFile.dumpTextWithErrors(ignoreErrors: Set<DiagnosticFactory<*>> = emptySet()): String {
val text = text
if (InTextDirectivesUtils.isDirectiveDefined(text, "// DISABLE-ERRORS")) return text
val diagnostics = kotlin.run {
var lastException: Exception? = null
for (attempt in 0 until 2) {
try {
analyzeWithContent().diagnostics.let {
return@run it
}
} catch (e: Exception) {
if (e is ControlFlowException) {
lastException = e.cause as? Exception ?: e
continue
}
lastException = e
}
}
throw lastException ?: IllegalStateException()
}
val errors = diagnostics.filter { diagnostic ->
diagnostic.severity == Severity.ERROR && diagnostic.factory !in ignoreErrors
}
if (errors.isEmpty()) return text
val header = errors.joinToString("\n", postfix = "\n") { "// ERROR: " + DefaultErrorMessages.render(it).replace('\n', ' ') }
return header + text
}
fun JavaCodeInsightTestFixture.dumpErrorLines(): List<String> {
if (InTextDirectivesUtils.isDirectiveDefined(file.text, "// DISABLE-ERRORS")) return emptyList()
return doHighlighting().filter { it.severity == HighlightSeverity.ERROR }.map {
"// ERROR: ${it.description.replace('\n', ' ')}"
}
}
fun Project.waitIndexingComplete(indexingReason: String? = null) {
val project = this
UIUtil.dispatchAllInvocationEvents()
invokeAndWaitIfNeeded {
// TODO: [VD] a dirty hack to reindex created android project
IndexingFlag.cleanupProcessedFlag()
with(DumbService.getInstance(project)) {
UnindexedFilesUpdater(project, indexingReason).queue()
completeJustSubmittedTasks()
}
UIUtil.dispatchAllInvocationEvents()
}
}
fun closeAndDeleteProject() = LightPlatformTestCase.closeAndDeleteProject()
fun invalidateLibraryCache(project: Project) {
LibraryModificationTracker.getInstance(project).incModificationCount()
}
fun Document.extractMarkerOffset(project: Project, caretMarker: String = "<caret>"): Int {
return extractMultipleMarkerOffsets(project, caretMarker).singleOrNull() ?: -1
}
fun Document.extractMultipleMarkerOffsets(project: Project, caretMarker: String = "<caret>"): List<Int> {
val offsets = ArrayList<Int>()
runWriteAction {
val text = StringBuilder(text)
while (true) {
val offset = text.indexOf(caretMarker)
if (offset >= 0) {
text.delete(offset, offset + caretMarker.length)
setText(text.toString())
offsets += offset
} else {
break
}
}
}
PsiDocumentManager.getInstance(project).commitAllDocuments()
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(this)
return offsets
}
fun checkPluginIsCorrect(isFirPlugin: Boolean){
if (isFirPlugin) {
checkKotlinPluginKind(KotlinPluginKind.FIR_PLUGIN)
} else {
checkKotlinPluginKind(KotlinPluginKind.FE10_PLUGIN)
}
}
|
apache-2.0
|
c66b6dc9af8e18eac573de6c1b19806b
| 37.958678 | 158 | 0.711012 | 4.799389 | false | true | false | false |
JetBrains/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/CountTransformation.kt
|
1
|
3514
|
// 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.idea.intentions.loopToCallChain.result
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.*
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence.FilterTransformationBase
import org.jetbrains.kotlin.psi.*
class CountTransformation(
loop: KtForExpression,
private val inputVariable: KtCallableDeclaration,
initialization: VariableInitialization,
private val filter: KtExpression?
) : AssignToVariableResultTransformation(loop, initialization) {
override fun mergeWithPrevious(previousTransformation: SequenceTransformation, reformat: Boolean): ResultTransformation? {
if (previousTransformation !is FilterTransformationBase) return null
if (previousTransformation.indexVariable != null) return null
val newFilter = if (filter == null)
previousTransformation.effectiveCondition.asExpression(reformat)
else
KtPsiFactory(filter.project).createExpressionByPattern(
"$0 && $1", previousTransformation.effectiveCondition.asExpression(reformat), filter,
reformat = reformat
)
return CountTransformation(loop, previousTransformation.inputVariable, initialization, newFilter)
}
override val presentation: String
get() = "count" + (if (filter != null) "{}" else "()")
override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression {
val reformat = chainedCallGenerator.reformat
val call = if (filter != null) {
val lambda = generateLambda(inputVariable, filter, reformat)
chainedCallGenerator.generate("count $0:'{}'", lambda)
} else {
chainedCallGenerator.generate("count()")
}
return if (initialization.initializer.isZeroConstant()) {
call
} else {
KtPsiFactory(call.project).createExpressionByPattern("$0 + $1", initialization.initializer, call, reformat = reformat)
}
}
/**
* Matches:
* val variable = 0
* for (...) {
* ...
* variable++ (or ++variable)
* }
*/
object Matcher : TransformationMatcher {
override val indexVariableAllowed: Boolean
get() = false
override val shouldUseInputVariables: Boolean
get() = false
override fun match(state: MatchingState): TransformationMatch.Result? {
val operand = state.statements.singleOrNull()?.isPlusPlusOf() ?: return null
val initialization =
operand.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = true) ?: return null
// this should be the only usage of this variable inside the loop
if (initialization.variable.countUsages(state.outerLoop) != 1) return null
val variableType = initialization.variable.resolveToDescriptorIfAny()?.type ?: return null
if (!KotlinBuiltIns.isInt(variableType)) return null
val transformation = CountTransformation(state.outerLoop, state.inputVariable, initialization, null)
return TransformationMatch.Result(transformation)
}
}
}
|
apache-2.0
|
53e9c8f1fd538f901a1aecae13eb4e62
| 42.9375 | 158 | 0.686682 | 5.42284 | false | false | false | false |
JetBrains/intellij-community
|
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/CompositeIntentionQuickFix.kt
|
1
|
2533
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInspection
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.codeInsight.intention.preview.IntentionPreviewUtils
import com.intellij.lang.jvm.JvmModifiersOwner
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.SmartPointerManager
import com.intellij.util.asSafely
/**
* A quickfix that can call multiple JVM intention actions and bundle them into a single quick fix.
*/
abstract class CompositeIntentionQuickFix: LocalQuickFix {
override fun startInWriteAction(): Boolean = false
protected fun generatePreviews(project: Project, previewDescriptor: ProblemDescriptor, element: PsiElement): IntentionPreviewInfo {
val containingFile = previewDescriptor.startElement.containingFile ?: return IntentionPreviewInfo.EMPTY
val editor = IntentionPreviewUtils.getPreviewEditor() ?: return IntentionPreviewInfo.EMPTY
val target = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(element)
getActions(project, previewDescriptor).forEach { factory ->
val actions = factory(target.element?.nonPreviewElement ?: return@forEach)
actions.forEach { action ->
action.generatePreview(project, editor, containingFile)
}
}
return IntentionPreviewInfo.DIFF
}
protected fun applyFixes(project: Project, descriptor: ProblemDescriptor, element: PsiElement) {
val containingFile = descriptor.psiElement.containingFile ?: return
val target = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(element)
if (!FileModificationService.getInstance().prepareFileForWrite(element.containingFile)) return
getActions(project, descriptor).forEach { factory ->
val actions = factory(target.element.asSafely<JvmModifiersOwner>() ?: return@forEach)
actions.forEach { action ->
if (action.startInWriteAction()) {
runWriteAction { action.invoke(project, null, containingFile) }
} else {
action.invoke(project, null, containingFile)
}
}
}
}
protected abstract fun getActions(project: Project, descriptor: ProblemDescriptor): List<(JvmModifiersOwner) -> List<IntentionAction>>
}
|
apache-2.0
|
830a33ef1cc22f1b617514dbbf096fe3
| 48.686275 | 136 | 0.782077 | 5.2881 | false | false | false | false |
scenerygraphics/scenery
|
src/main/kotlin/graphics/scenery/repl/REPL.kt
|
1
|
3864
|
package graphics.scenery.repl
import graphics.scenery.Hub
import graphics.scenery.Hubable
import net.imagej.lut.LUTService
import org.scijava.Context
import org.scijava.`object`.ObjectService
import org.scijava.script.ScriptREPL
import org.scijava.ui.swing.script.InterpreterWindow
import java.util.*
import javax.swing.SwingUtilities
/**
* Constructs a read-eval-print loop (REPL) to interactive manipulate scenery's
* scene rendering.
*
* @author Ulrik Günther <[email protected]>
* @property[addAccessibleObject] A list of objects that should be accessible right away in the REPL
* @constructor Returns a REPL, equipped with a window for input/output.
*/
class REPL @JvmOverloads constructor(override var hub : Hub?, scijavaContext: Context? = null, vararg accessibleObjects: Any) : Hubable {
/** SciJava context for the REPL */
protected var context: Context
/** SciJava interpreter window, handles input and output. */
protected var interpreterWindow: InterpreterWindow? = null
/** SciJava REPL **/
protected var repl: ScriptREPL? = null
/** Code to evaluate upon launch. */
protected var startupScriptCode: String = ""
/** A startup script to evaluate upon launch. */
protected var startupScript = "startup.py"
/** The [startupScript] will be searched for in the resources of this class. */
protected var startupScriptClass: Class<*> = REPL::class.java
/** Whether we are running headless or not */
protected val headless = (System.getProperty("scenery.Headless", "false")?.toBoolean() ?: false) || (System.getProperty("java.awt.headless", "false")?.toBoolean() ?: false)
init {
hub?.add(this)
context = scijavaContext ?: Context(ObjectService::class.java, LUTService::class.java)
if(!headless) {
interpreterWindow = InterpreterWindow(context)
interpreterWindow?.isVisible = false
repl = interpreterWindow?.repl
} else {
repl = ScriptREPL(context, "Python", System.out)
repl?.initialize()
}
setStartupScript(startupScript, startupScriptClass)
accessibleObjects.forEach { context.getService(ObjectService::class.java).addObject(it) }
}
/**
* Sets a startup script and its class to find it in its resources.
*
* @param[scriptFileName] The file name of the script
* @param[baseClass] The class whose resources to search for the script
*/
fun setStartupScript(scriptFileName: String, baseClass: Class<*>) {
startupScriptClass = baseClass
startupScript = scriptFileName
startupScriptCode = Scanner(startupScriptClass.getResourceAsStream(startupScript), "UTF-8").useDelimiter("\\A").next()
}
/**
* Adds an object to the REPL's accessible objects
*
* @param[obj] The object to add.
*/
fun addAccessibleObject(obj: Any) {
context.getService(ObjectService::class.java).addObject(obj)
}
/**
* Shows the interpreter window
*/
fun showConsoleWindow() {
interpreterWindow?.isVisible = true
}
/**
* Hides the interpreter window
*/
fun hideConsoleWindow() {
interpreterWindow?.isVisible = false
}
/**
* Launches the REPL and evaluates any set startup code.
*/
fun start() {
repl?.lang("Python")
eval(startupScriptCode)
}
/**
* Evaluate a string in the REPL
*
* @param[code] The code to evaluate.
*/
fun eval(code: String): Any? {
return repl?.interpreter?.eval(code)
}
/**
* Closes the REPL instance.
*/
fun close() {
if(!headless) {
SwingUtilities.invokeAndWait {
interpreterWindow?.isVisible = false
interpreterWindow?.dispose()
}
}
}
}
|
lgpl-3.0
|
3d1799e87b3313e2251b4821a97ff75a
| 30.92562 | 176 | 0.653119 | 4.49186 | false | false | false | false |
allotria/intellij-community
|
java/java-tests/testSrc/com/intellij/java/codeInsight/generation/surroundWith/JavaSurroundWith12Test.kt
|
3
|
2498
|
// 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 com.intellij.java.codeInsight.generation.surroundWith
import com.intellij.codeInsight.generation.surroundWith.*
import com.intellij.lang.LanguageSurrounders
import com.intellij.lang.java.JavaLanguage
import com.intellij.lang.surroundWith.Surrounder
import com.intellij.testFramework.LightJavaCodeInsightTestCase
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase.JAVA_15
import com.intellij.util.containers.ContainerUtil
class JavaSurroundWith13Test : LightJavaCodeInsightTestCase() {
private val BASE_PATH = "/codeInsight/generation/surroundWith/java13/"
override fun getProjectDescriptor(): LightProjectDescriptor = JAVA_15
fun testCaseBlockWithIf() = doTest(JavaWithIfSurrounder())
fun testCaseResultWithIf() = doTest(JavaWithIfSurrounder())
fun testCaseThrowWithIf() = doTest(JavaWithIfSurrounder())
fun testCaseResultWithSynchronized() = doTest(JavaWithSynchronizedSurrounder())
fun testDefaultBlockWithTryFinally() = doTest(JavaWithTryFinallySurrounder())
fun testCaseThrowWithTryCatch() = doTest(JavaWithTryCatchSurrounder())
fun testDefaultResultWithTryCatchFinally() = doTest(JavaWithTryCatchFinallySurrounder())
fun testDefaultBlockWithDoWhile() = doTest(JavaWithDoWhileSurrounder())
fun testCaseThrowWithBlock() = doTest(JavaWithBlockSurrounder())
fun testDefaultResultWithRunnable() = doTest(JavaWithRunnableSurrounder())
fun testCatchBlockWithFor() = doTest(JavaWithForSurrounder())
fun testCatchResultWithFor() = doTest(JavaWithForSurrounder())
fun testDefaultThrowWithIfElse() = doTest(JavaWithIfElseSurrounder())
fun testDefaultResultWithWhile() = doTest(JavaWithWhileSurrounder())
private fun doTest(surrounder: Surrounder) {
val fileName = getTestName(false)
configureByFile("${BASE_PATH}${fileName}.java")
val descriptor = ContainerUtil.getFirstItem(LanguageSurrounders.INSTANCE.allForLanguage(JavaLanguage.INSTANCE))!!
val selectionModel = getEditor().selectionModel
val elements = descriptor.getElementsToSurround(getFile(), selectionModel.selectionStart, selectionModel.selectionEnd)
assertTrue(surrounder.isApplicable(elements))
SurroundWithHandler.invoke(getProject(), getEditor(), getFile(), surrounder)
checkResultByFile("${BASE_PATH}${fileName}_after.java")
}
}
|
apache-2.0
|
10170acf2b4df1dc6cd4d655bf450795
| 53.326087 | 140 | 0.815853 | 4.907662 | false | true | false | false |
allotria/intellij-community
|
platform/platform-api/src/com/intellij/openapi/ui/MessageUtil.kt
|
3
|
1711
|
// Copyright 2000-2018 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.
@file:JvmName("MessageUtil")
package com.intellij.openapi.ui
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts.*
import javax.swing.Icon
fun showYesNoDialog(@DialogTitle title: String,
@DialogMessage message: String,
project: Project?,
@Button yesText: String = Messages.getYesButton(),
@Button noText: String = Messages.getNoButton(),
icon: Icon? = null): Boolean {
return Messages.showYesNoDialog(project, message, title, yesText, noText, icon) == Messages.YES
}
fun showOkNoDialog(@DialogTitle title: String,
@DialogMessage message: String,
project: Project?,
@Button okText: String = Messages.getOkButton(),
@Button noText: String = Messages.getNoButton(),
icon: Icon? = null): Boolean {
return Messages.showYesNoDialog(project, message, title, okText, noText, icon) == Messages.YES
}
@Messages.OkCancelResult
fun showOkCancelDialog(@DialogTitle title: String,
@DialogMessage message: String,
@Button okText: String,
@Button cancelText: String = Messages.getCancelButton(),
icon: Icon? = null,
doNotAskOption: DialogWrapper.DoNotAskOption? = null,
project: Project? = null): Int {
return Messages.showOkCancelDialog(project, message, title, okText, cancelText, icon, doNotAskOption)
}
|
apache-2.0
|
cf002a34fb54dd2de5dae03813adab62
| 46.555556 | 140 | 0.624781 | 4.95942 | false | false | false | false |
allotria/intellij-community
|
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/containers/NonNegativeIntIntMultiMap.kt
|
2
|
11619
|
// 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 com.intellij.workspaceModel.storage.impl.containers
import it.unimi.dsi.fastutil.ints.*
import org.jetbrains.annotations.TestOnly
import java.util.function.BiConsumer
import java.util.function.IntConsumer
import java.util.function.IntFunction
/**
* Int to Int multimap that can hold *ONLY* non-negative integers and optimized for memory and reading.
*
* See:
* - [ImmutableNonNegativeIntIntMultiMap.ByList]
* and
* - [MutableNonNegativeIntIntMultiMap.ByList]
*
*
* Immutable version of this map holds the values in the following way:
* 1) If the key has _only a single_ associated value, it stores the pair directly in the [links] map.
* 2) If the key has multiple values, it stores the key in [links] map and the values in [values] array:
* - [links] contains _key to "-offset"_ associations where offset defines the offset in [values]. "-offset" is the negated offset, so we
* could distinct offset from real value (see point 1). E.g. if the value is "5" - this is a real value (see point 1),
* and if the value is "-5", real values are stored in [values] by offset 5.
* - [values] contains a sequences of values. The last value in the sequence is negated.
* E.g. [3, 1, 5, 3, -8, 4, 2, -1]: This [values] contains two values: [3, 1, 5, 3, 8] and [4, 2, 1]
*
* @author Alex Plate
*/
sealed class ImmutableNonNegativeIntIntMultiMap(
override var values: IntArray,
override val links: Int2IntMap
) : NonNegativeIntIntMultiMap() {
class ByList internal constructor(values: IntArray, links: Int2IntMap) : ImmutableNonNegativeIntIntMultiMap(values, links) {
override fun toMutable(): MutableNonNegativeIntIntMultiMap.ByList = MutableNonNegativeIntIntMultiMap.ByList(values, links)
}
override operator fun get(key: Int): IntSequence {
if (!links.containsKey(key)) return EmptyIntSequence
val idx = links.get(key)
if (idx >= 0) return SingleResultIntSequence(idx)
return RoMultiResultIntSequence(values, idx.unpack())
}
abstract fun toMutable(): MutableNonNegativeIntIntMultiMap
override fun keys(): IntSet = IntOpenHashSet().also {
it.addAll(links.keys)
}
private class RoMultiResultIntSequence(
private val values: IntArray,
private val idx: Int
) : IntSequence() {
override fun getIterator(): IntIterator = object : IntIterator() {
private var index = idx
private var hasNext = true
override fun hasNext(): Boolean = hasNext
override fun nextInt(): Int {
val value = values[index++]
return if (value < 0) {
hasNext = false
value.unpack()
}
else {
value
}
}
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ImmutableNonNegativeIntIntMultiMap
if (!values.contentEquals(other.values)) return false
if (links != other.links) return false
return true
}
override fun hashCode(): Int {
var result = values.contentHashCode()
result = 31 * result + links.hashCode()
return result
}
}
sealed class MutableNonNegativeIntIntMultiMap(
override var values: IntArray,
override var links: Int2IntMap,
protected var freezed: Boolean
) : NonNegativeIntIntMultiMap() {
internal val modifiableValues = HashMap<Int, IntList>()
class ByList private constructor(values: IntArray, links: Int2IntMap, freezed: Boolean) : MutableNonNegativeIntIntMultiMap(values, links,
freezed) {
constructor() : this(IntArray(0), Int2IntOpenHashMap(), false)
internal constructor(values: IntArray, links: Int2IntMap) : this(values, links, true)
override fun toImmutable(): ImmutableNonNegativeIntIntMultiMap.ByList {
if (freezed) return ImmutableNonNegativeIntIntMultiMap.ByList(values, links)
val resultingList = IntArrayList(values.size)
val newLinks = Int2IntOpenHashMap()
var valuesCounter = 0
links.forEach(BiConsumer { key, value ->
if (value >= 0) {
newLinks[key] = value
}
else {
var size = 0
this[key].forEach {
resultingList.add(it)
size += 1
}
resultingList[resultingList.lastIndex] = resultingList.getInt(resultingList.lastIndex).pack()
newLinks[key] = valuesCounter.pack()
valuesCounter += size
}
})
modifiableValues.forEach { (key, value) ->
if (value.isEmpty()) return@forEach
if (value.size == 1) {
newLinks[key] = value.single()
}
else {
resultingList.addAll(value)
resultingList[resultingList.lastIndex] = resultingList.getInt(resultingList.lastIndex).pack()
newLinks[key] = valuesCounter.pack()
valuesCounter += value.size
}
}
val newValues = resultingList.toIntArray()
modifiableValues.clear()
this.values = newValues
this.links = newLinks
this.freezed = true
return ImmutableNonNegativeIntIntMultiMap.ByList(newValues, newLinks)
}
}
override fun get(key: Int): IntSequence {
if (links.containsKey(key)) {
var idx = links.get(key)
if (idx >= 0) return SingleResultIntSequence(idx)
// idx is a link to values
idx = idx.unpack()
val size = size(key)
val vals = values.sliceArray(idx until (idx + size))
vals[vals.lastIndex] = vals.last().unpack()
return RwIntSequence(vals)
}
else if (key in modifiableValues) {
val array = modifiableValues.getValue(key).toIntArray()
return if (array.isEmpty()) EmptyIntSequence else RwIntSequence(array)
}
return EmptyIntSequence
}
fun putAll(key: Int, newValues: IntArray): Boolean {
if (newValues.isEmpty()) return false
startWrite()
startModifyingKey(key).addAll(newValues.asIterable())
return true
}
fun remove(key: Int) {
if (links.containsKey(key)) {
startWrite()
links.remove(key)
}
else if (key in modifiableValues) {
modifiableValues.remove(key)
}
}
fun remove(key: Int, value: Int): Boolean {
startWrite()
val values = startModifyingKey(key)
val index = values.indexOf(value)
return if (index >= 0) {
values.removeInt(index)
if (values.isEmpty()) {
modifiableValues.remove(key)
}
true
}
else false
}
override fun keys(): IntSet = IntOpenHashSet().also {
it.addAll(links.keys)
it.addAll(modifiableValues.keys)
}
private fun startModifyingKey(key: Int): IntList {
if (key in modifiableValues) return modifiableValues.getValue(key)
return if (links.containsKey(key)) {
var valueOrLink = links.get(key)
if (valueOrLink >= 0) {
val values = IntArrayList()
values.add(valueOrLink)
modifiableValues[key] = values
links.remove(key)
values
}
else {
valueOrLink = valueOrLink.unpack()
val size = size(key)
val vals = values.sliceArray(valueOrLink until (valueOrLink + size))
vals[vals.lastIndex] = vals.last().unpack()
val values = IntArrayList(vals)
modifiableValues[key] = values
links.remove(key)
values
}
}
else {
val values = IntArrayList()
modifiableValues[key] = values
values
}
}
/** This method works o(n) in some cases */
private fun size(key: Int): Int {
if (links.containsKey(key)) {
var idx = links.get(key)
if (idx >= 0) return 1
idx = idx.unpack()
// idx is a link to values
var res = 0
while (values[idx++] >= 0) res++
return res + 1
}
else if (key in modifiableValues) {
modifiableValues.getValue(key).size
}
return 0
}
private fun startWrite() {
if (!freezed) return
values = values.clone()
links = Int2IntOpenHashMap(links)
freezed = false
}
private fun startWriteDoNotCopyValues() {
if (!freezed) return
links = Int2IntOpenHashMap(links)
freezed = false
}
fun clear() {
startWriteDoNotCopyValues()
links.clear()
values = IntArray(0)
modifiableValues.clear()
}
abstract fun toImmutable(): ImmutableNonNegativeIntIntMultiMap
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is MutableNonNegativeIntIntMultiMap) return false
if (!super.equals(other)) return false
if (!values.contentEquals(other.values)) return false
if (links != other.links) return false
if (freezed != other.freezed) return false
if (modifiableValues != other.modifiableValues) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + values.contentHashCode()
result = 31 * result + links.hashCode()
result = 31 * result + freezed.hashCode()
result = 31 * result + modifiableValues.hashCode()
return result
}
private class RwIntSequence(private val values: IntArray) : IntSequence() {
override fun getIterator(): IntIterator = values.iterator()
}
}
sealed class NonNegativeIntIntMultiMap {
protected abstract var values: IntArray
protected abstract val links: Int2IntMap
abstract operator fun get(key: Int): IntSequence
abstract fun keys(): IntSet
companion object {
internal fun Int.pack(): Int = if (this == 0) Int.MIN_VALUE else -this
internal fun Int.unpack(): Int = if (this == Int.MIN_VALUE) 0 else -this
}
abstract class IntSequence {
abstract fun getIterator(): IntIterator
fun forEach(action: IntConsumer) {
val iterator = getIterator()
while (iterator.hasNext()) action.accept(iterator.nextInt())
}
fun isEmpty(): Boolean = !getIterator().hasNext()
/**
* Please use this method only for debugging purposes.
* Some of implementations doesn't have any memory overhead when using [IntSequence].
*/
@TestOnly
internal fun toArray(): IntArray {
val list = ArrayList<Int>()
this.forEach { list.add(it) }
return list.toTypedArray().toIntArray()
}
/**
* Please use this method only for debugging purposes.
* Some of implementations doesn't have any memory overhead when using [IntSequence].
*/
@TestOnly
internal fun single(): Int = toArray().single()
open fun <T> map(transformation: IntFunction<T>): Sequence<T> {
return Sequence {
object : Iterator<T> {
private val iterator = getIterator()
override fun hasNext(): Boolean = iterator.hasNext()
override fun next(): T = transformation.apply(iterator.nextInt())
}
}
}
}
protected class SingleResultIntSequence(private val value: Int) : IntSequence() {
override fun getIterator(): IntIterator = object : IntIterator() {
private var hasNext = true
override fun hasNext(): Boolean = hasNext
override fun nextInt(): Int {
if (!hasNext) throw NoSuchElementException()
hasNext = false
return value
}
}
}
protected object EmptyIntSequence : IntSequence() {
override fun getIterator(): IntIterator = IntArray(0).iterator()
override fun <T> map(transformation: IntFunction<T>): Sequence<T> = emptySequence()
}
}
|
apache-2.0
|
824590a3b9ea70053c062ef8c43c15d2
| 28.792308 | 140 | 0.648679 | 4.254486 | false | false | false | false |
grover-ws-1/http4k
|
http4k-aws/src/main/kotlin/org/http4k/aws/AwsHmacSha256.kt
|
1
|
1185
|
package org.http4k.aws
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
object AwsHmacSha256 {
fun hash(payload: String): String = hash(payload.toByteArray())
fun hash(payload: ByteArray): String {
try {
val digest = MessageDigest.getInstance("SHA-256")
val res = digest.digest(payload)
return hex(res)
} catch (e: NoSuchAlgorithmException) {
throw RuntimeException(e)
}
}
fun hmacSHA256(key: ByteArray, data: String): ByteArray {
try {
val algorithm = "HmacSHA256"
val mac = Mac.getInstance(algorithm)
mac.init(SecretKeySpec(key, algorithm))
return mac.doFinal(data.toByteArray(charset("UTF8")))
} catch (e: Exception) {
throw RuntimeException("Could not run HMAC SHA256", e)
}
}
fun hex(data: ByteArray): String {
val result = StringBuilder()
for (aByte in data) {
result.append(String.format("%02x", aByte))
}
return result.toString().toLowerCase()
}
}
|
apache-2.0
|
d228ef2c1aa2bb5d1ff7d814d0b077f0
| 28.625 | 67 | 0.613502 | 4.505703 | false | false | false | false |
leafclick/intellij-community
|
plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/SvnBranchConfigurationManager.kt
|
1
|
7678
|
// 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 org.jetbrains.idea.svn.branchConfig
import com.intellij.openapi.application.ApplicationManager.getApplication
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.State
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.util.BackgroundTaskUtil.syncPublisher
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.committed.VcsConfigurationChangeListener.BRANCHES_CHANGED
import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl
import com.intellij.openapi.vcs.impl.VcsInitObject
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.ProgressManagerQueue
import org.jetbrains.idea.svn.SvnUtil.createUrl
import org.jetbrains.idea.svn.SvnVcs
import org.jetbrains.idea.svn.api.Url
import org.jetbrains.idea.svn.commandLine.SvnBindException
import java.util.*
private val LOG = logger<SvnBranchConfigurationManager>()
@State(name = "SvnBranchConfigurationManager")
internal class SvnBranchConfigurationManager(private val project: Project) : PersistentStateComponent<SvnBranchConfigurationManager.ConfigurationBean> {
private val branchesLoader = ProgressManagerQueue(project, "Subversion Branches Preloader")
val svnBranchConfigManager: NewRootBunch = NewRootBunch(project, branchesLoader)
private var isInitialized = false
val supportValue: Long?
get() = configurationBean.myVersion
private var configurationBean = ConfigurationBean()
init {
// TODO: Seems that ProgressManagerQueue is not suitable here at least for some branches loading tasks. For instance,
// TODO: for DefaultConfigLoader it would be better to run modal cancellable task - so branches structure could be detected and
// TODO: shown in dialog. Currently when "Configure Branches" is invoked for the first time - no branches are shown.
// TODO: If "Cancel" is pressed and "Configure Branches" invoked once again - already detected (in background) branches are shown.
ProjectLevelVcsManagerImpl.getInstanceImpl(project).addInitializationRequest(VcsInitObject.BRANCHES) {
getApplication().runReadAction {
if (!project.isDisposed) branchesLoader.start()
}
}
}
class ConfigurationBean {
@JvmField
var myConfigurationMap: MutableMap<String, SvnBranchConfiguration> = TreeMap()
/**
* version of "support SVN in IDEA". for features tracking. should grow
*/
@JvmField
var myVersion: Long? = null
}
fun get(vcsRoot: VirtualFile): SvnBranchConfigurationNew = svnBranchConfigManager.getConfig(vcsRoot)
fun setConfiguration(vcsRoot: VirtualFile, configuration: SvnBranchConfigurationNew) {
svnBranchConfigManager.updateForRoot(vcsRoot, InfoStorage(configuration, InfoReliability.setByUser), true)
SvnBranchMapperManager.getInstance().notifyBranchesChanged(project, vcsRoot, configuration)
syncPublisher(project, BRANCHES_CHANGED).execute(project, vcsRoot)
}
override fun getState(): ConfigurationBean = ConfigurationBean().apply {
myVersion = configurationBean.myVersion
for (root in svnBranchConfigManager.mapCopy.keys) {
val configuration = svnBranchConfigManager.getConfig(root)
val configurationToPersist = SvnBranchConfiguration().apply {
isUserinfoInUrl = !configuration.trunk?.userInfo.isNullOrEmpty()
trunkUrl = configuration.trunk?.let(::removeUserInfo)?.toDecodedString()
branchUrls = configuration.branchLocations.map { removeUserInfo(it) }.map(Url::toString)
}
myConfigurationMap[root.path] = configurationToPersist
}
}
override fun loadState(state: ConfigurationBean) {
configurationBean = state
}
@Synchronized
private fun initialize() {
if (!isInitialized) {
isInitialized = true
preloadBranches(resolveAllBranchPoints())
}
}
private fun resolveAllBranchPoints(): Set<Pair<VirtualFile, SvnBranchConfigurationNew>> {
val lfs = LocalFileSystem.getInstance()
val branchPointsToLoad = mutableSetOf<Pair<VirtualFile, SvnBranchConfigurationNew>>()
for ((path, persistedConfiguration) in configurationBean.myConfigurationMap) {
val root = lfs.refreshAndFindFileByPath(path)
if (root != null) {
val configuration = resolveConfiguration(root, persistedConfiguration, branchPointsToLoad)
svnBranchConfigManager.updateForRoot(root, InfoStorage(configuration, InfoReliability.setByUser), false)
}
else {
LOG.info("root not found: $path")
}
}
return branchPointsToLoad
}
private fun resolveConfiguration(root: VirtualFile,
persistedConfiguration: SvnBranchConfiguration,
branchPointsToLoad: MutableSet<Pair<VirtualFile, SvnBranchConfigurationNew>>): SvnBranchConfigurationNew {
val userInfo = if (persistedConfiguration.isUserinfoInUrl) SvnVcs.getInstance(project).svnFileUrlMapping.getUrlForFile(
virtualToIoFile(root))?.userInfo
else null
val result = SvnBranchConfigurationNew().apply {
// trunk url could be either decoded or encoded depending on the code flow
trunk = persistedConfiguration.trunkUrl?.let { addUserInfo(it, true, userInfo) }
isUserInfoInUrl = persistedConfiguration.isUserinfoInUrl
}
val storage = project.service<SvnLoadedBranchesStorage>()
for (branchLocation in persistedConfiguration.branchUrls.mapNotNull { addUserInfo(it, false, userInfo) }) {
val storedBranches = storage.get(branchLocation)?.sorted() ?: mutableListOf()
result.addBranches(branchLocation,
InfoStorage(storedBranches, if (storedBranches.isNotEmpty()) InfoReliability.setByUser else InfoReliability.empty))
if (storedBranches.isEmpty()) {
branchPointsToLoad.add(root to result)
}
}
return result
}
private fun preloadBranches(branchPoints: Collection<Pair<VirtualFile, SvnBranchConfigurationNew>>) {
ProjectLevelVcsManagerImpl.getInstanceImpl(project).addInitializationRequest(VcsInitObject.BRANCHES) {
getApplication().executeOnPooledThread {
for ((root, configuration) in branchPoints) {
svnBranchConfigManager.reloadBranches(root, null, configuration)
}
}
}
}
private fun removeUserInfo(url: Url) = if (url.userInfo.isNullOrEmpty()) url
else try {
url.setUserInfo(null)
}
catch (e: SvnBindException) {
LOG.info("Could not remove user info ${url.userInfo} from url ${url.toDecodedString()}", e)
url
}
private fun addUserInfo(urlValue: String, smartParse: Boolean, userInfo: String?): Url? {
val result: Url
try {
result = createUrl(urlValue, !smartParse || '%' in urlValue)
}
catch (e: SvnBindException) {
LOG.info("Could not parse url $urlValue", e)
return null
}
return if (userInfo.isNullOrEmpty()) result
else try {
result.setUserInfo(userInfo)
}
catch (e: SvnBindException) {
LOG.info("Could not add user info $userInfo to url $urlValue", e)
result
}
}
companion object {
@JvmStatic
fun getInstance(project: Project): SvnBranchConfigurationManager =
ServiceManager.getService(project, SvnBranchConfigurationManager::class.java)!!.apply { initialize() }
}
}
|
apache-2.0
|
59142c22377b6e787fdea6f0a292a1f1
| 40.502703 | 152 | 0.747981 | 4.940798 | false | true | false | false |
JuliusKunze/kotlin-native
|
samples/gitchurn/src/main/kotlin/org/konan/libgit/GitChurn.kt
|
1
|
2437
|
/*
* Copyright 2010-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 org.konan.libgit
import kotlinx.cinterop.*
import platform.posix.*
import libgit2.*
fun main(args: Array<String>) {
if (args.size == 0)
return help()
val workDir = args[0]
val limit = if (args.size > 1) {
args[1].toInt()
} else
null
println("Opening…")
val repository = git.repository(workDir)
val map = mutableMapOf<String, Int>()
var count = 0
val commits = repository.commits()
val limited = limit?.let { commits.take(it) } ?: commits
println("Calculating…")
limited.forEach { commit ->
if (count % 100 == 0)
println("Commit #$count [${commit.time.format()}]: ${commit.summary}")
commit.parents.forEach { parent ->
val diff = commit.tree.diff(parent.tree)
diff.deltas().forEach { delta ->
val path = delta.newPath
val n = map[path] ?: 0
map.put(path, n + 1)
}
diff.close()
parent.close()
}
commit.close()
count++
}
println("Report:")
map.toList().sortedByDescending { it.second }.take(10).forEach {
println("File: ${it.first}")
println(" ${it.second}")
println()
}
repository.close()
git.close()
}
fun git_time_t.format() = memScoped {
val commitTime = alloc<time_tVar>()
commitTime.value = this@format
ctime(commitTime.ptr)!!.toKString().trim()
}
private fun printTree(commit: GitCommit) {
commit.tree.entries().forEach { entry ->
when (entry) {
is GitTreeEntry.File -> println(" ${entry.name}")
is GitTreeEntry.Folder -> println(" /${entry.name} (${entry.subtree.entries().size})")
}
}
}
fun help() {
println("Working directory should be provided")
}
|
apache-2.0
|
76808bc35068de7455a1108d563545ab
| 27.290698 | 102 | 0.599671 | 3.962541 | false | false | false | false |
chromeos/video-composition-sample
|
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/media/encoder/utils/EncoderUtils.kt
|
1
|
2370
|
/*
* Copyright (c) 2021 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 dev.chromeos.videocompositionsample.presentation.media.encoder.utils
import java.nio.ByteBuffer
enum class VideoMimeType(val mimeType: String) {
h264("video/avc"),
h265("video/hevc")
}
fun getVideoOptimalBitrate(videoMimeType: VideoMimeType, width: Int, height: Int): Int {
val size = width * height
val bitrate = when {
size <= 640 * 480 -> 1000000
size <= 1280 * 720 -> 2000000
size <= 1920 * 1080 -> 7000000
else -> 10000000
}
return when (videoMimeType) {
VideoMimeType.h264 -> bitrate
VideoMimeType.h265 -> bitrate / 2
}
}
fun deepCopy(source: ByteBuffer): ByteBuffer {
val sourceP = source.position()
val sourceL = source.limit()
val target = ByteBuffer.allocate(source.remaining())
target.put(source)
target.position(sourceP)
target.limit(sourceL)
source.position(sourceP)
source.limit(sourceL)
return target
}
/**
* @param size range [0..size] to remove from ByteBuffer
* @param byteBuffer ByteBuffer where all data over size position shift to the begin
* @return ByteBuffer of collapsed data
*/
fun collapseBufferBeginRange(size: Int, byteBuffer: ByteBuffer): ByteBuffer {
val position = byteBuffer.position()
val limit = byteBuffer.limit()
// if (position < size) {
// position = size
// }
val outRangeBuffer = ByteBuffer.allocate(size)
byteBuffer.position(0)
byteBuffer.limit(size)
outRangeBuffer.put(byteBuffer)
outRangeBuffer.flip()
byteBuffer.limit(limit)
val data = byteBuffer.duplicate()
data.limit(byteBuffer.limit())
data.position(position)
byteBuffer.position(0)
byteBuffer.put(data)
byteBuffer.position(position - size)
return outRangeBuffer
}
|
apache-2.0
|
9e37f20a604d7ad1109eeaf0d7b30ca4
| 28.6375 | 88 | 0.694515 | 4.051282 | false | false | false | false |
Nunnery/MythicDrops
|
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/commands/DebugCommand.kt
|
1
|
4268
|
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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 com.tealcube.minecraft.bukkit.mythicdrops.commands
import co.aikar.commands.BaseCommand
import co.aikar.commands.annotation.CommandAlias
import co.aikar.commands.annotation.CommandPermission
import co.aikar.commands.annotation.Dependency
import co.aikar.commands.annotation.Description
import co.aikar.commands.annotation.Subcommand
import com.tealcube.minecraft.bukkit.mythicdrops.api.errors.LoadingErrorManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.CustomItemManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.SettingsManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.tiers.TierManager
import com.tealcube.minecraft.bukkit.mythicdrops.chatColorize
import com.tealcube.minecraft.bukkit.mythicdrops.debug.MythicDebugManager
import com.tealcube.minecraft.bukkit.mythicdrops.sendMythicMessage
import com.tealcube.minecraft.bukkit.mythicdrops.toggleDebug
import com.tealcube.minecraft.bukkit.mythicdrops.utils.JsonUtil
import io.pixeloutlaw.minecraft.spigot.bandsaw.JulLoggerFactory
import org.bukkit.Bukkit
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
@CommandAlias("mythicdrops|md")
class DebugCommand : BaseCommand() {
companion object {
private val logger = JulLoggerFactory.getLogger(DebugCommand::class)
}
@field:Dependency
lateinit var customItemManager: CustomItemManager
@field:Dependency
lateinit var loadingErrorManager: LoadingErrorManager
@field:Dependency
lateinit var mythicDebugManager: MythicDebugManager
@field:Dependency
lateinit var settingsManager: SettingsManager
@field:Dependency
lateinit var tierManager: TierManager
@Description("Prints information to log. Useful for getting help in the Discord.")
@Subcommand("debug")
@CommandPermission("mythicdrops.command.debug")
fun debugCommand(sender: CommandSender) {
logger.info("server package: ${Bukkit.getServer().javaClass.getPackage()}")
logger.info("number of tiers: ${tierManager.get().size}")
logger.info("number of custom items: ${customItemManager.get().size}")
logger.info(
"settings: ${
JsonUtil.moshi.adapter(SettingsManager::class.java).indent(" ").toJson(settingsManager)
}"
)
sender.sendMessage(
settingsManager.languageSettings.command.debug.chatColorize()
)
}
@Description("Prints any loading errors. Useful for getting help in the Discord.")
@Subcommand("errors")
@CommandPermission("mythicdrops.command.errors")
fun errorsCommand(sender: CommandSender) {
sender.sendMythicMessage("&6=== MythicDrops Loading Errors ===")
loadingErrorManager.get().forEach { sender.sendMythicMessage(it) }
}
@Description("Toggles debug mode for the running player. This is intended for development use only.")
@Subcommand("toggledebug")
@CommandPermission("mythicdrops.command.toggledebug")
fun toggleDebugCommand(sender: Player) {
sender.toggleDebug(mythicDebugManager)
}
}
|
mit
|
8aef612edb8b06bdaf980fc7c08c5bf0
| 43.458333 | 105 | 0.764527 | 4.659389 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/j2k/new/tests/testData/inference/nullability/compareWithNull.kt
|
13
|
423
|
fun a(): /*T0@*/Int? {
return 42/*LIT*/
}
val b: /*T1@*/Int? = 2/*LIT*/
fun c(p: /*T2@*/Int?) {
if (p/*T2@Int*/ == null/*LIT*/);
}
fun check() {
if (a()/*T0@Int*/ == null/*LIT*/ || b/*T1@Int*/ == null/*LIT*//*LIT*/);
}
//LOWER <: T0 due to 'RETURN'
//LOWER <: T1 due to 'INITIALIZER'
//T2 := UPPER due to 'COMPARE_WITH_NULL'
//T0 := UPPER due to 'COMPARE_WITH_NULL'
//T1 := UPPER due to 'COMPARE_WITH_NULL'
|
apache-2.0
|
16f91eb4835d7f14212a6d2f75478c52
| 21.263158 | 75 | 0.51773 | 2.431034 | false | false | false | false |
LouisCAD/Splitties
|
samples/android-app/src/main/kotlin/com/example/splitties/preferences/SamplePreferences.kt
|
1
|
1191
|
/*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package com.example.splitties.preferences
import kotlinx.coroutines.flow.*
import splitties.preferences.DataStorePreferences
import splitties.preferences.DataStorePreferencesPreview
import splitties.preferences.SuspendPrefsAccessor
@OptIn(DataStorePreferencesPreview::class)
class SamplePreferences private constructor() : DataStorePreferences(name = "sample") {
val enableAnnoyingFeaturesField = boolPref("annoying_features", defaultValue = true)
var enableAnnoyingFeatures by enableAnnoyingFeaturesField
val showAnnoyingPopupAtLaunchField = boolPref("annoying_popup_launch", defaultValue = true)
var showAnnoyingPopupAtLaunch by showAnnoyingPopupAtLaunchField
val showAnnoyingPopupInLoopField = boolPref("annoying_popup_loop", defaultValue = false)
var showAnnoyingPopupInLoop by showAnnoyingPopupInLoopField
val someFlow: Flow<Boolean>
var somePrefField by boolPref("somePref", defaultValue = false).also {
someFlow = it.valueFlow()
}
companion object : SuspendPrefsAccessor<SamplePreferences>(::SamplePreferences)
}
|
apache-2.0
|
4378e4f7ff980d999e98007affabce40
| 41.535714 | 109 | 0.802687 | 4.427509 | false | false | false | false |
fabmax/kool
|
kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/gl/VboBinder.kt
|
1
|
1020
|
package de.fabmax.kool.platform.gl
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL20.glVertexAttribPointer
import org.lwjgl.opengl.GL30.glVertexAttribIPointer
/**
* A VboBinder for the specified buffer. By default the type is set to GL_FLOAT and the offset to 0.
*
* @author fabmax
*/
class VboBinder(
val vbo: BufferResource,
val elemSize: Int,
val strideBytes: Int,
val offset: Int = 0,
val type: Int = GL_FLOAT) {
/**
* Is called by the used shader to bind a vertex attribute buffer to the specified target.
*
* @param target the buffer target index as used in glVertexAttribPointer()
*/
fun bindAttribute(target: Int) {
vbo.bind()
if (type == GL_INT || type == GL_UNSIGNED_INT) {
glVertexAttribIPointer(target, elemSize, type, strideBytes, (offset * 4).toLong())
} else {
glVertexAttribPointer(target, elemSize, type, false, strideBytes, (offset * 4).toLong())
}
}
}
|
apache-2.0
|
ea541a0b90d8e3a45eac7cd7653a2071
| 29.909091 | 100 | 0.641176 | 3.908046 | false | false | false | false |
AndrewJack/gatekeeper
|
mobile/src/main/java/technology/mainthread/apps/gatekeeper/data/VibratorTunes.kt
|
1
|
1060
|
package technology.mainthread.apps.gatekeeper.data
import androidx.collection.ArrayMap
object VibratorTunes {
var KEY_STANDARD = "STANDARD"
var KEY_STAR_WARS = "STAR_WARS"
var KEY_SUPER_MARIO = "SUPER_MARIO"
var KEY_JAMES_BOND = "JAMES_BOND"
var STANDARD = longArrayOf(0, 100, 100, 100, 100)
var STAR_WARS = longArrayOf(0, 500, 110, 500, 110, 450, 110, 200, 110, 170, 40, 450, 110, 200, 110, 170, 40, 500)
var SUPER_MARIO = longArrayOf(0, 125, 75, 125, 275, 200, 275, 125, 75, 125, 275, 200, 600, 200, 600)
var JAMES_BOND = longArrayOf(0, 200, 100, 200, 275, 425, 100, 200, 100, 200, 275, 425, 100, 75, 25, 75, 125, 75, 25, 75, 125, 100, 100)
var VIBRATE_TUNES = tunesMap
private val tunesMap: ArrayMap<String, LongArray>
get() {
val map = ArrayMap<String, LongArray>()
map.put(KEY_STANDARD, STANDARD)
map.put(KEY_STAR_WARS, STAR_WARS)
map.put(KEY_SUPER_MARIO, SUPER_MARIO)
map.put(KEY_JAMES_BOND, JAMES_BOND)
return map
}
}
|
apache-2.0
|
9bb60e65e5de569d726d70834dc6153c
| 35.551724 | 139 | 0.619811 | 3.099415 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddAnnotationUseSiteTargetIntention.kt
|
1
|
6450
|
// 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.intentions
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.psi.PsiComment
import com.intellij.util.PlatformIcons
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget.*
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class AddAnnotationUseSiteTargetIntention : SelfTargetingIntention<KtAnnotationEntry>(
KtAnnotationEntry::class.java,
KotlinBundle.lazyMessage("add.use.site.target")
) {
override fun isApplicableTo(element: KtAnnotationEntry, caretOffset: Int): Boolean {
val useSiteTargets = element.applicableUseSiteTargets()
if (useSiteTargets.isEmpty()) return false
if (useSiteTargets.size == 1) {
setTextGetter(KotlinBundle.lazyMessage("text.add.use.site.target.0", useSiteTargets.first().renderName))
}
return true
}
override fun applyTo(element: KtAnnotationEntry, editor: Editor?) {
val project = editor?.project ?: return
val useSiteTargets = element.applicableUseSiteTargets()
CommandProcessor.getInstance().runUndoTransparentAction {
if (useSiteTargets.size == 1)
element.addUseSiteTarget(useSiteTargets.first(), project)
else
JBPopupFactory
.getInstance()
.createListPopup(createListPopupStep(element, useSiteTargets, project))
.showInBestPositionFor(editor)
}
}
private fun createListPopupStep(
annotationEntry: KtAnnotationEntry,
useSiteTargets: List<AnnotationUseSiteTarget>,
project: Project
): ListPopupStep<*> {
return object : BaseListPopupStep<AnnotationUseSiteTarget>(KotlinBundle.message("choose.use.site.target"), useSiteTargets) {
override fun isAutoSelectionEnabled() = false
override fun onChosen(selectedValue: AnnotationUseSiteTarget, finalChoice: Boolean): PopupStep<*>? {
if (finalChoice) {
annotationEntry.addUseSiteTarget(selectedValue, project)
}
return PopupStep.FINAL_CHOICE
}
override fun getIconFor(value: AnnotationUseSiteTarget) = PlatformIcons.ANNOTATION_TYPE_ICON
override fun getTextFor(value: AnnotationUseSiteTarget) = value.renderName
}
}
}
private fun KtAnnotationEntry.applicableUseSiteTargets(): List<AnnotationUseSiteTarget> {
if (useSiteTarget != null) return emptyList()
val annotationShortName = this.shortName ?: return emptyList()
val modifierList = getStrictParentOfType<KtModifierList>() ?: return emptyList()
val annotated = modifierList.owner as? KtElement ?: return emptyList()
val applicableTargets = when (annotated) {
is KtParameter ->
if (annotated.getStrictParentOfType<KtPrimaryConstructor>() != null)
when (annotated.valOrVarKeyword?.node?.elementType) {
KtTokens.VAR_KEYWORD ->
listOf(CONSTRUCTOR_PARAMETER, FIELD, PROPERTY, PROPERTY_GETTER, PROPERTY_SETTER, SETTER_PARAMETER)
KtTokens.VAL_KEYWORD ->
listOf(CONSTRUCTOR_PARAMETER, FIELD, PROPERTY, PROPERTY_GETTER)
else ->
emptyList()
}
else
emptyList()
is KtProperty ->
when {
annotated.delegate != null ->
listOf(PROPERTY, PROPERTY_GETTER, PROPERTY_DELEGATE_FIELD)
!annotated.isLocal -> {
val backingField = LightClassUtil.getLightClassPropertyMethods(annotated).backingField
if (annotated.isVar) {
if (backingField != null)
listOf(FIELD, PROPERTY, PROPERTY_GETTER, PROPERTY_SETTER, SETTER_PARAMETER)
else
listOf(PROPERTY, PROPERTY_GETTER, PROPERTY_SETTER, SETTER_PARAMETER)
} else {
if (backingField != null)
listOf(FIELD, PROPERTY, PROPERTY_GETTER)
else
listOf(PROPERTY, PROPERTY_GETTER)
}
}
else ->
emptyList()
}
is KtTypeReference -> listOf(RECEIVER)
else -> emptyList()
}
val existingTargets = modifierList.annotationEntries.mapNotNull {
if (annotationShortName == it.shortName) it.useSiteTarget?.getAnnotationUseSiteTarget() else null
}
val targets = applicableTargets.filter { it !in existingTargets }
return if (ApplicationManager.getApplication().isUnitTestMode) {
val chosenTarget = containingKtFile.findDescendantOfType<PsiComment>()
?.takeIf { it.text.startsWith("// CHOOSE_USE_SITE_TARGET:") }
?.text
?.split(":")
?.getOrNull(1)
?.trim()
if (chosenTarget.isNullOrBlank())
targets.take(1)
else
targets.asSequence().filter { it.renderName == chosenTarget }.take(1).toList()
} else {
targets
}
}
fun KtAnnotationEntry.addUseSiteTarget(useSiteTarget: AnnotationUseSiteTarget, project: Project) {
project.executeWriteCommand(KotlinBundle.message("add.use.site.target")) {
replace(KtPsiFactory(this).createAnnotationEntry("@${useSiteTarget.renderName}:${text.drop(1)}"))
}
}
|
apache-2.0
|
5828e771db73e3c30285837febc11219
| 43.482759 | 158 | 0.653798 | 5.456853 | false | false | false | false |
feelfreelinux/WykopMobilny
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/fragments/entries/EntriesInteractor.kt
|
1
|
1472
|
package io.github.feelfreelinux.wykopmobilny.ui.fragments.entries
import io.github.feelfreelinux.wykopmobilny.api.entries.EntriesApi
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Entry
import io.reactivex.Single
import javax.inject.Inject
class EntriesInteractor @Inject constructor(val entriesApi: EntriesApi) {
fun voteEntry(entry: Entry): Single<Entry> =
entriesApi.voteEntry(entry.id, true)
.map {
entry.voteCount = it.voteCount
entry.isVoted = true
entry
}
fun unvoteEntry(entry: Entry): Single<Entry> =
entriesApi.unvoteEntry(entry.id, true)
.map {
entry.voteCount = it.voteCount
entry.isVoted = false
entry
}
fun markFavorite(entry: Entry): Single<Entry> =
entriesApi.markFavorite(entry.id)
.map {
entry.isFavorite = it.userFavorite
entry
}
fun deleteEntry(entry: Entry): Single<Entry> =
entriesApi.deleteEntry(entry.id)
.map {
entry.embed = null
entry.survey = null
entry.body = "[Wpis usunięty]"
entry
}
fun voteSurvey(entry: Entry, index: Int): Single<Entry> =
entriesApi.voteSurvey(entry.id, index)
.map {
entry.survey = it
entry
}
}
|
mit
|
2b56a13f7468d88175f23a1fcc2ffaea
| 29.040816 | 73 | 0.564922 | 4.526154 | false | false | false | false |
siosio/intellij-community
|
build/tasks/src/org/jetbrains/intellij/build/io/zip.kt
|
1
|
4919
|
// 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.intellij.build.io
import java.nio.channels.FileChannel
import java.nio.file.*
import java.time.Duration
import java.util.*
import java.util.concurrent.ForkJoinTask
import java.util.zip.Deflater
import java.util.zip.ZipEntry
// symlinks not supported but can be easily implemented - see CollectingVisitor.visitFile
fun zip(targetFile: Path, dirs: Map<Path, String>, compress: Boolean = true, addDirEntries: Boolean = false, logger: System.Logger? = null) {
// note - dirs contain duplicated directories (you cannot simply add directory entry on visit - uniqueness must be preserved)
// anyway, directory entry are not added
Files.createDirectories(targetFile.parent)
val start = System.currentTimeMillis()
FileChannel.open(targetFile, EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE)).use {
val zipCreator = ZipFileWriter(it, if (compress) Deflater(Deflater.DEFAULT_COMPRESSION, true) else null)
val fileAdded: ((String) -> Boolean)?
val dirNameSetToAdd: Set<String>
if (addDirEntries) {
dirNameSetToAdd = LinkedHashSet()
fileAdded = { name ->
if (!name.endsWith(".class") && !name.endsWith("/package.html") && name != "META-INF/MANIFEST.MF") {
var slashIndex = name.lastIndexOf('/')
if (slashIndex != -1) {
while (dirNameSetToAdd.add(name.substring(0, slashIndex))) {
slashIndex = name.lastIndexOf('/', slashIndex - 2)
if (slashIndex == -1) {
break
}
}
}
}
true
}
}
else {
fileAdded = null
dirNameSetToAdd = emptySet()
}
val archiver = ZipArchiver(method = if (compress) ZipEntry.DEFLATED else ZipEntry.STORED, zipCreator, fileAdded)
for ((dir, prefix) in dirs.entries) {
val normalizedDir = dir.toAbsolutePath().normalize()
archiver.setRootDir(normalizedDir, prefix)
compressDir(normalizedDir, archiver, excludes = null)
}
if (dirNameSetToAdd.isNotEmpty()) {
addDirForResourceFiles(zipCreator, dirNameSetToAdd)
}
zipCreator.finish(null)
}
logger?.info("${targetFile.fileName} created in ${formatDuration(System.currentTimeMillis() - start)}")
}
fun bulkZipWithPrefix(commonSourceDir: Path, items: List<Map.Entry<String, Path>>, compress: Boolean, logger: System.Logger) {
val tasks = mutableListOf<ForkJoinTask<*>>()
logger.debug { "Create ${items.size} archives in parallel (commonSourceDir=$commonSourceDir)" }
for (item in items) {
tasks.add(ForkJoinTask.adapt(Runnable {
zip(item.value, mapOf(commonSourceDir.resolve(item.key) to item.key), compress, logger = logger)
}))
}
ForkJoinTask.invokeAll(tasks)
}
private fun formatDuration(value: Long): String {
return Duration.ofMillis(value).toString().substring(2)
.replace(Regex("(\\d[HMS])(?!$)"), "$1 ")
.lowercase()
}
private fun addDirForResourceFiles(out: ZipFileWriter, dirNameSetToAdd: Set<String>) {
for (dir in dirNameSetToAdd) {
out.addDirEntry("$dir/")
}
}
internal class ZipArchiver(private val method: Int,
private val zipCreator: ZipFileWriter,
val fileAdded: ((String) -> Boolean)?,) {
private var localPrefixLength = -1
private var archivePrefix = ""
// rootDir must be absolute and normalized
fun setRootDir(rootDir: Path, prefix: String) {
archivePrefix = when {
prefix.isNotEmpty() && !prefix.endsWith('/') -> "$prefix/"
prefix == "/" -> ""
else -> prefix
}
localPrefixLength = rootDir.toString().length + 1
}
fun addFile(file: Path) {
val name = archivePrefix + file.toString().substring(localPrefixLength).replace('\\', '/')
if (fileAdded == null || fileAdded.invoke(name)) {
zipCreator.writeEntry(name, method, file)
}
}
}
internal fun compressDir(startDir: Path, archiver: ZipArchiver, excludes: List<PathMatcher>?) {
val dirCandidates = ArrayDeque<Path>()
dirCandidates.add(startDir)
val tempList = ArrayList<Path>()
while (true) {
val dir = dirCandidates.pollFirst() ?: break
tempList.clear()
Files.newDirectoryStream(dir).use {
if (excludes == null) {
tempList.addAll(it)
}
else {
l@ for (child in it) {
val relative = startDir.relativize(child)
for (exclude in excludes) {
if (exclude.matches(relative)) {
continue@l
}
}
tempList.add(child)
}
}
}
tempList.sort()
for (file in tempList) {
if (Files.isDirectory(file, LinkOption.NOFOLLOW_LINKS)) {
dirCandidates.add(file)
}
else {
archiver.addFile(file)
}
}
}
}
|
apache-2.0
|
6c2749195ac9623823572965ce2c1a8a
| 33.166667 | 158 | 0.651352 | 4.147555 | false | false | false | false |
allotria/intellij-community
|
platform/vcs-log/impl/src/com/intellij/vcs/log/util/FilterConfigMigrationUtil.kt
|
2
|
1297
|
// 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 com.intellij.vcs.log.util
import com.intellij.vcs.log.VcsLogFilterCollection
import com.intellij.vcs.log.impl.VcsLogProjectTabsProperties.RecentGroup
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
object FilterConfigMigrationUtil {
private const val RECENT_USER_FILTER_NAME = "User"
@JvmStatic
fun migrateRecentUserFilters(recentFilters: MutableMap<String, MutableList<RecentGroup>>) {
val recentUserFilterGroups: MutableList<RecentGroup> = recentFilters[RECENT_USER_FILTER_NAME] ?: return
recentFilters[RECENT_USER_FILTER_NAME] = recentUserFilterGroups
.map { RecentGroup(migrateOldMeFilters(it.FILTER_VALUES)) }
.toMutableList()
}
@JvmStatic
fun migrateTabUserFilters(filters: MutableMap<String, MutableList<String>>) {
val userFilters: MutableList<String> = filters[VcsLogFilterCollection.USER_FILTER.name] ?: return
filters[VcsLogFilterCollection.USER_FILTER.name] = migrateOldMeFilters(userFilters).toMutableList()
}
private fun migrateOldMeFilters(userFilters: List<String>): List<String> {
return userFilters.map { if (it == "me") VcsLogFilterObject.ME else it }
}
}
|
apache-2.0
|
05c8663eda16d751804f89332602f103
| 40.83871 | 140 | 0.77872 | 4.14377 | false | false | false | false |
google/iosched
|
mobile/src/main/java/com/google/samples/apps/iosched/ui/sessiondetail/SessionDetailDataBindingAdapters.kt
|
1
|
6705
|
/*
* Copyright 2018 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 com.google.samples.apps.iosched.ui.sessiondetail
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.samples.apps.iosched.R
import com.google.samples.apps.iosched.model.Session
import com.google.samples.apps.iosched.model.SessionType.AFTER_DARK
import com.google.samples.apps.iosched.model.SessionType.APP_REVIEW
import com.google.samples.apps.iosched.model.SessionType.GAME_REVIEW
import com.google.samples.apps.iosched.model.SessionType.KEYNOTE
import com.google.samples.apps.iosched.model.SessionType.OFFICE_HOURS
import com.google.samples.apps.iosched.model.SessionType.SESSION
import com.google.samples.apps.iosched.model.userdata.UserSession
import com.google.samples.apps.iosched.shared.util.TimeUtils
import com.google.samples.apps.iosched.ui.reservation.ReservationViewState
import com.google.samples.apps.iosched.ui.reservation.ReservationViewState.RESERVABLE
import com.google.samples.apps.iosched.ui.reservation.StarReserveFab
import org.threeten.bp.Duration
import org.threeten.bp.ZoneId
import org.threeten.bp.ZonedDateTime
/* Narrow headers used for events that have neither a photo nor video url. */
@BindingAdapter("eventNarrowHeader")
fun eventNarrowHeaderImage(imageView: ImageView, session: Session?) {
session ?: return
val resId = when (session.type) {
KEYNOTE -> R.drawable.event_narrow_keynote
// For the next few types, we choose a random image, but we should use the same image for a
// given event, so use the id to pick.
SESSION -> when (session.id.hashCode() % 4) {
0 -> R.drawable.event_narrow_session1
1 -> R.drawable.event_narrow_session2
2 -> R.drawable.event_narrow_session3
else -> R.drawable.event_narrow_session4
}
OFFICE_HOURS -> when (session.id.hashCode() % 3) {
0 -> R.drawable.event_narrow_office_hours1
1 -> R.drawable.event_narrow_office_hours2
else -> R.drawable.event_narrow_office_hours3
}
APP_REVIEW -> when (session.id.hashCode() % 3) {
0 -> R.drawable.event_narrow_app_reviews1
1 -> R.drawable.event_narrow_app_reviews2
else -> R.drawable.event_narrow_app_reviews3
}
GAME_REVIEW -> when (session.id.hashCode() % 3) {
0 -> R.drawable.event_narrow_game_reviews1
1 -> R.drawable.event_narrow_game_reviews2
else -> R.drawable.event_narrow_game_reviews3
}
AFTER_DARK -> R.drawable.event_narrow_afterhours
else -> R.drawable.event_narrow_other
}
imageView.setImageResource(resId)
}
/* Photos are used if the event has a photo and/or a video url. */
@BindingAdapter("eventPhoto")
fun eventPhoto(imageView: ImageView, session: Session?) {
session ?: return
val resId = when (session.type) {
KEYNOTE -> R.drawable.event_placeholder_keynote
// Choose a random image, but we should use the same image for a given session, so use ID to
// pick.
SESSION -> when (session.id.hashCode() % 4) {
0 -> R.drawable.event_placeholder_session1
1 -> R.drawable.event_placeholder_session2
2 -> R.drawable.event_placeholder_session3
else -> R.drawable.event_placeholder_session4
}
// Other event types probably won't have photos or video, but just in case...
else -> R.drawable.event_placeholder_keynote
}
if (session.hasPhoto) {
Glide.with(imageView)
.load(session.photoUrl)
.apply(RequestOptions().placeholder(resId))
.into(imageView)
} else {
imageView.setImageResource(resId)
}
}
@BindingAdapter(
value = ["sessionDetailStartTime", "sessionDetailEndTime", "timeZoneId"], requireAll = true
)
fun timeString(
view: TextView,
sessionDetailStartTime: ZonedDateTime?,
sessionDetailEndTime: ZonedDateTime?,
timeZoneId: ZoneId?
) {
if (sessionDetailStartTime == null || sessionDetailEndTime == null || timeZoneId == null) {
view.text = ""
} else {
view.text = TimeUtils.timeString(
TimeUtils.zonedTime(sessionDetailStartTime, timeZoneId),
TimeUtils.zonedTime(sessionDetailEndTime, timeZoneId)
)
}
}
@BindingAdapter("sessionStartCountdown")
fun sessionStartCountdown(view: TextView, timeUntilStart: Duration?) {
if (timeUntilStart == null) {
view.visibility = GONE
} else {
view.visibility = VISIBLE
val minutes = timeUntilStart.toMinutes()
view.text = view.context.resources.getQuantityString(
R.plurals.session_starting_in, minutes.toInt(), minutes.toString()
)
}
}
@BindingAdapter(
"userSession",
"isSignedIn",
"isRegistered",
"isReservable",
"isReservationDeniedByCutoff",
"eventListener",
requireAll = true
)
fun assignFab(
fab: StarReserveFab,
userSession: UserSession?,
isSignedIn: Boolean,
isRegistered: Boolean,
isReservable: Boolean,
isReservationDeniedByCutoff: Boolean,
eventListener: SessionDetailEventListener
) {
userSession ?: return
when {
!isSignedIn -> {
if (isReservable) {
fab.reservationStatus = RESERVABLE
} else {
fab.isChecked = false
}
fab.setOnClickListener { eventListener.onLoginClicked() }
}
isRegistered && isReservable -> {
fab.reservationStatus = ReservationViewState.fromUserEvent(
userSession.userEvent,
isReservationDeniedByCutoff
)
fab.setOnClickListener { eventListener.onReservationClicked() }
}
else -> {
fab.isChecked = userSession.userEvent.isStarred
fab.setOnClickListener { eventListener.onStarClicked(userSession) }
}
}
}
|
apache-2.0
|
fc3713144e749f75079ea337fda8ea57
| 36.25 | 100 | 0.677256 | 4.180175 | false | false | false | false |
androidx/androidx
|
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/HeartRateVariabilitySdnnRecord.kt
|
3
|
2058
|
/*
* Copyright (C) 2022 The Android 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.
*/
package androidx.health.connect.client.records
import androidx.annotation.RestrictTo
import androidx.health.connect.client.records.metadata.Metadata
import java.time.Instant
import java.time.ZoneOffset
/**
* Captures user's heart rate variability (HRV) as measured by the standard deviation of all N-N
* intervals.
*
* @suppress
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class HeartRateVariabilitySdnnRecord(
override val time: Instant,
override val zoneOffset: ZoneOffset?,
/** Heart rate variability in milliseconds. Required field. */
public val heartRateVariabilityMillis: Double,
override val metadata: Metadata = Metadata.EMPTY,
) : InstantaneousRecord {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is HeartRateVariabilitySdnnRecord) return false
if (heartRateVariabilityMillis != other.heartRateVariabilityMillis) return false
if (time != other.time) return false
if (zoneOffset != other.zoneOffset) return false
if (metadata != other.metadata) return false
return true
}
override fun hashCode(): Int {
var result = 0
result = 31 * result + heartRateVariabilityMillis.hashCode()
result = 31 * result + time.hashCode()
result = 31 * result + (zoneOffset?.hashCode() ?: 0)
result = 31 * result + metadata.hashCode()
return result
}
}
|
apache-2.0
|
bf812d19f8f413330f7da534cea928ee
| 35.105263 | 96 | 0.709427 | 4.425806 | false | false | false | false |
androidx/androidx
|
compose/ui/ui-text/src/skikoMain/kotlin/androidx/compose/ui/text/platform/SkiaParagraphIntrinsics.skiko.kt
|
3
|
3362
|
/*
* Copyright 2020 The Android 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.
*/
package androidx.compose.ui.text.platform
import androidx.compose.ui.text.AnnotatedString.Range
import androidx.compose.ui.text.ParagraphIntrinsics
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.ResolvedTextDirection
import androidx.compose.ui.text.style.TextDirection
import androidx.compose.ui.unit.Density
import kotlin.math.ceil
internal actual fun ActualParagraphIntrinsics(
text: String,
style: TextStyle,
spanStyles: List<Range<SpanStyle>>,
placeholders: List<Range<Placeholder>>,
density: Density,
fontFamilyResolver: FontFamily.Resolver
): ParagraphIntrinsics =
SkiaParagraphIntrinsics(
text,
style,
spanStyles,
placeholders,
density,
fontFamilyResolver
)
internal class SkiaParagraphIntrinsics(
val text: String,
private val style: TextStyle,
private val spanStyles: List<Range<SpanStyle>>,
private val placeholders: List<Range<Placeholder>>,
private val density: Density,
private val fontFamilyResolver: FontFamily.Resolver
) : ParagraphIntrinsics {
val textDirection = resolveTextDirection(style.textDirection)
private var layouter: ParagraphLayouter? = newLayouter()
fun layouter(): ParagraphLayouter {
val layouter = this.layouter ?: newLayouter()
this.layouter = null
return layouter
}
private fun newLayouter() = ParagraphLayouter(
text, textDirection, style, spanStyles, placeholders, density, fontFamilyResolver
)
override var minIntrinsicWidth = 0f
private set
override var maxIntrinsicWidth = 0f
private set
init {
val para = layouter!!.layoutParagraph(Float.POSITIVE_INFINITY)
minIntrinsicWidth = ceil(para.minIntrinsicWidth)
maxIntrinsicWidth = ceil(para.maxIntrinsicWidth)
}
private fun resolveTextDirection(direction: TextDirection?): ResolvedTextDirection {
return when (direction) {
TextDirection.Ltr -> ResolvedTextDirection.Ltr
TextDirection.Rtl -> ResolvedTextDirection.Rtl
TextDirection.Content -> contentBasedTextDirection() ?: ResolvedTextDirection.Ltr
TextDirection.ContentOrLtr -> contentBasedTextDirection() ?: ResolvedTextDirection.Ltr
TextDirection.ContentOrRtl -> contentBasedTextDirection() ?: ResolvedTextDirection.Rtl
else -> ResolvedTextDirection.Ltr
}
}
private fun contentBasedTextDirection() = text.contentBasedTextDirection()
}
internal expect fun String.contentBasedTextDirection(): ResolvedTextDirection?
|
apache-2.0
|
688976b20d3aa6262b5f072cedac3e43
| 35.16129 | 98 | 0.735277 | 4.980741 | false | false | false | false |
SDS-Studios/ScoreKeeper
|
app/src/main/java/io/github/sdsstudios/ScoreKeeper/Database/Dao/GameDao.kt
|
1
|
2710
|
package io.github.sdsstudios.ScoreKeeper.Database.Dao
import android.arch.lifecycle.LiveData
import android.arch.persistence.room.*
import io.github.sdsstudios.ScoreKeeper.Database.TypeConverters.DateConverter
import io.github.sdsstudios.ScoreKeeper.Game.Game
import io.github.sdsstudios.ScoreKeeper.Game.GameWithRounds
import io.github.sdsstudios.ScoreKeeper.Game.Player
import io.github.sdsstudios.ScoreKeeper.Game.Scores
import io.github.sdsstudios.ScoreKeeper.GameListItem
/**
* Created by sethsch1 on 29/10/17.
*/
@Dao
@TypeConverters(DateConverter::class)
abstract class GameDao : BaseDao<Game>() {
companion object {
const val TABLE_NAME = "games"
//columns
const val KEY_ID = "id"
const val KEY_COMPLETED = "completed"
const val KEY_WINNING_SCORE = "winning_score"
const val KEY_SCORE_INTERVAL = "score_interval"
const val KEY_SCORE_DIFF_TO_WIN = "score_diff_to_win"
const val KEY_NUM_SETS_CHOSEN = "number_sets_chosen"
const val KEY_NUM_SETS_PLAYED = "number_sets_played"
const val KEY_STARTING_SCORE = "starting_score"
const val KEY_DURATION = "duration"
const val KEY_CREATION_DATE = "creation_date"
const val KEY_LAST_PLAYED_DATE = "last_played_date"
const val KEY_TITLE = "title"
const val KEY_REVERSE_SCORING = "reverse_scoring"
const val KEY_USE_STOPWATCH = "use_stopwatch"
const val KEY_NOTES = "notes"
const val KEY_TIME_LIMIT = "time_limit"
}
@Transaction
open fun updateGameWithRounds(game: GameWithRounds) {
update(game)
updateSets(*game.rounds.toTypedArray())
updatePlayers(*game.rounds.map { it.player }.toTypedArray())
}
@Transaction
@Query("SELECT * FROM ${GameDao.TABLE_NAME} WHERE games.id = :arg0")
abstract fun getGameWithSets(gameId: Long): LiveData<GameWithRounds>
@Transaction
@Query("SELECT ${GameDao.KEY_ID}, ${GameDao.KEY_TITLE}, ${GameDao.KEY_COMPLETED}," +
"${GameDao.KEY_LAST_PLAYED_DATE} " +
"FROM ${GameDao.TABLE_NAME} WHERE ${GameDao.KEY_COMPLETED} = :arg0 " +
"ORDER BY ${GameDao.KEY_LAST_PLAYED_DATE} DESC")
abstract fun getGamesByState(state: Int): LiveData<List<GameListItem>>
@Update
abstract fun updateSets(vararg sets: Scores)
@Update
abstract fun updatePlayers(vararg player: Player)
@Query("SELECT * FROM ${GameDao.TABLE_NAME} WHERE games.id = :arg0")
abstract fun getGame(gameId: Long): LiveData<Game>
@Query("DELETE FROM $TABLE_NAME WHERE id IN (:arg0)")
abstract fun deleteById(vararg ids: Long)
@Query("DELETE FROM $TABLE_NAME")
abstract fun deleteAll()
}
|
gpl-3.0
|
4a25845cddb5137c4a5a5445de2a163e
| 36.136986 | 88 | 0.684502 | 3.79021 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/oldGenerateUtil.kt
|
1
|
1760
|
// 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.idea.core
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.openapi.application.runWriteAction
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
fun <T : KtDeclaration> insertMembersAfterAndReformat(
editor: Editor?,
classOrObject: KtClassOrObject,
members: Collection<T>,
anchor: PsiElement? = null,
getAnchor: (KtDeclaration) -> PsiElement? = { null },
): List<T> {
val codeStyleManager = CodeStyleManager.getInstance(classOrObject.project)
return runWriteAction {
val insertedMembersElementPointers = insertMembersAfter(editor, classOrObject, members, anchor, getAnchor)
val firstElement = insertedMembersElementPointers.firstOrNull() ?: return@runWriteAction emptyList()
fun insertedMembersElements() = insertedMembersElementPointers.mapNotNull { it.element }
ShortenReferences.DEFAULT.process(insertedMembersElements())
if (editor != null) {
firstElement.element?.let { moveCaretIntoGeneratedElement(editor, it) }
}
insertedMembersElementPointers.onEach { it.element?.let { element -> codeStyleManager.reformat(element) } }
insertedMembersElements()
}
}
fun <T : KtDeclaration> insertMembersAfterAndReformat(editor: Editor?, classOrObject: KtClassOrObject, declaration: T, anchor: PsiElement? = null): T {
return insertMembersAfterAndReformat(editor, classOrObject, listOf(declaration), anchor).single()
}
|
apache-2.0
|
587a9c8ae559f2cbee14ca5b30f2efde
| 45.315789 | 158 | 0.759659 | 4.743935 | false | false | false | false |
jwren/intellij-community
|
platform/platform-impl/src/com/intellij/internal/ui/RoundedIconTestAction.kt
|
1
|
5193
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.ui
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.IconLoader
import com.intellij.ui.Gray
import com.intellij.ui.RoundedIcon
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.paint.RectanglePainter
import com.intellij.util.IconUtil
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.ImageUtil
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import java.awt.*
import java.awt.BorderLayout.*
import java.awt.event.ActionListener
import java.awt.geom.Ellipse2D
import java.awt.image.BufferedImage
import javax.swing.*
import javax.swing.event.ChangeListener
@Suppress("HardCodedStringLiteral")
class RoundedIconTestAction : DumbAwareAction("Show Rounded Icon") {
override fun actionPerformed(e: AnActionEvent) {
object : DialogWrapper(e.project, null, true, IdeModalityType.IDE, false) {
private val myLabel = JBLabel("Some text").apply {
horizontalAlignment = SwingConstants.CENTER
horizontalTextPosition = SwingConstants.LEFT
}
private val iconChooser = JCheckBox("Splash", true).apply { isOpaque = false }
private val formChooser = JCheckBox("Superellipse", true).apply { isOpaque = false }
val slider = JSlider(0, 100).apply {
value = 33
paintLabels = true
paintTicks = true
minorTickSpacing = 1
majorTickSpacing = 10
isOpaque = false
}
val splashIcon: Icon? by lazy { IconLoader.findIcon(ApplicationInfoImpl.getShadowInstanceImpl().splashImageUrl, ApplicationInfoImpl::class.java.classLoader) }
val generatedIcon: Icon? by lazy {
IconUtil.createImageIcon((createRandomImage(splashIcon!!.iconWidth, splashIcon!!.iconHeight) as Image))
}
init {
title = "Rounded Icon Demo"
isResizable = false
init()
slider.addChangeListener(ChangeListener {
updateIcon()
})
updateIcon()
}
override fun getStyle(): DialogStyle {
return DialogStyle.COMPACT
}
override fun createCenterPanel(): JComponent {
val panel = object : BorderLayoutPanel() {
override fun paintComponent(g: Graphics?) {
super.paintComponent(g)
GraphicsUtil.setupAAPainting(g as Graphics2D)
g.paint = GradientPaint(0f, 0f, UIUtil.getLabelDisabledForeground(), 0f, height.toFloat(), Gray.TRANSPARENT)
var x = -height
while (x < width + height) {
g.drawLine(x, 0, x + height, height)
g.drawLine(x, 0, x - height, height)
x += 10
}
}
}.apply { border = createDefaultBorder() }
val actionListener = ActionListener {
updateIcon()
}
iconChooser.addActionListener(actionListener)
formChooser.addActionListener(actionListener)
panel.add(myLabel, CENTER)
val southPanel = NonOpaquePanel(BorderLayout())
val chooserPanel = NonOpaquePanel(GridLayout(2, 1))
chooserPanel.add(iconChooser)
chooserPanel.add(formChooser)
southPanel.add(chooserPanel, WEST)
southPanel.add(slider, CENTER)
panel.add(southPanel, SOUTH)
return panel
}
fun updateIcon() {
myLabel.icon = RoundedIcon(if (iconChooser.isSelected) splashIcon!! else generatedIcon!!,
(slider.value * 0.01),
formChooser.isSelected)
}
override fun createActions() = emptyArray<Action>()
}.show()
}
private fun topHalf() = (0.5 + Math.random() / 2).toFloat()
private fun randomColor() = Color(topHalf(), topHalf(), topHalf(), topHalf())
private fun createRandomImage(width: Int, height: Int): BufferedImage {
val image = ImageUtil.createImage(width, height, BufferedImage.TRANSLUCENT)
val g = image.graphics as Graphics2D
try {
g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY)
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g.color = randomColor()
RectanglePainter.FILL.paint(g, 0, 0, width, height, null)
for (i in 0 until 100) {
g.color = randomColor()
val r = Math.random() * Math.min(width, height) / Math.PI
g.fill(Ellipse2D.Double(Math.random() * width, Math.random() * height, r, r))
}
g.color = Color(0, 0, 0, 85) //mark center of a picture
g.fill(Ellipse2D.Double((width/2 - 2).toDouble(), (height/2 - 2).toDouble(), 4.toDouble(), 4.toDouble()))
}
finally {
g.dispose()
}
return image
}
}
|
apache-2.0
|
cc64173ea311f4895d86c18d1df94ede
| 38.348485 | 164 | 0.674754 | 4.400847 | false | false | false | false |
vovagrechka/fucking-everything
|
alraune/alraune/src/main/java/alraune/DebugCodeConsole.kt
|
1
|
3922
|
package alraune
import pieces100.*
import vgrechka.*
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
abstract class DebugCodeConsole {
abstract fun initEngine(engine: ScriptEngine)
open fun onExecution() {}
open fun onExecutionSuccess() {}
open fun onExecutionException(e: Throwable) {}
val select = select()
val textArea = textarea()
val runButton = button()
val ticker = div()
val resultDiv = div()
val errorDiv = div()
var initialCode: String? = null
val presets = mutableListOf(ValueTitle("", ""))
private var initialPresetIndex = 0
fun initialPresetIndex(x: Int) {initialPresetIndex = x + 1}
fun compose() = div().with {
oo(select.classes("form-control").style("margin-bottom: 8px;"))
for ((index, preset) in presets.withIndex()) {
select.add(option().value(preset.value).add(preset.title).selected(index == initialPresetIndex))
}
select.whenDomReady_addListener("change", "${textArea.jq()}.text(${select.jq()}.val())")
oo(div().style("position: relative;").with {
oo(textArea.autoFocus(true).rows(10).spellCheck(false).classes("form-control").style("font-family: monospace;")
.add(initialCode ?: presets[initialPresetIndex].value))
oo(runButton.add(FA.play()).classes("btn btn-primary").style("position: absolute; right: 8px; top: 8px;"))
oo(ticker.style("position: absolute; right: 8px; top: 8px; display: none;")
.add(composeBarTicker()))
})
oo(resultDiv.style("display: none; margin-top: 8px; padding-top: 8px; border-top: 2px dashed ${Color.Gray500}; white-space: pre-wrap; font-family: monospace; font-weight: bold; background: ${Color.Gray50};"))
oo(errorDiv.style("display: none; margin-top: 8px; padding-top: 8px; border-top: 2px dashed ${Color.Gray500}; white-space: pre-wrap; font-family: monospace; font-weight: bold; background: ${Color.Red50}; color: ${Color.Red900};"))
textArea.whenDomReady_addListener("keydown", """
if (event.ctrlKey && event.keyCode === 13) {
event.preventDefault()
event.stopPropagation()
${jsRun()}
}""")
runButton.whenDomReady_addListener("click", jsRun())
}
fun jsRun() = """
const code = ${textArea.jq()}.val()
${runButton.jq()}.hide()
${ticker.jq()}.show()
${resultDiv.jq()}.hide()
${errorDiv.jq()}.hide()
${jsCallBackendServantHandle(freakingServant(::serve), jsFillFtb = "ftb.code = code")}
"""
fun serve() {
val code = rctx0.ftbMap["code"] as String
clog("code = $code")
// Thread.sleep(1000) // Enjoy the ticker :)
val engine = ScriptEngineManager().getEngineByName("nashorn")
initEngine(engine)
var exception: Throwable? = null
var result by notNull<String>()
try {
val res = engine.eval(code)
result = res?.toString() ?: "<null>"
} catch (e: Throwable) {
exception = e
}
btfEval("""
${runButton.jq()}.show()
${ticker.jq()}.hide()""")
if (exception != null) {
btfEval("""
${errorDiv.jq()}.text(${jsStringLiteral(exception.stackTraceString)})
${errorDiv.jq()}.show()""")
onExecutionException(exception)
}
else {
btfEval("""
${resultDiv.jq()}.text(${jsStringLiteral(result)})
${resultDiv.jq()}.show()""")
onExecutionSuccess()
}
onExecution()
}
object Test1 {
@JvmStatic fun main(args: Array<String>) {
val engine = ScriptEngineManager().getEngineByName("nashorn")
engine.eval("""print("pizda"); print("hairy")""")
}
}
}
|
apache-2.0
|
59f031a21cf1e7d833785187fa917804
| 35.314815 | 238 | 0.579296 | 4.128421 | false | false | false | false |
GunoH/intellij-community
|
plugins/gradle/java/src/codeInspection/GradlePluginDslStructureInspection.kt
|
2
|
6175
|
// 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.plugins.gradle.codeInspection
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import com.intellij.util.asSafely
import org.jetbrains.plugins.groovy.codeInspection.GroovyLocalInspectionTool
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
import org.jetbrains.plugins.groovy.lang.psi.api.GrBlockLambdaBody
import org.jetbrains.plugins.groovy.lang.psi.api.GrExpressionLambdaBody
import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression
import org.jetbrains.plugins.groovy.lang.psi.api.GrLambdaExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
class GradlePluginDslStructureInspection : GroovyLocalInspectionTool() {
override fun buildGroovyVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): GroovyElementVisitor = object: GroovyElementVisitor() {
override fun visitFile(file: GroovyFileBase) {
val statements = file.statements
val lastPluginsStatement = statements.indexOfFirst { it is GrMethodCall && it.invokedExpression.text == "plugins" }
if (lastPluginsStatement == -1) {
return
}
val pluginsStatement = statements[lastPluginsStatement] as GrMethodCall
checkPluginsStatement(holder, pluginsStatement)
val statementsToCheck = statements.asList().subList(0, lastPluginsStatement)
for (suspiciousStatement in statementsToCheck) {
val psiToHighlight = getBadStatementHighlightingElement(suspiciousStatement) ?: continue
holder.registerProblem(psiToHighlight, GradleInspectionBundle.message("inspection.message.incorrect.buildscript.structure"), ProblemHighlightType.GENERIC_ERROR)
}
}
}
private fun checkPluginsStatement(holder: ProblemsHolder, pluginsStatement: GrMethodCall) {
val statements = getStatements(pluginsStatement)
for (statement in statements) {
if (statement !is GrMethodCall) {
holder.registerProblem(statement, GradleInspectionBundle.message("inspection.message.only.method.calls.to.id.alias.are.available.in.plugins.block"))
continue
}
val (refElement) = decomposeCall(statement) ?: continue
when (refElement?.text) {
"apply" -> checkApply(holder, statement)
"version" -> checkVersion(holder, statement)
else -> if (checkIdAlias(holder, statement)) {
holder.registerProblem(statement, GradleInspectionBundle.message("inspection.message.only.method.calls.to.id.alias.are.available.in.plugins.block"))
}
}
}
}
private fun decomposeCall(call: GrMethodCall) : Triple<PsiElement?, GrExpression?, String?>? {
val caller = call.invokedExpression.asSafely<GrReferenceExpression>() ?: return null
val qualifierCallName = caller.qualifierExpression.asSafely<GrMethodCall>()?.invokedExpression.asSafely<GrReferenceExpression>()?.referenceName
return Triple(caller.referenceNameElement, caller.qualifierExpression, qualifierCallName)
}
private fun checkApply(holder: ProblemsHolder, method: GrExpression?) {
if (method !is GrMethodCall) {
return
}
val (refElement, qualifier, qualifierCallName) = decomposeCall(method) ?: return
if (qualifierCallName == "version") {
checkVersion(holder, qualifier)
} else if (refElement != null && checkIdAlias(holder, qualifier)) {
holder.registerProblem(refElement, GradleInspectionBundle.message("inspection.message.only.method.calls.to.id.alias.are.available.in.plugins.block"))
}
}
private fun checkVersion(holder: ProblemsHolder, method: GrExpression?) {
if (method !is GrMethodCall) {
return
}
val (refElement, qualifier) = decomposeCall(method) ?: return
if (refElement != null && checkIdAlias(holder, qualifier)) {
holder.registerProblem(refElement, GradleInspectionBundle.message("inspection.message.only.method.calls.to.id.alias.are.available.in.plugins.block"))
}
}
private fun checkIdAlias(holder: ProblemsHolder, method: GrExpression?) : Boolean {
if (method !is GrMethodCall) {
return true
}
val (refElement, _) = decomposeCall(method) ?: return true
val methodName = refElement?.text
if (methodName != "id" && methodName != "alias") {
holder.registerProblem(refElement ?: method, GradleInspectionBundle.message("inspection.message.only.method.calls.to.id.alias.are.available.in.plugins.block"))
}
return false
}
private val allowedStrings = setOf("buildscript", "pluginManagement", "plugins")
private fun getBadStatementHighlightingElement(suspiciousStatement: GrStatement): PsiElement? {
if (suspiciousStatement !is GrMethodCall) {
return suspiciousStatement
}
if (suspiciousStatement.invokedExpression.text !in allowedStrings) {
return suspiciousStatement.invokedExpression
}
return null
}
companion object {
fun getStatements(call: GrMethodCall) : Array<GrStatement> {
val closure = call.closureArguments.singleOrNull() ?: call.expressionArguments.firstOrNull()?.asSafely<GrFunctionalExpression>() ?: return emptyArray()
return getStatements(closure)
}
private fun getStatements(funExpr: GrFunctionalExpression) : Array<GrStatement> {
return when (funExpr) {
is GrClosableBlock -> return funExpr.statements
is GrLambdaExpression -> when (val body = funExpr.body) {
is GrBlockLambdaBody -> body.statements
is GrExpressionLambdaBody -> arrayOf(body.expression)
else -> emptyArray()
}
else -> emptyArray()
}
}
}
}
|
apache-2.0
|
ea90472cc6a237716d9f6c1990c17837
| 45.787879 | 168 | 0.750121 | 4.681577 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateInvokeFunctionActionFactory.kt
|
3
|
2365
|
// 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.idea.quickfix.createFromUsage.createCallable
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.util.OperatorNameConventions
object CreateInvokeFunctionActionFactory : CreateCallableMemberFromUsageFactory<KtCallExpression>() {
override fun getElementOfInterest(diagnostic: Diagnostic): KtCallExpression? {
return diagnostic.psiElement.parent as? KtCallExpression
}
override fun createCallableInfo(element: KtCallExpression, diagnostic: Diagnostic): CallableInfo? {
val expectedType = Errors.FUNCTION_EXPECTED.cast(diagnostic).b
if (expectedType.isError) return null
val receiverType = TypeInfo(expectedType, Variance.IN_VARIANCE)
val anyType = element.builtIns.nullableAnyType
val parameters = element.valueArguments.map {
ParameterInfo(
it.getArgumentExpression()?.let { expression -> TypeInfo(expression, Variance.IN_VARIANCE) } ?: TypeInfo(
anyType,
Variance.IN_VARIANCE
),
it.getArgumentName()?.referenceExpression?.getReferencedName()
)
}
val returnType = TypeInfo(element, Variance.OUT_VARIANCE)
return FunctionInfo(
OperatorNameConventions.INVOKE.asString(),
receiverType,
returnType,
parameterInfos = parameters,
modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD)
)
}
}
|
apache-2.0
|
b5e00bad4a5fef0a798a0eb403f9eed5
| 46.3 | 158 | 0.746723 | 5.3386 | false | false | false | false |
pacmancoder/krayser
|
src/main/kotlin/org/krayser/util/Vec3D.kt
|
1
|
2787
|
package org.krayser.util
/**
* 3D Vector
*/
data class Vec3D(var x: Float, var y: Float, var z: Float) {
/**
* Constructs vector with scalar
*/
constructor(scalar: Float): this(scalar, scalar, scalar)
constructor(vec: Vec3D): this(vec.x, vec.y, vec.z)
constructor(vec: Vec2D, scalar: Float): this(vec.x, vec.y, scalar)
constructor(scalar: Float, vec: Vec2D): this(scalar, vec.x, vec.y)
/**
* Returns length of vector
*/
fun len() = Math.sqrt((x * x + y * y + z * z).toDouble()).toFloat()
fun clamped(min: Float, max: Float): Vec3D {
val v = Vec3D(this)
for (i in 0..2) {
if (v[i] < min) v[i] = min
if (v[i] > max) v[i] = max
}
return v
}
/**
* Returns normalized vector
*/
fun normalized() = this / len()
/**
* Reflects vector from palne, defined by [normal]
* @param normal plane normal
*/
fun reflect(normal: Vec3D) = this - 2f * (this dot normal) * normal
/**
* Returns projection of 3D vector on 2D plane
*/
fun project() = Vec2D(x, y)
/**
* Returns dot product of vectors
*/
infix fun dot(rhs: Vec3D) = x * rhs.x + y * rhs.y + z * rhs.z
/**
* Returns cross-product of vectors
*/
infix fun cross(rhs: Vec3D) = Vec3D(
+(rhs.y * z - rhs.z * y),
-(rhs.x * z - rhs.z * x),
+(rhs.x * y - rhs.y * x))
/**
* multiplies vector with scalar
*/
operator fun times(scalar: Float) = Vec3D(x * scalar, y * scalar, z * scalar)
/**
* divides vector with scalar
*/
operator fun div(scalar: Float) = Vec3D(x / scalar, y / scalar, z / scalar)
/**
* Returns difference between vectors
*/
operator fun minus(rhs: Vec3D) = Vec3D(x - rhs.x, y - rhs.y, z - rhs.z)
/**
* Returns sum of vectors
*/
operator fun plus(rhs: Vec3D) = Vec3D(x + rhs.x, y + rhs.y, z + rhs.z)
/**
* Returns inverted vector
*/
operator fun unaryMinus() = Vec3D(-x, -y, -z)
// vector mix
operator fun times(rhs: Vec3D) = Vec3D(x * rhs.x, y * rhs.y, z * rhs.z)
/**
* Index operator
*/
operator fun get(index: Int): Float = when (index) {
0 -> x
1 -> y
2 -> z
else -> throw IndexOutOfBoundsException("Vector3D have only 3 components")
}
operator fun set(index: Int, rhs: Float) = when (index) {
0 -> x = rhs
1 -> y = rhs
2 -> z = rhs
else -> throw IndexOutOfBoundsException("Vector3D have only 3 components")
}
}
/**
* multiplies vector by float
*/
operator fun Float.times(vec: Vec3D) = vec * this
/**
* divides vector by float
*/
operator fun Float.div(vec: Vec3D) = vec / this
|
mit
|
0321321b4467c7ff12746e45410a580a
| 24.117117 | 82 | 0.535701 | 3.286557 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/gradle/importAndCheckHighlighting/commonizeDummyCInterop/p1/src/nativeMain/kotlin/NativeMain.kt
|
10
|
876
|
import dummy.DummyStruct
import dummy.OtherStruct
import dummy.createDummyStruct
import dummy.createOtherStruct
import kotlinx.cinterop.*
fun useDummy(): Double {
memScoped {
alloc<DummyStruct> {
myShort = 0
myInteger = 1
myLong = 2
myFloat = 0.3f
myDouble = 0.4
}
}
val dummy: CPointer<DummyStruct> = createDummyStruct() ?: return 0.0
val other: CValue<OtherStruct> = createOtherStruct()
return sum(dummy.pointed) + other.useContents { sum(this) }
}
expect fun <lineMarker descr="Has actuals in Native (2 modules)">sum</lineMarker>(otherStruct: OtherStruct): Double
expect fun <lineMarker descr="Has actuals in Native (2 modules)">sum</lineMarker>(dummy: DummyStruct): Double
expect fun DummyStruct.<lineMarker descr="Has actuals in Native (2 modules)">reset</lineMarker>()
|
apache-2.0
|
9e9c8ef22b2e5f7f50c29cddef5ad62d
| 31.444444 | 115 | 0.682648 | 4.151659 | false | false | false | false |
cy6erGn0m/kotlin-frontend-plugin
|
kotlin-frontend/src/main/kotlin/org/jetbrains/kotlin/gradle/frontend/npm/GeneratePackagesJsonTask.kt
|
1
|
4967
|
package org.jetbrains.kotlin.gradle.frontend.npm
import groovy.json.*
import org.gradle.api.*
import org.gradle.api.plugins.*
import org.gradle.api.tasks.*
import org.jetbrains.kotlin.gradle.dsl.*
import org.jetbrains.kotlin.gradle.frontend.*
import org.jetbrains.kotlin.gradle.frontend.util.*
import java.io.*
import java.util.*
/**
* @author Sergey Mashkov
*/
open class GeneratePackagesJsonTask : DefaultTask() {
@Internal
lateinit var dependenciesProvider: () -> List<Dependency>
@get:Internal
val toolsDependencies: List<Dependency> by lazy { dependenciesProvider() }
@get:Input
@Suppress("unused")
val toolsDependenciesInput: String
get() = toolsDependencies.joinToString()
@get:InputFiles
val unpackResults: List<File>
get() = project.tasks.filterIsInstance<UnpackGradleDependenciesTask>().map { it.resultFile }
@Input
val configPartsDir = project.projectDir.resolve("package.json.d")
@Internal
private val npm = project.extensions.getByType(NpmExtension::class.java)!!
@get:Input
@Suppress("unused")
val dependenciesInput: String
get() = npm.dependencies.joinToString()
@get:Input
@Suppress("unused")
val devDependenciesInput: String
get() = npm.developmentDependencies.joinToString()
@Suppress("unused")
@get:Input
val versionReplacementsInput: String
get() = npm.versionReplacements.joinToString()
@get:Input
val moduleNames: List<String> by lazy { project.tasks.withType(KotlinJsCompile::class.java)
.filter { !it.name.contains("test", ignoreCase = true) }
.mapNotNull { it.kotlinOptions.outputFile?.substringAfterLast('/')?.substringAfterLast('\\')?.removeSuffix(".js") }
}
@OutputFile
lateinit var packageJsonFile: File
@OutputFile
lateinit var npmrcFile: File
val buildPackageJsonFile: File?
init {
if (configPartsDir.exists()) {
(inputs as TaskInputs).dir(configPartsDir)
}
buildPackageJsonFile = project.convention.findPlugin(JavaPluginConvention::class.java)?.sourceSets?.let { sourceSets ->
sourceSets.findByName("main")?.output?.resourcesDir?.resolve("package.json")
}
if (buildPackageJsonFile != null) {
outputs.file(buildPackageJsonFile)
}
onlyIf {
npm.dependencies.isNotEmpty() || npm.developmentDependencies.isNotEmpty() || toolsDependencies.isNotEmpty()
}
}
@TaskAction
fun generate() {
logger.info("Configuring npm")
val dependencies = npm.dependencies + (project.tasks.filterIsInstance<UnpackGradleDependenciesTask>().map { task ->
task.resultNames?.map { Dependency(it.name, it.semver, Dependency.RuntimeScope) } ?: task.resultFile.readLinesOrEmpty()
.map { it.split("/", limit = 4).map(String::trim) }
.filter { it.size == 4 }
.map { Dependency(it[0], it[2], Dependency.RuntimeScope) }
}).flatten() + toolsDependencies.filter { it.scope == Dependency.RuntimeScope }
val devDependencies = mutableListOf(*npm.developmentDependencies.toTypedArray())
devDependencies.addAll(toolsDependencies.filter {
(it.scope == Dependency.DevelopmentScope) && devDependencies.all { dep -> dep.name != it.name }
})
if (logger.isDebugEnabled) {
logger.debug(dependencies.joinToString(prefix = "Dependencies:\n", separator = "\n") { "${it.name}: ${it.versionOrUri}" })
}
val packagesJson: Map<*, *> = mapOf(
"name" to (moduleNames.singleOrNull() ?: project.name ?: "noname"),
"version" to (toSemver(project.version.toString())),
"description" to "simple description",
"main" to (moduleNames.singleOrNull()),
"dependencies" to dependencies.associateBy({ it.name }, { it.versionOrUri }),
"devDependencies" to devDependencies.associateBy({ it.name }, { it.versionOrUri })
)
val number = "^\\d+".toRegex()
val allIncluded = configPartsDir.listFiles()
.orEmpty()
.filter { it.isFile && it.canRead() }
.sortedBy { number.find(it.nameWithoutExtension)?.value?.toInt() ?: 0 }
.map { LinkedHashMap(JsonSlurper().parse(it) as Map<*, *>) }
val resultJson = allIncluded.fold(packagesJson, ::mergeMaps)
packageJsonFile.writeText(JsonBuilder(resultJson).toPrettyString())
npmrcFile.writeText("""
progress=false
package-lock=false
# cache-min=3600
""".trimIndent())
npmrcFile.resolveSibling("package-lock.json").delete()
if (buildPackageJsonFile != null) {
buildPackageJsonFile.parentFile.mkdirsOrFail()
packageJsonFile.copyTo(buildPackageJsonFile, overwrite = true)
}
}
}
|
apache-2.0
|
57d0342c112a200262939fa3d5020944
| 35.522059 | 134 | 0.639219 | 4.544373 | false | false | false | false |
blan4/MangaReader
|
api/src/main/kotlin/org/seniorsigan/mangareader/sources/readmanga/ReadmangaUrls.kt
|
1
|
992
|
package org.seniorsigan.mangareader.sources.readmanga
import java.net.URI
interface Urls {
val name: String
val base: URI
fun mangaList(offset: Int = 0): URI
val search: URI
}
object ReadmangaUrls: Urls {
override val name = "readmanga"
override val base = URI("http://readmanga.me")
override fun mangaList(offset: Int) = base.resolve("/list?sortType=rate&offset=$offset")!!
override val search = base.resolve("/search")!!
}
object MintmangaUrls: Urls {
override val name = "mintmanga"
override val base = URI("http://mintmanga.com")
override fun mangaList(offset: Int) = base.resolve("/list?sortType=rate&offset=$offset")!!
override val search = base.resolve("/search")!!
}
object SelfmangaUrls: Urls {
override val name = "selfmanga"
override val base = URI("http://selfmanga.ru")
override fun mangaList(offset: Int) = base.resolve("/list?sortType=rate&offset=$offset")!!
override val search = base.resolve("/search")!!
}
|
mit
|
fd6af25a0c2bbfe7bacb69713364d932
| 31.032258 | 94 | 0.689516 | 3.757576 | false | false | false | false |
joaomneto/TitanCompanion
|
src/main/java/pt/joaomneto/titancompanion/adventurecreation/impl/SOTSAdventureCreation.kt
|
1
|
1910
|
package pt.joaomneto.titancompanion.adventurecreation.impl
import android.view.View
import java.io.BufferedWriter
import java.io.IOException
import pt.joaomneto.titancompanion.R
import pt.joaomneto.titancompanion.adventurecreation.AdventureCreation
import pt.joaomneto.titancompanion.adventurecreation.impl.fragments.VitalStatisticsFragment
import pt.joaomneto.titancompanion.adventurecreation.impl.fragments.sots.SOTSAdventureCreationSkillFragment
import pt.joaomneto.titancompanion.adventurecreation.impl.fragments.sots.SOTSMartialArt
import pt.joaomneto.titancompanion.util.AdventureFragmentRunner
class SOTSAdventureCreation : AdventureCreation(
arrayOf(
AdventureFragmentRunner(R.string.title_adventure_creation_vitalstats, VitalStatisticsFragment::class),
AdventureFragmentRunner(
R.string.title_adventure_creation_skill,
SOTSAdventureCreationSkillFragment::class
)
)
) {
private var martialArt: SOTSMartialArt? = null
override fun rollGamebookSpecificStats(view: View) {}
@Throws(IOException::class)
override fun storeAdventureSpecificValuesInFile(bw: BufferedWriter) {
bw.write("honour=3\n")
bw.write("skill=" + martialArt!!.name + "\n")
bw.write("provisions=10\n")
bw.write("provisionsValue=4\n")
bw.write("gold=0\n")
if (SOTSMartialArt.KYUJUTSU == martialArt) {
bw.write("willowLeafArrows=3\n")
bw.write("bowelRakerArrows=3\n")
bw.write("armourPiercerArrows=3\n")
bw.write("hummingBulbArrows=3\n")
}
}
fun setSkill(martialArt: SOTSMartialArt) {
this.martialArt = martialArt
}
override fun validateCreationSpecificParameters(): String? {
val sb = StringBuilder()
if (this.martialArt == null) {
sb.append("Martial Art")
}
return sb.toString()
}
}
|
lgpl-3.0
|
edd0a06a25a0022c7c407997ec102234
| 35.037736 | 110 | 0.712042 | 4.04661 | false | false | false | false |
Waboodoo/HTTP-Shortcuts
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/headers/RequestHeadersAdapter.kt
|
1
|
4022
|
package ch.rmy.android.http_shortcuts.activities.editor.headers
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import ch.rmy.android.framework.extensions.color
import ch.rmy.android.framework.extensions.context
import ch.rmy.android.framework.extensions.setText
import ch.rmy.android.framework.ui.BaseAdapter
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.databinding.ListEmptyItemBinding
import ch.rmy.android.http_shortcuts.databinding.ListItemHeaderBinding
import ch.rmy.android.http_shortcuts.variables.VariablePlaceholderProvider
import ch.rmy.android.http_shortcuts.variables.Variables
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow
import javax.inject.Inject
class RequestHeadersAdapter
@Inject
constructor(
private val variablePlaceholderProvider: VariablePlaceholderProvider,
) :
BaseAdapter<HeaderListItem>() {
sealed interface UserEvent {
data class HeaderClicked(val id: String) : UserEvent
}
private val userEventChannel = Channel<UserEvent>(capacity = Channel.UNLIMITED)
val userEvents: Flow<UserEvent> = userEventChannel.receiveAsFlow()
override fun areItemsTheSame(oldItem: HeaderListItem, newItem: HeaderListItem): Boolean =
when (oldItem) {
is HeaderListItem.Header -> (newItem as? HeaderListItem.Header)?.id == oldItem.id
is HeaderListItem.EmptyState -> newItem is HeaderListItem.EmptyState
}
override fun getItemViewType(position: Int): Int =
when (items[position]) {
is HeaderListItem.Header -> VIEW_TYPE_HEADER
is HeaderListItem.EmptyState -> VIEW_TYPE_EMPTY_STATE
}
override fun createViewHolder(viewType: Int, parent: ViewGroup, layoutInflater: LayoutInflater): RecyclerView.ViewHolder? =
when (viewType) {
VIEW_TYPE_HEADER -> HeaderViewHolder(ListItemHeaderBinding.inflate(layoutInflater, parent, false))
VIEW_TYPE_EMPTY_STATE -> EmptyStateViewHolder(ListEmptyItemBinding.inflate(layoutInflater, parent, false))
else -> null
}
override fun bindViewHolder(holder: RecyclerView.ViewHolder, position: Int, item: HeaderListItem, payloads: List<Any>) {
when (holder) {
is HeaderViewHolder -> holder.setItem(item as HeaderListItem.Header)
is EmptyStateViewHolder -> holder.setItem(item as HeaderListItem.EmptyState)
}
}
inner class HeaderViewHolder(
private val binding: ListItemHeaderBinding,
) : RecyclerView.ViewHolder(binding.root) {
lateinit var headerId: String
private set
init {
binding.root.setOnClickListener {
userEventChannel.trySend(UserEvent.HeaderClicked(headerId))
}
}
private val variablePlaceholderColor by lazy(LazyThreadSafetyMode.NONE) {
color(context, R.color.variable)
}
fun setItem(item: HeaderListItem.Header) {
headerId = item.id
binding.headerKey.text = Variables.rawPlaceholdersToVariableSpans(
item.key,
variablePlaceholderProvider,
variablePlaceholderColor,
)
binding.headerValue.text = Variables.rawPlaceholdersToVariableSpans(
item.value,
variablePlaceholderProvider,
variablePlaceholderColor,
)
}
}
inner class EmptyStateViewHolder(
private val binding: ListEmptyItemBinding,
) : RecyclerView.ViewHolder(binding.root) {
fun setItem(item: HeaderListItem.EmptyState) {
binding.emptyMarker.setText(item.title)
binding.emptyMarkerInstructions.setText(item.instructions)
}
}
companion object {
private const val VIEW_TYPE_HEADER = 1
private const val VIEW_TYPE_EMPTY_STATE = 2
}
}
|
mit
|
894cf46dbd869cb59a19949a9dd205bb
| 36.588785 | 127 | 0.700398 | 4.947109 | false | false | false | false |
sky-map-team/stardroid
|
app/src/main/java/com/google/android/stardroid/control/ManualOrientationController.kt
|
1
|
3293
|
// Copyright 2008 Google 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 com.google.android.stardroid.control
import android.util.Log
import com.google.android.stardroid.math.calculateRotationMatrix
import com.google.android.stardroid.util.MiscUtil
/**
* Allows user-input elements such as touch screens and trackballs to move the
* map.
*
* @author John Taylor
*/
class ManualOrientationController : AbstractController() {
override fun start() {
// Nothing to do
}
override fun stop() {
// Nothing to do
}
/**
* Moves the astronomer's pointing right or left.
*
* @param radians the angular change in the pointing in radians (only
* accurate in the limit as radians tends to 0.)
*/
fun changeRightLeft(radians: Float) {
// TODO(johntaylor): Some of the Math in here perhaps belongs in
// AstronomerModel.
if (!enabled) {
return
}
val pointing = model.pointing
val pointingXyz = pointing.lineOfSight
val topXyz = pointing.perpendicular
val horizontalXyz = pointingXyz * topXyz
val deltaXyz = horizontalXyz * radians
val newPointingXyz = pointingXyz + deltaXyz
newPointingXyz.normalize()
model.setPointing(newPointingXyz, topXyz)
}
/**
* Moves the astronomer's pointing up or down.
*
* @param radians the angular change in the pointing in radians (only
* accurate in the limit as radians tends to 0.)
*/
fun changeUpDown(radians: Float) {
if (!enabled) {
return
}
// Log.d(TAG, "Scrolling up down");
val pointing = model.pointing
val pointingXyz = pointing.lineOfSight
// Log.d(TAG, "Current view direction " + viewDir);
val topXyz = pointing.perpendicular
val deltaXyz = topXyz * -radians
val newPointingXyz = pointingXyz + deltaXyz
newPointingXyz.normalize()
val deltaUpXyz = pointingXyz * radians
val newUpXyz = topXyz + deltaUpXyz
newUpXyz.normalize()
model.setPointing(newPointingXyz, newUpXyz)
}
/**
* Rotates the astronomer's view.
*/
fun rotate(degrees: Float) {
if (!enabled) {
return
}
Log.d(TAG, "Rotating by $degrees")
val pointing = model.pointing
val pointingXyz = pointing.lineOfSight
val rotation = calculateRotationMatrix(degrees, pointingXyz)
val topXyz = pointing.perpendicular
val newUpXyz = rotation * topXyz
newUpXyz.normalize()
model.setPointing(pointingXyz, newUpXyz)
}
companion object {
private val TAG = MiscUtil.getTag(ManualOrientationController::class.java)
}
}
|
apache-2.0
|
271dab26e2b116b7b4c477a8061732bf
| 31.613861 | 82 | 0.652596 | 4.227214 | false | false | false | false |
vector-im/vector-android
|
vector/src/main/java/im/vector/activity/PhoneNumberVerificationActivity.kt
|
2
|
11168
|
/*
* Copyright 2017 Vector Creations Ltd
* Copyright 2018 New Vector Ltd
*
* 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 im.vector.activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.MenuItem
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import im.vector.Matrix
import im.vector.R
import org.matrix.androidsdk.MXSession
import org.matrix.androidsdk.core.JsonUtils
import org.matrix.androidsdk.core.Log
import org.matrix.androidsdk.core.callback.ApiCallback
import org.matrix.androidsdk.core.model.MatrixError
import org.matrix.androidsdk.rest.client.LoginRestClient
import org.matrix.androidsdk.rest.model.SuccessResult
import org.matrix.androidsdk.rest.model.login.AuthParams
import org.matrix.androidsdk.rest.model.login.AuthParamsLoginPassword
import org.matrix.androidsdk.rest.model.pid.ThreePid
class PhoneNumberVerificationActivity : VectorAppCompatActivity(), TextView.OnEditorActionListener, TextWatcher {
private var mPhoneNumberCode: TextInputEditText? = null
private var mPhoneNumberCodeLayout: TextInputLayout? = null
private var mSession: MXSession? = null
private var mThreePid: ThreePid? = null
// True when a phone number token is submitted
// Used to prevent user to submit several times in a row
private var mIsSubmittingToken: Boolean = false
/*
* *********************************************************************************************
* Activity lifecycle
* *********************************************************************************************
*/
override fun getLayoutRes(): Int {
return R.layout.activity_phone_number_verification
}
override fun getTitleRes(): Int {
return R.string.settings_phone_number_verification
}
override fun initUiAndData() {
configureToolbar()
mPhoneNumberCode = findViewById(R.id.phone_number_code_value)
mPhoneNumberCodeLayout = findViewById(R.id.phone_number_code)
waitingView = findViewById(R.id.loading_view)
val intent = intent
mSession = Matrix.getInstance(this)!!.getSession(intent.getStringExtra(EXTRA_MATRIX_ID))
if (null == mSession || !mSession!!.isAlive) {
finish()
return
}
mThreePid = intent.getParcelableExtra(EXTRA_PID)
mPhoneNumberCode!!.addTextChangedListener(this)
mPhoneNumberCode!!.setOnEditorActionListener(this)
}
override fun onResume() {
super.onResume()
mIsSubmittingToken = false
}
override fun getMenuRes(): Int {
return R.menu.menu_phone_number_verification
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_verify_phone_number -> {
submitCode()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
/*
* *********************************************************************************************
* Utils
* *********************************************************************************************
*/
/**
* Submit code (token) to attach phone number to account
*/
private fun submitCode() {
if (!mIsSubmittingToken) {
mIsSubmittingToken = true
if (TextUtils.isEmpty(mPhoneNumberCode!!.text)) {
mPhoneNumberCodeLayout!!.isErrorEnabled = true
mPhoneNumberCodeLayout!!.error = getString(R.string.settings_phone_number_verification_error_empty_code)
} else {
showWaitingView()
mSession!!.identityServerManager.submitValidationToken(mThreePid!!, mPhoneNumberCode!!.text!!.toString(),
object : ApiCallback<SuccessResult> {
override fun onSuccess(result: SuccessResult) {
if (result.success) {
// the validation of mail ownership succeed, just resume the registration flow
// next step: just register
Log.e(LOG_TAG, "## submitPhoneNumberValidationToken(): onSuccess() - registerAfterEmailValidations() started")
registerAfterPhoneNumberValidation(mThreePid, null)
} else {
Log.e(LOG_TAG, "## submitPhoneNumberValidationToken(): onSuccess() - failed (success=false)")
onSubmitCodeError(getString(R.string.settings_phone_number_verification_error))
}
}
override fun onNetworkError(e: Exception) {
onSubmitCodeError(e.localizedMessage)
}
override fun onMatrixError(e: MatrixError) {
onSubmitCodeError(e.localizedMessage)
}
override fun onUnexpectedError(e: Exception) {
onSubmitCodeError(e.localizedMessage)
}
})
}
}
}
private fun registerAfterPhoneNumberValidation(pid: ThreePid?, auth: AuthParams?) {
mSession!!.identityServerManager.finalize3pidAddSession(pid!!, auth, object : ApiCallback<Void?> {
override fun onSuccess(info: Void?) {
val intent = Intent()
setResult(Activity.RESULT_OK, intent)
finish()
}
override fun onNetworkError(e: Exception) {
onSubmitCodeError(e.localizedMessage)
}
override fun onMatrixError(e: MatrixError) {
if (e.mStatus == 401 && e.mErrorBodyAsString.isNullOrBlank().not()) {
val flow = JsonUtils.toRegistrationFlowResponse(e.mErrorBodyAsString)
if (flow != null) {
val supportsLoginPassword = flow.flows.any { it.stages == listOf(LoginRestClient.LOGIN_FLOW_TYPE_PASSWORD) }
if (supportsLoginPassword) {
//we prompt for it
val invalidPassError = getString(R.string.login_error_forbidden)
.takeIf { e.errcode == MatrixError.FORBIDDEN }
DialogUtils.promptPassword(this@PhoneNumberVerificationActivity,
invalidPassError,
(auth as? AuthParamsLoginPassword)?.let { auth.password },
{ password ->
val authParams = AuthParamsLoginPassword().apply {
this.user = mSession?.myUserId
this.password = password
}
registerAfterPhoneNumberValidation(pid, authParams)
},
{
onSubmitCodeError(getString(R.string.settings_add_3pid_authentication_needed))
})
} else {
//you can only do that on mobile
AlertDialog.Builder(this@PhoneNumberVerificationActivity)
.setTitle(R.string.dialog_title_error)
.setMessage(R.string.settings_add_3pid_flow_not_supported)
.setPositiveButton(R.string._continue) { _, _ ->
hideWaitingView()
}
.show()
}
} else {
onSubmitCodeError(e.localizedMessage)
}
} else {
onSubmitCodeError(e.localizedMessage)
}
}
override fun onUnexpectedError(e: Exception) {
onSubmitCodeError(e.localizedMessage)
}
})
}
private fun onSubmitCodeError(errorMessage: String) {
mIsSubmittingToken = false
hideWaitingView()
Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show()
}
/*
* *********************************************************************************************
* Listeners
* *********************************************************************************************
*/
override fun onEditorAction(v: TextView, actionId: Int, event: KeyEvent): Boolean {
if (actionId == EditorInfo.IME_ACTION_DONE && !isFinishing) {
submitCode()
return true
}
return false
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable) {
if (mPhoneNumberCodeLayout!!.error != null) {
mPhoneNumberCodeLayout!!.error = null
mPhoneNumberCodeLayout!!.isErrorEnabled = false
}
}
companion object {
private val LOG_TAG = PhoneNumberVerificationActivity::class.java.simpleName
private val EXTRA_MATRIX_ID = "EXTRA_MATRIX_ID"
private val EXTRA_PID = "EXTRA_PID"
/*
* *********************************************************************************************
* Static methods
* *********************************************************************************************
*/
fun getIntent(context: Context, sessionId: String, pid: ThreePid): Intent {
val intent = Intent(context, PhoneNumberVerificationActivity::class.java)
intent.putExtra(EXTRA_MATRIX_ID, sessionId)
intent.putExtra(EXTRA_PID, pid)
return intent
}
}
}
|
apache-2.0
|
729e2a72e86dfe1cdf5d6f77ede5e190
| 39.028674 | 146 | 0.532324 | 5.686354 | false | false | false | false |
intrigus/jtransc
|
jtransc-utils/src/com/jtransc/vfs/io.kt
|
2
|
6431
|
/*
* Copyright 2016 Carlos Ballesteros Velasco
*
* 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.jtransc.vfs
import com.jtransc.error.noImpl
import com.jtransc.io.ProcessUtils
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.nio.charset.Charset
import java.util.*
//fun String.toBuffer(encoding: Charset = UTF8): ByteBuffer = encoding.toBuffer(this)
//fun ByteBuffer.toString(encoding: Charset): String = encoding.toString(this)
//fun Charset.toBuffer(_data: String): ByteBuffer = this.encode(_data)
//fun Charset.toString(data: ByteBuffer): String = this.toString(data.getBytes())
fun Charset.toBytes(data: String) = data.toByteArray(this)
fun Charset.toString(data: ByteArray) = data.toString(this)
//fun Charset.toString(data: ByteBuffer):String = data.getBytes().toString(this)
//fun ByteBuffer.length(): Int = this.limit()
//
//fun ByteBuffer.getBytes(): ByteArray {
// val out = ByteArray(this.length())
// for (n in 0 until out.size) out[n] = this.get(n)
// //this.get(out)
// return out
//}
//
//fun ByteArray.toBuffer(): ByteBuffer = ByteBuffer.wrap(this)
//object ByteBufferUtils {
// fun copy(from: ByteBuffer, fromOffset: Int, to: ByteBuffer, toOffset: Int, size: Int) {
// for (n in 0..size - 1) to.put(toOffset + n, from[fromOffset + n])
// }
//
// fun combine(buffers: Iterable<ByteBuffer>): ByteBuffer {
// val totalLength = buffers.sumBy { it.length() }
// val out = ByteBuffer.allocateDirect(totalLength)
// var pos = 0
// for (buffer in buffers) {
// copy(buffer, 0, out, pos, buffer.length())
// pos += buffer.length()
// }
// return out
// }
//}
inline fun <T> chdirTemp(path: String, callback: () -> T): T {
val old = RawIo.cwd()
RawIo.chdir(path)
try {
return callback();
} finally {
RawIo.chdir(old)
}
}
data class ProcessResult(val output: ByteArray, val error: ByteArray, val exitCode: Int) {
val outputString: String get() = output.toString(UTF8).trim()
val errorString: String get() = error.toString(UTF8).trim()
val success: Boolean get() = exitCode == 0
}
/*
data class Encoding(val name: String) {
public val charset: Charset = java.nio.charset.Charset.forName(name)
fun toBytes(data: String) = data.toByteArray(charset)
fun toString(data: ByteArray) = data.toString(charset)
fun toString(data: ByteBuffer) = data.getBytes().toString(charset)
}
*/
val UTF8 = Charsets.UTF_8
class StopExecException() : Exception()
fun File.readFastBytes(): ByteArray = FileInputStream(this@readFastBytes).use { s ->
//println("READ: $this")
val out = ByteArray([email protected]().toInt())
var offset = 0
while (true) {
val read = s.read(out, offset, out.size - offset)
if (read <= 0) break
offset += read
}
out
}
object RawIo {
private var userDir = System.getProperty("user.dir")
//private var userDir = File(".").getCanonicalPath()
fun fileRead(path: String): ByteArray = File(path).readFastBytes()
fun fileWrite(path: String, data: ByteArray): Unit = File(path).writeBytes(data)
fun listdir(path: String): Array<File> {
val file = File(path)
if (!file.exists()) {
throw FileNotFoundException("Can't find $path")
}
return file.listFiles()
}
fun fileExists(path: String): Boolean {
return File(path).exists()
}
fun rmdir(path: String): Unit {
File(path).delete()
}
fun fileRemove(path: String): Unit {
File(path).delete()
}
fun fileStat(path: String): File = File(path)
fun setMtime(path: String, time: Date) {
File(path).setLastModified(time.time)
}
fun cwd(): String = userDir
fun script(): String = userDir
fun chdir(path: String) {
userDir = File(path).canonicalPath
}
fun execOrPassthruSync(path: String, cmd: String, args: List<String>, options: ExecOptions): ProcessResult {
val result = ProcessUtils.run(File(path), cmd, args, options = options)
return ProcessResult(result.out.toByteArray(), result.err.toByteArray(), result.exitValue)
}
fun mkdir(path: String) {
File(path).mkdir()
}
//private fun getNioPath(path: String): java.nio.file.Path = Paths.get(URI("file://$path"))
fun chmod(path: String, mode: FileMode): Boolean {
noImpl("Not implemented chmod")
/*
try {
Files.setPosixFilePermissions(getNioPath(path), mode.toPosix())
return true
} catch (t: Throwable) {
return false
}
*/
}
fun symlink(link: String, target: String) {
noImpl("Not implemented symlink")
//Files.createSymbolicLink(getNioPath(link), getNioPath(target))
//execOrPassthruSync(".", "ln", listOf("-s", target, link))
}
}
//class BufferReader(val buffer: ByteBuffer) {
// //val rb = buffer.order(ByteOrder.LITTLE_ENDIAN)
// val rb = buffer.order(ByteOrder.BIG_ENDIAN)
//
// var offset = 0
// val length: Int get() = buffer.length()
//
// private fun move(count: Int): Int {
// val out = offset
// offset += count
// return out
// }
//
// fun dump() {
// for (n in 0..31) {
// println(Integer.toHexString(buffer.get(n).toInt() and 0xFF))
// }
// }
//
// fun f32(): Double = rb.getFloat(move(4)).toDouble()
// fun i32(): Int = rb.getInt(move(4))
// fun i16(): Int = rb.getShort(move(2)).toInt()
// fun i8(): Int = rb.get(move(1)).toInt()
//}
//fun BufferReader.buffer(len: Int): ByteBuffer {
// val out = ByteBuffer.allocateDirect(len)
// for (n in 0..len - 1) out.put(n, this.i8().toByte())
// return out
//}
//fun BufferReader.strRaw(len: Int): String = buffer(len).toString(UTF8)
//fun BufferReader.u32(): Int = i32() // 31 bit
//fun BufferReader.u16(): Int = i16() and 0xFFFF
//fun BufferReader.u8(): Int = i8() and 0xFF
//
//fun BufferReader.fs8() = u8().toDouble() / 255.0
//fun BufferReader.rgba8(): Int = i32()
//fun BufferReader.quality(): Int = u8()
//fun BufferReader.str(): String = strRaw(u16())
//fun BufferReader.bool(): Boolean = u8() != 0
//fun BufferReader.boolInt(): Int = if (u8() != 0) 1 else 0
//fun ByteBuffer.reader(): BufferReader = BufferReader(this)
|
apache-2.0
|
934b0555943527b0eb7a8b4ad4f4fb43
| 28.369863 | 109 | 0.685274 | 3.172669 | false | false | false | false |
deltadak/plep
|
src/main/kotlin/nl/deltadak/plep/ui/draganddrop/DragDrop.kt
|
1
|
3962
|
package nl.deltadak.plep.ui.draganddrop
import javafx.scene.control.ProgressIndicator
import javafx.scene.control.TreeCell
import javafx.scene.control.TreeItem
import javafx.scene.control.TreeView
import javafx.scene.input.DragEvent
import nl.deltadak.plep.HomeworkTask
import nl.deltadak.plep.database.ContentProvider
import nl.deltadak.plep.database.DatabaseFacade
import nl.deltadak.plep.ui.taskcell.selection.Selector
import nl.deltadak.plep.ui.treeview.TreeViewCleaner
import nl.deltadak.plep.ui.util.converters.getParentTasks
import nl.deltadak.plep.ui.util.converters.toHomeworkTaskList
import java.time.LocalDate
/**
* When the dragged object is dropped, updateOrInsert TreeView and database.
*
* @property taskCell TreeCell on which the task is dropped.
* @property tree TreeView to updateOrInsert.
* @property day of the TreeView.
* @property progressIndicator Needed for refreshing UI.
*/
class DragDrop(
private val taskCell: TreeCell<HomeworkTask>,
val tree: TreeView<HomeworkTask>,
val day: LocalDate,
val progressIndicator: ProgressIndicator) {
init {
taskCell.setOnDragDropped { event ->
setDragDrop(event)
}
}
private fun setDragDrop(event: DragEvent) {
val dragBoard = event.dragboard
var success = false
if (dragBoard.hasContent(DATA_FORMAT)) {
val newHomeworkTask = dragBoard.getContent(DATA_FORMAT) as HomeworkTask
success = dropTask(newHomeworkTask)
}
event.isDropCompleted = success
event.consume()
// Clean up immediately for a smooth reaction.
TreeViewCleaner().cleanSingleTreeView(tree)
// In order to show the subtasks again for the dropped item, we request them from the database.
// This may seem slow but in practice fast enough.
ContentProvider().setForOneDay(tree, day, progressIndicator)
}
private fun dropTask(newHomeworkTask: HomeworkTask): Boolean {
/*
* Insert the dropped task, removing the old one will happen in onDragDone.
* The item could be dropped way below the existing list, in which case we add it to the end.
*/
// If the task was dropped on an empty object, replace it, otherwise add it.
val receivingItem = taskCell.treeItem
// If dropped on a subtask.
if (taskCell.treeItem.parent != tree.root) {
// Get index of parent.
val parentIndex = tree.root.children.indexOf(taskCell.treeItem.parent)
// Drop task below subtasks.
tree.root.children.add(parentIndex + 1, TreeItem<HomeworkTask>(newHomeworkTask))
} else { // If dropped on a parent task.
if (receivingItem.value.text == "") {
// Replace empty item.
receivingItem.value = newHomeworkTask
} else {
val newItem = TreeItem<HomeworkTask>(newHomeworkTask)
// tree.root.children contains only parent tasks.
// taskCell.index is the index in the list including subtasks, so these two don't match.
// So we find the index counting parents only.
val index = tree.root.children.indexOf(taskCell.treeItem)
tree.root.children.add(index, newItem)
}
}
// Update database, only updateOrInsert the parents, because the subtasks only depend on their parents, and are independent of the day and the order in the day.
DatabaseFacade(progressIndicator).pushParentData(
day, tree.toHomeworkTaskList().getParentTasks()
)
// Clear selection on all other items immediately.
// This will result in a smooth reaction, whereas otherwise it takes a bit of noticable time before selection of the just-dragged item (on its previous location) is cleared.
Selector(tree).deselectAll()
return true
}
}
|
mit
|
a49033c88a2dd5ad47be09908a4b26f5
| 37.852941 | 181 | 0.676426 | 4.705463 | false | false | false | false |
hazuki0x0/YuzuBrowser
|
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/settings/preference/WebTextEncodeListPreference.kt
|
1
|
1552
|
/*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.settings.preference
import android.content.Context
import android.util.AttributeSet
import androidx.preference.ListPreference
import jp.hazuki.yuzubrowser.legacy.webencode.WebTextEncodeList
import jp.hazuki.yuzubrowser.ui.BrowserApplication
class WebTextEncodeListPreference @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ListPreference(context, attrs) {
override fun onClick() {
init(context)
super.onClick()
}
private fun init(context: Context) {
val encodes = WebTextEncodeList()
val moshi = (context.applicationContext as BrowserApplication).moshi
encodes.read(context, moshi)
val entries = arrayOfNulls<String>(encodes.size)
var i = 0
while (encodes.size > i) {
entries[i] = encodes[i].encoding
i++
}
setEntries(entries)
entryValues = entries
}
}
|
apache-2.0
|
b0ca05d077ad9187267cc0c23db23fa3
| 31.333333 | 141 | 0.708763 | 4.335196 | false | false | false | false |
kpspemu/kpspemu
|
src/commonMain/kotlin/com/soywiz/kpspemu/hle/audio/VagDecoder.kt
|
1
|
5635
|
package com.soywiz.kpspemu.hle.audio
/*
var VAG_f = [0, 0, 60, 0, 115, -52, 98, -55, 122, -60];
class VagDecoder {
static COMPRESSED_BYTES_IN_BLOCK = 14;
static DECOMPRESSED_SAMPLES_IN_BLOCK = VagDecoder.COMPRESSED_BYTES_IN_BLOCK * 2; // 28
decodedBlockSamples = <number[]>(new Array(VagDecoder.DECOMPRESSED_SAMPLES_IN_BLOCK));
private predict1: number = 0;
private predict2: number = 0;
sampleIndexInBlock: number;
sampleIndexInBlock2: number;
reachedEnd: boolean;
loopStack = <VagState[]>[];
currentState = new VagState();
currentLoopCount = 0;
totalLoopCount = 0;
get hasMore() { return !this.reachedEnd; }
constructor(private blockStream: Stream, private BlockTotalCount: number) {
this.reset();
}
reset() {
this.currentState = new VagState();
this.sampleIndexInBlock = 0;
this.sampleIndexInBlock2 = 0;
this.reachedEnd = false;
this.currentLoopCount = 0;
}
setLoopCount(LoopCount: number) {
this.currentLoopCount = 0;
this.totalLoopCount = LoopCount;
}
seekNextBlock() {
if (this.reachedEnd || this.currentState.blockIndex >= this.BlockTotalCount) { this.reachedEnd = true; return; }
this.blockStream.position = this.currentState.blockIndex * 16;
this.currentState.blockIndex++;
//var block = VagBlock.struct.read(this.blockStream);
var block = this.blockStream.readBytes(16);
switch (block[1]) {
case VagBlockType.LOOP_START:
var copyState = this.currentState.clone();
copyState.blockIndex--;
this.loopStack.push(copyState);
break;
case VagBlockType.LOOP_END:
if (this.currentLoopCount++ < this.totalLoopCount) {
this.currentState = this.loopStack.pop();
} else {
this.loopStack.pop();
}
break;
case VagBlockType.END:
this.reachedEnd = true;
return;
}
this.decodeBlock(block);
}
private sample = new Sample(0, 0);
getNextSample() {
if (this.reachedEnd) return this.sample.set(0, 0);
this.sampleIndexInBlock %= VagDecoder.DECOMPRESSED_SAMPLES_IN_BLOCK;
if (this.sampleIndexInBlock == 0) {
this.seekNextBlock();
}
if (this.reachedEnd) return this.sample.set(0, 0);
var value = this.decodedBlockSamples[this.sampleIndexInBlock++];
return this.sample.set(value, value);
}
decodeBlock(block: Uint8Array) {
var sampleOffset = 0;
var shiftFactor = BitUtils.extract(block[0], 0, 4);
var predictIndex = BitUtils.extract(block[0], 4, 4) % VAG_f.length;
this.predict1 = VAG_f[predictIndex * 2 + 0];
this.predict2 = VAG_f[predictIndex * 2 + 1];
// Mono 4-bit/28 Samples per block.
for (var n = 0; n < VagDecoder.COMPRESSED_BYTES_IN_BLOCK; n++) {
var dataByte = block[n + 2];
//debugger;
var v1 = MathUtils.sextend16((((dataByte >>> 0) & 0xF) << 12)) >> shiftFactor;
var v2 = MathUtils.sextend16((((dataByte >>> 4) & 0xF) << 12)) >> shiftFactor;
this.decodedBlockSamples[sampleOffset + 0] = this.handleSampleKeepHistory(v1);
this.decodedBlockSamples[sampleOffset + 1] = this.handleSampleKeepHistory(v2);
//console.log("" + dataByte, ':', block.modificator, shiftFactor, ':', v1, v2, ':', this.currentState.history1, this.currentState.history2, ':', this.predict1, this.predict2, ':', this.decodedBlockSamples[sampleOffset + 0], this.decodedBlockSamples[sampleOffset + 1]);
sampleOffset += 2;
}
//console.log('--------------> ', this.currentState.history1, this.currentState.history2);
}
private handleSampleKeepHistory(unpackedSample: number) {
var sample = this.handleSample(unpackedSample);
this.currentState.history2 = this.currentState.history1;
this.currentState.history1 = sample;
return sample;
}
private handleSample(unpackedSample: number) {
var sample = 0;
sample += unpackedSample * 1;
sample += ((this.currentState.history1 * this.predict1) / 64) >> 0; // integer divide by 64
sample += ((this.currentState.history2 * this.predict2) / 64) >> 0;
//console.log(unpackedSample, '->', sample, ' : ');
return MathUtils.clamp(sample, -32768, 32767);
}
}
enum VagBlockType { LOOP_END = 3, LOOP_START = 6, END = 7 }
/*
class VagBlock {
modificator: number;
type: VagBlockType;
data: number[];
static struct = StructClass.create<VagBlock>(VagBlock, [
{ modificator: UInt8 },
{ type: UInt8 },
{ data: StructArray<number>(UInt8, 14) },
]);
}
*/
class VagHeader {
magic: number;
vagVersion: number;
dataSize: number;
sampleRate: number;
//name: string;
static struct = StructClass.create<VagHeader>(VagHeader, [
{ magic: UInt32 },
{ vagVersion: UInt32_b },
{ dataSize: UInt32_b },
{ sampleRate: UInt32_b },
//{ name: Stringz(16) },
]);
}
export class VagSoundSource {
private header: VagHeader = null;
private samplesCount: number = 0;
private decoder: VagDecoder = null
constructor(stream: Stream, loopCount: number) {
if (stream.length < 0x10) {
this.header = null;
this.samplesCount = 0;
this.decoder = new VagDecoder(stream, 0);
} else {
var headerStream = stream.sliceWithLength(0, VagHeader.struct.length);
var dataStream = stream.sliceWithLength(VagHeader.struct.length);
//debugger;
this.header = VagHeader.struct.read(headerStream);
this.samplesCount = Math.floor(dataStream.length * 56 / 16);
this.decoder = new VagDecoder(dataStream, Math.floor(dataStream.length / 16));
}
}
reset() {
this.decoder.reset();
}
get hasMore() {
return this.decoder.hasMore;
}
getNextSample(): Sample {
return this.decoder.getNextSample();
}
}
class VagState {
constructor(public blockIndex = 0, public history1 = 0, public history2 = 0) {
}
clone() {
return new VagState(this.blockIndex, this.history1, this.history2);
}
}
*/
|
mit
|
56c172f7eddeea3ac29e5bc6cc877e0b
| 26.359223 | 271 | 0.688021 | 3.037736 | false | false | false | false |
EMResearch/EvoMaster
|
core/src/test/kotlin/org/evomaster/core/search/gene/sql/geometric/SqlMultiPointGeneTest.kt
|
1
|
3464
|
package org.evomaster.core.search.gene.sql.geometric
import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType
import org.evomaster.core.search.gene.numeric.FloatGene
import org.evomaster.core.search.service.Randomness
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
class SqlMultiPointGeneTest {
val rand = Randomness()
@BeforeEach
fun resetSeed() {
rand.updateSeed(42)
}
@Test
fun testGetValueForEmptyH2() {
val gene = SqlMultiPointGene("multipoint", databaseType = DatabaseType.H2)
gene.randomize(rand, true)
gene.points.killAllChildren()
assertEquals("\"MULTIPOINT EMPTY\"", gene.getValueAsPrintableString())
}
@Test
fun testGetValueForNontEmptyH2() {
val gene = SqlMultiPointGene("multipoint", databaseType = DatabaseType.H2)
gene.randomize(rand, true)
gene.points.killAllChildren()
gene.points.addElement(
SqlPointGene("p0",databaseType = DatabaseType.H2,
x = FloatGene("x", value = 0f),
y = FloatGene("y", value = 0f)
)
)
assertEquals("\"MULTIPOINT(0.0 0.0)\"", gene.getValueAsPrintableString())
}
@Test
fun testGetValueForTwoPointsH2() {
val gene = SqlMultiPointGene("multipoint", databaseType = DatabaseType.H2)
gene.randomize(rand, true)
gene.points.killAllChildren()
gene.points.addElement(
SqlPointGene("p0", databaseType = DatabaseType.H2,
x = FloatGene("x", value = 0f),
y = FloatGene("y", value = 0f)
)
)
gene.points.addElement(
SqlPointGene("p1", databaseType = DatabaseType.H2,
x = FloatGene("x", value = 1.0f),
y = FloatGene("y", value = 1.0f)
)
)
assertEquals("\"MULTIPOINT(0.0 0.0, 1.0 1.0)\"", gene.getValueAsPrintableString())
}
@Test
fun testGetValueForNontEmptyMySQL() {
val gene = SqlMultiPointGene("multipoint", databaseType = DatabaseType.MYSQL)
gene.randomize(rand, true)
gene.points.killAllChildren()
gene.points.addElement(
SqlPointGene("p0", databaseType = DatabaseType.MYSQL,
x = FloatGene("x", value = 0f),
y = FloatGene("y", value = 0f)
)
)
assertEquals("MULTIPOINT(POINT(0.0, 0.0))", gene.getValueAsPrintableString())
}
@Test
fun testGetValueForTwoPointsMySQL() {
val gene = SqlMultiPointGene("multipoint", databaseType = DatabaseType.MYSQL)
gene.randomize(rand, true)
gene.points.killAllChildren()
gene.points.addElement(
SqlPointGene("p0", databaseType = DatabaseType.MYSQL,
x = FloatGene("x", value = 0f),
y = FloatGene("y", value = 0f)
)
)
gene.points.addElement(
SqlPointGene("p1", databaseType = DatabaseType.MYSQL,
x = FloatGene("x", value = 1.0f),
y = FloatGene("y", value = 1.0f)
)
)
assertEquals("MULTIPOINT(POINT(0.0, 0.0), POINT(1.0, 1.0))", gene.getValueAsPrintableString())
}
}
|
lgpl-3.0
|
f9eae14ca032329bfcbb10498620a5b4
| 33.306931 | 102 | 0.573903 | 4.407125 | false | true | false | false |
j-selby/kotgb
|
core/src/main/kotlin/net/jselby/kotgb/cpu/interpreter/instructions/alu/Comparisons.kt
|
1
|
1328
|
package net.jselby.kotgb.cpu.interpreter.instructions.alu
import net.jselby.kotgb.Gameboy
import net.jselby.kotgb.cpu.CPU
import net.jselby.kotgb.cpu.Registers
import net.jselby.kotgb.cpu.interpreter.instructions.getN
import kotlin.reflect.KMutableProperty1
/**
* Comparisons compare values with each other.
*/
fun compareRegisters(registers: Registers, number : Short) {
val value = (registers.a - number) and 0xFF
registers.flagZ = number == registers.a
registers.flagN = true
registers.flagH = (registers.a.toInt() and 0x0f) < (number.toInt() and 0x0f)
registers.flagC = registers.a < value
}
/**
* **0xB8 ~ 0xBE** - *CP X* - Compares a with field X
*/
val x_CP : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Short>) -> (Int) = {
_, registers, _, x ->
compareRegisters(registers, x.get(registers))
/*Cycles: */ 4
}
/**
* **0xBE** - *CP (hl)* - Compare a with (hl)
*/
val xBE : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
compareRegisters(registers, (gb.ram.readByte(registers.hl.toLong() and 0xFFFF).toInt() and 0xFF).toShort())
/*Cycles: */ 8
}
/**
* **0xFE** - *CP #* - Compare a with #
*/
val xFE : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
compareRegisters(registers, getN(registers, gb))
/*Cycles: */ 8
}
|
mit
|
0fb2c0552bbde5f7595cf99f15f9ddc2
| 25.58 | 111 | 0.652861 | 3.184652 | false | false | false | false |
konrad-jamrozik/droidmate
|
dev/droidmate/projects/reporter/src/main/kotlin/org/droidmate/report/extensions_misc.kt
|
1
|
2742
|
// DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2016 Konrad Jamrozik
//
// 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/>.
//
// email: [email protected]
// web: www.droidmate.org
package org.droidmate.report
import org.droidmate.device.datatypes.Widget
import org.droidmate.exploration.strategy.WidgetStrategy
import java.math.BigDecimal
import java.math.RoundingMode
import java.time.Duration
/**
* Zeroes digits before (i.e. left of) comma. E.g. if [digitsToZero] is 2, then 6789 will become 6700.
*/
// Reference: http://stackoverflow.com/questions/2808535/round-a-double-to-2-decimal-places
fun Int.zeroLeastSignificantDigits(digitsToZero: Int): Long {
return BigDecimal(this.toString()).setScale(-digitsToZero, RoundingMode.DOWN).toBigInteger().toLong()
}
/**
* Given a string builder over a string containing variables in form of "$var_name" (without ""), it will replace
* all such variables with their value. For examples, see [org.droidmate.report.extensions_miscKtTest.replaceVariableTest].
*/
fun StringBuilder.replaceVariable(varName: String, value: String) : StringBuilder
{
val fullVarName = '$'+varName
while (this.indexOf(fullVarName) != -1) {
val startIndex = this.indexOf(fullVarName)
val endIndex = startIndex + fullVarName.length
this.replace(startIndex, endIndex, value)
}
return this
}
val Duration.minutesAndSeconds: String get() {
val m = this.toMinutes()
val s = this.seconds - m * 60
return "$m".padStart(4, ' ') + "m " + "$s".padStart(2, ' ') + "s"
}
val Widget.uniqueString: String get() {
return WidgetStrategy.WidgetInfo(this).uniqueString
}
fun <T, TItem> Iterable<T>.setByUniqueString(
extractItems: (T) -> Iterable<TItem>,
uniqueString: (TItem) -> String
): Set<TItem> {
val grouped: Map<String, List<TItem>> = this.flatMap { extractItems(it) }.groupBy { uniqueString(it) }
val uniquesByString: Map<String, TItem> = grouped.mapValues { it.value.first() }
val uniques: Collection<TItem> = uniquesByString.values
val uniquesSet = uniques.toSet()
check(uniques.size == uniquesSet.size)
return uniquesSet
}
|
gpl-3.0
|
9460129261c2539ea44a3a55625c0977
| 37.097222 | 123 | 0.737053 | 3.735695 | false | false | false | false |
ujpv/intellij-rust
|
src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustImplItemImplMixin.kt
|
1
|
1380
|
package org.rust.lang.core.psi.impl.mixin
import com.intellij.ide.projectView.PresentationData
import com.intellij.lang.ASTNode
import com.intellij.navigation.ItemPresentation
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RustIcons
import org.rust.lang.core.psi.RustImplItemElement
import org.rust.lang.core.psi.RustNamedElement
import org.rust.lang.core.psi.RustPathTypeElement
import org.rust.lang.core.psi.impl.RustStubbedElementImpl
import org.rust.lang.core.stubs.RustImplItemElementStub
abstract class RustImplItemImplMixin : RustStubbedElementImpl<RustImplItemElementStub>, RustImplItemElement {
constructor(node: ASTNode) : super(node)
constructor(stub: RustImplItemElementStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getIcon(flags: Int) = RustIcons.IMPL
override val isPublic: Boolean get() = false // pub does not affect imls at all
override fun getPresentation(): ItemPresentation {
val t = type
if (t is RustPathTypeElement) {
val pres = (t.path?.reference?.resolve() as? RustNamedElement)?.presentation
if (pres != null) {
return PresentationData(pres.presentableText, pres.locationString, RustIcons.IMPL, null)
}
}
return PresentationData(type?.text ?: "Impl", null, RustIcons.IMPL, null)
}
}
|
mit
|
3d8f858396fb77658f71a99668d31c53
| 40.818182 | 109 | 0.744203 | 4.233129 | false | false | false | false |
proxer/ProxerAndroid
|
src/main/kotlin/me/proxer/app/anime/NoWifiDialog.kt
|
1
|
1573
|
package me.proxer.app.anime
import android.app.Dialog
import android.os.Bundle
import android.widget.CheckBox
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.fragment.app.setFragmentResult
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import kotterknife.bindView
import me.proxer.app.R
import me.proxer.app.base.BaseDialog
import me.proxer.app.util.extension.getSafeString
/**
* @author Ruben Gees
*/
class NoWifiDialog : BaseDialog() {
companion object {
const val STREAM_ID_RESULT = "stream_id"
private const val STREAM_ID_ARGUMENT = "stream_id"
fun show(activity: AppCompatActivity, streamId: String) = NoWifiDialog()
.apply { arguments = bundleOf(STREAM_ID_ARGUMENT to streamId) }
.show(activity.supportFragmentManager, "no_wifi_dialog")
}
private val remember by bindView<CheckBox>(R.id.remember)
private val streamId: String
get() = requireArguments().getSafeString(STREAM_ID_ARGUMENT)
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = MaterialDialog(requireContext())
.customView(R.layout.dialog_no_wifi, scrollable = true)
.positiveButton(R.string.dialog_no_wifi_positive) {
if (remember.isChecked) {
preferenceHelper.shouldCheckCellular = false
}
setFragmentResult(STREAM_ID_RESULT, bundleOf(STREAM_ID_RESULT to streamId))
}
.negativeButton(R.string.cancel)
}
|
gpl-3.0
|
c0b40976437541735234a955fa5c4a23
| 33.195652 | 103 | 0.723458 | 4.369444 | false | false | false | false |
REPLicated/classpath-collision-detector
|
src/test/kotlin/io/fuchs/gradle/collisiondetector/testkit/CollisionDetectorPluginTest.kt
|
1
|
2602
|
package io.fuchs.gradle.collisiondetector.testkit
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class CollisionDetectorPluginTest {
@get:Rule
val temporaryFolder = TemporaryFolder()
@Test
fun `plugin applies without error`() {
copyBuildFileToTempDir("apply_plugin_only.gradle")
GradleRunner.create()
.withProjectDir(temporaryFolder.root)
.withTestKitDir(temporaryFolder.newFolder())
.withPluginClasspath()
.build()
}
@Test
fun `task detects no collision`() {
copyBuildFileToTempDir("apply_plugin_only.gradle")
val buildResult = GradleRunner.create()
.withProjectDir(temporaryFolder.root)
.withTestKitDir(temporaryFolder.newFolder())
.withPluginClasspath()
.withArguments(":detectCollisions")
.build()
val detectCollisionsTask = buildResult.task(":detectCollisions")
assertEquals(TaskOutcome.SUCCESS, detectCollisionsTask?.outcome)
}
@Test
fun `detects collisions and fails`() {
copyBuildFileToTempDir("found_collisions.gradle")
val buildResult = GradleRunner.create()
.withProjectDir(temporaryFolder.root)
.withTestKitDir(temporaryFolder.newFolder())
.withPluginClasspath()
.withArguments(":detectCollisions")
.buildAndFail()
val detectCollisionsTask = buildResult.task(":detectCollisions")
assertEquals(TaskOutcome.FAILED, detectCollisionsTask?.outcome)
}
@Test
fun `all collisions are ignored`() {
copyBuildFileToTempDir("ignored_collisions.gradle")
val buildResult = GradleRunner.create()
.withProjectDir(temporaryFolder.root)
.withTestKitDir(temporaryFolder.newFolder())
.withPluginClasspath()
.withArguments(":detectCollisions")
.build()
val detectCollisionsTask = buildResult.task(":detectCollisions")
assertEquals(TaskOutcome.SUCCESS, detectCollisionsTask?.outcome)
}
fun copyBuildFileToTempDir(buildFile: String) {
val file = temporaryFolder.newFile("build.gradle")
ClassLoader.getSystemResourceAsStream(buildFile).use { inputStream ->
file.outputStream().use { inputStream.copyTo(it) }
}
}
}
|
apache-2.0
|
bcf7c95ed90b07889be841d43691f211
| 31.949367 | 77 | 0.649885 | 5.267206 | false | true | false | false |
LorittaBot/Loritta
|
web/showtime/showtime-frontend/src/jsMain/kotlin/net/perfectdreams/loritta/cinnamon/showtime/frontend/views/ViewManager.kt
|
1
|
3082
|
package net.perfectdreams.loritta.cinnamon.showtime.frontend.views
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import net.perfectdreams.loritta.cinnamon.showtime.frontend.ShowtimeFrontend
import net.perfectdreams.loritta.cinnamon.showtime.frontend.routes.ApplicationCommandsRoute
import net.perfectdreams.loritta.cinnamon.showtime.frontend.routes.BaseRoute
import net.perfectdreams.loritta.cinnamon.showtime.frontend.routes.HomeRoute
import net.perfectdreams.loritta.cinnamon.showtime.frontend.routes.LegacyCommandsRoute
import kotlin.math.max
class ViewManager(val showtime: ShowtimeFrontend) {
var currentView: DokyoView? = null
var preparingView: DokyoView? = null
// We need to use a lock to avoid calling "onLoad()" before "onPreLoad()" is finished!
var preparingMutex = Mutex()
val routes = mutableListOf<BaseRoute>(
HomeRoute(showtime),
LegacyCommandsRoute(showtime),
ApplicationCommandsRoute(showtime)
)
suspend fun preparePreLoad(path: String) {
println("Path: $path")
val matchedRoute = routes.firstOrNull { matches(it.path, path) }
println("Found route $matchedRoute for $path")
if (matchedRoute == null) {
this.preparingView = null
return
}
val preparingView = matchedRoute.onRequest()
if (preparingView != null) {
this.preparingView = preparingView
preparingMutex.withLock {
preparingView.onPreLoad()
}
}
}
// Implementação básica do sistema de paths do ktor
fun matches(path: String, input: String): Boolean {
val sourceSplit = path.removeSuffix("/").split("/")
val inputSplit = input.removeSuffix("/").split("/")
var inputSplitLength = 0
for (index in 0 until max(sourceSplit.size, inputSplit.size)) {
val sInput = sourceSplit.getOrNull(index)
val iInput = inputSplit.getOrNull(index)
// Check if it is a group match
if (sInput != null && sInput.startsWith("{") && sInput.endsWith("}")) {
if (iInput == null && sInput.endsWith("?}")) {
inputSplitLength++
continue
}
inputSplitLength++
continue
}
if (iInput == null)
return false
if (iInput != sInput) // Input does not match
return false
inputSplitLength++
}
return true
}
/**
* Switches the current [preparingView] to the [currentView]
*/
suspend fun switchPreparingToActiveView() {
// Now we will wipe all page specific coroutines
showtime.pageSpecificTasks.forEach { it.cancel() }
showtime.pageSpecificTasks.clear()
// Now that all of the elements are loaded, we can call the "onLoad()"
showtime.viewManager.preparingView?.onLoad()
showtime.viewManager.currentView = showtime.viewManager.preparingView
}
}
|
agpl-3.0
|
dc6cbea00d15811077389ef82d96b423
| 34.402299 | 91 | 0.637869 | 4.722393 | false | false | false | false |
vgaidarji/dependencies-overview
|
dependencies-overview/src/main/kotlin/com/vgaidarji/dependencies/overview/writer/MarkdownWriter.kt
|
1
|
1222
|
package com.vgaidarji.dependencies.overview.writer
import net.steppschuh.markdowngenerator.table.Table
import org.gradle.api.artifacts.ResolvedModuleVersion
open class MarkdownWriter : DependenciesWriter<List<ResolvedModuleVersion>> {
companion object {
const val OUTPUT_FILE_NAME = "DEPENDENCIES-OVERVIEW.md"
const val GROUP = "Group"
const val NAME = "Name"
const val VERSION = "Version"
}
override fun write(artifacts: List<ResolvedModuleVersion>) {
// TODO parametrize task and print to console conditionally
writeToFile(OUTPUT_FILE_NAME, artifactsToMarkdownTable(artifacts).toString())
}
override fun write(folder: String?, artifacts: List<ResolvedModuleVersion>) {
writeToFile(folder, OUTPUT_FILE_NAME, artifactsToMarkdownTable(artifacts).toString())
}
private fun artifactsToMarkdownTable(artifacts: List<ResolvedModuleVersion>): Table {
val builder = Table.Builder()
.withAlignments(Table.ALIGN_LEFT, Table.ALIGN_LEFT)
.addRow(GROUP, NAME, VERSION)
artifacts.forEach {
builder.addRow(it.id.group, it.id.name, it.id.version)
}
return builder.build()
}
}
|
apache-2.0
|
36a8042b0e0447aab081563891aaa191
| 37.1875 | 93 | 0.698036 | 4.411552 | false | false | false | false |
nebula-plugins/java-source-refactor
|
rewrite-java/src/test/kotlin/org/openrewrite/java/refactor/ChangeFieldNameTest.kt
|
1
|
3098
|
/**
* Copyright 2016 Netflix, 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.openrewrite.java.refactor
import org.junit.jupiter.api.Test
import org.openrewrite.java.JavaParser
import org.openrewrite.java.asClass
import org.openrewrite.java.assertRefactored
import org.openrewrite.java.tree.JavaType
open class ChangeFieldNameTest : JavaParser() {
@Test
fun changeFieldName() {
val a = parse("""
import java.util.List;
public class A {
List collection = null;
}
""".trimIndent())
val fixed = a.refactor()
.visit(ChangeFieldName(a.classes[0].type.asClass(), "collection", "list"))
.fix().fixed
assertRefactored(fixed, """
import java.util.List;
public class A {
List list = null;
}
""")
}
@Test
fun changeFieldNameReferences() {
val b = parse("""
public class B {
int n;
{
n = 1;
n /= 2;
if(n + 1 == 2) {}
n++;
}
public int foo(int n) {
return n + this.n;
}
}
""".trimIndent())
val fixed = b.refactor()
.visit(ChangeFieldName(JavaType.Class.build("B"), "n", "n1"))
.fix().fixed
assertRefactored(fixed, """
public class B {
int n1;
{
n1 = 1;
n1 /= 2;
if(n1 + 1 == 2) {}
n1++;
}
public int foo(int n) {
return n + this.n1;
}
}
""")
}
@Test
fun changeFieldNameReferencesInOtherClass() {
val b = """
public class B {
int n;
}
""".trimIndent()
val a = parse("""
public class A {
B b = new B();
{
b.n = 1;
}
}
""".trimIndent(), b)
val fixed = a.refactor()
.visit(ChangeFieldName(JavaType.Class.build("B"), "n", "n1"))
.fix().fixed
assertRefactored(fixed, """
public class A {
B b = new B();
{
b.n1 = 1;
}
}
""")
}
}
|
apache-2.0
|
a738bafd54cc7ec117fa1e77e5c9938c
| 25.254237 | 90 | 0.448031 | 4.744257 | false | false | false | false |
robinverduijn/gradle
|
subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/serialization/codecs/CollectionCodecs.kt
|
1
|
2832
|
/*
* Copyright 2019 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.instantexecution.serialization.codecs
import org.gradle.instantexecution.serialization.Codec
import org.gradle.instantexecution.serialization.codec
import org.gradle.instantexecution.serialization.readArray
import org.gradle.instantexecution.serialization.readCollectionInto
import org.gradle.instantexecution.serialization.readMapInto
import org.gradle.instantexecution.serialization.writeArray
import org.gradle.instantexecution.serialization.writeCollection
import org.gradle.instantexecution.serialization.writeMap
import java.util.LinkedList
import java.util.TreeMap
import java.util.TreeSet
import java.util.concurrent.ConcurrentHashMap
internal
val arrayListCodec: Codec<ArrayList<Any?>> = collectionCodec { ArrayList<Any?>(it) }
internal
val linkedListCodec: Codec<LinkedList<Any?>> = collectionCodec { LinkedList<Any?>() }
internal
val hashSetCodec: Codec<HashSet<Any?>> = collectionCodec { HashSet<Any?>(it) }
internal
val linkedHashSetCodec: Codec<LinkedHashSet<Any?>> = collectionCodec { LinkedHashSet<Any?>(it) }
internal
val treeSetCodec: Codec<TreeSet<Any?>> = codec(
{
write(it.comparator())
writeCollection(it)
},
{
@Suppress("unchecked_cast")
val comparator = read() as Comparator<Any?>?
readCollectionInto { TreeSet(comparator) }
})
internal
fun <T : MutableCollection<Any?>> collectionCodec(factory: (Int) -> T) = codec(
{ writeCollection(it) },
{ readCollectionInto(factory) }
)
internal
val hashMapCodec: Codec<HashMap<Any?, Any?>> = mapCodec { HashMap<Any?, Any?>(it) }
internal
val linkedHashMapCodec: Codec<LinkedHashMap<Any?, Any?>> = mapCodec { LinkedHashMap<Any?, Any?>(it) }
internal
val concurrentHashMapCodec: Codec<ConcurrentHashMap<Any?, Any?>> = mapCodec { ConcurrentHashMap<Any?, Any?>(it) }
internal
val treeMapCodec: Codec<TreeMap<Any?, Any?>> = mapCodec { TreeMap<Any?, Any?>() }
internal
fun <T : MutableMap<Any?, Any?>> mapCodec(factory: (Int) -> T): Codec<T> = codec(
{ writeMap(it) },
{ readMapInto(factory) }
)
internal
val arrayCodec: Codec<Array<*>> = codec({
writeArray(it) { element ->
write(element)
}
}, {
readArray { read() }
})
|
apache-2.0
|
72ebb860e710dbf992fb90da3b7a0815
| 27.606061 | 113 | 0.732698 | 4.051502 | false | false | false | false |
Deletescape-Media/Lawnchair
|
lawnchair/src/app/lawnchair/overview/TaskOverlayFactoryImpl.kt
|
1
|
2352
|
package app.lawnchair.overview
import android.content.Context
import android.graphics.Matrix
import androidx.annotation.Keep
import com.android.quickstep.TaskOverlayFactory
import com.android.quickstep.views.OverviewActionsView
import com.android.quickstep.views.TaskThumbnailView
import com.android.systemui.shared.recents.model.Task
import com.android.systemui.shared.recents.model.ThumbnailData
@Keep
class TaskOverlayFactoryImpl(@Suppress("UNUSED_PARAMETER") context: Context) : TaskOverlayFactory() {
override fun createOverlay(thumbnailView: TaskThumbnailView) = TaskOverlay(thumbnailView)
class TaskOverlay(
taskThumbnailView: TaskThumbnailView
) : TaskOverlayFactory.TaskOverlay<LawnchairOverviewActionsView>(taskThumbnailView) {
override fun initOverlay(
task: Task?,
thumbnail: ThumbnailData?,
matrix: Matrix,
rotated: Boolean
) {
actionsView.updateDisabledFlags(
OverviewActionsView.DISABLED_NO_THUMBNAIL,
thumbnail == null
)
if (thumbnail != null) {
actionsView.updateDisabledFlags(OverviewActionsView.DISABLED_ROTATED, rotated)
val isAllowedByPolicy = mThumbnailView.isRealSnapshot
actionsView.setCallbacks(OverlayUICallbacksImpl(isAllowedByPolicy, task))
}
}
private inner class OverlayUICallbacksImpl(
isAllowedByPolicy: Boolean,
task: Task?
) : TaskOverlayFactory.TaskOverlay<LawnchairOverviewActionsView>.OverlayUICallbacksImpl(
isAllowedByPolicy,
task
), OverlayUICallbacks {
override fun onShare() {
if (mIsAllowedByPolicy) {
endLiveTileMode { mImageApi.startShareActivity(null) }
} else {
showBlockedByPolicyMessage()
}
}
override fun onLens() {
if (mIsAllowedByPolicy) {
endLiveTileMode { mImageApi.startLensActivity() }
} else {
showBlockedByPolicyMessage()
}
}
}
}
interface OverlayUICallbacks : TaskOverlayFactory.OverlayUICallbacks {
fun onShare()
fun onLens()
}
}
|
gpl-3.0
|
a011171134c21610b993a82f341d72a9
| 33.086957 | 101 | 0.633078 | 4.962025 | false | false | false | false |
FredJul/TaskGame
|
TaskGame-Hero/src/main/java/net/fred/taskgame/hero/fragments/StoryFragment.kt
|
1
|
8069
|
/*
* Copyright (c) 2012-2017 Frederic Julian
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package net.fred.taskgame.hero.fragments
import android.graphics.Color
import android.os.Bundle
import android.os.Parcelable
import android.support.annotation.RawRes
import android.support.v4.content.ContextCompat
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import kotlinx.android.synthetic.main.fragment_story.*
import net.fred.taskgame.hero.R
import net.fred.taskgame.hero.activities.MainActivity
import net.fred.taskgame.hero.models.Card
import net.fred.taskgame.hero.models.Level
import net.fred.taskgame.hero.utils.UiUtils
import org.jetbrains.anko.sdk21.coroutines.onClick
import org.parceler.Parcels
import java.util.*
class StoryFragment : BaseFragment() {
private var level: Level? = null
private var isInTextAnimation: Boolean = false
private var isEndStory: Boolean = false
private var sentences: ArrayList<String>? = null
override val mainMusicResId: Int
@RawRes
get() {
level?.let { lvl ->
if (!isEndStory && lvl.startStoryMusicResId != Level.INVALID_ID) {
return lvl.startStoryMusicResId
} else if (isEndStory && lvl.endStoryMusicResId != Level.INVALID_ID) {
return lvl.endStoryMusicResId
}
}
return R.raw.story_normal
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val layout = inflater.inflate(R.layout.fragment_story, container, false)
level = Parcels.unwrap<Level>(arguments.getParcelable<Parcelable>(ARG_LEVEL))
isEndStory = arguments.getBoolean(ARG_IS_END_STORY)
if (savedInstanceState != null) {
sentences = savedInstanceState.getStringArrayList(STATE_SENTENCES)
} else {
level?.let { lvl ->
if (!isEndStory) {
sentences = ArrayList(Arrays.asList(*lvl.getStartStory(context).split("\n".toRegex()).dropLastWhile(String::isEmpty).toTypedArray()))
} else {
sentences = ArrayList(Arrays.asList(*lvl.getEndStory(context).split("\n".toRegex()).dropLastWhile(String::isEmpty).toTypedArray()))
}
}
}
return layout
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
updateUI()
skip_button.onClick { endStory() }
root_view.onClick {
if (!isInTextAnimation) {
if ((sentences?.size ?: 0) > 1) {
sentences?.removeAt(0)
updateUI()
} else {
endStory()
}
}
}
}
private fun updateUI() {
sentences?.let {
val sentence = it[0]
val separatorIndex = sentence.indexOf(':')
val charInfo = sentence.substring(0, separatorIndex)
if ("story" == charInfo.trim { it <= ' ' }) {
right_char.animate().alpha(0f)
right_char_text.animate().alpha(0f)
right_char_separator.animate().alpha(0f)
left_char.animate().alpha(0f)
left_char_text.animate().alpha(0f)
displayTextCharPerChar(story_text, SpannableString(sentence.substring(separatorIndex + 1)), 50)
story_text.alpha = 0f
story_text.animate().alpha(1f)
} else {
story_text.animate().alpha(0f)
val charId = charInfo.substring(0, charInfo.length - 2).trim { it <= ' ' }
Level.STORY_CHARS_INFO_MAP[charId]?.let { char ->
val charName = getString(char.first)
val charResId = char.second
val isLeft = "L" == charInfo.substring(charInfo.length - 1)
val text = charName + ": " + sentence.substring(separatorIndex + 1)
val spannedText = SpannableString(text)
spannedText.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.color_accent)), 0, charName.length + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
if (isLeft) {
right_char.animate().alpha(0f)
right_char_text.animate().alpha(0f)
right_char_separator.animate().alpha(0f)
left_char.setImageResource(charResId)
left_char.animate().alpha(1f)
displayTextCharPerChar(left_char_text, spannedText, 20)
left_char_text.alpha = 0f
left_char_text.animate().alpha(1f)
} else {
left_char.animate().alpha(0f)
left_char_text.animate().alpha(0f)
right_char.setImageResource(charResId)
right_char.animate().alpha(1f)
right_char_separator.animate().alpha(1f)
displayTextCharPerChar(right_char_text, spannedText, 20)
right_char_text.alpha = 0f
right_char_text.animate().alpha(1f)
}
}
}
}
}
private fun displayTextCharPerChar(textView: TextView, text: SpannableString, delay: Int) {
isInTextAnimation = true
textView.tag = 1
val displayOneChar = object : Runnable {
override fun run() {
val at = textView.tag as Int
val textViewString = SpannableString(text)
textViewString.setSpan(ForegroundColorSpan(Color.TRANSPARENT), at, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
textView.text = textViewString
if (at < text.length) {
textView.tag = at + 1
textView.postDelayed(this, delay.toLong())
} else {
isInTextAnimation = false
}
}
}
textView.postDelayed(displayOneChar, (delay * 2).toLong())
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putStringArrayList(STATE_SENTENCES, sentences)
super.onSaveInstanceState(outState)
}
private fun endStory() {
fragmentManager.popBackStack()
if (!isEndStory) {
val transaction = fragmentManager.beginTransaction()
UiUtils.animateTransition(transaction, UiUtils.TransitionType.TRANSITION_FADE_IN)
mainActivity?.playSound(MainActivity.SOUND_ENTER_BATTLE)
level?.let {
transaction.replace(R.id.fragment_container, BattleFragment.newInstance(it, Card.deckCardList), BattleFragment::class.java.name).addToBackStack(null).commitAllowingStateLoss()
}
}
}
companion object {
val ARG_LEVEL = "ARG_LEVEL"
val ARG_IS_END_STORY = "ARG_IS_END_STORY"
private val STATE_SENTENCES = "STATE_SENTENCES"
fun newInstance(level: Level, isEndStory: Boolean): StoryFragment {
val fragment = StoryFragment()
val args = Bundle()
args.putParcelable(ARG_LEVEL, Parcels.wrap(level))
args.putBoolean(ARG_IS_END_STORY, isEndStory)
fragment.arguments = args
return fragment
}
}
}
|
gpl-3.0
|
e0f48c3c93b0c06551a8adfac3740ee4
| 36.530233 | 191 | 0.61445 | 4.495265 | false | false | false | false |
reime005/splintersweets
|
core/src/de/reimerm/splintersweets/utils/GameManager.kt
|
1
|
3480
|
/*
* Copyright (c) 2017. Marius Reimer
*
* 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 de.reimerm.splintersweets.utils
import com.badlogic.gdx.physics.box2d.Body
import com.badlogic.gdx.physics.box2d.World
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.utils.Timer
import de.reimerm.splintersweets.enums.Color
import de.reimerm.splintersweets.enums.GameState
import de.reimerm.splintersweets.menu.GameMenu
import java.util.*
import java.util.concurrent.ConcurrentHashMap
/**
* Singleton to manage game relevant objects.
*
* Created by Marius Reimer on 21-Jun-16.
*/
object GameManager {
lateinit var bodiesToRemove: Set<Body>
lateinit var actorsToAdd: Set<Actor>
var listener: GameEventListener? = null
@Synchronized get
lateinit var world: World
@Synchronized get
lateinit var gameState: GameState
@Synchronized get
@Synchronized set
var menu: GameMenu? = null
var time = GameSettings.GAME_TIME
@Synchronized get
@Synchronized set
var score: Long = 0
@Synchronized get
@Synchronized set
var lastColorRemoved: Color = Color.RED
var comboPoints = GameSettings.CIRCLE_REMOVE_CHAIN
var levelsPlayed = 0
var appFirstStart = true
var onlineScore: Long = 0
fun reset() {
gameState = GameState.RUNNING
bodiesToRemove = Collections.newSetFromMap(ConcurrentHashMap<Body, Boolean>())
actorsToAdd = Collections.newSetFromMap(ConcurrentHashMap<Actor, Boolean>())
menu = null
time = GameSettings.GAME_TIME
score = 0
}
@Synchronized
fun addBodyToRemove(body: Body) {
bodiesToRemove = bodiesToRemove.plus(body)
}
@Synchronized
fun addActorToAdd(actor: Actor) {
actorsToAdd = actorsToAdd.plus(actor)
}
@Synchronized
fun onPause() {
if (gameState == GameState.RUNNING) {
gameState = GameState.PAUSED
AudioUtils.stopMusic()
}
}
@Synchronized
fun destroyBody(body: Body) {
// if, for some reason, the body is already destroyed
if (body.userData == null || body.fixtureList.size == 0) {
bodiesToRemove = bodiesToRemove.minus(body)
return
}
// for some reason there there was a non reproducible null pointer exception thrown
try {
world.destroyBody(body)
} catch (e: NullPointerException) {
e.printStackTrace()
}
bodiesToRemove = bodiesToRemove.minus(body)
}
fun onGameOver() {
levelsPlayed++
if (score > onlineScore) {
onlineScore = score
}
if (levelsPlayed >= 5) {
levelsPlayed = 0
Timer.schedule(object : Timer.Task() {
override fun run() {
listener?.showInterstitialAd()
}
}, 0.5f)
}
}
}
|
apache-2.0
|
7479c7e2dc81441fcff6de1b2c4450ca
| 25.776923 | 91 | 0.646839 | 4.366374 | false | false | false | false |
mrkirby153/KirBot
|
src/main/kotlin/me/mrkirby153/KirBot/command/CommandExecutor.kt
|
1
|
15901
|
package me.mrkirby153.KirBot.command
import com.google.common.util.concurrent.ThreadFactoryBuilder
import io.sentry.Sentry
import io.sentry.event.UserBuilder
import me.mrkirby153.KirBot.Bot
import me.mrkirby153.KirBot.command.annotations.AdminCommand
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.annotations.CommandDescription
import me.mrkirby153.KirBot.command.annotations.IgnoreWhitelist
import me.mrkirby153.KirBot.command.annotations.LogInModlogs
import me.mrkirby153.KirBot.command.args.ArgumentParseException
import me.mrkirby153.KirBot.command.args.ArgumentParser
import me.mrkirby153.KirBot.command.args.ContextResolvers
import me.mrkirby153.KirBot.command.tree.CommandNode
import me.mrkirby153.KirBot.command.tree.CommandNodeMetadata
import me.mrkirby153.KirBot.database.models.CustomCommand
import me.mrkirby153.KirBot.inject.Injectable
import me.mrkirby153.KirBot.logger.LogEvent
import me.mrkirby153.KirBot.stats.Statistics
import me.mrkirby153.KirBot.utils.Context
import me.mrkirby153.KirBot.utils.checkPermissions
import me.mrkirby153.KirBot.utils.escapeMentions
import me.mrkirby153.KirBot.utils.getClearance
import me.mrkirby153.KirBot.utils.globalAdmin
import me.mrkirby153.KirBot.utils.logName
import me.mrkirby153.KirBot.utils.nameAndDiscrim
import me.mrkirby153.KirBot.utils.settings.GuildSettings
import me.mrkirby153.KirBot.utils.toTypedArray
import me.mrkirby153.kcutils.Time
import net.dv8tion.jda.api.entities.ChannelType
import net.dv8tion.jda.api.entities.GuildChannel
import net.dv8tion.jda.api.sharding.ShardManager
import org.reflections.Reflections
import org.reflections.scanners.MethodAnnotationsScanner
import java.lang.reflect.InvocationTargetException
import java.util.LinkedList
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.system.measureTimeMillis
@Injectable
@Singleton
class CommandExecutor @Inject constructor(private val shardManager: ShardManager, private val contextResolvers: ContextResolvers) {
private val rootNode = CommandNode("<<ROOT>>").apply {
rootNode = true
}
private val executorThread = Executors.newFixedThreadPool(2,
ThreadFactoryBuilder().setDaemon(true).setNameFormat(
"KirBot Command Executor-%d").build())
private val commandWatchdogThread = Executors.newCachedThreadPool(
ThreadFactoryBuilder().setDaemon(true).setNameFormat("Command Watchdog-%d").build())
fun loadAll() {
Bot.LOG.info("Starting loading of commands, this may take a while")
val time = measureTimeMillis {
val reflections = Reflections("me.mrkirby153.KirBot", MethodAnnotationsScanner())
val commands = reflections.getMethodsAnnotatedWith(
Command::class.java).map { it.declaringClass }.toSet()
Bot.LOG.info("Found ${commands.size} classes")
val instances = commands.map { Bot.applicationContext.newInstance(it) }
instances.forEach(this::register)
}
Bot.LOG.info("Commands registered in ${Time.format(1, time, Time.TimeUnit.FIT)}")
}
fun register(instance: Any) {
val methods = instance.javaClass.declaredMethods.filter { method ->
method.isAnnotationPresent(Command::class.java)
}
methods.forEach { method ->
val commandAnnotation = method.getAnnotation(Command::class.java)
val log = method.isAnnotationPresent(LogInModlogs::class.java)
val ignoreWhitelist = method.isAnnotationPresent(IgnoreWhitelist::class.java)
val admin = method.isAnnotationPresent(AdminCommand::class.java)
val descriptionAnnotation = method.getAnnotation(
CommandDescription::class.java)
val metadata = CommandNodeMetadata(commandAnnotation.arguments.toList(),
commandAnnotation.clearance, commandAnnotation.permissions, admin,
ignoreWhitelist, log, descriptionAnnotation?.value, commandAnnotation.category)
var parentNode = if (commandAnnotation.parent.isNotBlank()) this.rootNode.getChild(
commandAnnotation.parent) else this.rootNode
if (parentNode == null) {
val node = CommandNode(commandAnnotation.parent)
this.rootNode.addChild(node)
parentNode = node
}
var p = parentNode
commandAnnotation.name.split(" ").forEachIndexed { i, cmd ->
val child = p?.getChild(cmd)
if (child != null) {
if (i == commandAnnotation.name.split(" ").size - 1) {
// We're at the end of the chain, insert the node
if (child.isSkeleton()) {
child.instance = instance
child.method = method
child.metadata = metadata
child.aliases.addAll(commandAnnotation.aliases)
} else {
throw IllegalArgumentException(
"Attempting to register a command that already exists: ${commandAnnotation.name}")
}
}
p = child
} else {
val node = if (i == commandAnnotation.name.split(" ").size - 1) {
CommandNode(cmd, method, instance, metadata).apply {
aliases.addAll(commandAnnotation.aliases)
}
} else {
CommandNode(cmd)
}
p?.addChild(node)
p = node
}
}
}
}
fun printCommandTree(parent: CommandNode = rootNode, depth: Int = 0) {
print(" ".repeat(depth * 5))
println(parent.name)
parent.getChildren().forEach { child ->
printCommandTree(child, depth + 1)
}
}
fun execute(context: Context) {
if (context.channel.type == ChannelType.PRIVATE)
return // Ignore DMs
val message = context.contentRaw
val prefix = GuildSettings.commandPrefix.get(context.guild)
val mention = isMention(message)
if (!message.startsWith(prefix) && !mention)
return
Bot.LOG.debug("Processing command \"$message\"")
// Strip the command prefix from the message
val strippedMessage = if (mention) message.replace(Regex("^<@!?\\d{17,18}>\\s?"),
"") else message.substring(prefix.length)
val args = LinkedList(strippedMessage.split(" "))
val rootCommandName = args[0]
if (args.isEmpty() || strippedMessage.isEmpty()) {
if (mention) {
context.channel.sendMessage(
"The command prefix on this server is `$prefix`").queue()
return
}
}
var node = resolve(args)
val alias = context.kirbotGuild.commandAliases.firstOrNull { it.command == rootCommandName }
if (alias != null && alias.alias?.isNotEmpty() == true) {
// An alias exists for this command
args[0] = alias.alias!!
node = resolve(args)
}
if (node == null || node.isSkeleton()) {
val parts = strippedMessage.split(" ")
executeCustomCommand(context, parts[0], parts.drop(1).toTypedArray())
return
}
val metadata = node.metadata!!
val defaultAlias = context.kirbotGuild.commandAliases.firstOrNull { it.command == "*" }
if (!canExecuteInChannel(node, context.channel as GuildChannel)) {
Bot.LOG.debug("Ignoring because whitelist")
return
}
var clearance = defaultAlias?.clearance ?: 0
val cmdClearance = if (alias == null || alias.clearance == -1) metadata.clearance else alias.clearance
if (cmdClearance > clearance) {
// The node's clearance is higher than the default, escalate it
clearance = cmdClearance
}
if (metadata.admin && !context.author.globalAdmin) {
Bot.LOG.debug("Attempting to execute an admin command while not being a global admin")
return
}
if (clearance > context.author.getClearance(context.guild)) {
Bot.LOG.debug(
"${context.author} was denied access due to lack of clearance. Required $clearance -- Found ${context.author.getClearance(
context.guild)}")
if (GuildSettings.commandSilentFail.get(context.guild)) {
context.channel.sendMessage(
":lock: You do not have permission to perform this command").queue()
}
return
}
Bot.LOG.debug("Beginning parsing of arguments: [${args.joinToString(", ")}]")
val parser = ArgumentParser(contextResolvers, args.toTypedArray())
val cmdContext = try {
parser.parse(metadata.arguments.toTypedArray())
} catch (e: ArgumentParseException) {
val msg = buildString {
if (e.message != null) {
appendln(e.message.escapeMentions())
} else {
appendln("An unknown error occurred!")
}
append("Usage: `")
append(prefix.trim())
if (node.parentString.isNotBlank()) {
append(node.parentString.trim() + " ")
}
append(node.name.trim())
if(node.metadata?.arguments != null) {
append(" ")
append(node.metadata?.arguments?.joinToString(" "))
}
append("`")
}
context.send().error(msg).queue()
return
}
Bot.LOG.debug("Parsed $cmdContext")
val missingPermissions = metadata.permissions.filter {
!context.channel.checkPermissions(it)
}
if (missingPermissions.isNotEmpty()) {
context.send().error(
"Missing the required permissions: `${missingPermissions.joinToString(", ")}`")
return
}
Statistics.commandsRan.labels(rootCommandName, context.guild.id.toString()).inc()
try {
try {
val runtime = measureTimeMillis {
node.method!!.invoke(node.instance, context, cmdContext)
}
Statistics.commandDuration.labels(rootCommandName).observe(runtime.toDouble())
} catch (e: InvocationTargetException) {
throw e.targetException
} finally {
if (metadata.log) {
context.kirbotGuild.logManager.genericLog(LogEvent.ADMIN_COMMAND, ":tools:",
"${context.author.logName} Executed `${context.message.contentRaw}` in **#${context.channel.name}**")
}
}
} catch (e: CommandException) {
context.send().error(e.message ?: "An unknown error has occurred!").queue()
} catch (e: InterruptedException) {
// Ignore
} catch (e: java.lang.Exception) {
Bot.LOG.error("An unknown error occurred when executing the command $rootCommandName", e)
Sentry.getContext().user = UserBuilder().apply {
setUsername(context.author.nameAndDiscrim)
setId(context.author.id)
}.build()
Sentry.getContext().addExtra("guild", context.guild.id)
Sentry.getContext().addExtra("command", rootCommandName)
Sentry.getContext().addExtra("context", cmdContext.getContextString())
Sentry.capture(e)
Sentry.clearContext()
context.send().error("An unknown error occurred!").queue()
}
Bot.LOG.debug("Command execution finished")
}
fun executeAsync(context: Context) {
val future = this.executorThread.submit {
execute(context)
}
commandWatchdogThread.submit {
try {
future.get(10, TimeUnit.SECONDS)
} catch (e: TimeoutException) {
Bot.LOG.debug("Command hit timeout, canceling")
if (!future.cancel(true)) {
Bot.LOG.warn("Could not interrupt command: ${context.message.contentRaw}")
}
context.send().error("Your command timed out").queue()
}
}
}
tailrec fun resolve(arguments: LinkedList<String>,
parent: CommandNode = rootNode): CommandNode? {
if (arguments.peek() == null) {
if (parent == rootNode)
return null
return parent
}
val childName = arguments.peek()
val childNode = parent.getChild(childName)
if (childNode == null) {
if (rootNode == parent)
return null
return parent
} else {
arguments.pop()
}
if (arguments.peek() != null && childNode.getChild(arguments.peek()) == null)
return childNode
return resolve(arguments, childNode)
}
private fun isMention(message: String): Boolean {
return message.matches(Regex("^<@!?${shardManager.getShardById(0)!!.selfUser.id}>.*"))
}
fun executeCustomCommand(context: Context, command: String, args: Array<String>) {
val customCommand = context.kirbotGuild.customCommands.firstOrNull {
it.name.equals(command, true)
} ?: return
if (customCommand.clearance > context.author.getClearance(context.guild)) {
if (GuildSettings.commandSilentFail.get(context.guild)) {
context.channel.sendMessage(
":lock: You do not have permission to perform this command").queue()
}
return
}
if (!canExecuteInChannel(customCommand, context.channel as GuildChannel)) {
return
}
var response = customCommand.data
for (i in 0 until args.size) {
response = response.replace("%${i + 1}", args[i])
}
context.channel.sendMessage(response).queue()
}
private fun canExecuteInChannel(command: CommandNode, channel: GuildChannel): Boolean {
try {
val channels = GuildSettings.commandWhitelistChannels.get(channel.guild).toTypedArray(
String::class.java)
if (command.metadata?.admin == true)
return true
return if (command.metadata?.ignoreWhitelist == false) {
if (channels.isEmpty())
return true
channels.any { it == channel.id }
} else {
true
}
} catch (e: Throwable) {
Bot.LOG.error("An error occurred in canExeuteInChannel", e)
Sentry.capture(e)
}
return false
}
private fun canExecuteInChannel(command: CustomCommand, channel: GuildChannel): Boolean {
val channels = GuildSettings.commandWhitelistChannels.get(channel.guild).toTypedArray(String::class.java)
return if (command.respectWhitelist) {
if (channels.isEmpty())
return true
channels.any { it == channel.id }
} else {
true
}
}
fun getAllLeaves(): List<CommandNode> {
return this.rootNode.getLeaves()
}
fun getRoot(): CommandNode {
return this.rootNode
}
}
|
mit
|
094c72510e74b923b03e8f0467279dbc
| 39.670077 | 142 | 0.594868 | 4.87163 | false | false | false | false |
toastkidjp/Yobidashi_kt
|
image/src/main/java/jp/toastkid/image/preview/ImagePreviewUi.kt
|
1
|
15997
|
/*
* Copyright (c) 2022 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.image.preview
import android.graphics.BitmapFactory
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.animateRotateBy
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.FractionalThreshold
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ResistanceConfig
import androidx.compose.material.Slider
import androidx.compose.material.Surface
import androidx.compose.material.SwipeableState
import androidx.compose.material.Text
import androidx.compose.material.swipeable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.net.toUri
import androidx.exifinterface.media.ExifInterface
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import coil.compose.AsyncImage
import coil.request.ImageRequest
import jp.toastkid.image.Image
import jp.toastkid.image.R
import jp.toastkid.image.factory.GifImageLoaderFactory
import jp.toastkid.image.preview.attach.AttachToAnyAppUseCase
import jp.toastkid.image.preview.attach.AttachToThisAppBackgroundUseCase
import jp.toastkid.image.preview.detail.ExifInformationExtractorUseCase
import jp.toastkid.image.preview.viewmodel.ImagePreviewViewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.ui.dialog.ConfirmDialog
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileInputStream
@OptIn(ExperimentalMaterialApi::class)
@Composable
internal fun ImagePreviewUi(images: List<Image>, initialIndex: Int) {
val imageLoader = GifImageLoaderFactory().invoke(LocalContext.current)
val viewModel = remember { ImagePreviewViewModel() }
LaunchedEffect(key1 = Unit, block = {
viewModel.setIndex(initialIndex)
viewModel.replaceImages(images)
})
val contentViewModel = (LocalContext.current as? ViewModelStoreOwner)?.let {
ViewModelProvider(it).get(ContentViewModel::class.java)
}
val context = LocalContext.current
val sizePx = with(LocalDensity.current) { 200.dp.toPx() }
val anchors = mapOf(sizePx to -1, 0f to 0, -sizePx to 1)
val swipeableState = SwipeableState(
initialValue = 0,
confirmStateChange = {
if (it == -1) {
viewModel.moveToPrevious()
} else if (it == 1) {
viewModel.moveToNext()
}
true
}
)
val coroutineScope = rememberCoroutineScope()
Box {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(viewModel.getCurrentImage().path).crossfade(true).build(),
imageLoader = imageLoader,
contentDescription = viewModel.getCurrentImage().name,
colorFilter = viewModel.colorFilterState.value,
modifier = Modifier
.fillMaxSize()
.graphicsLayer(
scaleX = viewModel.scale.value,
scaleY = viewModel.scale.value,
rotationY = viewModel.rotationY.value,
rotationZ = viewModel.rotationZ.value
)
.offset {
IntOffset(
viewModel.offset.value.x.toInt(),
viewModel.offset.value.y.toInt()
)
}
.transformable(state = viewModel.state)
.pointerInput(Unit) {
detectDragGestures { change, dragAmount ->
change.consume()
viewModel.offset.value += dragAmount
}
}
.pointerInput(Unit) {
detectTapGestures(
onPress = { /* Called when the gesture starts */ },
onDoubleTap = { viewModel.resetStates() },
onLongPress = { /* Called on Long Press */ },
onTap = { /* Called on Tap */ }
)
}
)
Row(
modifier = Modifier
.fillMaxWidth()
.height(60.dp)
.align(Alignment.Center)
.swipeable(
swipeableState,
anchors = anchors,
thresholds = { _, _ -> FractionalThreshold(0.75f) },
resistance = ResistanceConfig(0.5f),
orientation = Orientation.Horizontal
)
) {
}
Surface(
elevation = 4.dp,
modifier = Modifier.align(Alignment.BottomCenter)
) {
Column {
Icon(
painterResource(id = if (viewModel.openMenu.value) R.drawable.ic_down else R.drawable.ic_up),
contentDescription = stringResource(id = R.string.open),
modifier = Modifier
.clickable {
viewModel.openMenu.value = viewModel.openMenu.value.not()
}
.padding(8.dp)
.align(Alignment.CenterHorizontally)
)
if (viewModel.openMenu.value) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp)
) {
Text(stringResource(R.string.title_alpha_slider))
Slider(
viewModel.alphaSliderPosition.value,
onValueChange = {
viewModel.alphaSliderPosition.value = it
viewModel.updateColorFilter()
},
valueRange = -1.5f .. 1f,
steps = 150
)
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp)
) {
Text(stringResource(R.string.title_contrast_slider))
Slider(
viewModel.contrastSliderPosition.value,
onValueChange = {
viewModel.contrastSliderPosition.value = it
viewModel.updateColorFilter()
},
valueRange = 0f .. 3f,
steps = 300
)
}
Row(
modifier = Modifier.padding(16.dp)
) {
Icon(
painterResource(id = R.drawable.ic_rotate_left),
contentDescription = stringResource(id = R.string.content_description_rotate_left),
tint = MaterialTheme.colors.onSurface,
modifier = Modifier.clickable {
coroutineScope.launch {
viewModel.state.animateRotateBy(-90f)
}
}
)
Icon(
painterResource(id = R.drawable.ic_rotate_right),
contentDescription = stringResource(id = R.string.content_description_rotate_right),
tint = MaterialTheme.colors.onSurface,
modifier = Modifier
.clickable {
coroutineScope.launch {
viewModel.state.animateRotateBy(90f)
}
}
.padding(start = 16.dp)
)
Icon(
painterResource(id = R.drawable.ic_flip),
contentDescription = stringResource(id = R.string.content_description_reverse_image),
tint = MaterialTheme.colors.onSurface,
modifier = Modifier
.clickable {
coroutineScope.launch {
viewModel.rotationY.value =
if (viewModel.rotationY.value == 0f) 180f else 0f
}
}
.padding(start = 16.dp)
)
Icon(
painterResource(id = R.drawable.ic_brush),
contentDescription = stringResource(id = R.string.content_description_reverse_color),
tint = Color(0xCCCDDC39),
modifier = Modifier
.clickable {
viewModel.reverse.value = viewModel.reverse.value.not()
viewModel.updateColorFilter()
}
.padding(start = 16.dp)
)
Icon(
painterResource(id = R.drawable.ic_brush),
contentDescription = stringResource(id = R.string.content_description_sepia_color_filter),
tint = Color(0xDDFF5722),
modifier = Modifier
.clickable { viewModel.setSepia() }
.padding(start = 16.dp)
)
Icon(
painterResource(id = R.drawable.ic_brush),
contentDescription = stringResource(id = R.string.content_description_gray_scale),
tint = Color(0xFFAAAAAA),
modifier = Modifier
.clickable {
viewModel.saturation.value = viewModel.saturation.value.not()
viewModel.updateColorFilter()
}
.padding(start = 16.dp)
)
Box(
Modifier
.clickable { viewModel.openOtherMenu.value = true }
.padding(start = 16.dp)
) {
Icon(
painterResource(id = R.drawable.ic_set_to),
contentDescription = stringResource(id = R.string.content_description_set_to),
tint = MaterialTheme.colors.onSurface
)
DropdownMenu(
viewModel.openOtherMenu.value,
onDismissRequest = { viewModel.openOtherMenu.value = false }
) {
DropdownMenuItem(
onClick = {
viewModel.openOtherMenu.value = false
contentViewModel ?: return@DropdownMenuItem
val image = viewModel.getCurrentImage()
AttachToThisAppBackgroundUseCase(contentViewModel)
.invoke(context, image.path.toUri(), BitmapFactory.decodeFile(image.path))
}
) {
Text(
stringResource(id = R.string.this_app),
fontSize = 20.sp
)
}
DropdownMenuItem(
onClick = {
viewModel.openOtherMenu.value = false
contentViewModel ?: return@DropdownMenuItem
AttachToAnyAppUseCase({ context.startActivity(it) })
.invoke(context, BitmapFactory.decodeFile(viewModel.getCurrentImage().path))
}
) {
Text(
stringResource(id = R.string.other_app),
fontSize = 20.sp
)
}
}
}
Icon(
painterResource(id = R.drawable.ic_info_white),
contentDescription = stringResource(R.string.content_description_information),
tint = MaterialTheme.colors.onSurface,
modifier = Modifier
.clickable {
viewModel.openDialog.value = true
}
.padding(start = 16.dp)
)
}
}
}
}
}
if (viewModel.openDialog.value) {
val inputStream = FileInputStream(File(viewModel.getCurrentImage().path))
val exifInterface = ExifInterface(inputStream)
ConfirmDialog(
visibleState = viewModel.openDialog,
title = viewModel.getCurrentImage().name,
message = ExifInformationExtractorUseCase().invoke(exifInterface) ?: "Not found"
)
}
BackHandler(viewModel.openMenu.value) {
viewModel.openMenu.value = false
}
contentViewModel?.hideAppBar()
}
|
epl-1.0
|
14a647ac7f783a888e107b2ed9190f2d
| 43.436111 | 120 | 0.499156 | 6.166924 | false | false | false | false |
canou/Simple-Commons
|
commons/src/main/kotlin/com/simplemobiletools/commons/views/PatternTab.kt
|
1
|
2914
|
package com.simplemobiletools.commons.views
import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.widget.RelativeLayout
import com.andrognito.patternlockview.PatternLockView
import com.andrognito.patternlockview.listener.PatternLockViewListener
import com.andrognito.patternlockview.utils.PatternLockUtils
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.extensions.toast
import com.simplemobiletools.commons.extensions.updateTextColors
import com.simplemobiletools.commons.helpers.PROTECTION_PATTERN
import com.simplemobiletools.commons.interfaces.HashListener
import com.simplemobiletools.commons.interfaces.SecurityTab
import kotlinx.android.synthetic.main.tab_pattern.view.*
class PatternTab(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs), SecurityTab {
private var hash = ""
private var requiredHash = ""
lateinit var hashListener: HashListener
override fun onFinishInflate() {
super.onFinishInflate()
val textColor = context.baseConfig.textColor
context.updateTextColors(pattern_lock_holder)
pattern_lock_view.correctStateColor = context.baseConfig.primaryColor
pattern_lock_view.normalStateColor = textColor
pattern_lock_view.addPatternLockListener(object : PatternLockViewListener {
override fun onComplete(pattern: MutableList<PatternLockView.Dot>?) {
receivedHash(PatternLockUtils.patternToSha1(pattern_lock_view, pattern))
}
override fun onCleared() {
}
override fun onStarted() {
}
override fun onProgress(progressPattern: MutableList<PatternLockView.Dot>?) {
}
})
}
override fun initTab(requiredHash: String, listener: HashListener) {
this.requiredHash = requiredHash
hash = requiredHash
hashListener = listener
}
private fun receivedHash(newHash: String) {
if (hash.isEmpty()) {
hash = newHash
pattern_lock_view.clearPattern()
pattern_lock_title.setText(R.string.repeat_pattern)
} else if (hash == newHash) {
pattern_lock_view.setViewMode(PatternLockView.PatternViewMode.CORRECT)
Handler().postDelayed({
hashListener.receivedHash(hash, PROTECTION_PATTERN)
}, 300)
} else {
pattern_lock_view.setViewMode(PatternLockView.PatternViewMode.WRONG)
context.toast(R.string.wrong_pattern)
Handler().postDelayed({
pattern_lock_view.clearPattern()
if (requiredHash.isEmpty()) {
hash = ""
pattern_lock_title.setText(R.string.insert_pattern)
}
}, 1000)
}
}
}
|
apache-2.0
|
401f4a112affe702e4fb712c7a8e9704
| 38.378378 | 103 | 0.687714 | 4.722853 | false | false | false | false |
devunt/ika
|
app/src/main/kotlin/org/ozinger/ika/definition/Member.kt
|
1
|
812
|
package org.ozinger.ika.definition
import org.ozinger.ika.state.IRCChannels
import org.ozinger.ika.state.IRCUsers
data class Member(
val channelName: ChannelName,
val universalUserId: UniversalUserId,
) {
val channel: IRCChannel = IRCChannels[channelName]
val user: IRCUser = IRCUsers[universalUserId]
val modes = mutableSetOf<Char>()
init {
user.memberOf.add(this)
}
fun addMode(mode: Char?) {
if (mode != null) {
modes.add(mode)
}
}
fun removeMode(mode: Char?) {
if (mode != null) {
modes.remove(mode)
}
}
fun leave() {
user.memberOf.remove(this)
channel.members.remove(universalUserId)
if (channel.isEmpty) {
IRCChannels -= channelName
}
}
}
|
agpl-3.0
|
8ff79db57fe97b81cd493e05fb15335e
| 20.368421 | 54 | 0.597291 | 3.922705 | false | false | false | false |
dataloom/conductor-client
|
src/main/kotlin/com/openlattice/assembler/MaterializedEntitySet.kt
|
1
|
2199
|
/*
* Copyright (C) 2019. OpenLattice, Inc.
*
* 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/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.assembler
import com.openlattice.organization.OrganizationEntitySetFlag
import java.time.OffsetDateTime
import java.util.EnumSet
data class MaterializedEntitySet(
val assemblyKey: EntitySetAssemblyKey,
/**
* Holds the user set refresh rate in milliseconds.
* If it's null, that means, that it should NOT be refreshed automatically.
*/
var refreshRate: Long?,
val flags: EnumSet<OrganizationEntitySetFlag> = EnumSet.noneOf(OrganizationEntitySetFlag::class.java),
var lastRefresh: OffsetDateTime = OffsetDateTime.now()) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is MaterializedEntitySet) return false
if (assemblyKey != other.assemblyKey) return false
if (refreshRate != other.refreshRate) return false
if (flags != other.flags) return false
if (lastRefresh.toInstant() != other.lastRefresh.toInstant()) return false
return true
}
override fun hashCode(): Int {
var result = assemblyKey.hashCode()
result = 31 * result + (refreshRate?.hashCode() ?: 0)
result = 31 * result + flags.hashCode()
result = 31 * result + lastRefresh.hashCode()
return result
}
}
|
gpl-3.0
|
2261bca6b103be8f1bfd83872ca75d0f
| 39 | 110 | 0.657117 | 4.75974 | false | false | false | false |
mbuhot/eskotlin
|
src/main/kotlin/mbuhot/eskotlin/query/compound/FunctionScore.kt
|
1
|
2200
|
/*
* Copyright (c) 2016. Michael Buhot [email protected]
*/
package mbuhot.eskotlin.query.compound
import org.elasticsearch.common.lucene.search.function.CombineFunction
import org.elasticsearch.common.lucene.search.function.FieldValueFactorFunction
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder
import org.elasticsearch.index.query.MatchAllQueryBuilder
import org.elasticsearch.index.query.QueryBuilder
import org.elasticsearch.index.query.functionscore.FieldValueFactorFunctionBuilder
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders
data class FunctionScoreData(
var query: QueryBuilder = MatchAllQueryBuilder(),
var boost: Float? = null,
var functions: List<Pair<QueryBuilder?, ScoreFunctionBuilder<*>>> = emptyList(),
var field_value_factor: FieldValueFactorFunctionBuilder? = null,
var max_boost: Float? = null,
var score_mode: String? = null,
var boost_mode: String? = null,
var min_score: Float? = null)
fun function_score(init: FunctionScoreData.() -> Unit): FunctionScoreQueryBuilder {
val params = FunctionScoreData().apply(init)
val factorWrapper = listOf(Pair(null as QueryBuilder?, params.field_value_factor as ScoreFunctionBuilder<*>?))
val merged = factorWrapper + params.functions;
val filterFunctions = merged.filter { it.second != null }.map {
if (it.first == null) {
FunctionScoreQueryBuilder.FilterFunctionBuilder(it.second)
} else {
FunctionScoreQueryBuilder.FilterFunctionBuilder(it.first, it.second)
}
}
val builder = FunctionScoreQueryBuilder(params.query, filterFunctions.toTypedArray())
return builder.apply {
params.boost?.let { boost(it) }
params.max_boost?.let { maxBoost(it) }
params.score_mode?.let { scoreMode(FunctionScoreQuery.ScoreMode.fromString(it)) }
params.boost_mode?.let { boostMode(CombineFunction.fromString(it)) }
params.min_score?.let { setMinScore(it) }
}
}
|
mit
|
e81d4ebf0f6413e38840dab5f6a56631
| 43.897959 | 114 | 0.737273 | 4.190476 | false | false | false | false |
desilvai/mockito-kotlin
|
mockito-kotlin/src/main/kotlin/com/nhaarman/mockito_kotlin/CreateInstance.kt
|
1
|
7666
|
/*
* The MIT License
*
* Copyright (c) 2016 Niek Haarman
* Copyright (c) 2007 Mockito contributors
*
* 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 com.nhaarman.mockito_kotlin
import org.mockito.Answers
import org.mockito.internal.creation.MockSettingsImpl
import org.mockito.internal.creation.bytebuddy.MockAccess
import org.mockito.internal.util.MockUtil
import java.io.File
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Modifier
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.KType
import kotlin.reflect.defaultType
import kotlin.reflect.jvm.isAccessible
import kotlin.reflect.jvm.javaType
import kotlin.reflect.jvm.jvmName
import java.lang.reflect.Array as JavaArray
/**
* A collection of functions that tries to create an instance of
* classes to avoid NPE's when using Mockito with Kotlin.
*/
/**
* Checks whether the resource file to enable mocking of final classes is present.
*/
private var mockMakerInlineEnabled: Boolean? = null
private fun mockMakerInlineEnabled(jClass: Class<out Any>): Boolean {
return mockMakerInlineEnabled ?:
jClass.getResource("mockito-extensions/org.mockito.plugins.MockMaker")?.let {
mockMakerInlineEnabled = File(it.file).readLines().filter { it == "mock-maker-inline" }.isNotEmpty()
mockMakerInlineEnabled
} ?: false
}
inline fun <reified T> createArrayInstance() = arrayOf<T>()
inline fun <reified T : Any> createInstance() = createInstance(T::class)
@Suppress("UNCHECKED_CAST")
fun <T : Any> createInstance(kClass: KClass<T>): T {
return MockitoKotlin.instanceCreator(kClass)?.invoke() as T? ?:
when {
kClass.hasObjectInstance() -> kClass.objectInstance!!
kClass.isMockable() -> kClass.java.uncheckedMock()
kClass.isPrimitive() -> kClass.toDefaultPrimitiveValue()
kClass.isEnum() -> kClass.java.enumConstants.first()
kClass.isArray() -> kClass.toArrayInstance()
kClass.isClassObject() -> kClass.toClassObject()
else -> kClass.easiestConstructor().newInstance()
}
}
/**
* Tries to find the easiest constructor which it can instantiate.
*/
private fun <T : Any> KClass<T>.easiestConstructor(): KFunction<T> {
return constructors
.sortedBy { it.parameters.size }
// Filter out any constructor that uses this class as a parameter
// (e.g., a copy constructor) so we don't get into an infinite loop.
.withoutParametersOfType(this.defaultType)
.withoutArrayParameters()
.firstOrNull() ?: constructors.sortedBy { it.parameters.size }
.withoutParametersOfType(this.defaultType)
.first()
}
private fun <T> List<KFunction<T>>.withoutArrayParameters() = filter {
it.parameters.filter { parameter -> parameter.type.toString().toLowerCase().contains("array") }.isEmpty()
}
/**
* Filters out functions with the given type.
*/
private fun <T: Any> List<KFunction<T>>.withoutParametersOfType(type: KType) = filter {
it.parameters.filter { it.type == type }.isEmpty()
}
@Suppress("SENSELESS_COMPARISON")
private fun KClass<*>.hasObjectInstance() = objectInstance != null
private fun KClass<*>.isMockable(): Boolean {
return !Modifier.isFinal(java.modifiers) || mockMakerInlineEnabled(java)
}
private fun KClass<*>.isEnum() = java.isEnum
private fun KClass<*>.isArray() = java.isArray
private fun KClass<*>.isClassObject() = jvmName.equals("java.lang.Class")
private fun KClass<*>.isPrimitive() =
java.isPrimitive || !defaultType.isMarkedNullable && simpleName in arrayOf(
"Boolean",
"Byte",
"Short",
"Int",
"Double",
"Float",
"Long",
"String"
)
@Suppress("UNCHECKED_CAST", "IMPLICIT_CAST_TO_ANY")
private fun <T : Any> KClass<T>.toDefaultPrimitiveValue(): T {
return when (simpleName) {
"Boolean" -> true
"Byte" -> 0.toByte()
"Short" -> 0.toShort()
"Int" -> 0
"Double" -> 0.0
"Float" -> 0f
"Long" -> 0
"String" -> ""
else -> throw UnsupportedOperationException("Cannot create default primitive for $simpleName.")
} as T
}
@Suppress("UNCHECKED_CAST", "IMPLICIT_CAST_TO_ANY")
private fun <T : Any> KClass<T>.toArrayInstance(): T {
return when (simpleName) {
"ByteArray" -> byteArrayOf()
"ShortArray" -> shortArrayOf()
"IntArray" -> intArrayOf()
"LongArray" -> longArrayOf()
"DoubleArray" -> doubleArrayOf()
"FloatArray" -> floatArrayOf()
else -> {
val name = java.name.drop(2).dropLast(1)
return JavaArray.newInstance(Class.forName(name), 0) as T
}
} as T
}
@Suppress("UNCHECKED_CAST")
private fun <T : Any> KClass<T>.toClassObject(): T {
return Class.forName("java.lang.Object") as T
}
private fun <T : Any> KFunction<T>.newInstance(): T {
try {
isAccessible = true
return callBy(parameters.associate {
it to it.type.createNullableInstance<T>()
})
} catch(e: InvocationTargetException) {
throw MockitoKotlinException(
"""
Could not create an instance of class ${this.returnType}, because of an error with the following message:
"${e.cause?.message}"
Try registering an instance creator yourself, using MockitoKotlin.registerInstanceCreator<${this.returnType}> {...}.""",
e.cause
)
}
}
@Suppress("UNCHECKED_CAST")
private fun <T : Any> KType.createNullableInstance(): T? {
if (isMarkedNullable) {
return null
}
val javaType: Type = javaType
return when (javaType) {
is ParameterizedType -> (javaType.rawType as Class<T>).uncheckedMock()
is Class<*> -> createInstance((javaType as Class<T>).kotlin)
else -> null
}
}
/**
* Creates a mock instance of given class, without modifying or checking any internal Mockito state.
*/
@Suppress("UNCHECKED_CAST")
fun <T> Class<T>.uncheckedMock(): T {
val impl = MockSettingsImpl<T>().defaultAnswer(Answers.RETURNS_DEFAULTS) as MockSettingsImpl<T>
val creationSettings = impl.confirm(this)
return MockUtil.createMock(creationSettings).apply {
(this as? MockAccess)?.mockitoInterceptor = null
}
}
|
mit
|
ee212be8858c1c32747a4ab03edc5489
| 35.504762 | 128 | 0.661753 | 4.358158 | false | false | false | false |
blackbbc/Tucao
|
app/src/main/kotlin/me/sweetll/tucao/extension/HistoryHelpers.kt
|
1
|
3019
|
package me.sweetll.tucao.extension
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import me.sweetll.tucao.model.json.Video
object HistoryHelpers {
private val HISTORY_FILE_NAME = "history"
private val KEY_S_SEARCH_HISTORY ="search_history"
private val KEY_S_PLAY_HISTORY = "play_history"
private val KEY_S_STAR = "star"
private val adapter by lazy {
val moshi = Moshi.Builder()
.build()
val type = Types.newParameterizedType(MutableList::class.java, Video::class.java)
moshi.adapter<MutableList<Video>>(type)
}
private fun loadHistory(fileName: String, key: String): MutableList<Video> {
val sp = fileName.getSharedPreference()
val jsonString = sp.getString(key, "[]")
return adapter.fromJson(jsonString)!!
}
fun loadSearchHistory(): MutableList<Video> = loadHistory(HISTORY_FILE_NAME, KEY_S_SEARCH_HISTORY)
fun loadPlayHistory(): MutableList<Video> = loadHistory(HISTORY_FILE_NAME, KEY_S_PLAY_HISTORY)
fun loadStar(): MutableList<Video> = loadHistory(HISTORY_FILE_NAME, KEY_S_STAR)
private fun saveHistory(fileName: String, key: String, video: Video) {
val histories = loadHistory(fileName, key)
if (key == KEY_S_SEARCH_HISTORY) {
histories.removeAll {
it.title == video.title
}
} else {
histories.removeAll {
it.hid == video.hid
}
}
histories.add(0, video)
val jsonString = adapter.toJson(histories)
val sp = fileName.getSharedPreference()
sp.edit {
putString(key, jsonString)
}
}
fun saveSearchHistory(video: Video) {
saveHistory(HISTORY_FILE_NAME, KEY_S_SEARCH_HISTORY, video)
}
fun savePlayHistory(video: Video) {
val histories = loadHistory(HISTORY_FILE_NAME, KEY_S_PLAY_HISTORY)
val existVideo = histories.find { it.hid == video.hid }
if (existVideo != null) {
video.parts = video.parts.plus(existVideo.parts).distinctBy { it.vid }.toMutableList()
}
saveHistory(HISTORY_FILE_NAME, KEY_S_PLAY_HISTORY, video)
}
fun saveStar(video: Video) {
saveHistory(HISTORY_FILE_NAME, KEY_S_STAR, video)
}
private fun removeHistory(fileName: String, key: String, video: Video): Int {
val histories = loadHistory(fileName, key)
val removedIndex = histories.indexOf(video)
histories.remove(video)
val jsonString = adapter.toJson(histories)
val sp = fileName.getSharedPreference()
sp.edit {
putString(key, jsonString)
}
return removedIndex
}
fun removeSearchHistory(video: Video) = removeHistory(HISTORY_FILE_NAME, KEY_S_SEARCH_HISTORY, video)
fun removePlayHistory(video: Video) = removeHistory(HISTORY_FILE_NAME, KEY_S_PLAY_HISTORY, video)
fun removeStar(video: Video) = removeHistory(HISTORY_FILE_NAME, KEY_S_STAR, video)
}
|
mit
|
09a56f696c0ee2b7a65ae07e38fc3e89
| 33.306818 | 105 | 0.644253 | 3.925878 | false | false | false | false |
weiweiwitch/third-lab
|
src/main/kotlin/com/ariane/thirdlab/controller/SummaryController.kt
|
1
|
1806
|
package com.ariane.thirdlab.controller
import com.ariane.thirdlab.controller.resp.TlBaseResp
import com.ariane.thirdlab.domains.Summary
import com.ariane.thirdlab.repositories.SummaryRepository
import com.ariane.thirdlab.rtcode.SUCCESS
import com.ariane.thirdlab.rtcode.SUMMARY_NOT_FOUND
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import javax.transaction.Transactional
@RestController
@RequestMapping("/api", produces = ["application/json"])
@Transactional
open class SummaryController() {
@Autowired
lateinit var summaryRepository: SummaryRepository
data class SummaryResp(val id: Long, val summary: String)
@GetMapping("/summary")
open fun findSummary(): TlBaseResp<SummaryResp> {
var summary = summaryRepository.findFirstByOrderByIdAsc()
if (summary == null) {
val newSummary = Summary()
newSummary.summary = "## SUMMARY"
summaryRepository.save(newSummary)
summary = newSummary
}
val summaryResp = SummaryResp(summary.id, summary.summary)
val resp = TlBaseResp<SummaryResp>(SUCCESS)
resp.data = summaryResp
return resp
}
data class UpdateSummaryReq(val summary: String)
data class UpdateSummaryResp(val id: Long)
@PutMapping("/summary")
open fun updateSummary(@RequestBody req: UpdateSummaryReq): TlBaseResp<UpdateSummaryResp?> {
val summary = summaryRepository.findFirstByOrderByIdAsc()
if (summary == null) {
return TlBaseResp<UpdateSummaryResp?>(SUMMARY_NOT_FOUND)
}
summary.summary = req.summary
val resp = TlBaseResp<UpdateSummaryResp?>(SUCCESS)
resp.data = UpdateSummaryResp(summary.id)
return resp
}
}
|
mit
|
afc4ea7649c8322673e3fe531eb73659
| 32.462963 | 96 | 0.712071 | 4.372881 | false | false | false | false |
ratabb/Hishoot2i
|
app/src/main/java/org/illegaller/ratabb/hishoot2i/ui/common/behavior/FabQuickHideBehavior.kt
|
1
|
3952
|
package org.illegaller.ratabb.hishoot2i.ui.common.behavior
import android.animation.Animator
import android.animation.ObjectAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.annotation.Keep
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.res.use
import androidx.core.view.ViewCompat
import com.google.android.material.floatingactionbutton.FloatingActionButton
import common.ext.dp2px
import kotlin.math.roundToInt
import androidx.appcompat.R as AppcompatR
@Keep
class FabQuickHideBehavior @JvmOverloads @Keep constructor(
context: Context? = null,
attrs: AttributeSet? = null
) : FabSnackBarAwareBehavior(context, attrs) {
private var scrollThreshold: Int = 0
private var scrollDistance: Int = 0
private var scrollingDirection: Int = 0
private var scrollingTrigger: Int = 0
private var animator: Animator? = null
init {
context?.obtainStyledAttributes(intArrayOf(AppcompatR.attr.actionBarSize))?.use {
scrollThreshold = it.getDimensionPixelSize(0, context.dp2px(56F).roundToInt()) / 2
}
}
override fun onStartNestedScroll(
coordinatorLayout: CoordinatorLayout,
child: FloatingActionButton,
directTargetChild: View,
target: View,
axes: Int,
type: Int
): Boolean = axes and ViewCompat.SCROLL_AXIS_VERTICAL != 0
override fun onNestedPreScroll(
coordinatorLayout: CoordinatorLayout,
child: FloatingActionButton,
target: View,
dx: Int,
dy: Int,
consumed: IntArray,
type: Int
) {
if (dy > 0 && scrollingDirection != DIRECTION_UP) {
scrollingDirection = DIRECTION_UP
scrollDistance = 0
} else if (dy < 0 && scrollingDirection != DIRECTION_DOWN) {
scrollingDirection = DIRECTION_DOWN
scrollDistance = 0
}
}
override fun onNestedScroll(
coordinatorLayout: CoordinatorLayout,
child: FloatingActionButton,
target: View,
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int,
type: Int
) {
scrollDistance += dyConsumed
if (scrollDistance > scrollThreshold && scrollingTrigger != DIRECTION_UP) {
scrollingTrigger = DIRECTION_UP
resetAnimator(child, getTargetHideValue(coordinatorLayout, child))
} else if (scrollDistance < -scrollThreshold && scrollingTrigger != DIRECTION_DOWN) {
scrollingTrigger = DIRECTION_DOWN
resetAnimator(child, 0f)
}
}
override fun onNestedFling(
coordinatorLayout: CoordinatorLayout,
child: FloatingActionButton,
target: View,
velocityX: Float,
velocityY: Float,
consumed: Boolean
): Boolean {
if (consumed) {
if (velocityY > 0 && scrollingTrigger != DIRECTION_UP) {
scrollingTrigger = DIRECTION_UP
resetAnimator(child, getTargetHideValue(coordinatorLayout, child))
} else if (velocityY < 0 && scrollingTrigger != DIRECTION_DOWN) {
scrollingTrigger = DIRECTION_DOWN
resetAnimator(child, 0F)
}
}
return false
}
//
private fun resetAnimator(fab: FloatingActionButton, value: Float) {
animator?.let {
it.cancel()
animator = null
}
animator = ObjectAnimator.ofFloat(fab, View.TRANSLATION_Y, value)
.setDuration(250)
.apply { start() }
}
private fun getTargetHideValue(parent: ViewGroup, target: FloatingActionButton): Float =
(parent.height - target.top).toFloat()
companion object {
private const val DIRECTION_UP = 1
private const val DIRECTION_DOWN = -1
}
}
|
apache-2.0
|
1903db6f633fe5a1fe011a91ec78c320
| 31.661157 | 94 | 0.648279 | 4.952381 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement
|
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/CreateDataProvider.kt
|
1
|
2650
|
// Copyright 2020 The Cross-Media Measurement 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.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers
import org.wfanet.measurement.gcloud.spanner.bufferInsertMutation
import org.wfanet.measurement.gcloud.spanner.bufferTo
import org.wfanet.measurement.gcloud.spanner.set
import org.wfanet.measurement.gcloud.spanner.setJson
import org.wfanet.measurement.internal.kingdom.DataProvider
import org.wfanet.measurement.internal.kingdom.copy
class CreateDataProvider(private val dataProvider: DataProvider) :
SpannerWriter<DataProvider, DataProvider>() {
override suspend fun TransactionScope.runTransaction(): DataProvider {
val internalCertificateId = idGenerator.generateInternalId()
dataProvider.certificate.toInsertMutation(internalCertificateId).bufferTo(transactionContext)
val internalDataProviderId = idGenerator.generateInternalId()
val externalDataProviderId = idGenerator.generateExternalId()
transactionContext.bufferInsertMutation("DataProviders") {
set("DataProviderId" to internalDataProviderId)
set("PublicKeyCertificateId" to internalCertificateId)
set("ExternalDataProviderId" to externalDataProviderId)
set("DataProviderDetails" to dataProvider.details)
setJson("DataProviderDetailsJson" to dataProvider.details)
}
val externalDataProviderCertificateId = idGenerator.generateExternalId()
transactionContext.bufferInsertMutation("DataProviderCertificates") {
set("DataProviderId" to internalDataProviderId)
set("CertificateId" to internalCertificateId)
set("ExternalDataProviderCertificateId" to externalDataProviderCertificateId)
}
return dataProvider.copy {
this.externalDataProviderId = externalDataProviderId.value
certificate =
certificate.copy {
this.externalDataProviderId = externalDataProviderId.value
externalCertificateId = externalDataProviderCertificateId.value
}
}
}
override fun ResultScope<DataProvider>.buildResult(): DataProvider {
return checkNotNull(transactionResult)
}
}
|
apache-2.0
|
d4488f1dcb6a52fdc0fe4a6343db393f
| 41.063492 | 97 | 0.784528 | 5.047619 | false | false | false | false |
nicorsm/S3-16-simone
|
app/src/main/java/app/simone/settings/view/CreditsActivity.kt
|
2
|
3426
|
package app.simone.settings.view
import android.app.Dialog
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.view.MotionEvent
import android.widget.Button
import android.widget.ImageView
import app.simone.R
import app.simone.settings.model.SimonCreditsColor
import app.simone.shared.utils.AudioPlayer
import java.util.*
class CreditsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_credits)
SimonCreditsColor.allColors.forEach {
val image = findViewById(it.getImageViewId()) as ImageView
image.setImageResource(it.getImageId())
val button = findViewById(it.buttonId)
button.setOnTouchListener { _, motionEvent ->
when (motionEvent.action) {
MotionEvent.ACTION_DOWN ->
this.showPicture(it)
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL ->
this.hidePicture(it)
else -> false
}
}
}
val creditsButton = findViewById(R.id.credits_fab)
creditsButton.setOnClickListener { openAppInfo() }
}
fun openAppInfo() {
try {
val pInfo = this.packageManager.getPackageInfo(packageName, 0)
val textMessage = "Simone for Android v" + pInfo.versionName + "\n\n" +
"Homepage: https://simoneapp.github.io\n\n" +
"Simone is open source! Take a look to our repositories at https://github.com/simoneapp\n\n" +
"Built with ❤️ in San Marino 🇸🇲\n\n" +
"© " + Calendar.getInstance().get(Calendar.YEAR) + " Simone Dev Team. All rights reserved. \n\n" +
"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."
val alert = AlertDialog.Builder(this).create()
alert.setTitle("App Info")
alert.setMessage(textMessage)
alert.setButton(Dialog.BUTTON_POSITIVE, "Dismiss", DialogInterface.OnClickListener { _, i ->
//finish()
})
alert.show()
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
}
fun showPicture(color: SimonCreditsColor): Boolean {
val button = findViewById(color.buttonId) as Button
button.alpha = 0.4f
AudioPlayer().play(applicationContext, color.soundId)
return true
}
fun hidePicture(color: SimonCreditsColor): Boolean {
val button = findViewById(color.buttonId) as Button
button.alpha = 1.0f
return true
}
}
|
mit
|
7e7ec9cae0dbe02790ee156c01cb0283
| 37.806818 | 118 | 0.620498 | 4.684499 | false | false | false | false |
SimonVT/cathode
|
cathode-sync/src/main/java/net/simonvt/cathode/sync/trakt/UserList.kt
|
1
|
3615
|
/*
* Copyright (C) 2017 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.sync.trakt
import android.content.Context
import net.simonvt.cathode.api.body.ListInfoBody
import net.simonvt.cathode.api.enumeration.Privacy
import net.simonvt.cathode.api.enumeration.SortBy
import net.simonvt.cathode.api.enumeration.SortOrientation
import net.simonvt.cathode.api.service.UsersService
import net.simonvt.cathode.common.event.ErrorEvent
import net.simonvt.cathode.jobqueue.JobManager
import net.simonvt.cathode.provider.helper.ListDatabaseHelper
import net.simonvt.cathode.remote.sync.SyncUserActivity
import net.simonvt.cathode.sync.R
import timber.log.Timber
import java.io.IOException
import javax.inject.Inject
class UserList @Inject constructor(
private val context: Context,
private val usersServie: UsersService,
private val jobManager: JobManager,
private val listHelper: ListDatabaseHelper
) {
fun create(
name: String,
description: String,
privacy: Privacy,
displayNumbers: Boolean,
allowComments: Boolean,
sortBy: SortBy,
sortOrientation: SortOrientation
): Boolean {
try {
val call = usersServie.createList(
ListInfoBody(
name, description, privacy, displayNumbers, allowComments, sortBy,
sortOrientation
)
)
val response = call.execute()
if (response.isSuccessful) {
val userList = response.body()
listHelper.updateOrInsert(userList!!)
jobManager.addJob(SyncUserActivity())
return true
}
} catch (e: IOException) {
Timber.d(e, "Unable to create list %s", name)
}
ErrorEvent.post(context.getString(R.string.list_create_error, name))
return false
}
fun update(
traktId: Long,
name: String,
description: String,
privacy: Privacy,
displayNumbers: Boolean,
allowComments: Boolean,
sortBy: SortBy,
sortOrientation: SortOrientation
): Boolean {
try {
val call = usersServie.updateList(
traktId,
ListInfoBody(
name, description, privacy, displayNumbers, allowComments, sortBy,
sortOrientation
)
)
val response = call.execute()
if (response.isSuccessful) {
val userList = response.body()
listHelper.updateOrInsert(userList!!)
jobManager.addJob(SyncUserActivity())
return true
}
} catch (e: IOException) {
Timber.d(e, "Unable to create list %s", name)
}
ErrorEvent.post(context.getString(R.string.list_update_error, name))
return false
}
fun delete(traktId: Long, name: String): Boolean {
try {
val call = usersServie.deleteList(traktId)
val response = call.execute()
if (response.isSuccessful) {
val body = response.body()
jobManager.addJob(SyncUserActivity())
return true
}
} catch (e: IOException) {
Timber.d(e, "Unable to delete list %s", name)
}
ErrorEvent.post(context.getString(R.string.list_delete_error, name))
return false
}
}
|
apache-2.0
|
a646586536f3e9ce8a9981e591c12838
| 29.125 | 76 | 0.692946 | 4.179191 | false | false | false | false |
RoverPlatform/rover-android
|
experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/concerns/text/TextViewModel.kt
|
1
|
2878
|
package io.rover.sdk.experiences.ui.blocks.concerns.text
import android.graphics.Paint
import io.rover.sdk.core.data.domain.FontWeight
import io.rover.sdk.core.data.domain.Text
import io.rover.sdk.core.data.domain.TextAlignment
import io.rover.sdk.experiences.data.mapToFont
import io.rover.sdk.experiences.logging.log
import io.rover.sdk.experiences.services.MeasurementService
import io.rover.sdk.experiences.ui.RectF
import io.rover.sdk.experiences.ui.asAndroidColor
/**
* Text styling and size concerns.
*/
internal class TextViewModel(
private val styledText: Text,
private val measurementService: MeasurementService,
override val singleLine: Boolean = false,
override val centerVertically: Boolean = false
) : TextViewModelInterface {
override val text: String
get() = styledText.rawValue
override val fontAppearance: FontAppearance
// this maps from the Rover font weight to a named font-family and typeface style,
// which is what Android will ultimately expect since it doesn't explicitly support
// a font weight.
get() {
val font = styledText.font.weight.mapToFont()
return FontAppearance(
styledText.font.size,
font,
styledText.color.asAndroidColor(),
when (styledText.alignment) {
TextAlignment.Center -> Paint.Align.CENTER
TextAlignment.Left -> Paint.Align.LEFT
TextAlignment.Right -> Paint.Align.RIGHT
}
)
}
override fun boldRelativeToBlockWeight(): Font {
FontWeight.values().lastIndex
val addedOrdinal = styledText.font.weight.ordinal + 3
val addedWeight = if (addedOrdinal <= FontWeight.values().lastIndex) {
FontWeight.values()[addedOrdinal]
} else {
FontWeight.values().last()
}
return addedWeight.mapToFont()
}
override fun intrinsicHeight(bounds: RectF): Float {
val width = if (bounds.width() < 0) {
log.w("Bounds width somehow less than zero? Was ${bounds.width()}. Full bounds is $bounds. Bottoming out at zero. Can happen if Fill block shrank down to zero on narrower screen than expected.")
0f
} else bounds.width()
return measurementService.measureHeightNeededForRichText(
if (singleLine) {
// only measure a single line as configured.
// However, as things stand, no single-line TextViewModels are actually measured, so
// this case for intrinsicHeight() is only here for completeness.
"1"
} else {
styledText.rawValue
},
fontAppearance,
boldRelativeToBlockWeight(),
width
)
}
}
|
apache-2.0
|
fbfa33ed42ee3ee4b50cf13c7e6c2500
| 36.881579 | 207 | 0.633426 | 4.820771 | false | false | false | false |
Geobert/radis
|
app/src/main/kotlin/fr/geobert/radis/ui/CheckingOpDashboard.kt
|
1
|
2000
|
package fr.geobert.radis.ui
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import fr.geobert.radis.MainActivity
import fr.geobert.radis.R
import fr.geobert.radis.data.Operation
import fr.geobert.radis.db.OperationTable
import fr.geobert.radis.tools.TargetSumWatcher
import fr.geobert.radis.tools.extractSumFromStr
import fr.geobert.radis.tools.formatSum
import fr.geobert.radis.tools.getGroupSeparator
import fr.geobert.radis.tools.getSumSeparator
// TODO :�useless in this current form, deactivated. see later if I can do something with it
public class CheckingOpDashboard(val activity: MainActivity, layout: LinearLayout) {
val targetedSumEdt = layout.findViewById(R.id.targeted_sum) as EditText
val sumWatcher = TargetSumWatcher(getSumSeparator(), getGroupSeparator(), targetedSumEdt, this)
val statusLbl = layout.findViewById(R.id.checking_op_status) as TextView
init {
sumWatcher.setAutoNegate(false)
targetedSumEdt.setOnFocusChangeListener { view, b ->
if (b) {
sumWatcher.setAutoNegate(false)
(view as EditText).selectAll()
}
}
updateDisplay()
}
fun updateDisplay() {
val accountManager = activity.mAccountManager
val target = targetedSumEdt.text.toString().extractSumFromStr()
val checkedSum = accountManager.getCurrentAccountCheckedSum()
val total = accountManager.currentAccountStartSum - checkedSum
val diff = target - total
statusLbl.text = "%s\n%s".format((total / 100.0).formatSum(), (diff / 100.0).formatSum())
}
fun onCheckedChanged(op: Operation, b: Boolean) {
OperationTable.updateOpCheckedStatus(activity, op, b)
op.mIsChecked = b
updateDisplay()
}
fun onResume() {
targetedSumEdt.addTextChangedListener(sumWatcher)
}
fun onPause() {
targetedSumEdt.removeTextChangedListener(sumWatcher);
}
}
|
gpl-2.0
|
1f29f8881841a071dab3a39fd6fa70b6
| 34.052632 | 99 | 0.713714 | 4.269231 | false | false | false | false |
timusus/Shuttle
|
buildSrc/src/main/kotlin/dependencies/Dependencies.kt
|
1
|
11676
|
package dependencies
object Dependencies {
const val minSdk = 21
const val targetSdk = 28
const val compileSdk = 28
object Versions {
const val nanoHttp = "2.3.1"
const val crashlytics = "2.9.9"
const val dashClockApi = "2.0.0"
const val fastScroll = "1.0.20"
const val glide = "3.8.0"
const val glideOkhttp = "1.4.0@aar"
const val materialDialogs = "0.9.6.0"
const val permiso = "0.3.0"
const val streams = "1.2.1"
const val butterknife = "8.8.1"
const val butterknifeAnnotationProcessor = "8.8.1"
const val dagger = "2.21"
const val daggerAssistedInject = "0.3.2"
const val expandableRecyclerView = "3.0.0-RC1"
const val billing = "1.2"
}
// Kotlin
const val kotlin = "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${Plugins.Versions.kotlin}"
const val ktx = "androidx.core:core-ktx:${Plugins.Versions.ktx}"
// NanoHttp - https://github.com/NanoHttpd/nanohttpd (Various)
const val nanoHttp = "org.nanohttpd:nanohttpd-webserver:${Versions.nanoHttp}"
// Crashlytics - https://fabric.io/kits/android/crashlytics
const val crashlytics = "com.crashlytics.sdk.android:crashlytics:${Versions.crashlytics}"
// Dashclock - https://git.io/vix9g (Roman Nurik)
const val dashClockApi = "com.google.android.apps.dashclock:dashclock-api:${Versions.dashClockApi}"
// RecyclerView-FastScroll - https://git.io/vix5z
const val fastScroll = "com.simplecityapps:recyclerview-fastscroll:${Versions.fastScroll}"
// Glide - https://git.io/vtn9K (Bump)
const val glide = "com.github.bumptech.glide:glide:${Versions.glide}"
// Glide - OkHttp integration - https://git.io/vihvW (Bump)
const val glideOkhttp = "com.github.bumptech.glide:okhttp3-integration:${Versions.glideOkhttp}"
// Material Dialogs - https://git.io/vixHf (Aidan Follestad)
const val materialDialogs = "com.afollestad.material-dialogs:core:${Versions.materialDialogs}"
const val materialDialogCommons = "com.afollestad.material-dialogs:commons:${Versions.materialDialogs}"
// Permiso - https://git.io/vixQ4 (Greyson Parrelli)
const val permiso = "com.greysonparrelli.permiso:permiso:${Versions.permiso}"
// Streams Backport - https://git.io/vCazA (Victor Melnik)
const val streams = "com.annimon:stream:${Versions.streams}"
// Butterknife
const val butterknife = "com.jakewharton:butterknife:${Versions.butterknife}"
const val butterknifeAnnotationProcessor = "com.jakewharton:butterknife-compiler:${Versions.butterknifeAnnotationProcessor}"
// Dagger
const val dagger = "com.google.dagger:dagger:${Versions.dagger}"
const val daggerCompiler = "com.google.dagger:dagger-compiler:${Versions.dagger}"
const val daggerProcessor = "com.google.dagger:dagger-android-processor:${Versions.dagger}"
const val daggerSupport = "com.google.dagger:dagger-android-support:${Versions.dagger}"
// Dagger Assisted Inject
const val daggerAssistedInject = "com.squareup.inject:assisted-inject-annotations-dagger2:${Versions.daggerAssistedInject}"
const val daggerAssistedInjectProcessor = "com.squareup.inject:assisted-inject-processor-dagger2:${Versions.daggerAssistedInject}"
// Expandable Recycler View - https://github.com/thoughtbot/expandable-recycler-view
const val expandableRecyclerView = "com.bignerdranch.android:expandablerecyclerview:${Versions.expandableRecyclerView}"
// In app purchases
const val billing = "com.android.billingclient:billing:${Versions.billing}"
object Plugins {
object Versions {
const val androidGradlePlugin = "3.3.1"
const val kotlin = "1.3.21"
const val ktx = "1.0.0"
const val dexcountGradlePlugin = "0.8.6"
const val fabricGradlePlugin = "1.+"
const val gradleVersions = "0.20.0"
const val playServices = "4.2.0"
}
const val android = "com.android.tools.build:gradle:${Versions.androidGradlePlugin}"
const val kotlin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}"
const val dexcount = "com.getkeepsafe.dexcount:dexcount-gradle-plugin:${Versions.dexcountGradlePlugin}"
const val fabric = "io.fabric.tools:gradle:${Versions.fabricGradlePlugin}"
const val playPublisher = "com.github.triplet.play"
const val gradleVersions = "com.github.ben-manes:gradle-versions-plugin:${Versions.gradleVersions}"
const val playServices = "com.google.gms:google-services:${Versions.playServices}"
}
object Google {
object Versions {
const val supportLib = "28.0.0"
const val firebaseCore = "16.0.5"
const val firebaseRemoteConfig = "16.1.0"
const val constraintLayout = "2.0.0-alpha3"
const val chromeCastFramework = "16.1.0"
}
const val cardView = "com.android.support:cardview-v7:${Versions.supportLib}"
const val design = "com.android.support:design:${Versions.supportLib}"
const val palette = "com.android.support:palette-v7:${Versions.supportLib}"
const val recyclerView = "com.android.support:recyclerview-v7:${Versions.supportLib}"
const val supportv4 = "com.android.support:support-v4:${Versions.supportLib}"
const val firebaseCore = "com.google.firebase:firebase-core:${Versions.firebaseCore}"
const val firebaseRemoteConfig = "com.google.firebase:firebase-config:${Versions.firebaseRemoteConfig}"
const val appcompat = "com.android.support:appcompat-v7:${Versions.supportLib}"
const val mediarouter = "com.android.support:mediarouter-v7:${Versions.supportLib}"
const val constraintLayout = "com.android.support.constraint:constraint-layout:${Versions.constraintLayout}"
const val prefCompat = "com.android.support:preference-v7:${Versions.supportLib}"
const val prefCompatv14 = "com.android.support:preference-v14:${Versions.supportLib}"
const val chromeCastFramework = "com.google.android.gms:play-services-cast-framework:${Versions.chromeCastFramework}"
}
object Square {
object Versions {
const val haha = "2.0.4"
const val leakCanary = "1.6.3"
const val okio = "2.1.0"
const val okhttp = "3.11.0"
const val retrofit = "2.4.0"
const val retrofitGson = "2.4.0"
const val sqlBrite = "2.0.0"
}
const val haha = "com.squareup.haha:haha:${Versions.haha}"
const val leakCanaryDebug = "com.squareup.leakcanary:leakcanary-android:${Versions.leakCanary}"
const val leakCanaryRel = "com.squareup.leakcanary:leakcanary-android-no-op:${Versions.leakCanary}"
const val okio = "com.squareup.okio:okio:${Versions.okio}"
const val okhttp = "com.squareup.okhttp3:okhttp:${Versions.okhttp}"
const val retrofit = "com.squareup.retrofit2:retrofit:${Versions.retrofit}"
const val retrofitGson = "com.squareup.retrofit2:converter-gson:${Versions.retrofitGson}"
const val sqlBrite = "com.squareup.sqlbrite2:sqlbrite:${Versions.sqlBrite}"
}
object Rx {
object Versions {
const val rxAndroid = "2.1.0"
const val rxBinding = "2.2.0"
const val rxBindingAppCompat = "2.2.0"
const val rxJava = "2.1.9"
const val rxRelay = "2.1.0"
const val rxBroadcast = "2.0.0"
const val rxPrefs = "2.0.0"
const val rxKotlin = "2.3.0"
const val rxDogTag = "0.2.0"
}
// RxJava - https://git.io/vihv0 (ReactiveX)
const val rxAndroid = "io.reactivex.rxjava2:rxandroid:${Versions.rxAndroid}"
// rxBinding - https://git.io/vix5y (Jake Wharton)
const val rxBinding = "com.jakewharton.rxbinding2:rxbinding:${Versions.rxBinding}"
// rxBinding AppCompat - https://git.io/vix5y (Jake Wharton)
const val rxBindingAppCompat = "com.jakewharton.rxbinding2:rxbinding-appcompat-v7:${Versions.rxBindingAppCompat}"
// RxJava - https://git.io/rxjava (ReactiveX)
const val rxJava = "io.reactivex.rxjava2:rxjava:${Versions.rxJava}"
// RX Image Picker - https://git.io/vix5H (MLSDev )
const val rxImagePicker = "com.github.timusus:RxImagePicker:permission-check-fix-SNAPSHOT"
// RX Relay - https://github.com/JakeWharton/RxRelay
const val rxRelay = "com.jakewharton.rxrelay2:rxrelay:${Versions.rxRelay}"
// Rx Receivers - https://github.com/f2prateek/rx-receivers
const val rxBroadcast = "com.cantrowitz:rxbroadcast:${Versions.rxBroadcast}"
// Rx Prefs - https://github.com/f2prateek/rx-preferences
const val rxPrefs = "com.f2prateek.rx.preferences2:rx-preferences:${Versions.rxPrefs}"
const val rxKotlin = "io.reactivex.rxjava2:rxkotlin:${Versions.rxKotlin}"
const val rxDogTag = "com.uber.rxdogtag:rxdogtag:${Versions.rxDogTag}"
}
object Testing {
object Versions {
const val junit = "4.12"
const val espressoCore = "3.0.0"
const val assertj = "3.9.0"
// Mockito version restriction -- PowerMock does not fully support Mockito2 yet.
// https://github.com/powermock/powermock/wiki/Mockito2_maven
const val mockito = "2.8.47"
const val powermock = "1.7.1"
// Future note: PowerMock and Robolectric can't work together until Robolectric 3.3 is released
// https://github.com/robolectric/robolectric/wiki/Using-PowerMock
const val robolectric = "3.6.1"
}
// JUnit
const val junit = "junit:junit:${Versions.junit}"
// Espresso
const val espresso = "com.android.support.test.espresso:espresso-core:${Versions.espressoCore}"
// Mockito - https://github.com/mockito/mockito
const val mockito = "org.mockito:mockito-core:${Versions.mockito}"
// Powermock - https://github.com/powermock/powermock
const val powermock = "org.powermock:powermock-api-mockito2:${Versions.powermock}"
const val powermockjunit = "org.powermock:powermock-module-junit4:${Versions.powermock}"
// Robolectric - https://github.com/robolectric/robolectric
const val robolectric = "org.robolectric:robolectric:${Versions.robolectric}"
// AssertJ - http://joel-costigliola.github.io/assertj/
const val assertj = "org.assertj:assertj-core:${Versions.assertj}"
}
object Projects {
// Glide Palette - https://git.io/vix57 (Florent Champigny)
val glidePalette = ":libraries:glidepalette"
// Internal navigation library
val navigation = ":libraries:navigation"
// Internal recycler adapter library
val recyclerAdapter = ":libraries:recycler-adapter"
// Multi Sheet View
val multiSheetView = ":libraries:multisheetview"
// Aesthetic - Theming Engine
val aesthetic = ":libraries:aesthetic"
}
object BuildPlugins {
const val androidApplication = "com.android.application"
const val androidLibrary = "com.android.library"
const val kotlin = "kotlin-android"
const val kotlinAndroidExtensions = "kotlin-android-extensions"
const val kapt = "kotlin-kapt"
const val dexCount = "com.getkeepsafe.dexcount"
const val fabric = "io.fabric"
const val gradleVersions = "com.github.ben-manes.versions"
const val playServices = "com.google.gms.google-services"
}
}
|
gpl-3.0
|
38e9e8b40d7a8e84b7ede5870a207320
| 44.081081 | 134 | 0.666324 | 3.948597 | false | false | false | false |
clappr/clappr-android
|
clappr/src/main/kotlin/io/clappr/player/playback/NoOpPlayback.kt
|
1
|
743
|
package io.clappr.player.playback
import io.clappr.player.base.Options
import io.clappr.player.components.Playback
import io.clappr.player.components.PlaybackEntry
import io.clappr.player.components.PlaybackSupportCheck
class NoOpPlayback(source: String, mimeType: String? = null, options: Options = Options()) : Playback(source, mimeType, options, name = name, supportsSource = supportsSource) {
companion object {
const val name = "no_op"
val supportsSource: PlaybackSupportCheck = { _, _ -> true }
val entry = PlaybackEntry(
name = name,
supportsSource = supportsSource,
factory = { source, mimeType, options -> NoOpPlayback(source, mimeType, options) })
}
}
|
bsd-3-clause
|
3bf1bef0b85a35ec57a37186cc759a9e
| 42.764706 | 176 | 0.69179 | 4.345029 | false | false | false | false |
TeamAmaze/AmazeFileManager
|
app/src/main/java/com/amaze/filemanager/ui/dialogs/DecryptFingerprintDialog.kt
|
1
|
3131
|
/*
* Copyright (C) 2014-2022 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.amaze.filemanager.ui.dialogs
import android.content.Context
import android.content.Intent
import android.hardware.fingerprint.FingerprintManager
import android.os.Build
import android.view.View
import android.widget.Button
import androidx.annotation.RequiresApi
import com.afollestad.materialdialogs.MaterialDialog
import com.amaze.filemanager.R
import com.amaze.filemanager.filesystem.files.CryptUtil
import com.amaze.filemanager.filesystem.files.EncryptDecryptUtils.DecryptButtonCallbackInterface
import com.amaze.filemanager.ui.activities.MainActivity
import com.amaze.filemanager.ui.theme.AppTheme
import com.amaze.filemanager.utils.FingerprintHandler
import java.io.IOException
import java.security.GeneralSecurityException
/**
* Decrypt dialog prompt for user fingerprint.
*/
object DecryptFingerprintDialog {
/**
* Display dialog prompting user for fingerprint in order to decrypt file.
*/
@JvmStatic
@RequiresApi(api = Build.VERSION_CODES.M)
@Throws(
GeneralSecurityException::class,
IOException::class
)
fun show(
c: Context,
main: MainActivity,
intent: Intent,
appTheme: AppTheme,
decryptButtonCallbackInterface: DecryptButtonCallbackInterface
) {
val accentColor = main.accent
val builder = MaterialDialog.Builder(c)
builder.title(c.getString(R.string.crypt_decrypt))
val rootView = View.inflate(c, R.layout.dialog_decrypt_fingerprint_authentication, null)
val cancelButton = rootView.findViewById<Button>(R.id.button_decrypt_fingerprint_cancel)
cancelButton.setTextColor(accentColor)
builder.customView(rootView, true)
builder.canceledOnTouchOutside(false)
builder.theme(appTheme.getMaterialDialogTheme(c))
val dialog = builder.show()
cancelButton.setOnClickListener { v: View? -> dialog.cancel() }
val manager = c.getSystemService(FingerprintManager::class.java)
val handler = FingerprintHandler(c, intent, dialog, decryptButtonCallbackInterface)
val `object` = FingerprintManager.CryptoObject(CryptUtil.initCipher())
handler.authenticate(manager, `object`)
}
}
|
gpl-3.0
|
12e81ea94cb20424e9ef57c89ec117b5
| 39.662338 | 107 | 0.748962 | 4.485673 | false | false | false | false |
AoEiuV020/PaNovel
|
api/src/main/java/cc/aoeiuv020/panovel/api/site/liewen.kt
|
1
|
2042
|
package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
import cc.aoeiuv020.panovel.api.firstThreeIntPattern
import cc.aoeiuv020.panovel.api.firstTwoIntPattern
/**
* Created by AoEiuV020 on 2018.06.06-16:47:20.
*/
class Liewen : DslJsoupNovelContext() {init {
upkeep = false
site {
name = "猎文网"
baseUrl = "https://www.liewen.la"
logo = "https://www.liewen.la/images/logo.gif"
}
search {
get {
// https://www.liewen.la/search.php?keyword=%E9%83%BD%E5%B8%82
url = "/search.php"
data {
"q" to it
}
}
document {
items("div.result-list > div") {
name("> div.result-game-item-detail > h3 > a")
author("> div.result-game-item-detail > div > p:nth-child(1) > span:nth-child(2)")
}
}
}
// https://www.liewen.la/b/5/5024/
bookIdRegex = firstTwoIntPattern
detailPageTemplate = "/b/%s/"
detail {
document {
novel {
name("#info > h1")
author("#info > p:nth-child(2)", block = pickString("作\\s*者:(\\S*)"))
}
image("#fmimg > img")
update("#info > p:nth-child(4)", format = "yyyy-MM-dd HH:mm:ss", block = pickString("最后更新:(.*)"))
introduction("#intro")
}
}
chapters {
document {
items("#list > dl > dd > a")
lastUpdate("#info > p:nth-child(4)", format = "yyyy-MM-dd HH:mm:ss", block = pickString("最后更新:(.*)"))
}
}
// https://www.liewen.la/b/5/5024/13777631.html
bookIdWithChapterIdRegex = firstThreeIntPattern
contentPageTemplate = "/b/%s.html"
content {
document {
/*
有混杂这样的广告,不好处理,无视,
? ?猎文 w?w?w?. l?i?e?w?e?n?.cc
*/
items("#content")
}
}
}
}
|
gpl-3.0
|
44779c1fc4571074d01014dee98bd5bd
| 28.484848 | 113 | 0.507708 | 3.320819 | false | false | false | false |
soniccat/android-taskmanager
|
app_wordteacher/src/main/java/com/aglushkov/wordteacher/features/definitions/vm/DefinitionsVM.kt
|
1
|
2399
|
package com.aglushkov.wordteacher.features.definitions.vm
import android.app.Application
import android.util.Log
import androidx.lifecycle.*
import com.aglushkov.modelcore.resource.*
import com.aglushkov.modelcore_ui.extensions.getErrorString
import com.aglushkov.wordteacher.di.AppComponentOwner
import com.aglushkov.wordteacher.features.definitions.repository.WordRepository
import com.aglushkov.modelcore_ui.view.BaseViewItem
import com.aglushkov.wordteacher.model.WordTeacherWord
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
class DefinitionsVM(app: Application,
private val state: SavedStateHandle): AndroidViewModel(app) {
private val appComponent = (app as AppComponentOwner).appComponent
private val wordRepository: WordRepository = appComponent.getWordRepository()
private val innerDefinitions = MutableLiveData<Resource<List<BaseViewItem<*>>>>(Resource.Uninitialized())
val definitions: LiveData<Resource<List<BaseViewItem<*>>>> = innerDefinitions
// State
var word: String?
get() {
return state["word"]
}
set(value) {
state["word"] = value
}
init {
word?.let {
load(it)
} ?: run {
load("owl")
}
}
// Events
fun onTryAgainClicked() {
load(word!!)
}
// Actions
private fun load(word: String) {
this.word = word
innerDefinitions.load(wordRepository.scope, true) {
buildViewItems(wordRepository.define(word).flow.first {
if (it is Resource.Error) {
throw it.throwable
}
it.isLoaded()
}.data()!!)
}
}
private fun buildViewItems(words: List<WordTeacherWord>): List<BaseViewItem<*>> {
val items = mutableListOf<BaseViewItem<*>>()
for (word in words) {
items.add(WordTitleViewItem(word.word))
word.transcription?.let {
items.add(WordTranscriptionViewItem(it))
}
}
return items
}
fun getErrorText(res: Resource<*>): String? {
val hasConnection = appComponent.getConnectivityManager().isDeviceOnline
val hasResponse = true // TODO: handle error server response
return res.getErrorString(getApplication(), hasConnection, hasResponse)
}
}
|
mit
|
e5f03fd9bd027091a87979c9daa7a9b9
| 29.769231 | 109 | 0.644852 | 4.694716 | false | false | false | false |
LachlanMcKee/gsonpath
|
compiler/standard/src/main/java/gsonpath/adapter/common/SubTypeMetadataFactory.kt
|
1
|
4704
|
package gsonpath.adapter.common
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.WildcardTypeName
import gsonpath.ProcessingException
import gsonpath.adapter.util.NullableUtil
import gsonpath.annotation.GsonSubtype
import gsonpath.annotation.GsonSubtypeGetter
import gsonpath.model.FieldType
import gsonpath.util.MethodElementContent
import gsonpath.util.TypeHandler
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.TypeElement
interface SubTypeMetadataFactory {
fun getGsonSubType(
gsonSubType: GsonSubtype,
fieldType: FieldType.Other,
fieldName: String,
element: TypeElement): SubTypeMetadata
}
class SubTypeMetadataFactoryImpl(
private val typeHandler: TypeHandler) : SubTypeMetadataFactory {
override fun getGsonSubType(
gsonSubType: GsonSubtype,
fieldType: FieldType.Other,
fieldName: String,
element: TypeElement): SubTypeMetadata {
val jsonKeys = gsonSubType.jsonKeys
validateJsonKeys(element, jsonKeys)
return getGsonSubtypeGetterMethod(element)
.also { methodContent -> validateGsonSubtypeGetterMethod(element, methodContent) }
.let { methodContent -> createSubTypeMetadata(methodContent, jsonKeys) }
}
private fun validateJsonKeys(classElement: TypeElement, jsonKeys: Array<String>) {
if (jsonKeys.isEmpty()) {
throw ProcessingException("At least one json key must be defined for GsonSubType", classElement)
}
if (jsonKeys.any { it.isBlank() }) {
throw ProcessingException("A blank json key is not valid for GsonSubType", classElement)
}
jsonKeys.groupingBy { it }
.eachCount()
.filter { it.value > 1 }
.keys
.firstOrNull()
.let {
if (it != null) {
throw ProcessingException("The json key '\"$it\"' appears more than once", classElement)
}
}
}
private fun getGsonSubtypeGetterMethod(classElement: TypeElement): MethodElementContent {
return typeHandler.getMethods(classElement)
.filter { it.element.getAnnotation(GsonSubtypeGetter::class.java) != null }
.let {
when {
it.isEmpty() -> throw ProcessingException("An @GsonSubtypeGetter method must be defined. See the annotation for more information", classElement)
it.size > 1 -> throw ProcessingException("Only one @GsonSubtypeGetter method may exist", classElement)
else -> it.first()
}
}
}
private fun validateGsonSubtypeGetterMethod(classElement: TypeElement, methodContent: MethodElementContent) {
val actualReturnType = typeHandler.getTypeName(methodContent.generifiedElement.returnType)
val elementTypeName = TypeName.get(classElement.asType())
val expectedReturnType = ParameterizedTypeName.get(ClassName.get(Class::class.java), WildcardTypeName.subtypeOf(elementTypeName))
if (actualReturnType != expectedReturnType) {
throw ProcessingException("Incorrect return type for @GsonSubtypeGetter method. It must be Class<? extends ${classElement.simpleName}>", methodContent.element)
}
}
private fun createSubTypeMetadata(methodContent: MethodElementContent, jsonKeys: Array<String>): SubTypeMetadata {
val executableType = methodContent.element as ExecutableElement
val parameters = executableType.parameters
if (parameters.size != jsonKeys.size) {
throw ProcessingException("The parameters size does not match the json keys size", methodContent.element)
}
val fieldInfoList = parameters.zip(jsonKeys)
.mapIndexed { index, (parameter, key) ->
val nonNullAnnotationExists = parameter.annotationMirrors
.any { NullableUtil.isNullableKeyword(it.annotationType.asElement().simpleName.toString()) }
val parameterTypeName = TypeName.get(parameter.asType())
val nullable = !nonNullAnnotationExists && !parameterTypeName.isPrimitive
GsonSubTypeFieldInfo(key, "subTypeElement$index", parameterTypeName, nullable)
}
return SubTypeMetadata(
fieldInfoList,
methodContent.element.simpleName.toString()
)
}
}
|
mit
|
d4feb4f4f8b74af9662c8319f5eac0b1
| 42.165138 | 171 | 0.661352 | 5.425606 | false | false | false | false |
binout/soccer-league
|
src/main/kotlin/io/github/binout/soccer/interfaces/rest/LeagueMatchDateResource.kt
|
1
|
2804
|
/*
* Copyright 2016 Benoît Prioux
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.binout.soccer.interfaces.rest
import io.github.binout.soccer.application.*
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("rest/match-dates/league")
class LeagueMatchDateResource(
val allLeagueMatchDates: GetAllLeagueMatchDates,
val nextLeagueMatchDates: GetNextLeagueMatchDates,
val addLeagueMatchDate: AddLeagueMatchDate,
val getLeagueMatchDate: GetLeagueMatchDate,
val addPlayerToLeagueMatchDate: AddPlayerToLeagueMatchDate,
val removePlayerToLeagueMatchDate: RemovePlayerToLeagueMatchDate) {
@GetMapping
fun all(): List<RestMatchDate> = allLeagueMatchDates.execute().map { it.toRestModel() }
@GetMapping("next")
fun next(): List<RestMatchDate> = nextLeagueMatchDates.execute().map { it.toRestModel() }
@PutMapping("{dateParam}")
fun put(@PathVariable("dateParam") dateParam: String): ResponseEntity<*> {
val date = dateParam.toRestDate()
addLeagueMatchDate.execute(date.year, date.month, date.day)
return ResponseEntity.ok().build<Any>()
}
@GetMapping("{dateParam}")
fun get(@PathVariable("dateParam") dateParam: String): ResponseEntity<*> {
val date = dateParam.toRestDate()
return getLeagueMatchDate.execute(date.year, date.month, date.day)
?.let { ResponseEntity.ok(it.toRestModel()) }
?: ResponseEntity.notFound().build<Any>()
}
@PutMapping("{dateParam}/players/{name}")
fun putPlayers(@PathVariable("dateParam") dateParam: String, @PathVariable("name") name: String): ResponseEntity<*> {
val date = dateParam.toRestDate()
addPlayerToLeagueMatchDate.execute(name, date.year, date.month, date.day)
return ResponseEntity.ok().build<Any>()
}
@DeleteMapping("{dateParam}/players/{name}")
fun deletePlayers(@PathVariable("dateParam") dateParam: String, @PathVariable("name") name: String): ResponseEntity<*> {
val date = dateParam.toRestDate()
removePlayerToLeagueMatchDate.execute(name, date.year, date.month, date.day)
return ResponseEntity.ok().build<Any>()
}
}
|
apache-2.0
|
98f75ddc0136de297b7134644ba99453
| 41.469697 | 124 | 0.712451 | 4.202399 | false | false | false | false |
ofalvai/BPInfo
|
app/src/main/java/com/ofalvai/bpinfo/api/notice/NoticeClient.kt
|
1
|
3981
|
/*
* Copyright 2018 Olivér Falvai
*
* 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.ofalvai.bpinfo.api.notice
import android.content.Context
import android.content.SharedPreferences
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.VolleyError
import com.android.volley.toolbox.JsonArrayRequest
import com.ofalvai.bpinfo.Config
import com.ofalvai.bpinfo.R
import org.json.JSONArray
import timber.log.Timber
/**
* Fetches messages (notices) from our own backend. This is used to inform the users when the API is
* down or broken, without updating the app itself.
*/
class NoticeClient(
private val requestQueue: RequestQueue,
private val context: Context,
private val sharedPreferences: SharedPreferences
) : Response.ErrorListener {
private val isDebugActivated: Boolean
get() = sharedPreferences.getBoolean(
context.getString(R.string.pref_key_debug_mode), false
)
interface NoticeListener {
/**
* Called only when there's at least 1 notice to display
* @param noticeBody HTML string of 1 or more notices appended
*/
fun onNoticeResponse(noticeBody: String)
fun onNoNotice()
}
fun fetchNotice(noticeListener: NoticeListener, languageCode: String) {
val url = Config.Url.NOTICES
val request = JsonArrayRequest(
url,
{ response ->
onResponseCallback(response, noticeListener, languageCode)
},
this
)
// Invalidating Volley's cache for this URL to always get the latest notice
requestQueue.cache.remove(url)
requestQueue.add(request)
}
override fun onErrorResponse(error: VolleyError) {
// We don't display anything on the UI because this feature is meant to be silent
Timber.e(error.toString())
}
private fun onResponseCallback(
response: JSONArray,
listener: NoticeListener,
languageCode: String
) {
try {
val noticeBuilder = StringBuilder()
// The response contains an array of notices, we display the ones marked as enabled
for (i in 0 until response.length()) {
val notice = response.getJSONObject(i)
val enabled = notice.getBoolean(NoticeContract.ENABLED)
val debugEnabled = notice.getBoolean(NoticeContract.ENABLED_DEBUG)
// Only display notice if it's marked as enabled OR marked as enabled for debug mode
// and debug mode is actually turned on:
if (enabled || debugEnabled && isDebugActivated) {
val noticeText: String = if (languageCode == "hu") {
notice.getString(NoticeContract.TEXT_HU)
} else {
notice.getString(NoticeContract.TEXT_EN)
}
noticeBuilder.append(noticeText)
noticeBuilder.append("<br /><br />")
}
}
if (noticeBuilder.isNotEmpty()) {
listener.onNoticeResponse(noticeBuilder.toString())
} else {
listener.onNoNotice()
}
} catch (ex: Exception) {
// We don't display anything on the UI because this feature is meant to be silent
Timber.e(ex.toString())
}
}
}
|
apache-2.0
|
e8dab9a966018ff051d5f2c5dff6a157
| 34.221239 | 100 | 0.636432 | 4.853659 | false | false | false | false |
nickbutcher/plaid
|
core/src/main/java/io/plaidapp/core/ui/filter/FilterHolderInfo.kt
|
1
|
999
|
/*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.core.ui.filter
import androidx.recyclerview.widget.RecyclerView
class FilterHolderInfo : RecyclerView.ItemAnimator.ItemHolderInfo() {
var doEnable: Boolean = false
var doDisable: Boolean = false
var doHighlight: Boolean = false
companion object {
const val FILTER_ENABLED = 1
const val FILTER_DISABLED = 2
const val HIGHLIGHT = 3
}
}
|
apache-2.0
|
139c0fe96c2f139ce686121cccf3cce8
| 29.272727 | 75 | 0.721722 | 4.287554 | false | false | false | false |
ohmae/mmupnp
|
mmupnp/src/main/java/net/mm2d/upnp/internal/manager/EmptySubscribeManager.kt
|
1
|
868
|
/*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.manager
import net.mm2d.upnp.Service
internal class EmptySubscribeManager : SubscribeManager {
override fun checkEnabled() = throw IllegalStateException()
override fun getEventPort(): Int = 0
override fun initialize() = Unit
override fun start() = Unit
override fun stop() = Unit
override fun terminate() = Unit
override fun getSubscribeService(subscriptionId: String): Service? = null
override fun register(service: Service, timeout: Long, keep: Boolean) = Unit
override fun renew(service: Service, timeout: Long) = Unit
override fun setKeepRenew(service: Service, keep: Boolean) = Unit
override fun unregister(service: Service) = Unit
}
|
mit
|
8afa3e2330c961f9e12d597fb666915a
| 34.833333 | 80 | 0.726744 | 4.236453 | false | false | false | false |
soywiz/korge
|
korge-spine/src/commonMain/kotlin/com/esotericsoftware/spine/utils/SpineArrayExt.kt
|
1
|
1785
|
package com.esotericsoftware.spine.utils
import com.soywiz.kds.*
import kotlin.math.*
internal fun FloatArrayList.setSize(size: Int) = run { this.size = size }.let { this.data }
internal fun IntArrayList.setSize(size: Int) = run { this.size = size }.let { this.data }
internal fun ShortArrayList.setSize(size: Int) = run { this.size = size }.let { this }
internal fun FloatArrayList.toArray() = this.toFloatArray()
internal fun BooleanArrayList.setSize(size: Int) {
this.size = size
}
internal fun IntArrayList.toArray() = this.toIntArray()
internal fun ShortArrayList.toArray(): ShortArray = ShortArray(size) { this[it] }
internal fun <T> FastArrayList<T>.setAndGrow(index: Int, value: T) {
if (index >= size) {
val items = this as MutableList<Any?>
while (items.size <= index) items.add(null)
}
this[index] = value
}
internal fun <T> FastArrayList<T>.indexOfIdentity(value: T?): Int {
fastForEachWithIndex { index, current -> if (current === value) return index }
return -1
}
internal fun <T> FastArrayList<T>.removeValueIdentity(value: T?): Boolean {
val index = indexOfIdentity(value)
val found = index >= 0
if (found) removeAt(index)
return found
}
internal fun <T> FastArrayList<T>.containsIdentity(value: T?): Boolean = indexOfIdentity(value) >= 0
internal fun <T> FastArrayList<T>.shrink() = run { if (size != size) resize(size) }
internal fun <T> FastArrayList<T>.setSize(newSize: Int): FastArrayList<T> {
truncate(max(8, newSize))
return this
}
internal fun <T> FastArrayList<T>.resize(newSize: Int) = run {
truncate(newSize)
}
internal fun <T> FastArrayList<T>.truncate(newSize: Int) {
require(newSize >= 0) { "newSize must be >= 0: $newSize" }
while (size > newSize) removeAt(size - 1)
}
|
apache-2.0
|
177b41f9baa900475cd266500505c09c
| 34 | 100 | 0.689636 | 3.577154 | false | false | false | false |
Nanoware/Terasology
|
build-logic/src/main/kotlin/org/terasology/gradology/ModuleInfoException.kt
|
2
|
1176
|
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.gradology
import org.gradle.api.Project
import java.io.File
class ModuleInfoException(
cause: Throwable,
@Suppress("MemberVisibilityCanBePrivate") val file: File? = null,
private val project: Project? = null
) : RuntimeException(cause) {
override val message: String
get() {
// trying to get the fully-qualified-class-name-mess off the front and just show
// the useful part.
val detail = cause?.cause?.localizedMessage ?: cause?.localizedMessage
return "Error while reading module info from ${describeFile()}:\n ${detail}"
}
private fun describeFile(): String {
return if (project != null && file != null) {
project.rootProject.relativePath(file)
} else if (file != null) {
file.toString()
} else {
"[unnamed file]"
}
}
override fun toString(): String {
val causeType = cause?.let { it::class.simpleName }
return "ModuleInfoException(file=${describeFile()}, cause=${causeType})"
}
}
|
apache-2.0
|
34c99b6e4a491860bb40bb31fab5dcf7
| 31.666667 | 92 | 0.625 | 4.471483 | false | false | false | false |
shlusiak/Freebloks-Android
|
app/src/main/java/de/saschahlusiak/freebloks/statistics/StatisticsActivity.kt
|
1
|
9337
|
package de.saschahlusiak.freebloks.statistics
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.*
import android.widget.AdapterView.OnItemSelectedListener
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dagger.hilt.android.AndroidEntryPoint
import de.saschahlusiak.freebloks.R
import de.saschahlusiak.freebloks.database.HighScoreDB
import de.saschahlusiak.freebloks.model.GameMode
import de.saschahlusiak.freebloks.model.GameMode.Companion.from
import de.saschahlusiak.freebloks.model.Shape
import de.saschahlusiak.freebloks.databinding.StatisticsActivityBinding
import de.saschahlusiak.freebloks.utils.GooglePlayGamesHelper
import de.saschahlusiak.freebloks.utils.viewBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@AndroidEntryPoint
class StatisticsActivity : AppCompatActivity() {
private val db = HighScoreDB(this)
private var adapter: StatisticsAdapter? = null
private var gameMode = GameMode.GAMEMODE_4_COLORS_4_PLAYERS
private val values: Array<String?> = arrayOfNulls(9)
private var menu: Menu? = null
@Inject
lateinit var gameHelper: GooglePlayGamesHelper
private val binding by viewBinding(StatisticsActivityBinding::inflate)
private var googleSignInButton: View? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
db.open()
with(binding) {
val labels = resources.getStringArray(R.array.statistics_labels)
adapter = StatisticsAdapter(this@StatisticsActivity, labels, values)
listView.adapter = adapter
ok.setOnClickListener { finish() }
val prefs = PreferenceManager.getDefaultSharedPreferences(this@StatisticsActivity)
[email protected] = from(prefs.getInt("gamemode", GameMode.GAMEMODE_4_COLORS_4_PLAYERS.ordinal))
refreshData()
val actionBar = supportActionBar
if (actionBar == null) {
gameMode.setSelection([email protected])
gameMode.onItemSelectedListener =
object : OnItemSelectedListener {
override fun onItemSelected(adapter: AdapterView<*>?, view: View?, position: Int, id: Long) {
[email protected] = from(position)
refreshData()
}
override fun onNothingSelected(adapterView: AdapterView<*>?) {}
}
} else {
gameMode.visibility = View.GONE
val mSpinnerAdapter: SpinnerAdapter = ArrayAdapter.createFromResource(
this@StatisticsActivity, R.array.game_modes,
android.R.layout.simple_spinner_dropdown_item
)
actionBar.navigationMode = androidx.appcompat.app.ActionBar.NAVIGATION_MODE_LIST
actionBar.setListNavigationCallbacks(mSpinnerAdapter) { itemPosition, _ ->
[email protected] = from(itemPosition)
refreshData()
true
}
actionBar.setSelectedNavigationItem([email protected])
actionBar.setDisplayShowTitleEnabled(false)
actionBar.setDisplayHomeAsUpEnabled(true)
}
if (gameHelper.isAvailable) {
googleSignInButton = gameHelper.newSignInButton(this@StatisticsActivity)
googleSignInButton?.let {
signinStub.addView(
it,
ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
)
signinStub.isVisible = true
}
googleSignInButton?.setOnClickListener {
gameHelper.beginUserInitiatedSignIn(this@StatisticsActivity, REQUEST_SIGN_IN)
}
gameHelper.signedIn.observe(this@StatisticsActivity) { onGoogleAccountChanged(it) }
}
}
}
override fun onDestroy() {
super.onDestroy()
db.close()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.stats_optionsmenu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
val isSignedIn = gameHelper.isSignedIn
this.menu = menu
menu.findItem(R.id.signout).isVisible = isSignedIn
menu.findItem(R.id.achievements).isVisible = isSignedIn
menu.findItem(R.id.leaderboard).isVisible = isSignedIn
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
R.id.clear -> {
db.clearHighScores()
refreshData()
return true
}
R.id.signout -> {
gameHelper.startSignOut()
invalidateOptionsMenu()
return true
}
R.id.achievements -> {
if (gameHelper.isSignedIn) gameHelper.startAchievementsIntent(this, REQUEST_ACHIEVEMENTS)
return true
}
R.id.leaderboard -> {
if (gameHelper.isSignedIn) gameHelper.startLeaderboardIntent(this, getString(R.string.leaderboard_points_total), REQUEST_LEADERBOARD)
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
REQUEST_SIGN_IN -> gameHelper.onActivityResult(resultCode, data) { error ->
MaterialAlertDialogBuilder(this).apply {
setMessage(error ?: getString(R.string.google_play_games_signin_failed))
setPositiveButton(android.R.string.ok) { d, _ -> d.dismiss()}
show()
}
}
else -> super.onActivityResult(requestCode, resultCode, data)
}
}
private fun refreshData() = lifecycleScope.launch {
withContext(Dispatchers.IO) {
var games = db.getTotalNumberOfGames(gameMode)
val points = db.getTotalNumberOfPoints(gameMode)
val perfect = db.getNumberOfPerfectGames(gameMode)
var good = db.getNumberOfGoodGames(gameMode)
val stonesLeft = db.getTotalNumberOfStonesLeft(gameMode)
var stonesUsed = games * Shape.COUNT - stonesLeft
var i = 0
while (i < values.size) {
values[i] = ""
i++
}
values[0] = String.format("%d", games)
values[8] = String.format("%d", points)
if (games == 0) /* avoid divide by zero */ {
games = 1
stonesUsed = 0
}
good -= perfect
values[1] = String.format("%.1f%%", 100.0f * good.toFloat() / games.toFloat())
values[2] = String.format("%.1f%%", 100.0f * perfect.toFloat() / games.toFloat())
i = 0
while (i < 4) {
val n = db.getNumberOfPlace(gameMode, i + 1)
values[3 + i] = String.format("%.1f%%", 100.0f * n.toFloat() / games.toFloat())
i++
}
when (gameMode) {
GameMode.GAMEMODE_2_COLORS_2_PLAYERS,
GameMode.GAMEMODE_DUO,
GameMode.GAMEMODE_JUNIOR -> {
values[6] = null
values[5] = values[6]
}
else -> {
}
}
values[7] = String.format("%.1f%%", 100.0f * stonesUsed.toFloat() / games.toFloat() / Shape.COUNT.toFloat())
}
adapter?.notifyDataSetChanged()
}
private fun onGoogleAccountChanged(signedIn: Boolean) {
if (signedIn) {
googleSignInButton?.visibility = View.GONE
invalidateOptionsMenu()
gameHelper.submitScore(
getString(R.string.leaderboard_games_won),
db.getNumberOfPlace(null, 1).toLong())
gameHelper.submitScore(
getString(R.string.leaderboard_points_total),
db.getTotalNumberOfPoints(null).toLong())
} else {
googleSignInButton?.visibility = View.VISIBLE
invalidateOptionsMenu()
}
}
companion object {
private const val REQUEST_LEADERBOARD = 1
private const val REQUEST_ACHIEVEMENTS = 2
private const val REQUEST_SIGN_IN = 3
}
}
|
gpl-2.0
|
f6146cae67c24dc9050febefb6a8525f
| 38.400844 | 149 | 0.604048 | 5.118969 | false | false | false | false |
stripe/stripe-android
|
payments-core/src/main/java/com/stripe/android/payments/bankaccount/ui/CollectBankAccountViewModel.kt
|
1
|
8712
|
package com.stripe.android.payments.bankaccount.ui
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.createSavedStateHandle
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.CreationExtras
import com.stripe.android.core.Logger
import com.stripe.android.financialconnections.FinancialConnectionsSheetResult
import com.stripe.android.financialconnections.model.FinancialConnectionsSession
import com.stripe.android.payments.bankaccount.CollectBankAccountConfiguration
import com.stripe.android.payments.bankaccount.di.DaggerCollectBankAccountComponent
import com.stripe.android.payments.bankaccount.domain.AttachFinancialConnectionsSession
import com.stripe.android.payments.bankaccount.domain.CreateFinancialConnectionsSession
import com.stripe.android.payments.bankaccount.domain.RetrieveStripeIntent
import com.stripe.android.payments.bankaccount.navigation.CollectBankAccountContract
import com.stripe.android.payments.bankaccount.navigation.CollectBankAccountContract.Args.ForPaymentIntent
import com.stripe.android.payments.bankaccount.navigation.CollectBankAccountContract.Args.ForSetupIntent
import com.stripe.android.payments.bankaccount.navigation.CollectBankAccountResponse
import com.stripe.android.payments.bankaccount.navigation.CollectBankAccountResult
import com.stripe.android.payments.bankaccount.navigation.CollectBankAccountResult.Cancelled
import com.stripe.android.payments.bankaccount.navigation.CollectBankAccountResult.Completed
import com.stripe.android.payments.bankaccount.ui.CollectBankAccountViewEffect.OpenConnectionsFlow
import com.stripe.android.utils.requireApplication
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@Suppress("ConstructorParameterNaming", "LongParameterList")
internal class CollectBankAccountViewModel @Inject constructor(
// bound instances
private val args: CollectBankAccountContract.Args,
private val _viewEffect: MutableSharedFlow<CollectBankAccountViewEffect>,
// injected instances
private val createFinancialConnectionsSession: CreateFinancialConnectionsSession,
private val attachFinancialConnectionsSession: AttachFinancialConnectionsSession,
private val retrieveStripeIntent: RetrieveStripeIntent,
private val savedStateHandle: SavedStateHandle,
private val logger: Logger
) : ViewModel() {
private var hasLaunched: Boolean
get() = savedStateHandle.get<Boolean>(KEY_HAS_LAUNCHED) == true
set(value) = savedStateHandle.set(KEY_HAS_LAUNCHED, value)
val viewEffect: SharedFlow<CollectBankAccountViewEffect> = _viewEffect
init {
if (hasLaunched.not()) {
viewModelScope.launch {
createFinancialConnectionsSession()
}
}
}
private suspend fun createFinancialConnectionsSession() {
when (val configuration = args.configuration) {
is CollectBankAccountConfiguration.USBankAccount -> when (args) {
is ForPaymentIntent -> createFinancialConnectionsSession.forPaymentIntent(
publishableKey = args.publishableKey,
stripeAccountId = args.stripeAccountId,
clientSecret = args.clientSecret,
customerName = configuration.name,
customerEmail = configuration.email
)
is ForSetupIntent -> createFinancialConnectionsSession.forSetupIntent(
publishableKey = args.publishableKey,
stripeAccountId = args.stripeAccountId,
clientSecret = args.clientSecret,
customerName = configuration.name,
customerEmail = configuration.email
)
}
.mapCatching { requireNotNull(it.clientSecret) }
.onSuccess { financialConnectionsSessionSecret: String ->
logger.debug("Bank account session created! $financialConnectionsSessionSecret.")
hasLaunched = true
_viewEffect.emit(
OpenConnectionsFlow(
financialConnectionsSessionSecret = financialConnectionsSessionSecret,
publishableKey = args.publishableKey,
stripeAccountId = args.stripeAccountId
)
)
}
.onFailure { finishWithError(it) }
}
}
fun onConnectionsResult(result: FinancialConnectionsSheetResult) {
hasLaunched = false
viewModelScope.launch {
when (result) {
is FinancialConnectionsSheetResult.Canceled ->
finishWithResult(Cancelled)
is FinancialConnectionsSheetResult.Failed ->
finishWithError(result.error)
is FinancialConnectionsSheetResult.Completed ->
if (args.attachToIntent) {
attachFinancialConnectionsSessionToIntent(result.financialConnectionsSession)
} else {
finishWithFinancialConnectionsSession(result.financialConnectionsSession)
}
}
}
}
private suspend fun finishWithResult(result: CollectBankAccountResult) {
_viewEffect.emit(CollectBankAccountViewEffect.FinishWithResult(result))
}
private fun finishWithFinancialConnectionsSession(financialConnectionsSession: FinancialConnectionsSession) {
viewModelScope.launch {
retrieveStripeIntent(
args.publishableKey,
args.clientSecret
).onSuccess { stripeIntent ->
finishWithResult(
Completed(
CollectBankAccountResponse(
intent = stripeIntent,
financialConnectionsSession = financialConnectionsSession
)
)
)
}.onFailure {
finishWithError(it)
}
}
}
private fun attachFinancialConnectionsSessionToIntent(financialConnectionsSession: FinancialConnectionsSession) {
viewModelScope.launch {
when (args) {
is ForPaymentIntent -> attachFinancialConnectionsSession.forPaymentIntent(
publishableKey = args.publishableKey,
stripeAccountId = args.stripeAccountId,
clientSecret = args.clientSecret,
linkedAccountSessionId = financialConnectionsSession.id
)
is ForSetupIntent -> attachFinancialConnectionsSession.forSetupIntent(
publishableKey = args.publishableKey,
stripeAccountId = args.stripeAccountId,
clientSecret = args.clientSecret,
linkedAccountSessionId = financialConnectionsSession.id
)
}
.mapCatching {
Completed(
CollectBankAccountResponse(
it,
financialConnectionsSession
)
)
}
.onSuccess { result: Completed ->
logger.debug("Bank account session attached to intent!!")
finishWithResult(result)
}
.onFailure { finishWithError(it) }
}
}
private suspend fun finishWithError(throwable: Throwable) {
logger.error("Error", Exception(throwable))
finishWithResult(CollectBankAccountResult.Failed(throwable))
}
class Factory(
private val argsSupplier: () -> CollectBankAccountContract.Args,
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T {
val application = extras.requireApplication()
val savedStateHandle = extras.createSavedStateHandle()
return DaggerCollectBankAccountComponent.builder()
.savedStateHandle(savedStateHandle)
.application(application)
.viewEffect(MutableSharedFlow())
.configuration(argsSupplier()).build()
.viewModel as T
}
}
companion object {
private const val KEY_HAS_LAUNCHED = "key_has_launched"
}
}
|
mit
|
73cf2e2a9e1fcfd95598c70dfdcf0e1a
| 44.375 | 117 | 0.65427 | 6.249641 | false | false | false | false |
kotlinz/kotlinz
|
src/main/kotlin/com/github/kotlinz/kotlinz/data/kleisli/Kleisli.kt
|
1
|
1361
|
package com.github.kotlinz.kotlinz.data.kleisli
import com.github.kotlinz.kotlinz.K1
import com.github.kotlinz.kotlinz.K2
import com.github.kotlinz.kotlinz.K3
import com.github.kotlinz.kotlinz.type.monad.Monad
class Kleisli<F, A, B>(val monad: Monad<F>, val run: (A) -> K1<F, B>) : K3<Kleisli.T, F, A, B> {
class T
companion object {
fun <F, A, B> narrow(v: K1<K2<T, F, A>, B>) : Kleisli<F, A, B> = v as Kleisli<F, A, B>
fun <F, A> id(monad: Monad<F>): Kleisli<F, A, A> = arrow(monad).id()
fun <F, A, B> arr(monad: Monad<F>, f: (A) -> B): Kleisli<F, A, B> = arrow(monad).arr(f)
fun <F, A, B> swap(monad: Monad<F>): K3<T, F, Pair<A, B>, Pair<B, A>> = arrow(monad).swap()
private fun <F> arrow(monad: Monad<F>) = object: KleisliArrow<F> { override val monad = monad }
}
fun <C> compose(g: K3<Kleisli.T, F, B, C>): Kleisli<F, A, C> = arrow().compose(g, this)
fun <C> first(): Kleisli<F, Pair<A, C>, Pair<B, C>> = arrow().first(this)
fun <C> second(): K3<T, F, Pair<C, A>, Pair<C, B>> = arrow().second(this)
fun <C, D> split(g: K3<T, F, C, D>): K3<T, F, Pair<A, C>, Pair<B, D>> = arrow().split(this, g)
fun <C>combine(g: K3<T, F, A, C>): K3<T, F, A, Pair<B, C>> = arrow().combine(this, g)
private fun arrow() = object: KleisliArrow<F> { override val monad = [email protected] }
}
|
apache-2.0
|
d283ee0bc18e312452fada98cdcef03b
| 47.607143 | 103 | 0.584864 | 2.358752 | false | false | false | false |
AndroidX/androidx
|
glance/glance-appwidget/integration-tests/template-demos/src/main/java/androidx/glance/appwidget/template/demos/GalleryDemoWidget.kt
|
3
|
6013
|
/*
* Copyright 2022 The Android 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.
*/
package androidx.glance.appwidget.template.demos
import androidx.compose.runtime.Composable
import androidx.glance.GlanceTheme
import androidx.glance.ImageProvider
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import androidx.glance.appwidget.action.actionRunCallback
import androidx.glance.appwidget.template.GalleryTemplate
import androidx.glance.appwidget.template.GlanceTemplateAppWidget
import androidx.glance.template.ActionBlock
import androidx.glance.template.AspectRatio
import androidx.glance.template.GalleryTemplateData
import androidx.glance.template.HeaderBlock
import androidx.glance.template.ImageBlock
import androidx.glance.template.ImageSize
import androidx.glance.template.TemplateImageWithDescription
import androidx.glance.template.TemplateText
import androidx.glance.template.TemplateTextButton
import androidx.glance.template.TextBlock
import androidx.glance.template.TextType
/**
* Gallery demo for the default Small sized images with 1:1 aspect ratio and left-to-right main
* text/image block flow using data and gallery template from [BaseGalleryTemplateWidget].
*/
class SmallGalleryTemplateDemoWidget : BaseGalleryTemplateWidget() {
@Composable
override fun TemplateContent() = GalleryTemplateContent()
}
/**
* Gallery demo for the Medium sized images with 16:9 aspect ratio and right-to-left main
* text/image block flow using data and gallery template from [BaseGalleryTemplateWidget].
*/
class MediumGalleryTemplateDemoWidget : BaseGalleryTemplateWidget() {
@Composable
override fun TemplateContent() =
GalleryTemplateContent(ImageSize.Medium, AspectRatio.Ratio16x9, false)
}
/**
* Gallery demo for the Large sized images with 2:3 aspect ratio and left-to-right main
* text/image block flow using data and gallery template from [BaseGalleryTemplateWidget].
*/
class LargeGalleryTemplateDemoWidget : BaseGalleryTemplateWidget() {
@Composable
override fun TemplateContent() = GalleryTemplateContent(ImageSize.Large, AspectRatio.Ratio2x3)
}
class SmallImageGalleryReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = SmallGalleryTemplateDemoWidget()
}
class MediumImageGalleryReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = MediumGalleryTemplateDemoWidget()
}
class LargeImageGalleryReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = LargeGalleryTemplateDemoWidget()
}
/**
* Base Gallery Demo widget binding [GalleryTemplateData] to [GalleryTemplate] layout.
* It is overridable by gallery image aspect ratio, image size, and main blocks ordering.
*/
abstract class BaseGalleryTemplateWidget : GlanceTemplateAppWidget() {
@Composable
internal fun GalleryTemplateContent(
imageSize: ImageSize = ImageSize.Small,
aspectRatio: AspectRatio = AspectRatio.Ratio1x1,
isMainTextBlockFirst: Boolean = true,
) {
GlanceTheme {
val galleryContent = mutableListOf<TemplateImageWithDescription>()
for (i in 1..30) {
galleryContent.add(
TemplateImageWithDescription(
ImageProvider(R.drawable.palm_leaf),
"gallery image $i"
)
)
}
GalleryTemplate(
GalleryTemplateData(
header = HeaderBlock(
text = TemplateText("Gallery Template example"),
icon = TemplateImageWithDescription(
ImageProvider(R.drawable.ic_widgets),
"test logo"
),
),
mainTextBlock = TextBlock(
text1 = TemplateText("Title1", TextType.Title),
text2 = TemplateText("Headline1", TextType.Headline),
text3 = TemplateText("Label1", TextType.Label),
priority = if (isMainTextBlockFirst) 0 else 1,
),
mainImageBlock = ImageBlock(
images = listOf(
TemplateImageWithDescription(
ImageProvider(R.drawable.palm_leaf),
"test image"
)
),
size = ImageSize.Medium,
priority = if (isMainTextBlockFirst) 1 else 0,
),
mainActionBlock = ActionBlock(
actionButtons = listOf(
TemplateTextButton(
actionRunCallback<DefaultNoopAction>(),
"Act1"
),
TemplateTextButton(
actionRunCallback<DefaultNoopAction>(),
"Act2"
),
),
),
galleryImageBlock = ImageBlock(
images = galleryContent,
aspectRatio = aspectRatio,
size = imageSize,
),
)
)
}
}
}
|
apache-2.0
|
08008514656a0307d769164f3063e532
| 39.904762 | 98 | 0.631133 | 5.417117 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/ide/actions/RsCreateFileAction.kt
|
3
|
1657
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.ide.actions.CreateFileFromTemplateAction
import com.intellij.ide.actions.CreateFileFromTemplateDialog
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.psi.PsiDirectory
import org.rust.cargo.project.model.cargoProjects
import org.rust.ide.icons.RsIcons
class RsCreateFileAction : CreateFileFromTemplateAction(CAPTION, "", RsIcons.RUST_FILE),
DumbAware {
override fun getActionName(directory: PsiDirectory?, newName: String, templateName: String?): String = CAPTION
override fun isAvailable(dataContext: DataContext): Boolean {
if (!super.isAvailable(dataContext)) return false
val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return false
val vFile = CommonDataKeys.VIRTUAL_FILE.getData(dataContext) ?: return false
return project.cargoProjects.allProjects.any {
val rootDir = it.rootDir ?: return@any false
VfsUtil.isAncestor(rootDir, vFile, false)
}
}
override fun buildDialog(project: Project, directory: PsiDirectory, builder: CreateFileFromTemplateDialog.Builder) {
builder.setTitle(CAPTION)
.addKind("Empty file", RsIcons.RUST_FILE, "Rust File")
}
private companion object {
private const val CAPTION = "Rust File"
}
}
|
mit
|
f65788ddddafd08524d56f650cae6951
| 37.534884 | 120 | 0.738081 | 4.602778 | false | false | false | false |
mvarnagiris/expensius
|
models/src/test/kotlin/com/mvcoding/expensius/model/extensions/TransactionExtensions.kt
|
1
|
2731
|
/*
* Copyright (C) 2017 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.model.extensions
import com.mvcoding.expensius.model.*
import java.math.BigDecimal
fun aTransactionId() = TransactionId(aStringId())
fun aTransactionType() = TransactionType.values().aRandomItem()
fun aTransactionState() = TransactionState.values().aRandomItem()
fun aTimestamp() = Timestamp(aLongTimestamp())
fun anAmount() = BigDecimal(anInt(100))
fun aMoney() = Money(anAmount(), aCurrency())
fun aNote() = Note(aString("note"))
fun aTransaction() = Transaction(
aTransactionId(),
aModelState(),
aTransactionType(),
aTransactionState(),
aTimestamp(),
aMoney(),
someTags(),
aNote())
fun someTransactions() = listOf(aTransaction(), aTransaction(), aTransaction())
fun someMoneys() = aRange().map { aMoney() }
fun Money.withCurrency(currency: Currency) = copy(currency = currency)
fun aBasicTransaction() = BasicTransaction(
aTransactionId(),
aModelState(),
aTransactionType(),
aTransactionState(),
aTimestamp(),
aMoney(),
someTagsIds(),
aNote())
fun aCreateTransaction() = CreateTransaction(aTransactionType(), aTransactionState(), aTimestamp(), aMoney(), someTags(), aNote())
fun Transaction.withAmount(amount: Int) = withAmount(amount.toDouble())
fun Transaction.withAmount(amount: Double) = copy(money = money.copy(amount = BigDecimal.valueOf(amount)))
fun Transaction.withAmount(amount: BigDecimal) = copy(money = money.copy(amount = amount))
fun Transaction.withTimestamp(millis: Long) = copy(timestamp = Timestamp(millis))
fun Transaction.withTimestamp(timestamp: Timestamp) = copy(timestamp = timestamp)
fun Transaction.withTransactionType(transactionType: TransactionType) = copy(transactionType = transactionType)
fun Transaction.withTransactionState(transactionState: TransactionState) = copy(transactionState = transactionState)
fun Transaction.withTags(tags: Set<Tag>) = copy(tags = tags)
fun Transaction.withNote(note: String) = copy(note = Note(note))
fun Transaction.withCurrency(currency: Currency) = copy(money = money.withCurrency(currency))
fun Note.withText(text: String) = copy(text = text)
|
gpl-3.0
|
f1bd5d83daa36a5350f70e1f55ef437d
| 41.6875 | 130 | 0.733065 | 4.280564 | false | false | false | false |
HabitRPG/habitrpg-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/IntroActivity.kt
|
1
|
5574
|
package com.habitrpg.android.habitica.ui.activities
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ContentRepository
import com.habitrpg.android.habitica.databinding.ActivityIntroBinding
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.ui.fragments.setup.IntroFragment
import com.viewpagerindicator.IconPagerAdapter
import javax.inject.Inject
class IntroActivity : BaseActivity(), View.OnClickListener, ViewPager.OnPageChangeListener {
private lateinit var binding: ActivityIntroBinding
@Inject
lateinit var contentRepository: ContentRepository
override fun getLayoutResId(): Int {
return R.layout.activity_intro
}
override fun getContentView(): View {
binding = ActivityIntroBinding.inflate(layoutInflater)
return binding.root
}
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupIntro()
binding.viewPagerIndicator.setViewPager(binding.viewPager)
binding.skipButton.setOnClickListener(this)
binding.finishButton.setOnClickListener(this)
compositeSubscription.add(contentRepository.retrieveContent().subscribe({ }, RxErrorHandler.handleEmptyError()))
window.statusBarColor = ContextCompat.getColor(this, R.color.black_20_alpha)
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
private fun setupIntro() {
binding.viewPager.adapter = PagerAdapter(supportFragmentManager)
binding.viewPager.addOnPageChangeListener(this)
}
override fun onClick(v: View) {
finishIntro()
}
private fun finishIntro() {
val intent = Intent(this, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
this.startActivity(intent)
overridePendingTransition(0, R.anim.activity_fade_out)
finish()
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { /* no-on */ }
override fun onPageSelected(position: Int) {
if (position == 2) {
binding.finishButton.visibility = View.VISIBLE
} else {
binding.finishButton.visibility = View.GONE
}
}
override fun onPageScrollStateChanged(state: Int) { /* no-on */ }
private inner class PagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT), IconPagerAdapter {
override fun getItem(position: Int): Fragment {
val fragment = IntroFragment()
configureFragment(fragment, position)
return fragment
}
override fun getIconResId(index: Int): Int {
return R.drawable.indicator_diamond
}
override fun getCount(): Int {
return 3
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val item = super.instantiateItem(container, position)
if (item is IntroFragment) {
configureFragment(item, position)
}
return item
}
}
private fun configureFragment(fragment: IntroFragment, position: Int) {
when (position) {
0 -> {
fragment.setImage(ResourcesCompat.getDrawable(resources, R.drawable.intro_1, null))
fragment.setSubtitle(getString(R.string.intro_1_subtitle))
fragment.setTitleImage(ResourcesCompat.getDrawable(resources, R.drawable.intro_1_title, null))
fragment.setDescription(getString(R.string.intro_1_description, getString(R.string.habitica_user_count)))
fragment.setBackgroundColor(ContextCompat.getColor(this@IntroActivity, R.color.brand_300))
}
1 -> {
fragment.setImage(ResourcesCompat.getDrawable(resources, R.drawable.intro_2, null))
fragment.setSubtitle(getString(R.string.intro_2_subtitle))
fragment.setTitle(getString(R.string.intro_2_title))
fragment.setDescription(getString(R.string.intro_2_description))
fragment.setBackgroundColor(ContextCompat.getColor(this@IntroActivity, R.color.blue_10))
}
2 -> {
fragment.setImage(ResourcesCompat.getDrawable(resources, R.drawable.intro_3, null))
fragment.setSubtitle(getString(R.string.intro_3_subtitle))
fragment.setTitle(getString(R.string.intro_3_title))
fragment.setDescription(getString(R.string.intro_3_description))
fragment.setBackgroundColor(ContextCompat.getColor(this@IntroActivity, R.color.red_100))
}
}
}
}
|
gpl-3.0
|
83a964d7f5482c28e5057352996e8478
| 38.391304 | 148 | 0.677969 | 4.893766 | false | false | false | false |
kiruto/debug-bottle
|
components/src/main/kotlin/com/exyui/android/debugbottle/components/fragments/__DisplayBlockFragment.kt
|
1
|
18953
|
package com.exyui.android.debugbottle.components.fragments
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.annotation.IdRes
import android.text.Html
import android.text.TextUtils
import android.text.format.DateUtils
import android.util.Log
import android.view.*
import android.widget.*
import com.exyui.android.debugbottle.components.R
import com.exyui.android.debugbottle.core.__CanaryCoreMgr
import com.exyui.android.debugbottle.core.__LogWriter
import com.exyui.android.debugbottle.core.log.__Block
import com.exyui.android.debugbottle.core.log.__BlockCanaryInternals
import com.exyui.android.debugbottle.core.log.__ProcessUtils
import com.exyui.android.debugbottle.ui.layout.__DisplayBlockActivity
import com.exyui.android.debugbottle.views.__DisplayLeakConnectorView
import com.exyui.android.debugbottle.views.__MoreDetailsView
import java.util.*
import java.util.concurrent.Executor
import java.util.concurrent.Executors
/**
* Created by yuriel on 9/3/16.
*/
class __DisplayBlockFragment: __ContentFragment() {
companion object {
private val TAG = "__DisplayBlockActivity"
private val SHOW_BLOCK_EXTRA = "show_latest"
val SHOW_BLOCK_EXTRA_KEY = "BlockStartTime"
@JvmOverloads fun createPendingIntent(context: Context, blockStartTime: String? = null): PendingIntent {
val intent = Intent(context, __DisplayBlockActivity::class.java)
intent.putExtra(SHOW_BLOCK_EXTRA, blockStartTime)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
return PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
internal fun classSimpleName(className: String): String {
val separator = className.lastIndexOf('.')
return if (separator == -1) {
className
} else {
className.substring(separator + 1)
}
}
}
private var rootView: ViewGroup? = null
private val mBlockEntries: MutableList<__Block> by lazy { ArrayList<__Block>() }
private var mBlockStartTime: String? = null
private val mListView by lazy { findViewById(R.id.__dt_canary_display_leak_list) as ListView }
private val mFailureView by lazy { findViewById(R.id.__dt_canary_display_leak_failure) as TextView }
private val mActionButton by lazy { findViewById(R.id.__dt_canary_action) as Button }
private val mMaxStoredBlockCount by lazy { resources.getInteger(R.integer.__block_canary_max_stored_count) }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val rootView = inflater.inflate(R.layout.__dt_canary_display_leak_light, container, false)
this.rootView = rootView as ViewGroup
if (savedInstanceState != null) {
mBlockStartTime = savedInstanceState.getString(SHOW_BLOCK_EXTRA_KEY)
} else {
val intent = context?.intent
if (intent?.hasExtra(SHOW_BLOCK_EXTRA) == true) {
mBlockStartTime = intent?.getStringExtra(SHOW_BLOCK_EXTRA)
}
}
setHasOptionsMenu(true)
updateUi()
return rootView
}
// No, it's not deprecated. Android lies.
// override fun onRetainNonConfigurationInstance(): Any {
// return mBlockEntries as Any
// }
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(SHOW_BLOCK_EXTRA_KEY, mBlockStartTime)
}
override fun onResume() {
super.onResume()
LoadBlocks.load(this)
}
// override fun setTheme(resid: Int) {
// // We don't want this to be called with an incompatible theme.
// // This could happen if you implement runtime switching of themes
// // using ActivityLifecycleCallbacks.
// if (resid != R.style.__dt_canary_BlockCanary_Base) {
// return
// }
// super.setTheme(resid)
// }
override fun onDestroy() {
super.onDestroy()
LoadBlocks.forgetActivity()
}
override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
val block = getBlock(mBlockStartTime)
if (block != null) {
menu.add(R.string.__block_canary_share_leak).setOnMenuItemClickListener {
shareBlock(block)
true
}
menu.add(R.string.__block_canary_share_stack_dump).setOnMenuItemClickListener {
shareHeapDump(block)
true
}
//return true
}
//return false
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
mBlockStartTime = null
updateUi()
}
return true
}
override fun onBackPressed(): Boolean {
return if (mBlockStartTime != null) {
mBlockStartTime = null
updateUi()
true
} else {
super.onBackPressed()
}
}
private fun shareBlock(block: __Block) {
val leakInfo = block.toString()
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_TEXT, leakInfo)
startActivity(Intent.createChooser(intent, getString(R.string.__block_canary_share_with)))
}
private fun shareHeapDump(block: __Block) {
val heapDumpFile = block.logFile
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
heapDumpFile?.setReadable(true, false)
}
val intent = Intent(Intent.ACTION_SEND)
intent.type = "application/octet-stream"
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(heapDumpFile))
startActivity(Intent.createChooser(intent, getString(R.string.__block_canary_share_with)))
}
private fun updateUi() {
val block = getBlock(mBlockStartTime)
if (block == null) {
mBlockStartTime = null
}
// Reset to defaults
mListView.visibility = View.VISIBLE
mFailureView.visibility = View.GONE
if (block != null) {
renderBlockDetail(block)
} else {
renderBlockList()
}
}
private fun renderBlockList() {
val listAdapter = mListView.adapter
if (listAdapter is BlockListAdapter) {
listAdapter.notifyDataSetChanged()
} else {
val adapter = BlockListAdapter()
mListView.adapter = adapter
mListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
mBlockStartTime = mBlockEntries[position].timeStart
updateUi()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
context?.invalidateOptionsMenu()
//val actionBar = actionBar
//actionBar?.setDisplayHomeAsUpEnabled(false)
}
//title = getString(R.string.__block_canary_block_list_title, packageName)
mActionButton.setText(R.string.__block_canary_delete_all)
mActionButton.setOnClickListener {
__LogWriter.deleteLogFiles()
mBlockEntries.clear()
updateUi()
}
}
mActionButton.visibility = if (mBlockEntries.isEmpty()) View.GONE else View.VISIBLE
}
private fun renderBlockDetail(block: __Block?) {
val listAdapter = mListView.adapter
val adapter: __BlockDetailAdapter
if (listAdapter is __BlockDetailAdapter) {
adapter = listAdapter
} else {
adapter = __BlockDetailAdapter()
mListView.adapter = adapter
mListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> adapter.toggleRow(position) }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
context?.invalidateOptionsMenu()
//val actionBar = actionBar
//actionBar?.setDisplayHomeAsUpEnabled(true)
}
mActionButton.visibility = View.VISIBLE
mActionButton.setText(R.string.__block_canary_delete)
mActionButton.setOnClickListener {
if (block != null) {
block.logFile?.delete()
mBlockStartTime = null
mBlockEntries.remove(block)
updateUi()
}
}
}
adapter.update(block)
//title = getString(R.string.__block_canary_class_has_blocked, block!!.timeCost)
}
private fun getBlock(startTime: String?): __Block? {
if (TextUtils.isEmpty(startTime)) {
return null
}
return mBlockEntries.firstOrNull { it.timeStart == startTime }
}
private fun findViewById(@IdRes id: Int): View? = rootView?.findViewById(id)
internal inner class BlockListAdapter : BaseAdapter() {
override fun getCount(): Int = mBlockEntries.size
override fun getItem(position: Int): __Block = mBlockEntries[position]
override fun getItemId(position: Int): Long = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var view = convertView
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.__dt_canary_block_row, parent, false)
}
val titleView = view!!.findViewById(R.id.__dt_canary_row_text) as TextView
val timeView = view.findViewById(R.id.__dt_canary_row_time) as TextView
val block = getItem(position)
val index: String = if (position == 0 && mBlockEntries.size == mMaxStoredBlockCount) {
"MAX. "
} else {
"${mBlockEntries.size - position}. "
}
val title = index + block.keyStackString + " " +
getString(R.string.__block_canary_class_has_blocked, block.timeCost)
titleView.text = title
val time = DateUtils.formatDateTime(context,
block.logFile?.lastModified()?: 0L,
DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_SHOW_DATE)
timeView.text = time
return view
}
}
internal class LoadBlocks(private var fragmentOrNull: __DisplayBlockFragment?) : Runnable {
private val mainHandler: Handler = Handler(Looper.getMainLooper())
override fun run() {
val blocks = ArrayList<__Block>()
val files = __BlockCanaryInternals.logFiles
if (files != null) {
for (blockFile in files) {
try {
blocks.add(__Block.newInstance(blockFile))
} catch (e: Exception) {
// Likely a format change in the blockFile
blockFile.delete()
Log.e(TAG, "Could not read block log file, deleted :" + blockFile, e)
}
}
Collections.sort(blocks) { lhs, rhs ->
rhs.logFile?.lastModified()?.compareTo((lhs.logFile?.lastModified())?: 0L)?: 0
}
}
mainHandler.post {
inFlight.remove(this@LoadBlocks)
if (fragmentOrNull != null) {
fragmentOrNull!!.mBlockEntries.clear()
fragmentOrNull!!.mBlockEntries.addAll(blocks)
//Log.d("BlockCanary", "load block entries: " + blocks.size());
fragmentOrNull!!.updateUi()
}
}
}
companion object {
val inFlight: MutableList<LoadBlocks> = ArrayList()
private val backgroundExecutor: Executor = Executors.newSingleThreadExecutor()
fun load(activity: __DisplayBlockFragment) {
val loadBlocks = LoadBlocks(activity)
inFlight.add(loadBlocks)
backgroundExecutor.execute(loadBlocks)
}
fun forgetActivity() {
for (loadBlocks in inFlight) {
loadBlocks.fragmentOrNull = null
}
inFlight.clear()
}
}
}
class __BlockDetailAdapter : BaseAdapter() {
private var mFoldings = BooleanArray(0)
private var mStackFoldPrefix: String? = null
private var mBlock: __Block? = null
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
var view = convertView
val context = parent.context
if (getItemViewType(position) == TOP_ROW) {
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.__dt_canary_ref_top_row, parent, false)
}
val textView = view!!.findViewById(R.id.__dt_canary_row_text) as TextView
textView.text = context.packageName
} else {
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.__dt_canary_ref_row, parent, false)
}
val textView = view!!.findViewById(R.id.__dt_canary_row_text) as TextView
val isThreadStackEntry = position == POSITION_THREAD_STACK + 1
val element = getItem(position)
var htmlString = elementToHtmlString(element, position, mFoldings[position])
if (isThreadStackEntry && !mFoldings[position]) {
htmlString += " <font color='#919191'>" + "blocked" + "</font>"
}
textView.text = Html.fromHtml(htmlString)
val connectorView = view.findViewById(R.id.__dt_canary_row_connector) as __DisplayLeakConnectorView
connectorView.setType(connectorViewType(position))
val moreDetailsView = view.findViewById(R.id.__dt_canary_row_more) as __MoreDetailsView
moreDetailsView.setFolding(mFoldings[position])
}
return view
}
private fun connectorViewType(position: Int): __DisplayLeakConnectorView.Type =
when (position) {
1 -> __DisplayLeakConnectorView.Type.START
count - 1 -> __DisplayLeakConnectorView.Type.END
else -> __DisplayLeakConnectorView.Type.NODE
}
private fun elementToHtmlString(element: String?, position: Int, folding: Boolean): String {
var htmlString = element?.replace(__Block.SEPARATOR.toRegex(), "<br>")
when (position) {
POSITION_BASIC -> {
if (folding) {
htmlString = htmlString?.substring(htmlString.indexOf(__Block.KEY_CPU_CORE))
}
htmlString = String.format("<font color='#c48a47'>%s</font> ", htmlString)
}
POSITION_TIME -> {
if (folding) {
htmlString = htmlString?.substring(0, htmlString.indexOf(__Block.KEY_TIME_COST_START))
}
htmlString = String.format("<font color='#f3cf83'>%s</font> ", htmlString)
}
POSITION_CPU -> {
// FIXME Figure out why sometimes \r\n cannot replace completely
htmlString = element
if (folding) {
htmlString = htmlString?.substring(0, htmlString.indexOf(__Block.KEY_CPU_RATE))
}
htmlString = htmlString?.replace("cpurate = ", "<br>cpurate<br/>")
htmlString = String.format("<font color='#998bb5'>%s</font> ", htmlString)
htmlString = htmlString.replace("]".toRegex(), "]<br>")
}
//POSITION_THREAD_STACK,
else -> {
if (folding) {
val index: Int = htmlString?.indexOf(stackFoldPrefix)?: 0
if (index > 0) {
htmlString = htmlString?.substring(index)
}
}
htmlString = String.format("<font color='#000000'>%s</font> ", htmlString)
}
}
return htmlString
}
fun update(block: __Block?) {
if (mBlock != null && block?.timeStart.equals(mBlock!!.timeStart)) {
// Same data, nothing to change.
return
}
mBlock = block
mFoldings = BooleanArray(mBlock!!.threadStackEntries.size + POSITION_THREAD_STACK)
Arrays.fill(mFoldings, true)
notifyDataSetChanged()
}
fun toggleRow(position: Int) {
mFoldings[position] = !mFoldings[position]
notifyDataSetChanged()
}
override fun getCount(): Int {
if (mBlock == null) {
return 0
}
return mBlock!!.threadStackEntries.size + POSITION_THREAD_STACK
}
override fun getItem(position: Int): String? {
if (getItemViewType(position) == TOP_ROW) {
return null
}
return when (position) {
POSITION_BASIC -> mBlock?.basicString
POSITION_TIME -> mBlock?.timeString
POSITION_CPU -> mBlock?.cpuString
//POSITION_THREAD_STACK,
else -> mBlock?.threadStackEntries?.get(position - POSITION_THREAD_STACK)
}
}
override fun getViewTypeCount(): Int = 2
override fun getItemViewType(position: Int): Int {
if (position == 0) {
return TOP_ROW
}
return NORMAL_ROW
}
override fun getItemId(position: Int): Long = position.toLong()
private val stackFoldPrefix: String
get() {
if (mStackFoldPrefix == null) {
val prefix = __CanaryCoreMgr.context?.stackFoldPrefix
mStackFoldPrefix = prefix?: __ProcessUtils.myProcessName()
}
return mStackFoldPrefix!!
}
companion object {
private val TOP_ROW = 0
private val NORMAL_ROW = 1
private val POSITION_BASIC = 1
private val POSITION_TIME = 2
private val POSITION_CPU = 3
private val POSITION_THREAD_STACK = 4
}
}
}
|
apache-2.0
|
531db2f32adacfb217efd5126570619e
| 37.679592 | 128 | 0.572627 | 4.929259 | false | false | false | false |
androidx/androidx
|
glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/translators/LazyVerticalGridTranslator.kt
|
3
|
5649
|
/*
* Copyright 2022 The Android 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.
*/
package androidx.glance.appwidget.translators
import android.os.Build
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_MUTABLE
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.content.Intent
import android.content.Intent.FILL_IN_COMPONENT
import android.widget.RemoteViews
import androidx.core.widget.RemoteViewsCompat
import androidx.core.widget.RemoteViewsCompat.setGridViewColumnWidth
import androidx.glance.appwidget.InsertedViewInfo
import androidx.glance.appwidget.LayoutType
import androidx.glance.appwidget.TopLevelLayoutsCount
import androidx.glance.appwidget.TranslationContext
import androidx.glance.appwidget.applyModifiers
import androidx.glance.appwidget.insertView
import androidx.glance.appwidget.lazy.EmittableLazyVerticalGrid
import androidx.glance.appwidget.lazy.EmittableLazyVerticalGridListItem
import androidx.glance.appwidget.lazy.GridCells
import androidx.glance.appwidget.lazy.ReservedItemIdRangeEnd
import androidx.glance.appwidget.translateChild
import androidx.glance.appwidget.translateComposition
import androidx.glance.layout.Alignment
/**
* Translates an EmittableLazyVerticalGrid and its children to a EmittableLazyList.
*/
internal fun RemoteViews.translateEmittableLazyVerticalGrid(
translationContext: TranslationContext,
element: EmittableLazyVerticalGrid,
) {
val viewDef = insertView(translationContext, element.gridCells.toLayout(), element.modifier)
translateEmittableLazyVerticalGrid(
translationContext,
element,
viewDef,
)
}
private fun RemoteViews.translateEmittableLazyVerticalGrid(
translationContext: TranslationContext,
element: EmittableLazyVerticalGrid,
viewDef: InsertedViewInfo,
) {
check(!translationContext.isLazyCollectionDescendant) {
"Glance does not support nested list views."
}
val gridCells = element.gridCells
if (gridCells is GridCells.Fixed) {
require(gridCells.count in 1..5) {
"Only counts from 1 to 5 are supported."
}
}
setPendingIntentTemplate(
viewDef.mainViewId,
PendingIntent.getActivity(
translationContext.context,
0,
Intent(),
FILL_IN_COMPONENT or FLAG_MUTABLE or FLAG_UPDATE_CURRENT,
)
)
val items = RemoteViewsCompat.RemoteCollectionItems.Builder().apply {
val childContext = translationContext.forLazyCollection(viewDef.mainViewId)
element.children.foldIndexed(false) { position, previous, itemEmittable ->
itemEmittable as EmittableLazyVerticalGridListItem
val itemId = itemEmittable.itemId
addItem(
itemId,
translateComposition(
childContext.forLazyViewItem(position, LazyVerticalGridItemStartingViewId),
listOf(itemEmittable),
translationContext.layoutConfiguration?.addLayout(itemEmittable) ?: -1,
)
)
// If the user specifies any explicit ids, we assume the list to be stable
previous || (itemId > ReservedItemIdRangeEnd)
}.let { setHasStableIds(it) }
setViewTypeCount(TopLevelLayoutsCount)
}.build()
RemoteViewsCompat.setRemoteAdapter(
translationContext.context,
this,
translationContext.appWidgetId,
viewDef.mainViewId,
items
)
if (Build.VERSION.SDK_INT >= 31 && gridCells is GridCells.Adaptive) {
setGridViewColumnWidth(viewId = viewDef.mainViewId,
value = gridCells.minSize.value,
unit = android.util.TypedValue.COMPLEX_UNIT_DIP)
}
applyModifiers(translationContext, this, element.modifier, viewDef)
}
/**
* Translates a list item either to its immediate only child, or a column layout wrapping all its
* children.
*/
internal fun RemoteViews.translateEmittableLazyVerticalGridListItem(
translationContext: TranslationContext,
element: EmittableLazyVerticalGridListItem
) {
require(element.children.size == 1 && element.alignment == Alignment.CenterStart) {
"Lazy vertical grid items can only have a single child align at the center start of the " +
"view. The normalization of the composition tree failed."
}
translateChild(translationContext, element.children.first())
}
// All the lazy list items should use the same ids, to ensure the layouts can be re-used.
// Using a very high number to avoid collision with the main app widget ids.
private const val LazyVerticalGridItemStartingViewId: Int = 0x00100000
private fun GridCells.toLayout(): LayoutType =
when (this) {
GridCells.Fixed(1) -> LayoutType.VerticalGridOneColumn
GridCells.Fixed(2) -> LayoutType.VerticalGridTwoColumns
GridCells.Fixed(3) -> LayoutType.VerticalGridThreeColumns
GridCells.Fixed(4) -> LayoutType.VerticalGridFourColumns
GridCells.Fixed(5) -> LayoutType.VerticalGridFiveColumns
else -> LayoutType.VerticalGridAutoFit
}
|
apache-2.0
|
aaa10695b608355e0861045a83c7be8a
| 38.788732 | 99 | 0.734997 | 4.783235 | false | false | false | false |
nrizzio/Signal-Android
|
app/src/androidTest/java/org/thoughtcrime/securesms/database/MmsHelper.kt
|
1
|
2054
|
package org.thoughtcrime.securesms.database
import org.thoughtcrime.securesms.database.model.ParentStoryId
import org.thoughtcrime.securesms.database.model.StoryType
import org.thoughtcrime.securesms.database.model.databaseprotos.GiftBadge
import org.thoughtcrime.securesms.mms.IncomingMediaMessage
import org.thoughtcrime.securesms.mms.OutgoingMediaMessage
import org.thoughtcrime.securesms.mms.OutgoingSecureMediaMessage
import org.thoughtcrime.securesms.recipients.Recipient
import java.util.Optional
/**
* Helper methods for inserting an MMS message into the MMS table.
*/
object MmsHelper {
fun insert(
recipient: Recipient = Recipient.UNKNOWN,
body: String = "body",
sentTimeMillis: Long = System.currentTimeMillis(),
subscriptionId: Int = -1,
expiresIn: Long = 0,
viewOnce: Boolean = false,
distributionType: Int = ThreadDatabase.DistributionTypes.DEFAULT,
threadId: Long = 1,
storyType: StoryType = StoryType.NONE,
parentStoryId: ParentStoryId? = null,
isStoryReaction: Boolean = false,
giftBadge: GiftBadge? = null,
secure: Boolean = true
): Long {
val message = OutgoingMediaMessage(
recipient,
body,
emptyList(),
sentTimeMillis,
subscriptionId,
expiresIn,
viewOnce,
distributionType,
storyType,
parentStoryId,
isStoryReaction,
null,
emptyList(),
emptyList(),
emptyList(),
emptySet(),
emptySet(),
giftBadge
).let {
if (secure) OutgoingSecureMediaMessage(it) else it
}
return insert(
message = message,
threadId = threadId
)
}
fun insert(
message: OutgoingMediaMessage,
threadId: Long
): Long {
return SignalDatabase.mms.insertMessageOutbox(message, threadId, false, GroupReceiptDatabase.STATUS_UNKNOWN, null)
}
fun insert(
message: IncomingMediaMessage,
threadId: Long
): Optional<MessageDatabase.InsertResult> {
return SignalDatabase.mms.insertSecureDecryptedMessageInbox(message, threadId)
}
}
|
gpl-3.0
|
7e951a47415b5872e0862040a7c3401e
| 26.756757 | 118 | 0.713242 | 4.445887 | false | false | false | false |
mvaldez/kotlin-examples
|
src/i_introduction/_7_Nullable_Types/NullableTypes.kt
|
1
|
1144
|
package i_introduction._7_Nullable_Types
import util.TODO
import util.doc7
fun test() {
val s: String = "this variable cannot store null references"
val q: String? = null
if (q != null) q.length // you have to check to dereference
val i: Int? = q?.length // null
val j: Int = q?.length ?: 0 // 0
}
fun todoTask7(client: Client?, message: String?, mailer: Mailer): Nothing = TODO(
"""
Task 7.
Rewrite JavaCode7.sendMessageToClient in Kotlin, using only one 'if' expression.
Declarations of Client, PersonalInfo and Mailer are given below.
""",
documentation = doc7(),
references = { JavaCode7().sendMessageToClient(client, message, mailer) }
)
fun sendMessageToClient(
client: Client?, message: String?, mailer: Mailer
) {
// todoTask7(client, message, mailer)
if (client?.personalInfo?.email == null || message == null) return
mailer.sendMessage(client?.personalInfo?.email, message)
}
class Client (val personalInfo: PersonalInfo?)
class PersonalInfo (val email: String?)
interface Mailer {
fun sendMessage(email: String, message: String)
}
|
mit
|
fe3d00f1819b064a0872c0e507750c07
| 28.333333 | 88 | 0.670455 | 3.986063 | false | false | false | false |
Soya93/Extract-Refactoring
|
platform/script-debugger/debugger-ui/src/MemberFilterWithNameMappings.kt
|
1
|
1426
|
/*
* 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.debugger
open class MemberFilterWithNameMappings(rawNameToSource: Map<String, String>?) : MemberFilter {
protected val rawNameToSource = rawNameToSource ?: emptyMap<String, String>()
override fun hasNameMappings(): Boolean {
return !rawNameToSource.isEmpty()
}
override fun rawNameToSource(variable: Variable): String {
val name = variable.name
val sourceName = rawNameToSource.get(name)
return sourceName ?: normalizeMemberName(name)
}
protected open fun normalizeMemberName(name: String): String {
return name
}
override fun sourceNameToRaw(name: String): String? {
if (!hasNameMappings()) {
return null
}
for (entry in rawNameToSource.entries) {
if (entry.value == name) {
return entry.key
}
}
return null
}
}
|
apache-2.0
|
ae7b1a89822d1387a8666acf65d0ea9b
| 29.340426 | 95 | 0.713184 | 4.374233 | false | false | false | false |
minecraft-dev/MinecraftDev
|
src/main/kotlin/platform/architectury/creator/ArchitecturyProjectConfig.kt
|
1
|
2672
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.architectury.creator
import com.demonwav.mcdev.creator.ProjectConfig
import com.demonwav.mcdev.creator.ProjectCreator
import com.demonwav.mcdev.creator.buildsystem.BuildSystemType
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleBuildSystem
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleCreator
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.util.License
import com.demonwav.mcdev.util.MinecraftVersions
import com.demonwav.mcdev.util.SemanticVersion
import com.demonwav.mcdev.util.VersionRange
import com.intellij.openapi.module.Module
import com.intellij.util.lang.JavaVersion
import java.nio.file.Path
class ArchitecturyProjectConfig : ProjectConfig(), GradleCreator {
var mcVersion: SemanticVersion = SemanticVersion.release()
var forgeVersion: SemanticVersion = SemanticVersion.release()
var forgeVersionText: String = ""
var fabricLoaderVersion = SemanticVersion.release()
var fabricApiVersion: SemanticVersion = SemanticVersion.release()
var architecturyApiVersion: SemanticVersion = SemanticVersion.release()
var loomVersion = SemanticVersion.release()
private var gradleVersion = SemanticVersion.release()
val architecturyGroup: String
get() = when {
architecturyApiVersion >= SemanticVersion.release(2, 0, 10) -> "dev.architectury"
else -> "me.shedaniel"
}
val architecturyPackage: String
get() = when {
architecturyApiVersion >= SemanticVersion.release(2, 0, 10) -> "dev.architectury"
else -> "me.shedaniel.architectury"
}
var modRepo: String? = null
fun hasRepo() = !modRepo.isNullOrBlank()
var modIssue: String? = null
fun hasIssue() = !modIssue.isNullOrBlank()
var fabricApi = true
var architecturyApi = true
var mixins = false
var license: License? = null
override var type = PlatformType.ARCHITECTURY
override val preferredBuildSystem = BuildSystemType.GRADLE
override val javaVersion: JavaVersion
get() = MinecraftVersions.requiredJavaVersion(mcVersion)
override val compatibleGradleVersions: VersionRange
get() = VersionRange.fixed(gradleVersion)
override fun buildGradleCreator(
rootDirectory: Path,
module: Module,
buildSystem: GradleBuildSystem
): ProjectCreator {
return ArchitecturyProjectCreator(
rootDirectory,
module,
buildSystem,
this
)
}
}
|
mit
|
216fd6a6c9e3f915077e6edfc5e2e409
| 33.25641 | 93 | 0.724551 | 4.498316 | false | false | false | false |
InfiniteSoul/ProxerAndroid
|
src/main/kotlin/me/proxer/app/profile/comment/ProfileCommentFragment.kt
|
1
|
5922
|
package me.proxer.app.profile.comment
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.core.os.bundleOf
import androidx.core.text.parseAsHtml
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.MaterialDialog
import com.google.android.material.snackbar.Snackbar
import com.mikepenz.iconics.utils.IconicsMenuInflaterUtil
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import me.proxer.app.R
import me.proxer.app.base.PagedContentFragment
import me.proxer.app.comment.EditCommentActivity
import me.proxer.app.comment.LocalComment
import me.proxer.app.media.MediaActivity
import me.proxer.app.profile.ProfileActivity
import me.proxer.app.util.extension.getSafeParcelableExtra
import me.proxer.app.util.extension.multilineSnackbar
import me.proxer.app.util.extension.subscribeAndLogErrors
import me.proxer.app.util.extension.unsafeLazy
import me.proxer.library.enums.Category
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import kotlin.properties.Delegates
/**
* @author Ruben Gees
*/
class ProfileCommentFragment : PagedContentFragment<ParsedUserComment>() {
companion object {
private const val CATEGORY_ARGUMENT = "category"
fun newInstance() = ProfileCommentFragment().apply {
arguments = bundleOf()
}
}
override val emptyDataMessage = R.string.error_no_data_comments
override val isSwipeToRefreshEnabled = false
override val pagingThreshold = 3
override val viewModel by viewModel<ProfileCommentViewModel> {
parametersOf(userId, username, category)
}
override val hostingActivity: ProfileActivity
get() = activity as ProfileActivity
private val userId: String?
get() = hostingActivity.userId
private val username: String?
get() = hostingActivity.username
private var category: Category?
get() = requireArguments().getSerializable(CATEGORY_ARGUMENT) as? Category
set(value) {
requireArguments().putSerializable(CATEGORY_ARGUMENT, value)
viewModel.category = value
}
override val layoutManager by unsafeLazy { LinearLayoutManager(context) }
override var innerAdapter by Delegates.notNull<ProfileCommentAdapter>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
innerAdapter = ProfileCommentAdapter(savedInstanceState, storageHelper)
innerAdapter.titleClickSubject
.autoDisposable(this.scope())
.subscribe {
MediaActivity.navigateTo(requireActivity(), it.entryId, it.entryName, it.category)
}
innerAdapter.editClickSubject
.autoDisposable(this.scope())
.subscribe {
EditCommentActivity.navigateTo(this, it.id, it.entryId, it.entryName)
}
innerAdapter.deleteClickSubject
.autoDisposable(this.scope())
.subscribe { comment ->
MaterialDialog(requireContext())
.message(text = getString(R.string.dialog_comment_delete_message, comment.entryName).parseAsHtml())
.negativeButton(res = R.string.cancel)
.positiveButton(res = R.string.dialog_comment_delete_positive) {
viewModel.deleteComment(comment)
}
.show()
}
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.itemDeletionError.observe(viewLifecycleOwner, Observer {
it?.let {
hostingActivity.multilineSnackbar(
getString(R.string.error_comment_deletion, getString(it.message)),
Snackbar.LENGTH_LONG, it.buttonMessage, it.toClickListener(hostingActivity)
)
}
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == EditCommentActivity.COMMENT_REQUEST && resultCode == Activity.RESULT_OK && data != null) {
Single.fromCallable { data.getSafeParcelableExtra<LocalComment>(EditCommentActivity.COMMENT_EXTRA) }
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.autoDisposable(this.scope())
.subscribeAndLogErrors { viewModel.updateComment(it) }
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
IconicsMenuInflaterUtil.inflate(inflater, requireContext(), R.menu.fragment_user_comments, menu, true)
when (category) {
Category.ANIME -> menu.findItem(R.id.anime).isChecked = true
Category.MANGA -> menu.findItem(R.id.manga).isChecked = true
else -> menu.findItem(R.id.all).isChecked = true
}
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.anime -> category = Category.ANIME
R.id.manga -> category = Category.MANGA
R.id.all -> category = null
}
item.isChecked = true
return super.onOptionsItemSelected(item)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
innerAdapter.saveInstanceState(outState)
}
}
|
gpl-3.0
|
cda0a57310ea4a271b0fe7cebb6ca243
| 35.555556 | 119 | 0.690645 | 5.005917 | false | false | false | false |
pyamsoft/power-manager
|
powermanager-base/src/main/java/com/pyamsoft/powermanager/base/states/AirplaneModeWrapperImpl.kt
|
1
|
2389
|
/*
* Copyright 2017 Peter Kenji Yamanaka
*
* 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.pyamsoft.powermanager.base.states
import android.content.ContentResolver
import android.content.Context
import android.provider.Settings
import com.pyamsoft.powermanager.base.logger.Logger
import com.pyamsoft.powermanager.base.preference.RootPreferences
import com.pyamsoft.powermanager.base.shell.ShellHelper
import com.pyamsoft.powermanager.model.States
import javax.inject.Inject
internal class AirplaneModeWrapperImpl @Inject internal constructor(context: Context,
private val logger: Logger, private val preferences: RootPreferences,
private val shellHelper: ShellHelper) : DeviceFunctionWrapper {
private val contentResolver: ContentResolver = context.applicationContext.contentResolver
private fun setAirplaneModeEnabled(enabled: Boolean) {
if (preferences.rootEnabled) {
logger.i("Airplane Mode: %s", if (enabled) "enable" else "disable")
val airplaneSettingsCommand = AIRPLANE_SETTINGS_COMMAND + if (enabled) "1" else "0"
val airplaneBroadcastCommand = AIRPLANE_BROADCAST_COMMAND + if (enabled) "true" else "false"
shellHelper.runSUCommand(airplaneSettingsCommand, airplaneBroadcastCommand)
} else {
logger.w("Root not enabled, cannot toggle Airplane Mode")
}
}
override fun enable() {
setAirplaneModeEnabled(true)
}
override fun disable() {
setAirplaneModeEnabled(false)
}
override val state: States
get() = if (Settings.Global.getInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON,
0) == 1) States.ENABLED
else States.DISABLED
companion object {
private const val AIRPLANE_SETTINGS_COMMAND = "settings put global airplane_mode_on "
private const val AIRPLANE_BROADCAST_COMMAND = "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state "
}
}
|
apache-2.0
|
8c4527d1d44daaaeb02673e78eab4239
| 38.163934 | 116 | 0.759732 | 4.351548 | false | false | false | false |
kenrube/Fantlab-client
|
app/src/main/kotlin/ru/fantlab/android/ui/modules/plans/pubplans/PubplansFragment.kt
|
2
|
4898
|
package ru.fantlab.android.ui.modules.plans.pubplans
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.annotation.StringRes
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.micro_grid_refresh_list.*
import kotlinx.android.synthetic.main.state_layout.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.ContextMenuBuilder
import ru.fantlab.android.data.dao.model.ContextMenus
import ru.fantlab.android.data.dao.model.Pubplans
import ru.fantlab.android.provider.rest.PubplansSortOption
import ru.fantlab.android.provider.rest.loadmore.OnLoadMore
import ru.fantlab.android.ui.adapter.PlansAdapter
import ru.fantlab.android.ui.base.BaseFragment
import ru.fantlab.android.ui.modules.edition.EditionActivity
import ru.fantlab.android.ui.modules.plans.PlansPagerMvp
import ru.fantlab.android.ui.widgets.dialog.ContextMenuDialogView
class PubplansFragment : BaseFragment<PubplansMvp.View, PubplansPresenter>(),
PubplansMvp.View {
private val onLoadMore: OnLoadMore<Int> by lazy { OnLoadMore(presenter) }
private val adapter: PlansAdapter by lazy { PlansAdapter(arrayListOf()) }
private var publisherCallback: PlansPagerMvp.View? = null
override fun fragmentLayout(): Int = R.layout.micro_grid_refresh_list
override fun providePresenter(): PubplansPresenter = PubplansPresenter()
override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
stateLayout.hideProgress()
}
stateLayout.setEmptyText(R.string.no_plans)
stateLayout.setOnReloadListener(this)
refresh.setOnRefreshListener(this)
recycler.setEmptyView(stateLayout, refresh)
adapter.listener = presenter
recycler.adapter = adapter
getLoadMore().initialize(presenter.getCurrentPage() - 1, presenter.getPreviousTotal())
recycler.addOnScrollListener(getLoadMore())
presenter.onCallApi(1, null)
fastScroller.attachRecyclerView(recycler)
recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
publisherCallback?.onScrolled(dy > 0)
}
})
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is PlansPagerMvp.View) {
publisherCallback = context
}
}
override fun onDetach() {
publisherCallback = null
super.onDetach()
}
override fun onDestroyView() {
recycler.removeOnScrollListener(getLoadMore())
super.onDestroyView()
}
override fun onNotifyAdapter(items: ArrayList<Pubplans.Object>, page: Int) {
hideProgress()
if (items.isEmpty()) {
adapter.clear()
stateLayout.showEmptyState()
return
}
if (page <= 1) {
adapter.insertItems(items)
} else {
adapter.addItems(items)
}
}
override fun getLoadMore() = onLoadMore
override fun onItemClicked(item: Pubplans.Object) {
EditionActivity.startActivity(context!!, item.editionId.toInt(), item.name)
}
override fun onItemLongClicked(position: Int, v: View?, item: Pubplans.Object) {
}
override fun onRefresh() {
presenter.getPubplans(1, true)
}
override fun onClick(v: View?) {
onRefresh()
}
override fun hideProgress() {
refresh.isRefreshing = false
stateLayout.hideProgress()
}
override fun showProgress(@StringRes resId: Int, cancelable: Boolean) {
refresh.isRefreshing = true
stateLayout.showProgress()
}
override fun showErrorMessage(msgRes: String?) {
callback?.showErrorMessage(msgRes)
}
override fun showMessage(titleRes: Int, msgRes: Int) {
showReload()
super.showMessage(titleRes, msgRes)
}
private fun showReload() {
hideProgress()
stateLayout.showReload(adapter.itemCount)
}
override fun onItemSelected(parent: String, item: ContextMenus.MenuItem, position: Int, listItem: Any) {
recycler?.scrollToPosition(0)
when (item.id) {
"sort" -> {
presenter.setCurrentSort(PubplansSortOption.values()[position], null, null)
}
else -> {
when (parent) {
"lang" -> {
presenter.setCurrentSort(null, item.id, null)
}
"publisher" -> {
presenter.setCurrentSort(null, null, item.id)
}
}
}
}
}
fun showSortDialog() {
val dialogView = ContextMenuDialogView()
val sort = presenter.getCurrentSort()
dialogView.initArguments("sort", ContextMenuBuilder.buildForPubplansSorting(recycler.context, sort.sortBy))
dialogView.show(childFragmentManager, "ContextMenuDialogView")
}
fun showFilterDialog() {
val dialogView = ContextMenuDialogView()
val sort = presenter.getCurrentSort()
dialogView.initArguments("filter", ContextMenuBuilder.buildForPubplansFilter(recycler.context, presenter.publishers, sort.filterLang, sort.filterPublisher))
dialogView.show(childFragmentManager, "ContextMenuDialogView")
}
companion object {
fun newInstance(): PubplansFragment {
val view = PubplansFragment()
return view
}
}
}
|
gpl-3.0
|
6616cf772192d3aea59829a5ad585815
| 28.512048 | 158 | 0.759494 | 3.799845 | false | false | false | false |
cy6erGn0m/klaxon
|
src/main/kotlin/com/beust/klaxon/Lookup.kt
|
1
|
2907
|
package com.beust.klaxon
import java.math.BigInteger
import java.util.ArrayList
@Suppress("UNCHECKED_CAST")
public fun <T> JsonObject.array(fieldName: String) : JsonArray<T>? = get(fieldName) as JsonArray<T>?
public fun JsonObject.obj(fieldName: String) : JsonObject? = get(fieldName) as JsonObject?
public fun JsonObject.int(fieldName: String) : Int? {
val value = get(fieldName)
when (value) {
is Number -> return value.toInt()
else -> return value as Int?
}
}
public fun JsonObject.long(fieldName: String) : Long? {
val value = get(fieldName)
when (value) {
is Number -> return value.toLong()
else -> return value as Long?
}
}
public fun JsonObject.bigInt(fieldName: String) : BigInteger? = get(fieldName) as BigInteger
public fun JsonObject.string(fieldName: String) : String? = get(fieldName) as String?
public fun JsonObject.double(fieldName: String) : Double? = get(fieldName) as Double?
public fun JsonObject.boolean(fieldName: String) : Boolean? = get(fieldName) as Boolean?
public fun JsonArray<*>.string(id: String) : JsonArray<String?> = mapChildren { it.string(id) }
public fun JsonArray<*>.obj(id: String) : JsonArray<JsonObject?> = mapChildren { it.obj(id) }
public fun JsonArray<*>.long(id: String) : JsonArray<Long?> = mapChildren { it.long(id) }
public fun JsonArray<*>.int(id: String) : JsonArray<Int?> = mapChildren { it.int(id) }
public fun JsonArray<*>.bigInt(id: String) : JsonArray<BigInteger?> = mapChildren { it.bigInt(id) }
public fun JsonArray<*>.double(id: String) : JsonArray<Double?> = mapChildren { it.double(id) }
public fun <T> JsonArray<*>.mapChildrenObjectsOnly(block : (JsonObject) -> T) : JsonArray<T> =
JsonArray(flatMapTo(ArrayList(size)) {
if (it is JsonObject) listOf(block(it))
else if (it is JsonArray<*>) it.mapChildrenObjectsOnly(block)
else listOf()
})
public fun <T : Any> JsonArray<*>.mapChildren(block : (JsonObject) -> T?) : JsonArray<T?> =
JsonArray(flatMapTo(ArrayList(size)) {
if (it is JsonObject) listOf(block(it))
else if (it is JsonArray<*>) it.mapChildren(block)
else listOf(null)
})
operator public fun JsonArray<*>.get(key : String) : JsonArray<Any?> = mapChildren { it[key] }
@Suppress("UNCHECKED_CAST")
private fun Any?.ensureArray() : JsonArray<Any?> =
if (this is JsonArray<*>) this as JsonArray<Any?>
else JsonArray(this)
public fun JsonBase.lookup(key : String) : JsonArray<Any?> =
key.split("[/\\.]".toRegex())
.filter{ it != "" }
.fold(this) { j, part ->
when (j) {
is JsonArray<*> -> j[part]
is JsonObject -> j[part].ensureArray()
else -> throw IllegalArgumentException("unsupported type of j = $j")
}
}.ensureArray()
|
apache-2.0
|
af4bb835c445d93d1ee534336b3b5cec
| 41.75 | 100 | 0.638459 | 3.891566 | false | false | false | false |
angryziber/synology-cast-photos-android
|
src/net/azib/photos/cast/DirsSuggestionAdapter.kt
|
1
|
1626
|
package net.azib.photos.cast
import android.widget.ArrayAdapter
import android.widget.Filter
import androidx.fragment.app.FragmentActivity
import java.net.URL
import java.util.Collections.emptyList
class DirsSuggestionAdapter(context: FragmentActivity, private val receiver: Receiver, private val path: String) : ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line) {
private var suggestions: List<String> = emptyList()
override fun getCount() = suggestions.size
override fun getItem(index: Int) = suggestions[index]
fun getSuggestions(dir: CharSequence?): List<String> {
try {
val lastPlus = dir!!.lastIndexOf('+') + 1
val prefix = dir.substring(0, lastPlus)
val query = dir.substring(lastPlus)
if (query.length <= 2) return emptyList()
val url = URL("${receiver.url}$path?dir=$query&accessToken=${receiver.token}")
return url.openStream().bufferedReader().useLines { it.map { prefix + it }.sortedDescending().toList() }
} catch (e: Exception) {
return emptyList()
}
}
override fun getFilter(): Filter {
return object : Filter() {
override fun performFiltering(constraint: CharSequence?): FilterResults {
val results = FilterResults()
suggestions = getSuggestions(constraint)
results.values = suggestions
results.count = suggestions.size
return results
}
override fun publishResults(constraint: CharSequence?, results: FilterResults) {
if (results.count > 0)
notifyDataSetChanged()
else
notifyDataSetInvalidated()
}
}
}
}
|
apache-2.0
|
23059f76aa62a32bf6f847b0ad13e4dd
| 34.369565 | 191 | 0.690037 | 4.606232 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.