content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.sksamuel.kotest.matchers.url
import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.should
import io.kotest.matchers.shouldNot
import io.kotest.matchers.url.haveHost
import io.kotest.matchers.url.haveParameter
import io.kotest.matchers.url.haveParameterValue
import io.kotest.matchers.url.havePath
import io.kotest.matchers.url.havePort
import io.kotest.matchers.url.haveProtocol
import io.kotest.matchers.url.haveRef
import io.kotest.matchers.url.shouldBeOpaque
import io.kotest.matchers.url.shouldHaveParameter
import io.kotest.matchers.url.shouldHaveParameterValue
import io.kotest.matchers.url.shouldHavePort
import io.kotest.matchers.url.shouldHaveProtocol
import io.kotest.matchers.url.shouldHaveRef
import io.kotest.matchers.url.shouldNotBeOpaque
import io.kotest.matchers.url.shouldNotHaveParameter
import io.kotest.matchers.url.shouldNotHaveParameterValue
import io.kotest.matchers.url.shouldNotHavePort
import io.kotest.matchers.url.shouldNotHaveProtocol
import java.net.URL
class UrlMatchersTest : WordSpec() {
init {
"beOpaque" should {
"test that a URL is opaque" {
URL("https:hostname:8080").shouldBeOpaque()
URL("https://path").shouldNotBeOpaque()
}
}
"haveProtocol" should {
"test that a URL has the specified protocol" {
URL("https://hostname").shouldHaveProtocol("https")
URL("https://hostname") should haveProtocol("https")
URL("ftp://hostname").shouldNotHaveProtocol("https")
URL("ftp://hostname") shouldNot haveProtocol("https")
}
}
"havePort" should {
"test that a URL has the specified port" {
URL("https://hostname:90") should havePort(90)
URL("https://hostname:90").shouldHavePort(90)
URL("https://hostname") should havePort(-1)
URL("ftp://hostname:14") shouldNot havePort(80)
URL("ftp://hostname:14").shouldNotHavePort(80)
}
}
"haveHost" should {
"test that a URL has the specified host" {
URL("https://hostname:90") should haveHost("hostname")
URL("https://wewqe") should haveHost("wewqe")
URL("ftp://hostname:14") shouldNot haveHost("qweqwe")
}
}
"haveParameter" should {
"test that a URL has the specified host" {
URL("https://hostname:90?a=b&c=d") should haveParameter("a")
URL("https://hostname:90?a=b&c=d").shouldHaveParameter("a")
URL("https://hostname:90?a=b&c=d") should haveParameter("c")
URL("https://hostname:90?a=b&c=d") shouldNot haveParameter("b")
URL("https://hostname:90?a=b&c=d").shouldNotHaveParameter("b")
}
"support testing for the value" {
URL("https://hostname:90?key=value").shouldHaveParameterValue("key", "value")
URL("https://hostname:90?key=value") should haveParameterValue("key", "value")
URL("https://hostname:90?key=value").shouldNotHaveParameterValue("key", "wibble")
}
}
"havePath" should {
"test that a URL has the specified path" {
URL("https://hostname:90/index.html#qwerty") should havePath("/index.html")
}
}
"haveRef" should {
"test that a URL has the specified host" {
URL("https://hostname:90#qwerty") should haveRef("qwerty")
URL("https://hostname:90#qwerty").shouldHaveRef("qwerty")
URL("https://hostname:90#") should haveRef("")
}
}
}
}
| kotest-assertions/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/url/UrlMatchersTest.kt | 1870938113 |
package io.kotest.assertions
import io.kotest.mpp.throwableLocation
/** An error that bundles multiple other [Throwable]s together */
class MultiAssertionError(errors: List<Throwable>) : AssertionError(createMessage(errors)) {
companion object {
private fun createMessage(errors: List<Throwable>) = buildString {
append("\nThe following ")
if (errors.size == 1) {
append("assertion")
} else {
append(errors.size).append(" assertions")
}
append(" failed:\n")
for ((i, err) in errors.withIndex()) {
append(i + 1).append(") ").append(err.message).append("\n")
err.throwableLocation()?.let {
append("\tat ").append(it).append("\n")
}
}
}
}
}
| kotest-assertions/src/commonMain/kotlin/io/kotest/assertions/MultiAssertionError.kt | 2552684803 |
/*
* 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 com.example.android.dfn.dsl
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.dynamicfeatures.activity
import androidx.navigation.dynamicfeatures.createGraph
import androidx.navigation.dynamicfeatures.fragment.DynamicNavHostFragment
import androidx.navigation.dynamicfeatures.fragment.fragment
import androidx.navigation.dynamicfeatures.includeDynamic
import com.example.android.dfn.dsl.databinding.ActivityMainBinding
/**
* Main entry point into the Kotlin DSL sample for Dynamic Feature Navigation.
* The navigation graph is declared in this class.
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(ActivityMainBinding.inflate(layoutInflater).root)
(supportFragmentManager.findFragmentByTag("nav_host") as DynamicNavHostFragment)
.navController
.apply {
// Create a dynamic navigation graph. Inside this destinations from within dynamic
// feature modules can be navigated to.
graph = createGraph(
id = R.id.graphId,
startDestination = R.id.startDestination
) {
// A fragment destination declared in the "base" feature module.
fragment<StartDestinationFragment>(R.id.startDestination)
// A fragment destination declared in the "ondemand" dynamic feature module.
fragment(R.id.onDemandFragment, "${baseContext.packageName}$ON_DEMAND_FRAGMENT") {
moduleName = MODULE_ON_DEMAND
}
// An activity destination declared in the "ondemand" dynamic feature module.
activity(id = R.id.featureActivity) {
moduleName = MODULE_ON_DEMAND
activityClassName = "${baseContext.packageName}$FEATURE_ACTIVITY"
}
/* A dynamically included graph in the "included" dynamic feature module.
This matches the <include-dynamic> tag in xml. */
includeDynamic(
id = R.id.includedFragment,
moduleName = MODULE_INCLUDED,
graphResourceName = INCLUDED_GRAPH_NAME
)
}
}
}
}
const val INCLUDED_GRAPH_NAME = "included_dynamically"
const val ON_DEMAND_FRAGMENT = ".ondemand.OnDemandFragment"
const val FEATURE_ACTIVITY = ".ondemand.FeatureActivity"
const val MODULE_INCLUDED = "included"
const val MODULE_ON_DEMAND = "ondemand"
| DynamicFeatureNavigation/DSL/app/src/main/java/com/example/android/dfn/dsl/MainActivity.kt | 4222242817 |
package misc.tileentity
import com.cout970.magneticraft.tileentity.TileBase
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* Created by cout970 on 2017/02/21.
*/
abstract class TileTrait(val tile: TileBase) : ITileTrait {
override fun getPos(): BlockPos = tile.pos
override fun getWorld(): World = tile.world
private var firstTick = false
override fun update() {
if (!firstTick){
firstTick = true
onFullyLoad()
}
}
open fun onFullyLoad() = Unit
} | ignore/test/misc/tileentity/TileTrait.kt | 1943064574 |
package org.botellier.server
import org.botellier.command.CommandParser
import org.botellier.value.Lexer
import org.botellier.value.LexerException
import org.botellier.value.ParserException
import org.botellier.value.toList
import java.net.Socket
import java.net.SocketException
import java.net.SocketTimeoutException
/**
* Container class for client information.
*/
data class Client(val socket: Socket, var dbIndex: Int = 0, var isAuthenticated: Boolean = false)
/**
* Class for handling a new client connection. It reads the input,
* tries to parse a command, and then sends back the constructed
* request using the provided callback.
* @property db the current db the client is connected to.
*/
class ClientHandler(val client: Client, val dispatcher: RequestDispatcher) : Runnable {
var readTimeout: Int = 1000
override fun run() {
println("Handling client ${client.socket.inetAddress.hostAddress}")
loop@while (true) {
try {
val stream = client.socket.waitInput()
client.socket.soTimeout = readTimeout
val tokens = Lexer(stream).lex().toList()
client.socket.soTimeout = 0
val command = CommandParser.parse(tokens)
dispatcher.dispatch(Request(client, command))
}
catch (e: SocketException) {
break@loop
}
catch (e: Throwable) {
println(e.message)
val writer = client.socket.getOutputStream().bufferedWriter()
when (e) {
// Exception for Lexer waiting too much.
is SocketTimeoutException ->
writer.write("-ERR Command read timeout\r\n")
// Exception regarding the serialized data.
is LexerException ->
writer.write("-COMMANDERR Unable to read command\r\n")
// Exception regarding the structure of the data.
is ParserException ->
writer.write("-COMMANDERR Unable to parse command\r\n")
// Exception regarding unknown command.
is CommandParser.UnknownCommandException ->
writer.write("-COMMANDERR ${e.message}\r\n")
// Exception that we don't know how to handle.
else -> {
client.socket.close()
break@loop
}
}
writer.flush()
}
}
println("Dropping client ${client.socket.inetAddress.hostAddress}")
}
}
| src/main/kotlin/org/botellier/server/Client.kt | 4265026126 |
// Copyright 2021 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.storage.testing
import com.google.protobuf.ByteString
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import org.wfanet.measurement.common.flatten
import org.wfanet.measurement.storage.StorageClient
/** In-memory [StorageClient]. */
class InMemoryStorageClient : StorageClient {
private val storageMap = ConcurrentHashMap<String, StorageClient.Blob>()
/** Exposes all the blobs in the [StorageClient]. */
val contents: Map<String, StorageClient.Blob>
get() = storageMap
private fun deleteKey(path: String) {
storageMap.remove(path)
}
override suspend fun writeBlob(blobKey: String, content: Flow<ByteString>): StorageClient.Blob {
val blob = Blob(blobKey, content.flatten())
storageMap[blobKey] = blob
return blob
}
override suspend fun getBlob(blobKey: String): StorageClient.Blob? {
return storageMap[blobKey]
}
private inner class Blob(private val blobKey: String, private val content: ByteString) :
StorageClient.Blob {
override val size: Long
get() = content.size().toLong()
override val storageClient: InMemoryStorageClient
get() = this@InMemoryStorageClient
override fun read(): Flow<ByteString> = flowOf(content)
override suspend fun delete() = storageClient.deleteKey(blobKey)
}
}
| src/main/kotlin/org/wfanet/measurement/storage/testing/InMemoryStorageClient.kt | 3568386435 |
/*
* 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 Gradle_Promotion.buildTypes
import common.Os
import common.builtInRemoteBuildCacheNode
import common.gradleWrapper
import common.requiresOs
import jetbrains.buildServer.configs.kotlin.v2018_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2018_2.vcs.GitVcsRoot
abstract class PublishGradleDistribution(
branch: String,
task: String,
val triggerName: String,
gitUserName: String = "Gradleware Git Bot",
gitUserEmail: String = "[email protected]",
extraParameters: String = "",
vcsRoot: GitVcsRoot = Gradle_Promotion.vcsRoots.Gradle_Promotion__master_
) : BasePromotionBuildType(vcsRoot = vcsRoot) {
init {
artifactRules = """
incoming-build-receipt/build-receipt.properties => incoming-build-receipt
**/build/git-checkout/build/build-receipt.properties
**/build/distributions/*.zip => promote-build-distributions
**/build/website-checkout/data/releases.xml
**/build/git-checkout/build/reports/integTest/** => distribution-tests
**/smoke-tests/build/reports/tests/** => post-smoke-tests
""".trimIndent()
steps {
gradleWrapper {
name = "Promote"
tasks = task
gradleParams = """-PuseBuildReceipt $extraParameters "-PgitUserName=$gitUserName" "-PgitUserEmail=$gitUserEmail" -Igradle/buildScanInit.gradle ${builtInRemoteBuildCacheNode.gradleParameters(Os.linux).joinToString(" ")}"""
}
}
dependencies {
artifacts(AbsoluteId("Gradle_Check_Stage_${[email protected]}_Trigger")) {
buildRule = lastSuccessful(branch)
cleanDestination = true
artifactRules = "build-receipt.properties => incoming-build-receipt/"
}
}
requirements {
requiresOs(Os.linux)
}
}
}
fun String.promoteNightlyTaskName(): String = "promote${if (this == "master") "" else capitalize()}Nightly"
| .teamcity/Gradle_Promotion/buildTypes/PublishGradleDistribution.kt | 2368465373 |
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.execution
import org.jetbrains.kotlin.lexer.KotlinLexer
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.lexer.KtTokens.COMMENTS
import org.jetbrains.kotlin.lexer.KtTokens.IDENTIFIER
import org.jetbrains.kotlin.lexer.KtTokens.LBRACE
import org.jetbrains.kotlin.lexer.KtTokens.PACKAGE_KEYWORD
import org.jetbrains.kotlin.lexer.KtTokens.RBRACE
import org.jetbrains.kotlin.lexer.KtTokens.WHITE_SPACE
internal
class UnexpectedBlock(val identifier: String, val location: IntRange) : RuntimeException("Unexpected block found.")
private
enum class State {
SearchingTopLevelBlock,
SearchingBlockStart,
SearchingBlockEnd
}
data class Packaged<T>(
val packageName: String?,
val document: T
) {
fun <U> map(transform: (T) -> U): Packaged<U> = Packaged(
packageName,
document = transform(document)
)
}
internal
data class LexedScript(
val comments: List<IntRange>,
val topLevelBlocks: List<TopLevelBlock>
)
/**
* Returns the comments and [top-level blocks][topLevelBlockIds] found in the given [script].
*/
internal
fun lex(script: String, vararg topLevelBlockIds: String): Packaged<LexedScript> {
var packageName: String? = null
val comments = mutableListOf<IntRange>()
val topLevelBlocks = mutableListOf<TopLevelBlock>()
var state = State.SearchingTopLevelBlock
var inTopLevelBlock: String? = null
var blockIdentifier: IntRange? = null
var blockStart: Int? = null
var depth = 0
fun reset() {
state = State.SearchingTopLevelBlock
inTopLevelBlock = null
blockIdentifier = null
blockStart = null
}
fun KotlinLexer.matchTopLevelIdentifier(): Boolean {
if (depth == 0) {
val identifier = tokenText
for (topLevelBlock in topLevelBlockIds) {
if (topLevelBlock == identifier) {
state = State.SearchingBlockStart
inTopLevelBlock = topLevelBlock
blockIdentifier = tokenStart..(tokenEnd - 1)
return true
}
}
}
return false
}
KotlinLexer().apply {
start(script)
while (tokenType != null) {
when (tokenType) {
WHITE_SPACE -> {
// ignore
}
in COMMENTS -> {
comments.add(
tokenStart..(tokenEnd - 1)
)
}
else -> {
when (state) {
State.SearchingTopLevelBlock -> {
when (tokenType) {
PACKAGE_KEYWORD -> {
advance()
skipWhiteSpaceAndComments()
packageName = parseQualifiedName()
}
IDENTIFIER -> matchTopLevelIdentifier()
LBRACE -> depth += 1
RBRACE -> depth -= 1
}
}
State.SearchingBlockStart -> {
when (tokenType) {
IDENTIFIER -> if (!matchTopLevelIdentifier()) reset()
LBRACE -> {
depth += 1
state = State.SearchingBlockEnd
blockStart = tokenStart
}
else -> reset()
}
}
State.SearchingBlockEnd -> {
when (tokenType) {
LBRACE -> depth += 1
RBRACE -> {
depth -= 1
if (depth == 0) {
topLevelBlocks.add(
topLevelBlock(
inTopLevelBlock!!,
blockIdentifier!!,
blockStart!!..tokenStart
)
)
reset()
}
}
}
}
}
}
}
advance()
}
}
return Packaged(
packageName,
LexedScript(comments, topLevelBlocks)
)
}
private
fun KotlinLexer.parseQualifiedName(): String =
StringBuilder().run {
while (tokenType == KtTokens.IDENTIFIER || tokenType == KtTokens.DOT) {
append(tokenText)
advance()
}
toString()
}
private
fun KotlinLexer.skipWhiteSpaceAndComments() {
while (tokenType in KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET) {
advance()
}
}
internal
fun topLevelBlock(identifier: String, identifierRange: IntRange, blockRange: IntRange) =
TopLevelBlock(identifier, ScriptSection(identifierRange, blockRange))
internal
data class TopLevelBlock(val identifier: String, val section: ScriptSection) {
val range: IntRange
get() = section.wholeRange
}
internal
fun List<TopLevelBlock>.singleBlockSectionOrNull(): ScriptSection? =
when (size) {
0 -> null
1 -> get(0).section
else -> {
val unexpectedBlock = get(1)
throw UnexpectedBlock(unexpectedBlock.identifier, unexpectedBlock.range)
}
}
| subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/execution/Lexer.kt | 3273949197 |
/*
* Copyright (c) 2015 Mark Platvoet<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* THE SOFTWARE.
*/
@file:JvmName("KovenantBulkApi")
package nl.komponents.kovenant
/**
* Creates a promise that is considered done if either all provided promises are successful or one fails.
*
* Creates a promise that is considered done if either all provided promises are successful or one fails. If all provided
* promises are successful this promise resolves with a `List<V>` of all the results. The order if the items in the list
* is the same order as the provided promises.
*
* If one or multiple promises result in failure this promise fails too. The error value of the first promise that fails
* will be the cause of fail of this promise. If [cancelOthersOnError] is `true` it is attempted to cancel the execution of
* the other promises.
*
* If provided no promises are provided an empty successful promise is returned.
*
* @param promises the promises that create the new combined promises of.
* @param context the context on which the newly created promise operates on. `Kovenant.context` by default.
* @param cancelOthersOnError whether an error of one promise attempts to cancel the other (unfinished) promises. `true` by default
*/
@JvmOverloads fun <V> all(vararg promises: Promise<V, Exception>,
context: Context = Kovenant.context,
cancelOthersOnError: Boolean = true): Promise<List<V>, Exception> {
return when (promises.size) {
0 -> Promise.ofSuccess(listOf(), context)
else -> concreteAll(promises = *promises, context = context, cancelOthersOnError = cancelOthersOnError)
}
}
/**
* Creates a promise that is considered done if either all provided promises are successful or one fails.
*
* Creates a promise that is considered done if either all provided promises are successful or one fails. If all provided
* promises are successful this promise resolves with a `List<V>` of all the results. The order if the items in the list
* is the same order as the provided promises.
*
* If one or multiple promises result in failure this promise fails too. The error value of the first promise that fails
* will be the cause of fail of this promise. If [cancelOthersOnError] is `true` it is attempted to cancel the execution of
* the other promises.
*
* If provided no promises are provided an empty successful promise is returned.
*
* @param promises the List of promises that create the new combined promises of.
* @param context the context on which the newly created promise operates on. `Kovenant.context` by default.
* @param cancelOthersOnError whether an error of one promise attempts to cancel the other (unfinished) promises. `true` by default
*/
@JvmOverloads fun <V> all(promises: List<Promise<V, Exception>>,
context: Context = Kovenant.context,
cancelOthersOnError: Boolean = true): Promise<List<V>, Exception> {
return when (promises.size) {
0 -> Promise.ofSuccess(listOf(), context)
else -> concreteAll(promises = promises, context = context, cancelOthersOnError = cancelOthersOnError)
}
}
/**
* Creates a promise that is considered done if either any provided promises is successful or all promises have failed.
*
* Creates a promise that is considered done if either any provided promises is successful or all promises have failed.
* If any of the provided promises is successful this promise resolves successful with that result.
* If [cancelOthersOnSuccess] is `true` it is attempted to cancel the execution of the other promises.
*
* If all promises result in failure this promise fails too with a `List` containing all failures. The order if the
* items in the list is the same order as the provided promises.
*
* If provided no promises are provided an empty failed promise is returned.
*
* @param promises the promises that create the new combined promises of.
* @param context the context on which the newly created promise operates on. `Kovenant.context` by default.
* @param cancelOthersOnSuccess whether a success of one promise attempts to cancel the other (unfinished) promises. `true` by default
*/
@JvmOverloads fun <V> any(vararg promises: Promise<V, Exception>,
context: Context = Kovenant.context,
cancelOthersOnSuccess: Boolean = true): Promise<V, List<Exception>> {
return when (promises.size) {
0 -> Promise.ofFail(listOf(), context)
else -> concreteAny(promises = *promises, context = context, cancelOthersOnSuccess = cancelOthersOnSuccess)
}
}
/**
* Creates a promise that is considered done if either any provided promises is successful or all promises have failed.
*
* Creates a promise that is considered done if either any provided promises is successful or all promises have failed.
* If any of the provided promises is successful this promise resolves successful with that result.
* If [cancelOthersOnSuccess] is `true` it is attempted to cancel the execution of the other promises.
*
* If all promises result in failure this promise fails too with a `List` containing all failures. The order if the
* items in the list is the same order as the provided promises.
*
* If provided no promises are provided an empty failed promise is returned.
*
* @param promises the List of promises that create the new combined promises of.
* @param context the context on which the newly created promise operates on. `Kovenant.context` by default.
* @param cancelOthersOnSuccess whether a success of one promise attempts to cancel the other (unfinished) promises. `true` by default
*/
@JvmOverloads fun <V> any(promises: List<Promise<V, Exception>>,
context: Context = Kovenant.context,
cancelOthersOnSuccess: Boolean = true): Promise<V, List<Exception>> {
return when (promises.size) {
0 -> Promise.ofFail(listOf(), context)
else -> concreteAny(promises = promises, context = context, cancelOthersOnSuccess = cancelOthersOnSuccess)
}
} | projects/core/src/main/kotlin/bulk-api.kt | 733624209 |
package net.upgaming.pbrengine.gameobject
import net.upgaming.pbrengine.material.Material
import net.upgaming.pbrengine.models.Model
import org.joml.Matrix4f
import org.joml.Vector3f
import org.lwjgl.system.MemoryUtil
import java.nio.FloatBuffer
class Entity(val model: Model, val material: Material = Material.default(), val position: Vector3f = Vector3f(),
val rotation: Vector3f = Vector3f(), var scale: Float = 1f) {
private val mmBuffer = MemoryUtil.memAllocFloat(16)
fun getModelMatrixFB(): FloatBuffer {
mmBuffer.clear()
val matrix = Matrix4f()
.translate(position)
.rotate(rotation.x, 1f, 0f, 0f)
.rotate(rotation.y, 0f, 1f, 0f)
.rotate(rotation.z, 0f, 0f, 1f)
.scale(scale)
matrix.get(mmBuffer)
return mmBuffer
}
fun delete() {
MemoryUtil.memFree(mmBuffer)
}
} | src/main/kotlin/net/upgaming/pbrengine/gameobject/Entity.kt | 1078078366 |
package io.particle.android.sdk.utils
import android.content.Intent
import androidx.localbroadcastmanager.content.LocalBroadcastManager
interface Broadcaster {
fun sendBroadcast(intent: Intent)
}
class BroadcastImpl(private val localBroadcaster: LocalBroadcastManager) : Broadcaster {
override fun sendBroadcast(intent: Intent) {
localBroadcaster.sendBroadcast(intent)
}
} | cloudsdk/src/main/java/io/particle/android/sdk/utils/Broadcaster.kt | 3129527323 |
package com.github.charbgr.cliffhanger.features.detail
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.ProgressBar
import android.widget.TextView
import com.github.charbgr.cliffhanger.features.detail.arch.Presenter
import com.github.charbgr.cliffhanger.features.detail.arch.UiBinder
import com.github.charbgr.cliffhanger.features.detail.arch.View
import com.github.charbgr.cliffhanger.shared.views.imageview.MovieImageView
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
class MovieDetailActivity : AppCompatActivity(), View {
companion object Contract {
const val MOVIE_ID_EXTRA = "movie:detail:id"
}
internal lateinit var uiBinder: UiBinder
internal lateinit var presenter: Presenter
private val disposable: CompositeDisposable = CompositeDisposable()
lateinit var backdrop: MovieImageView
lateinit var title: TextView
lateinit var poster: MovieImageView
lateinit var progressBar: ProgressBar
lateinit var overview: TextView
lateinit var tagline: TextView
lateinit var directedBy: TextView
lateinit var director: TextView
lateinit var chronology: TextView
lateinit var duration: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_movie_detail)
findViews()
uiBinder = UiBinder(this)
setUpPresenter()
uiBinder.onCreateView()
}
override fun onDestroy() {
presenter.destroy()
disposable.clear()
super.onDestroy()
}
private fun setUpPresenter() {
presenter = Presenter()
with(presenter) {
init(this@MovieDetailActivity)
bindIntents()
renders()
.subscribe { uiBinder.render(it) }
.addTo(disposable)
}
}
private fun findViews() {
backdrop = findViewById(R.id.movie_detail_backdrop)
title = findViewById(R.id.movie_detail_title)
poster = findViewById(R.id.movie_detail_poster)
overview = findViewById(R.id.movie_detail_overview)
tagline = findViewById(R.id.movie_detail_tagline)
directedBy = findViewById(R.id.movie_detail_directed_by)
director = findViewById(R.id.movie_detail_director)
chronology = findViewById(R.id.movie_detail_chronology)
duration = findViewById(R.id.movie_detail_duration)
progressBar = findViewById(R.id.movie_detail_progressbar)
}
override fun fetchMovieIntent(): Observable<Int> = uiBinder.fetchMovieIntent()
}
| cliffhanger/feature-movie-detail/src/main/kotlin/com/github/charbgr/cliffhanger/features/detail/MovieDetailActivity.kt | 1627589592 |
/*
* 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 common
interface BuildCache {
fun gradleParameters(os: Os): List<String>
}
data class RemoteBuildCache(val url: String, val username: String = "%gradle.cache.remote.username%", val password: String = "%gradle.cache.remote.password%") : BuildCache {
override fun gradleParameters(os: Os): List<String> {
return listOf("--build-cache",
os.escapeKeyValuePair("-Dgradle.cache.remote.url", url),
os.escapeKeyValuePair("-Dgradle.cache.remote.username", username),
os.escapeKeyValuePair("-Dgradle.cache.remote.password", password)
)
}
}
val builtInRemoteBuildCacheNode = RemoteBuildCache("%gradle.cache.remote.url%")
object NoBuildCache : BuildCache {
override fun gradleParameters(os: Os): List<String> {
return emptyList()
}
}
private
fun Os.escapeKeyValuePair(key: String, value: String) = if (this == Os.windows) """$key="$value"""" else """"$key=$value""""
| .teamcity/common/BuildCache.kt | 1884466384 |
package com.github.charbgr.cliffhanger.feature.home.arch.state
import com.github.charbgr.cliffhanger.domain.MovieCategory.NowPlaying
import com.github.charbgr.cliffhanger.domain.MovieCategory.Popular
import com.github.charbgr.cliffhanger.domain.MovieCategory.TopRated
import com.github.charbgr.cliffhanger.domain.MovieCategory.Upcoming
import com.github.charbgr.cliffhanger.feature.home.arch.HomeViewModel
class HomeStateReducer {
private val categoryReducer: CategoryStateReducer = CategoryStateReducer()
val reduce: (previousViewModel: HomeViewModel, partialChange: PartialChange) -> HomeViewModel =
{ previousViewModel, partialChange ->
when (partialChange.movieCategory) {
is TopRated -> {
val prevCategoryVM = previousViewModel.topRated
previousViewModel.copy(topRated = categoryReducer.reduce(prevCategoryVM, partialChange),
currentPartialChange = partialChange)
}
is NowPlaying -> {
val prevCategoryVM = previousViewModel.nowPlaying
previousViewModel.copy(
nowPlaying = categoryReducer.reduce(prevCategoryVM, partialChange),
currentPartialChange = partialChange)
}
is Upcoming -> {
val prevCategoryVM = previousViewModel.upcoming
previousViewModel.copy(upcoming = categoryReducer.reduce(prevCategoryVM, partialChange),
currentPartialChange = partialChange)
}
is Popular -> {
val prevCategoryVM = previousViewModel.popular
previousViewModel.copy(popular = categoryReducer.reduce(prevCategoryVM, partialChange),
currentPartialChange = partialChange)
}
else -> {
previousViewModel
}
}
}
}
| cliffhanger/feature-home/src/main/kotlin/com/github/charbgr/cliffhanger/feature/home/arch/state/HomeStateReducer.kt | 72009759 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho.codelab
import androidx.recyclerview.widget.OrientationHelper
import com.facebook.litho.Component
import com.facebook.litho.ComponentContext
import com.facebook.litho.annotations.FromEvent
import com.facebook.litho.annotations.LayoutSpec
import com.facebook.litho.annotations.OnCreateLayout
import com.facebook.litho.annotations.OnEvent
import com.facebook.litho.annotations.Prop
import com.facebook.litho.sections.SectionContext
import com.facebook.litho.sections.common.DataDiffSection
import com.facebook.litho.sections.common.RenderEvent
import com.facebook.litho.sections.widget.ListRecyclerConfiguration
import com.facebook.litho.sections.widget.RecyclerCollectionComponent
import com.facebook.litho.widget.ComponentRenderInfo
import com.facebook.litho.widget.RenderInfo
import com.facebook.litho.widget.SolidColor
/**
* This component renders a horizontal list. The height of the list is fixed, and it's set by
* passing a height prop to the RecyclerCollectionComponent.
*/
@Suppress("MagicNumber")
@LayoutSpec
object FixedHeightHscrollComponentSpec {
@OnCreateLayout
fun onCreateLayout(c: ComponentContext, @Prop colors: List<Int>): Component {
return RecyclerCollectionComponent.create(c)
.recyclerConfiguration(
ListRecyclerConfiguration.create().orientation(OrientationHelper.HORIZONTAL).build())
.section(
DataDiffSection.create<Int>(SectionContext(c))
.data(colors)
.renderEventHandler(FixedHeightHscrollComponent.onRender(c))
.build())
.heightDip(150f)
.build()
}
@OnEvent(RenderEvent::class)
fun onRender(c: ComponentContext, @FromEvent model: Int): RenderInfo {
return ComponentRenderInfo.create()
.component(SolidColor.create(c).color(model).heightDip(100f).widthDip(100f))
.build()
}
}
| codelabs/hscroll-height/app/src/main/java/com/facebook/litho/codelab/FixedHeightHscrollComponentSpec.kt | 2967102084 |
import com.google.gson.Gson
import io.vertx.core.AsyncResult
import io.vertx.core.Future
import io.vertx.core.Vertx
import io.vertx.core.json.Json
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import io.vertx.ext.web.handler.BodyHandler
import java.util.*
import kotlin.reflect.KClass
/**
* Step02 - In memory REST User repository
*/
object Vertx3KotlinRestJdbcTutorial {
val gson = Gson()
@JvmStatic fun main(args: Array<String>) {
val port = 9000
val vertx = Vertx.vertx()
val server = vertx.createHttpServer()
val router = Router.router(vertx)
router.route().handler(BodyHandler.create()) // Required for RoutingContext.bodyAsString
val userService = MemoryUserService()
router.get("/:userId").handler { ctx ->
val userId = ctx.request().getParam("userId")
jsonResponse(ctx, userService.getUser(userId))
}
router.post("/").handler { ctx ->
val user = jsonRequest<User>(ctx, User::class)
jsonResponse(ctx, userService.addUser(user))
}
router.delete("/:userId").handler { ctx ->
val userId = ctx.request().getParam("userId")
jsonResponse(ctx, userService.remUser(userId))
}
server.requestHandler { router.accept(it) }.listen(port) {
if (it.succeeded()) println("Server listening at $port")
else println(it.cause())
}
}
fun jsonRequest<T>(ctx: RoutingContext, clazz: KClass<out Any>): T =
gson.fromJson(ctx.bodyAsString, clazz.java) as T
fun jsonResponse<T>(ctx: RoutingContext, future: Future<T>) {
future.setHandler {
if (it.succeeded()) {
val res = if (it.result() == null) "" else gson.toJson(it.result())
ctx.response().end(res)
} else {
ctx.response().setStatusCode(500).end(it.cause().toString())
}
}
}
}
//-----------------------------------------------------------------------------
// API
data class User(val id:String, val fname: String, val lname: String)
interface UserService {
fun getUser(id: String): Future<User>
fun addUser(user: User): Future<Unit>
fun remUser(id: String): Future<Unit>
}
//-----------------------------------------------------------------------------
// IMPLEMENTATION
class MemoryUserService(): UserService {
val _users = HashMap<String, User>()
init {
addUser(User("1", "user1_fname", "user1_lname"))
}
override fun getUser(id: String): Future<User> {
return if (_users.containsKey(id)) Future.succeededFuture(_users.getOrImplicitDefault(id))
else Future.failedFuture(IllegalArgumentException("Unknown user $id"))
}
override fun addUser(user: User): Future<Unit> {
_users.put(user.id, user)
return Future.succeededFuture()
}
override fun remUser(id: String): Future<Unit> {
_users.remove(id)
return Future.succeededFuture()
}
} | step02/src/tutorial02.kt | 4239873261 |
package `in`.shabhushan.cp_trials.logic
import org.junit.Assert.assertArrayEquals
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class ArraysTest {
@Test
fun testContainsDuplicate() {
assertTrue(containsDuplicate(intArrayOf(1, 2, 3, 1)))
}
@Test
fun testContainsNearbyDuplicate() {
assertTrue(containsNearbyDuplicate(intArrayOf(1, 2, 3, 1), 3))
assertTrue(containsNearbyDuplicate(intArrayOf(1, 0, 1, 1), 1))
assertFalse(containsNearbyDuplicate(intArrayOf(1, 2, 3, 1, 2, 3), 2))
assertFalse(containsNearbyDuplicate(intArrayOf(), 0))
assertFalse(containsNearbyDuplicate(intArrayOf(1), 1))
assertFalse(containsNearbyDuplicate(intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 15))
}
@Test
fun testContainsNearbyAlmostDuplicate() {
assertTrue(containsNearbyAlmostDuplicate(intArrayOf(1, 2, 3, 1), 3, 0))
assertTrue(containsNearbyAlmostDuplicate(intArrayOf(1, 3, 1, 1), 1, 2))
assertFalse(containsNearbyAlmostDuplicate(intArrayOf(1, 5, 9, 1, 5, 9), 2, 3))
assertFalse(
containsNearbyAlmostDuplicate(
intArrayOf(-1, 2147483647),
1,
2147483647
)
)
}
@Test
fun testRemoveDuplicates_KeepingTwoOfSame() {
val input = intArrayOf(1,1,1,2,2,3)
val output = removeDuplicates(input)
assertArrayEquals(arrayOf(1,1,2,2,3), input.take(output).toTypedArray())
}
@Test
fun testHornerMethod() {
assertEquals(5, horner(intArrayOf(5, -6, 7, 8, -9), 1))
assertEquals(67, horner(intArrayOf(5, -6, 7, 8, -9), 2))
}
}
| cp-trials/src/test/kotlin/in/shabhushan/cp_trials/logic/ArraysTest.kt | 3050469067 |
package com.github.jaydeepw.boilerplate
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
}
| app/src/main/java/com/github/jaydeepw/boilerplate/MainActivity.kt | 2794798604 |
package org.wordpress.android.fluxc.store.qrcodeauth
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.any
import org.mockito.kotlin.whenever
import org.wordpress.android.fluxc.network.rest.wpcom.qrcodeauth.QRCodeAuthError
import org.wordpress.android.fluxc.network.rest.wpcom.qrcodeauth.QRCodeAuthErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.network.rest.wpcom.qrcodeauth.QRCodeAuthPayload
import org.wordpress.android.fluxc.network.rest.wpcom.qrcodeauth.QRCodeAuthRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.qrcodeauth.QRCodeAuthRestClient.QRCodeAuthAuthenticateResponse
import org.wordpress.android.fluxc.network.rest.wpcom.qrcodeauth.QRCodeAuthRestClient.QRCodeAuthValidateResponse
import org.wordpress.android.fluxc.store.qrcodeauth.QRCodeAuthStore.QRCodeAuthAuthenticateResult
import org.wordpress.android.fluxc.store.qrcodeauth.QRCodeAuthStore.QRCodeAuthResult
import org.wordpress.android.fluxc.store.qrcodeauth.QRCodeAuthStore.QRCodeAuthValidateResult
import org.wordpress.android.fluxc.test
import org.wordpress.android.fluxc.tools.initCoroutineEngine
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
@RunWith(MockitoJUnitRunner::class)
class QRCodeAuthStoreTest {
@Mock private lateinit var qrcodeAuthRestClient: QRCodeAuthRestClient
private lateinit var qrcodeAuthStore: QRCodeAuthStore
@Before
fun setUp() {
qrcodeAuthStore = QRCodeAuthStore(qrcodeAuthRestClient, initCoroutineEngine())
}
private val validateResponseSuccess = QRCodeAuthValidateResponse(
browser = BROWSER,
location = LOCATION,
success = SUCCESS
)
private val validateResultSuccess = QRCodeAuthValidateResult(
browser = BROWSER,
location = LOCATION,
success = SUCCESS
)
private val authenticateResponseSuccess = QRCodeAuthAuthenticateResponse(
authenticated = AUTHENTICATED
)
private val authenticateResultSuccess = QRCodeAuthAuthenticateResult(
authenticated = AUTHENTICATED
)
private val responseError = QRCodeAuthError(
type = GENERIC_ERROR
)
private val resultError = QRCodeAuthError(
type = GENERIC_ERROR
)
@Test
fun `given success, when validate is triggered, then validate result is returned`() = test {
whenever(qrcodeAuthRestClient.validate(any(), any())).thenReturn(
QRCodeAuthPayload(validateResponseSuccess)
)
val response = qrcodeAuthStore.validate(DATA_PARAM, TOKEN_PARAM)
assertNotNull(response.model)
assertEquals(QRCodeAuthResult(validateResultSuccess), response)
}
@Test
fun `given error, when validate is triggered, then error result is returned`() = test {
whenever(qrcodeAuthRestClient.validate(any(), any())).thenReturn(
QRCodeAuthPayload(responseError)
)
val response = qrcodeAuthStore.validate(DATA_PARAM, TOKEN_PARAM)
assertNull(response.model)
assertEquals(QRCodeAuthResult(resultError), response)
}
@Test
fun `given success, when authenticate is triggered, then authenticate result is returned`() = test {
whenever(qrcodeAuthRestClient.authenticate(any(), any())).thenReturn(
QRCodeAuthPayload(authenticateResponseSuccess)
)
val response = qrcodeAuthStore.authenticate(DATA_PARAM, TOKEN_PARAM)
assertNotNull(response.model)
assertEquals(QRCodeAuthResult(authenticateResultSuccess), response)
}
@Test
fun `given error, when authenticate is triggered, then error result is returned`() = test {
whenever(qrcodeAuthRestClient.authenticate(any(), any())).thenReturn(
QRCodeAuthPayload(responseError)
)
val response = qrcodeAuthStore.authenticate(DATA_PARAM, TOKEN_PARAM)
assertNull(response.model)
assertEquals(QRCodeAuthResult(resultError), response)
}
companion object {
private const val TOKEN_PARAM = "token_param"
private const val DATA_PARAM = "data_param"
private const val BROWSER = "Chrome"
private const val LOCATION = "Secaucus, New Jersey"
private const val SUCCESS = true
private const val AUTHENTICATED = true
}
}
| example/src/test/java/org/wordpress/android/fluxc/store/qrcodeauth/QRCodeAuthStoreTest.kt | 2274950139 |
/*
* Copyright 2019 Andrey Tolpeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.vase4kin.teamcityapp.runbuild.view
import android.content.Intent
import android.view.View
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.isEnabled
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.github.vase4kin.teamcityapp.R
import com.github.vase4kin.teamcityapp.TeamCityApplication
import com.github.vase4kin.teamcityapp.api.TeamCityService
import com.github.vase4kin.teamcityapp.buildlist.api.Build
import com.github.vase4kin.teamcityapp.dagger.components.AppComponent
import com.github.vase4kin.teamcityapp.dagger.components.RestApiComponent
import com.github.vase4kin.teamcityapp.dagger.modules.AppModule
import com.github.vase4kin.teamcityapp.dagger.modules.Mocks
import com.github.vase4kin.teamcityapp.dagger.modules.RestApiModule
import com.github.vase4kin.teamcityapp.helper.CustomActivityTestRule
import com.github.vase4kin.teamcityapp.helper.any
import com.github.vase4kin.teamcityapp.runbuild.api.Branch
import com.github.vase4kin.teamcityapp.runbuild.api.Branches
import com.github.vase4kin.teamcityapp.runbuild.interactor.CODE_FORBIDDEN
import com.github.vase4kin.teamcityapp.runbuild.interactor.EXTRA_BUILD_TYPE_ID
import io.reactivex.Single
import it.cosenonjaviste.daggermock.DaggerMockRule
import okhttp3.ResponseBody
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.instanceOf
import org.hamcrest.Matchers.not
import org.hamcrest.core.AllOf.allOf
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Matchers.anyString
import org.mockito.Mock
import org.mockito.Mockito.`when`
import retrofit2.HttpException
import retrofit2.Response
import java.util.ArrayList
/**
* Tests for [RunBuildActivity]
*/
@RunWith(AndroidJUnit4::class)
class RunBuildActivityMockTest {
@Rule
@JvmField
val daggerRule: DaggerMockRule<RestApiComponent> =
DaggerMockRule(RestApiComponent::class.java, RestApiModule(Mocks.URL))
.addComponentDependency(
AppComponent::class.java,
AppModule(InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication)
)
.set { restApiComponent ->
val app =
InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication
app.setRestApiInjector(restApiComponent)
}
@Rule
@JvmField
val activityRule: CustomActivityTestRule<RunBuildActivity> =
CustomActivityTestRule(RunBuildActivity::class.java)
@Mock
lateinit var responseBody: ResponseBody
@Mock
lateinit var teamCityService: TeamCityService
@Before
fun setUp() {
val app =
InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication
app.restApiInjector.sharedUserStorage().clearAll()
app.restApiInjector.sharedUserStorage()
.saveGuestUserAccountAndSetItAsActive(Mocks.URL, false)
}
@Test
fun testUserCanSeeErrorForbiddenSnackBarIfServerReturnsAnError() {
// Prepare mocks
val httpException = HttpException(Response.error<Build>(CODE_FORBIDDEN, responseBody))
`when`(teamCityService.queueBuild(any())).thenReturn(
Single.error(
httpException
)
)
`when`(teamCityService.listAgents(any(), any(), any())).thenReturn(Single.just(Mocks.connectedAgents()))
`when`(teamCityService.listBranches(any())).thenReturn(Single.just(Branches(emptyList())))
`when`(teamCityService.buildType(any())).thenReturn(Single.just(Mocks.buildTypeMock()))
// Prepare intent
val intent = Intent()
intent.putExtra(EXTRA_BUILD_TYPE_ID, "href")
// Starting the activity
activityRule.launchActivity(intent)
// Starting the build
onView(withId(R.id.fab_queue_build)).perform(click())
// Checking the error snackbar text
onView(withText(R.string.error_forbidden_error)).check(matches(isDisplayed()))
}
@Test
fun testUserCanSeeErrorSnackBarIfServerReturnsAnError() {
// Prepare mocks
`when`(teamCityService.queueBuild(any())).thenReturn(
Single.error(
RuntimeException("error")
)
)
`when`(teamCityService.listAgents(any(), any(), any())).thenReturn(Single.just(Mocks.connectedAgents()))
`when`(teamCityService.listBranches(any())).thenReturn(Single.just(Branches(emptyList())))
`when`(teamCityService.buildType(any())).thenReturn(Single.just(Mocks.buildTypeMock()))
// Prepare intent
val intent = Intent()
intent.putExtra(EXTRA_BUILD_TYPE_ID, "href")
// Starting the activity
activityRule.launchActivity(intent)
// Starting the build
onView(withId(R.id.fab_queue_build)).perform(click())
// Checking the error snackbar text
onView(withText(R.string.error_base_error)).check(matches(isDisplayed()))
}
@Test
fun testUserCanSeeMultipleBranchesIfBuildTypeHasMultipleAvailable() {
// Prepare mocks
val branches = ArrayList<Branch>()
branches.add(Branch("dev1"))
branches.add(Branch("dev2"))
`when`(teamCityService.listBranches(anyString())).thenReturn(Single.just(Branches(branches)))
`when`(teamCityService.listAgents(any(), any(), any())).thenReturn(Single.just(Mocks.connectedAgents()))
`when`(teamCityService.buildType(any())).thenReturn(Single.just(Mocks.buildTypeMock()))
// Prepare intent
val intent = Intent()
intent.putExtra(EXTRA_BUILD_TYPE_ID, "href")
// Starting the activity
activityRule.launchActivity(intent)
// Choose branch from autocomplete and verify it is appeared
onView(withId(R.id.autocomplete_branches))
.perform(typeText("dev"))
onData(allOf(`is`(instanceOf<Any>(String::class.java)), `is`<String>("dev1")))
.inRoot(RootMatchers.withDecorView(not(`is`<View>(activityRule.activity.window.decorView))))
.perform(click())
onView(withText("dev1")).perform(click())
onView(withId(R.id.autocomplete_branches)).check(
matches(
allOf(
withText("dev1"),
isEnabled()
)
)
)
}
}
| app/src/androidTest/java/com/github/vase4kin/teamcityapp/runbuild/view/RunBuildActivityMockTest.kt | 690291476 |
/*
* Copyright (C) 2019 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 com.example.android.architecture.blueprints.todoapp.data
import com.example.android.architecture.blueprints.todoapp.data.Result.Success
/**
* A generic class that holds a value with its loading status.
* @param <T>
*/
sealed class Result<out R> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
object Loading : Result<Nothing>()
override fun toString(): String {
return when (this) {
is Success<*> -> "Success[data=$data]"
is Error -> "Error[exception=$exception]"
Loading -> "Loading"
}
}
}
/**
* `true` if [Result] is of type [Success] & holds non-null [Success.data].
*/
val Result<*>.succeeded
get() = this is Success && data != null
| app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/Result.kt | 944144324 |
package org.jetbrains.dokka.base.templating
data class PathToRootSubstitutionCommand(override val pattern: String, val default: String): SubstitutionCommand() | plugins/base/src/main/kotlin/templating/PathToRootSubstitutionCommand.kt | 1229514765 |
package rxjoin.internal.codegen
import rxjoin.internal.codegen.Model.JoinerModel.InOutRegistry
import javax.annotation.processing.Filer
import javax.annotation.processing.Messager
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.element.Element
import javax.lang.model.element.TypeElement
import javax.lang.model.util.Elements
import javax.lang.model.util.Types
class Model(val roundEnv: RoundEnvironment, val filer: Filer,
val messager: Messager, val types: Types, val elements: Elements,
val joinerModels: MutableList<JoinerModel> = mutableListOf()) {
class JoinerModel(
val enclosing: TypeElement,
val enclosed: Element,
val registry: MutableList<InOutRegistry> = mutableListOf()) : MutableList<InOutRegistry> by registry {
class Entry(val enclosingElement: Element, val element: Element)
class InOutRegistry(val id: String, val outEntry: Entry, val inEntries: MutableList<Entry> = mutableListOf())
}
}
| compiler/src/main/kotlin/rxjoin/internal/codegen/Model.kt | 929018749 |
package com.artfable.telegram.api
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
/**
* @author aveselov
* @since 02/09/2020
*/
@JsonIgnoreProperties(ignoreUnknown = true)
data class Poll(
@JsonProperty("id") val id: String,
@JsonProperty("question") val question: String,
@JsonProperty("options") val options: List<PollOption>,
@JsonProperty("total_voter_count") val totalVoterCount: Int,
@JsonProperty("is_closed") val closed: Boolean,
@JsonProperty("is_anonymous") val anonymous: Boolean,
@JsonProperty("type") val type: PollType,
@JsonProperty("allows_multiple_answers") val allowsMultipleAnswers: Boolean,
@JsonProperty("correct_option_id") val correctOptionId: Int? = null,
@JsonProperty("explanation") val explanation: String? = null,
// TODO: explanation_entities Array of MessageEntity Optional.
@JsonProperty("open_period") val openPeriod: Long? = null,
@JsonProperty("close_date") val closeDate: Long? = null
) | src/main/kotlin/com/artfable/telegram/api/Poll.kt | 3400095078 |
package ii_collections
fun example6() {
listOf(1, 3).sum() == 4
listOf("a", "b", "cc").sumBy { it.length } == 4
}
fun Customer.getTotalOrderPrice(): Double {
// Return the sum of prices of all products that a customer has ordered.
// Note: a customer may order the same product for several times.
return orders.flatMap { it.products }.sumByDouble { it.price }
}
| src/ii_collections/n19Sum.kt | 1237852359 |
/*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.doctoror.fuckoffmusicplayer.domain.queue
import android.net.Uri
import io.reactivex.Observable
/**
* "File" playlist provider
*/
interface QueueProviderFiles {
fun fromFile(uri: Uri): Observable<List<Media>>
}
| domain/src/main/java/com/doctoror/fuckoffmusicplayer/domain/queue/QueueProviderFiles.kt | 1356643828 |
/*
* Copyright (c) 2019 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.yobidashi.settings.background.load
import android.content.ContentResolver
import android.graphics.Bitmap
import android.graphics.Matrix
import android.net.Uri
import androidx.exifinterface.media.ExifInterface
import java.io.FileDescriptor
/**
* @author toastkidjp
*/
class RotatedImageFixing(
private val exifInterfaceFactory: (FileDescriptor) -> ExifInterface = { ExifInterface(it) }
) {
operator fun invoke(contentResolver: ContentResolver, bitmap: Bitmap?, imageUri: Uri): Bitmap? {
if (bitmap == null) {
return null
}
val openFileDescriptor = contentResolver.openFileDescriptor(imageUri, "r") ?: return bitmap
val exifInterface = exifInterfaceFactory(openFileDescriptor.fileDescriptor)
val orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL
)
return when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> rotate(bitmap, 90F)
ExifInterface.ORIENTATION_ROTATE_180 -> rotate(bitmap, 180F)
ExifInterface.ORIENTATION_ROTATE_270 -> rotate(bitmap, 270F)
else -> bitmap
}
}
private fun rotate(bitmap: Bitmap, degree: Float): Bitmap? {
val matrix = Matrix()
matrix.postRotate(degree)
val rotatedBitmap = Bitmap.createBitmap(
bitmap,
0,
0,
bitmap.width,
bitmap.height,
matrix,
true
)
bitmap.recycle()
return rotatedBitmap
}
} | app/src/main/java/jp/toastkid/yobidashi/settings/background/load/RotatedImageFixing.kt | 1710042407 |
/*
* 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.article_viewer.zip
import android.content.Intent
import android.content.IntentFilter
class ZipLoadProgressBroadcastIntentFactory {
operator fun invoke(progress: Int): Intent {
val progressIntent = Intent(ACTION_PROGRESS_BROADCAST)
progressIntent.putExtra("progress", progress)
return progressIntent
}
companion object {
private const val ACTION_PROGRESS_BROADCAST = "jp.toastkid.articles.importing.progress"
fun makeProgressBroadcastIntentFilter() = IntentFilter(ACTION_PROGRESS_BROADCAST)
}
} | article/src/main/java/jp/toastkid/article_viewer/zip/ZipLoadProgressBroadcastIntentFactory.kt | 2558009415 |
package eu.kanade.tachiyomi.ui.setting
import android.graphics.drawable.Drawable
import android.support.v7.preference.PreferenceGroup
import android.support.v7.preference.PreferenceScreen
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.source.online.LoginSource
import eu.kanade.tachiyomi.util.LocaleHelper
import eu.kanade.tachiyomi.widget.preference.LoginCheckBoxPreference
import eu.kanade.tachiyomi.widget.preference.SourceLoginDialog
import eu.kanade.tachiyomi.widget.preference.SwitchPreferenceCategory
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.*
class SettingsSourcesController : SettingsController(),
SourceLoginDialog.Listener {
private val onlineSources by lazy { Injekt.get<SourceManager>().getOnlineSources() }
override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) {
titleRes = R.string.pref_category_sources
// Get the list of active language codes.
val activeLangsCodes = preferences.enabledLanguages().getOrDefault()
// Get a map of sources grouped by language.
val sourcesByLang = onlineSources.groupByTo(TreeMap(), { it.lang })
// Order first by active languages, then inactive ones
val orderedLangs = sourcesByLang.keys.filter { it in activeLangsCodes } +
sourcesByLang.keys.filterNot { it in activeLangsCodes }
orderedLangs.forEach { lang ->
val sources = sourcesByLang[lang].orEmpty().sortedBy { it.name }
// Create a preference group and set initial state and change listener
SwitchPreferenceCategory(context).apply {
preferenceScreen.addPreference(this)
title = LocaleHelper.getDisplayName(lang, context)
isPersistent = false
if (lang in activeLangsCodes) {
setChecked(true)
addLanguageSources(this, sources)
}
onChange { newValue ->
val checked = newValue as Boolean
val current = preferences.enabledLanguages().getOrDefault()
if (!checked) {
preferences.enabledLanguages().set(current - lang)
removeAll()
} else {
preferences.enabledLanguages().set(current + lang)
addLanguageSources(this, sources)
}
true
}
}
}
}
override fun setDivider(divider: Drawable?) {
super.setDivider(null)
}
/**
* Adds the source list for the given group (language).
*
* @param group the language category.
*/
private fun addLanguageSources(group: PreferenceGroup, sources: List<HttpSource>) {
val hiddenCatalogues = preferences.hiddenCatalogues().getOrDefault()
sources.forEach { source ->
val sourcePreference = LoginCheckBoxPreference(group.context, source).apply {
val id = source.id.toString()
title = source.name
key = getSourceKey(source.id)
isPersistent = false
isChecked = id !in hiddenCatalogues
onChange { newValue ->
val checked = newValue as Boolean
val current = preferences.hiddenCatalogues().getOrDefault()
preferences.hiddenCatalogues().set(if (checked)
current - id
else
current + id)
true
}
setOnLoginClickListener {
val dialog = SourceLoginDialog(source)
dialog.targetController = this@SettingsSourcesController
dialog.showDialog(router)
}
}
group.addPreference(sourcePreference)
}
}
override fun loginDialogClosed(source: LoginSource) {
val pref = findPreference(getSourceKey(source.id)) as? LoginCheckBoxPreference
pref?.notifyChanged()
}
private fun getSourceKey(sourceId: Long): String {
return "source_$sourceId"
}
} | app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsSourcesController.kt | 4110523605 |
package com.airbnb.mvrx.hellodagger
import com.airbnb.mvrx.Success
import com.airbnb.mvrx.test.MvRxTestRule
import com.airbnb.mvrx.withState
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.flow.flowOf
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
internal class HelloViewModelTest {
@get:Rule
val mvrxRule = MvRxTestRule()
@Test
fun `fetches message when created`() {
val repo = mockk<HelloRepository> {
every { sayHello() } returns flowOf("Hello!")
}
val viewModel = HelloViewModel(HelloState(), repo)
withState(viewModel) { state ->
assertEquals(Success("Hello!"), state.message)
}
}
} | hellodagger/src/test/java/com/airbnb/mvrx/hellodagger/HelloViewModelTest.kt | 1940567822 |
package edu.cs4730.recyclerviewswiperefresh_kt
import android.os.Bundle
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
class MainActivity : AppCompatActivity() {
lateinit var mRecyclerView: RecyclerView
lateinit var mAdapter: myAdapter
lateinit var mSwipeRefreshLayout: SwipeRefreshLayout
var values = arrayOf(
"Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
"Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
"Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
"Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
"Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
"Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
"British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
"Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
"Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
"Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
"Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
"Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
"East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
"Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
"Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
"French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
"Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
"Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
"Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
"Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
"Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
"Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
"Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
"Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
"Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
"Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
"Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
"Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
"Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
"Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
"Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
"Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
"Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
"Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
"Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
"The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
"Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
"Ukraine", "United Arab Emirates", "United Kingdom",
"United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
"Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
"Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//setup the RecyclerView
mRecyclerView = findViewById(R.id.list)
mRecyclerView.layoutManager = LinearLayoutManager(this)
mRecyclerView.itemAnimator = DefaultItemAnimator()
//setup the adapter, which is myAdapter, see the code.
mAdapter = myAdapter(values, R.layout.my_row, this)
//add the adapter to the recyclerview
mRecyclerView.adapter = mAdapter
//SwipeRefreshlayout setup.
mSwipeRefreshLayout = findViewById(R.id.activity_main_swipe_refresh_layout)
//setup some colors for the refresh circle.
mSwipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue)
//now setup the swiperefrestlayout listener where the main work is done.
mSwipeRefreshLayout.setOnRefreshListener {
//where we call the refresher parts. normally some kind of networking async task or web service.
// For demo purpose, the code in the refreshslower method so it will take a couple of seconds
//otherwise, the task or service would just be called here.
refreshslower() //this will be slower, for the demo.
}
//setup left/right swipes on the cardviews
val simpleItemTouchCallback: ItemTouchHelper.SimpleCallback =
object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
//likely allows to for animations? or moving items in the view I think.
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
//called when it has been animated off the screen. So item is no longer showing.
//use ItemtouchHelper.X to find the correct one.
if (direction == ItemTouchHelper.RIGHT) {
//Toast.makeText(getBaseContext(),"Right?", Toast.LENGTH_SHORT).show();
val item =
viewHolder.absoluteAdapterPosition //think this is where in the array it is.
mAdapter.removeitem(item)
}
}
}
val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback)
itemTouchHelper.attachToRecyclerView(mRecyclerView)
}
/**
* so this is just for demo purposed and will wait a specified time the last numbere there
* listed in milliseconds. so 1.5 seconds is 1500. make it longer to see more colors in
* the refreshing circle.
*/
fun refreshslower() {
Handler().postDelayed({
//update the listview with new values.
mAdapter.randomlist() //normally something better then a random update.
mAdapter.notifyDataSetChanged() //cause the recyclerview to update.
mSwipeRefreshLayout.isRefreshing = false //turn of the refresh.
}, 2500)
}
} | RecyclerViews/RecyclerViewSwipeRefresh_kt/app/src/main/java/edu/cs4730/recyclerviewswiperefresh_kt/MainActivity.kt | 1813879279 |
package com.abdodaoud.merlin.extensions
import android.text.format.DateUtils
import java.text.DateFormat
import java.util.*
fun Long.toDateString(dateFormat: Int = DateFormat.MEDIUM): String {
val df = DateFormat.getDateInstance(dateFormat, Locale.getDefault())
return df.format(this)
}
fun Long.maxDate(currentPage: Int = 1): Long {
if (currentPage == 1) return this
return this.minDate(currentPage-1).past()
}
fun Long.minDate(currentPage: Int = 1): Long {
return this.future().past(currentPage * 10)
}
fun Long.zeroedTime(): Long {
return this - (this % DateUtils.DAY_IN_MILLIS)
}
fun Long.past(days: Int = 1): Long {
return this - (days * DateUtils.DAY_IN_MILLIS)
}
fun Long.future(days: Int = 1): Long {
return this + (days * DateUtils.DAY_IN_MILLIS)
}
fun String.parseMessage(): String {
return "\"" + this + "\"" + " - discover more facts through Merlin https://goo.gl/KQJPmJ"
} | app/src/main/java/com/abdodaoud/merlin/extensions/ExtensionUtils.kt | 239399239 |
package com.airbnb.mvrx.todomvrx.data.source.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.airbnb.mvrx.todomvrx.data.Task
/**
* The Room Database that contains the Task table.
*/
@Database(entities = [Task::class], version = 2)
abstract class ToDoDatabase : RoomDatabase() {
abstract fun taskDao(): TasksDao
companion object {
private var INSTANCE: ToDoDatabase? = null
private val lock = Any()
fun getInstance(context: Context): ToDoDatabase {
synchronized(lock) {
if (INSTANCE == null) {
INSTANCE = Room
.databaseBuilder(context.applicationContext, ToDoDatabase::class.java, "Tasks.db")
.build()
}
return INSTANCE!!
}
}
}
}
| todomvrx/src/main/java/com/airbnb/mvrx/todomvrx/data/source/db/ToDoDatabase.kt | 2779231156 |
/*
Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.application.impl
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.io.IOContext
import com.fasterxml.jackson.core.util.JsonParserDelegate
import com.fasterxml.jackson.databind.MappingJsonFactory
import org.apache.commons.text.StringSubstitutor
import org.apache.commons.text.lookup.StringLookup
import java.io.Reader
private class EnvLookUp : StringLookup {
override fun lookup(key: String): String? =
System.getenv(key)
}
internal class JsonInterpolatorParser(d: JsonParser?) : JsonParserDelegate(d) {
private val strSub = StringSubstitutor(EnvLookUp())
override fun getText(): String? {
val value = super.getText()
return value?.let { interpolateString(it) } ?: value
}
override fun getValueAsString(): String? {
return getValueAsString(null)
}
override fun getValueAsString(defaultValue: String?): String? {
val value = super.getValueAsString(defaultValue)
return value?.let { interpolateString(it) }
}
private fun interpolateString(string: String?): String? {
return strSub.replace(string)
}
}
internal class JsonInterpolatorParserFactory : MappingJsonFactory() {
override fun _createParser(
data: CharArray,
offset: Int,
len: Int,
ctxt: IOContext,
recyclable: Boolean
): JsonParser {
return JsonInterpolatorParser(super._createParser(data, offset, len, ctxt, recyclable))
}
override fun _createParser(r: Reader?, ctxt: IOContext?): JsonParser {
return JsonInterpolatorParser(super._createParser(r, ctxt))
}
} | src/orbit-application/src/main/kotlin/orbit/application/impl/InterpolatorParser.kt | 2663031435 |
package org.http4k.serverless
import dev.forkhandles.bunting.use
import org.http4k.serverless.openwhisk.PackagePut
object CreatePackage {
@JvmStatic
fun main(args: Array<String>) =
OpenWhiskCliFlags(args).use {
val openWhiskClient = openWhiskClient()
openWhiskClient.updatePackage("_", packageName, "true",
PackagePut("_", packageName)
)
}
}
| http4k-serverless/openwhisk/integration-test/src/test/kotlin/org/http4k/serverless/CreatePackage.kt | 2697281261 |
package org.ooverkommelig.definition
import org.ooverkommelig.Definition
import org.ooverkommelig.SubGraphDefinition
import kotlin.reflect.KProperty
// The sub graph definition is passed to the constructor because otherwise "SubGraphDefinitionCommon" has to cast itself
// to "SubGraphDefinition", and then the casted itself to "getValue(SubGraphDefinition)".
internal class OnceDelegate<TObject>(private val owner: SubGraphDefinition, private val propertyName: String, internal val create: () -> TObject) :
ObjectCreatingDefinitionDelegate<Definition<TObject>, TObject>(),
DelegateOfObjectToCreateEagerly<TObject> {
override fun registerPropertyIfNeeded(owner: SubGraphDefinition, property: KProperty<*>) {
owner.addDefinitionProperty(property, true)
}
override fun createDefinition(owner: SubGraphDefinition, name: String): Definition<TObject> = OnceDefinition(owner, name, this)
override fun getValue() = getValue(owner, propertyName)
}
| main/src/commonMain/kotlin/org/ooverkommelig/definition/OnceDelegate.kt | 3454941154 |
package cm.aptoide.pt.home.bundles.appcoins
import android.content.Context.WINDOW_SERVICE
import android.graphics.Rect
import android.view.View
import android.view.WindowManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cm.aptoide.aptoideviews.skeleton.Skeleton
import cm.aptoide.aptoideviews.skeleton.applySkeleton
import cm.aptoide.pt.R
import cm.aptoide.pt.dataprovider.model.v7.Type
import cm.aptoide.pt.home.bundles.base.AppBundle
import cm.aptoide.pt.home.bundles.base.AppBundleViewHolder
import cm.aptoide.pt.home.bundles.base.HomeBundle
import cm.aptoide.pt.home.bundles.base.HomeEvent
import cm.aptoide.pt.utils.AptoideUtils
import kotlinx.android.synthetic.main.bundle_earn_appcoins.view.*
import rx.subjects.PublishSubject
import java.text.DecimalFormat
class EarnAppCoinsViewHolder(val view: View,
decimalFormatter: DecimalFormat,
val uiEventsListener: PublishSubject<HomeEvent>) :
AppBundleViewHolder(view) {
private var adapter: EarnAppCoinsListAdapter =
EarnAppCoinsListAdapter(decimalFormatter, uiEventsListener)
private var skeleton: Skeleton? = null
init {
val layoutManager = LinearLayoutManager(view.context, LinearLayoutManager.HORIZONTAL, false)
itemView.apps_list.addItemDecoration(object : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView,
state: RecyclerView.State) {
val margin = AptoideUtils.ScreenU.getPixelsForDip(8, view.resources)
val marginBottom = AptoideUtils.ScreenU.getPixelsForDip(4, view.resources)
outRect.set(margin, margin, 0, marginBottom)
}
})
itemView.apps_list.layoutManager = layoutManager
itemView.apps_list.adapter = adapter
itemView.apps_list.isNestedScrollingEnabled = false
itemView.apps_list.setHasFixedSize(true)
val resources = view.context.resources
val windowManager = view.context.getSystemService(WINDOW_SERVICE) as WindowManager
skeleton = itemView.apps_list.applySkeleton(R.layout.earn_appcoins_item_skeleton,
Type.APPCOINS_ADS.getPerLineCount(resources, windowManager) * 3)
}
override fun setBundle(homeBundle: HomeBundle?, position: Int) {
if (homeBundle !is AppBundle) {
throw IllegalStateException(this.javaClass.name + " is getting non AppBundle instance!")
}
if (homeBundle.content == null) {
skeleton?.showSkeleton()
} else {
skeleton?.showOriginal()
adapter.updateBundle(homeBundle, position)
itemView.apps_list.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (dx > 0) {
uiEventsListener.onNext(
HomeEvent(homeBundle, adapterPosition, HomeEvent.Type.SCROLL_RIGHT))
}
}
})
itemView.setOnClickListener {
uiEventsListener.onNext(
HomeEvent(homeBundle, adapterPosition, HomeEvent.Type.APPC_KNOW_MORE))
}
itemView.see_more_btn.setOnClickListener {
uiEventsListener.onNext(HomeEvent(homeBundle, adapterPosition, HomeEvent.Type.MORE))
}
}
}
} | app/src/main/java/cm/aptoide/pt/home/bundles/appcoins/EarnAppCoinsViewHolder.kt | 1754854538 |
/*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2015-present Benoit 'BoD' Lubek ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jraf.android.androidwearcolorpicker
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewAnimationUtils
import android.view.ViewGroup
import android.view.ViewTreeObserver
import androidx.annotation.ColorInt
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.wear.widget.CurvingLayoutCallback
import androidx.wear.widget.WearableLinearLayoutManager
import org.jraf.android.androidwearcolorpicker.databinding.AwcpColorPickBinding
class ColorPickActivity : Activity() {
companion object {
const val EXTRA_RESULT = "EXTRA_RESULT"
const val EXTRA_OLD_COLOR = "EXTRA_OLD_COLOR"
const val EXTRA_COLORS = "EXTRA_COLORS"
/**
* Extracts the picked color from an onActivityResult data Intent.
*
* @param data The intent passed to onActivityResult.
* @return The resulting picked color, or 0 if the result could not be found in the given Intent.
*/
@Suppress("unused")
fun getPickedColor(data: Intent) = data.getIntExtra(EXTRA_RESULT, 0)
}
private lateinit var binding: AwcpColorPickBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.awcp_color_pick)!!
binding.rclList.setHasFixedSize(true)
binding.rclList.isEdgeItemsCenteringEnabled = true
// Apply an offset + scale on the items depending on their distance from the center (only for Round screens)
if (resources.configuration.isScreenRound) {
binding.rclList.layoutManager =
WearableLinearLayoutManager(this, object : CurvingLayoutCallback(this) {
override fun onLayoutFinished(child: View, parent: RecyclerView) {
super.onLayoutFinished(child, parent)
val childTop = child.y + child.height / 2f
val childOffsetFromCenter = childTop - parent.height / 2f
child.pivotX = 1f
child.rotation = -15f * (childOffsetFromCenter / parent.height)
}
})
// Also snap
LinearSnapHelper().attachToRecyclerView(binding.rclList)
} else {
// Square screen: no scale effect and no snapping
binding.rclList.layoutManager = WearableLinearLayoutManager(this)
}
val adapter = ColorAdapter(this, intent.getIntArrayExtra(EXTRA_COLORS)) { colorArgb, clickedView ->
setResult(RESULT_OK, Intent().putExtra(EXTRA_RESULT, colorArgb))
binding.vieRevealedColor.setBackgroundColor(colorArgb)
val clickedViewRect = Rect()
clickedView.getGlobalVisibleRect(clickedViewRect)
val finalRadius = Math.hypot(
binding.vieRevealedColor.width.toDouble(),
binding.vieRevealedColor.height.toDouble()
).toFloat()
val anim = ViewAnimationUtils.createCircularReveal(
binding.vieRevealedColor,
clickedViewRect.centerX(),
clickedViewRect.centerY(),
clickedViewRect.width() / 2F - 4,
finalRadius
)
anim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
finish()
}
})
binding.vieRevealedColor.visibility = View.VISIBLE
anim.start()
}
binding.rclList.adapter = adapter
val initialPosition = adapter.getMiddlePosition() +
if (intent?.hasExtra(EXTRA_OLD_COLOR) != true) 0
else adapter.colorToPositions(
intent!!.getIntExtra(
EXTRA_OLD_COLOR,
Color.WHITE
)
).first
binding.rclList.viewTreeObserver.addOnGlobalLayoutListener(object :
ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
val oldColor = intent!!.getIntExtra(EXTRA_OLD_COLOR, Color.WHITE)
binding.vieRevealedColor.setBackgroundColor(oldColor)
binding.vieRevealedColor.visibility = View.VISIBLE
val selectedViewIdx = adapter.colorToPositions(oldColor).second
val selectedView = (binding.rclList.layoutManager!!.findViewByPosition(0) as ViewGroup).getChildAt(selectedViewIdx)
val selectedViewRect = Rect()
selectedView.getGlobalVisibleRect(selectedViewRect)
ViewAnimationUtils.createCircularReveal(
binding.vieRevealedColor,
selectedViewRect.centerX(),
selectedViewRect.centerY(),
Math.hypot(
binding.vieRevealedColor.width.toDouble(),
binding.vieRevealedColor.height.toDouble()
).toFloat(),
selectedViewRect.width() / 2F - 4
).apply {
startDelay = 300
duration = 500
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
binding.vieRevealedColor.visibility = View.INVISIBLE
}
})
}
.start()
// For some unknown reason, this must be posted - if done right away, it doesn't work
Handler(Looper.getMainLooper()).post {
binding.rclList.scrollToPosition(initialPosition)
binding.rclList.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
}
})
}
@Suppress("unused")
class IntentBuilder {
private var oldColor: Int = Color.WHITE
private var colors: List<Int>? = null
/**
* Sets the initial value for the picked color.
* The default value is white.
*
* @param oldColor The old color to use as an ARGB int (the alpha component is ignored).
* @return This builder.
*/
fun oldColor(@ColorInt oldColor: Int): IntentBuilder {
this.oldColor = oldColor
return this
}
/**
* Sets the colors to display in the picker.
* This is optional - if not specified, all the colors of the rainbow will be used.
*
* @param colors The colors to display as ARGB ints (the alpha component is ignored).
* @return This builder.
*/
fun colors(colors: List<Int>): IntentBuilder {
this.colors = colors
return this
}
/**
* Build the resulting Intent.
*
* @param context The context to use to build the Intent.
* @return The build Intent.
*/
fun build(context: Context): Intent = Intent(context, ColorPickActivity::class.java)
.putExtra(EXTRA_OLD_COLOR, oldColor)
.putExtra(EXTRA_COLORS, colors?.toIntArray())
}
} | library/src/main/kotlin/org/jraf/android/androidwearcolorpicker/ColorPickActivity.kt | 1933069263 |
package glimpse
/**
* Returns a frustum projection [Matrix].
* The [left] to [right], [top] to [bottom] rectangle is the [near] clipping plane of the frustum.
*/
fun frustumProjectionMatrix(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float): Matrix {
val width = right - left
val height = top - bottom
val depth = near - far
return Matrix(listOf(
2f * near / width, 0f, 0f, 0f,
0f, 2f * near / height, 0f, 0f,
(right + left) / width, (top + bottom) / height, (far + near) / depth, -1f,
0f, 0f, 2f * far * near / depth, 0f))
}
/**
* Returns a perspective projection [Matrix].
*
* @param fovY Field of view angle for Y-axis (viewport height axis).
* @param aspect Width aspect ratio against height.
* @param near Near clipping plane distance.
* @param far Far clipping plane distance.
*/
fun perspectiveProjectionMatrix(fovY: Angle, aspect: Float, near: Float, far: Float): Matrix {
val top = tan(fovY / 2f) * near
val right = aspect * top
val depth = near - far
return Matrix(listOf(
1f / right, 0f, 0f, 0f,
0f, 1f / top, 0f, 0f,
0f, 0f, (near + far) / depth, -1f,
0f, 0f, 2 * near * far / depth, 0f))
}
/**
* Returns an orthographic projection [Matrix].
*/
fun orthographicProjectionMatrix(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float): Matrix {
val width = right - left
val height = top - bottom
val depth = far - near
return Matrix(listOf(
2f / width, 0f, 0f, 0f,
0f, 2f / height, 0f, 0f,
0f, 0f, -2f / depth, 0f,
-(right + left) / width, -(top + bottom) / height, -(near + far) / depth, 1f))
}
/**
* Returns a look-at view [Matrix].
*/
fun lookAtViewMatrix(eye: Point, center: Point, up: Vector): Matrix {
val f = (eye to center).normalize
val s = (f * up).normalize
val u = s * f
return Matrix(listOf(
s.x, u.x, -f.x, 0f,
s.y, u.y, -f.y, 0f,
s.z, u.z, -f.z, 0f,
0f, 0f, 0f, 1f)) * translationMatrix(-eye.toVector())
}
/**
* Returns a transformation [Matrix] for a translation by an [vector].
*/
fun translationMatrix(vector: Vector): Matrix {
val (x, y, z) = vector
return Matrix(listOf(
1f, 0f, 0f, 0f,
0f, 1f, 0f, 0f,
0f, 0f, 1f, 0f,
x, y, z, 1f))
}
/**
* Returns a transformation [Matrix] for a rotation by an [angle] around an [axis].
*/
fun rotationMatrix(axis: Vector, angle: Angle): Matrix {
val (x, y, z) = axis.normalize
val sin = sin(angle)
val cos = cos(angle)
val nCos = 1f - cos(angle)
return Matrix(listOf(
cos + x * x * nCos, x * y * nCos + z * sin, x * z * nCos - y * sin, 0f,
x * y * nCos - z * sin, cos + y * y * nCos, y * z * nCos + x * sin, 0f,
x * z * nCos + y * sin, y * z * nCos - x * sin, cos + z * z * nCos, 0f,
0f, 0f, 0f, 1f))
}
/**
* Returns a transformation [Matrix] for a rotation by an [angle] around X axis.
*/
fun rotationMatrixX(angle: Angle): Matrix {
val sin = sin(angle)
val cos = cos(angle)
return Matrix(listOf(
1f, 0f, 0f, 0f,
0f, cos, sin, 0f,
0f, -sin, cos, 0f,
0f, 0f, 0f, 1f))
}
/**
* Returns a transformation [Matrix] for a rotation by an [angle] around Y axis.
*/
fun rotationMatrixY(angle: Angle): Matrix {
val sin = sin(angle)
val cos = cos(angle)
return Matrix(listOf(
cos, 0f, -sin, 0f,
0f, 1f, 0f, 0f,
sin, 0f, cos, 0f,
0f, 0f, 0f, 1f))
}
/**
* Returns a transformation [Matrix] for a rotation by an [angle] around Z axis.
*/
fun rotationMatrixZ(angle: Angle): Matrix {
val sin = sin(angle)
val cos = cos(angle)
return Matrix(listOf(
cos, sin, 0f, 0f,
-sin, cos, 0f, 0f,
0f, 0f, 1f, 0f,
0f, 0f, 0f, 1f))
}
/**
* Returns a transformation [Matrix] for uniform scaling.
*/
fun scalingMatrix(scale: Float): Matrix = scalingMatrix(scale, scale, scale)
/**
* Returns a transformation [Matrix] for scaling.
*/
fun scalingMatrix(x: Float = 1f, y: Float = 1f, z: Float = 1f): Matrix =
Matrix(listOf(
x, 0f, 0f, 0f,
0f, y, 0f, 0f,
0f, 0f, z, 0f,
0f, 0f, 0f, 1f))
/**
* Returns a transformation [Matrix] for reflection through a plane,
* defined by a [normal] vector and a [point] on the plane.
*/
fun reflectionMatrix(normal: Vector, point: Point): Matrix {
val (a, b, c) = normal.normalize
val d = -point.toVector() dot (normal.normalize)
return Matrix(listOf(
1f - 2f * a * a, -2f * b * a, -2f * c * a, 0f,
-2f * a * b, 1f - 2f * b * b, -2f * c * b, 0f,
-2f * a * c, -2f * b * c, 1f - 2f * c * c, 0f,
-2f * a * d, -2f * b * d, -2f * c * d, 1f))
}
| api/src/main/kotlin/glimpse/Matrices.kt | 1391880384 |
package com.nutrition.express.common
import android.annotation.TargetApi
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.TextureView
import android.view.View
import android.widget.*
import androidx.annotation.AttrRes
import androidx.annotation.StyleRes
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder
import com.facebook.drawee.view.SimpleDraweeView
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.video.VideoListener
import com.nutrition.express.R
import com.nutrition.express.application.toast
import com.nutrition.express.databinding.ItemVideoControlBinding
import com.nutrition.express.model.api.bean.BaseVideoBean
import com.nutrition.express.ui.video.VideoPlayerActivity
import com.nutrition.express.util.dp2Pixels
import java.util.*
class MyExoPlayerView : FrameLayout {
private val formatBuilder: StringBuilder = StringBuilder()
private val formatter: Formatter = Formatter(formatBuilder, Locale.getDefault())
private lateinit var uri: Uri
private var player: SimpleExoPlayer? = null
private var dragging = false
private var isConnected = false
private val showTimeoutMs = 3000L
private val progressBarMax = 1000
private var controlBinding: ItemVideoControlBinding =
ItemVideoControlBinding.inflate(LayoutInflater.from(context), this, true)
private var videoView: TextureView
private lateinit var thumbnailView: SimpleDraweeView
private lateinit var loadingBar: ProgressBar
private var playView: ImageView
private var leftTime: TextView
private val videoListener = object : VideoListener {
override fun onRenderedFirstFrame() {
thumbnailView.visibility = View.GONE
}
}
private val eventListener = object : Player.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
when (playbackState) {
Player.STATE_BUFFERING -> loadingBar.visibility = View.VISIBLE
Player.STATE_ENDED -> {
show()
loadingBar.visibility = View.GONE
keepScreenOn = false
}
Player.STATE_READY -> {
loadingBar.visibility = View.GONE
keepScreenOn = true
}
Player.STATE_IDLE -> {
loadingBar.visibility = View.GONE
keepScreenOn = false
}
}
updatePlayPauseButton()
updateProgress()
updateLeftTime()
}
override fun onPlayerError(error: ExoPlaybackException) {
disconnect()
context.toast(R.string.video_play_error)
}
}
private val updateProgressAction = Runnable {
updateProgress()
}
private val hideAction = Runnable {
hide()
}
private val updateTimeAction = Runnable {
updateLeftTime()
}
constructor(context: Context): super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int) : super(context, attrs, defStyleAttr)
@TargetApi(21)
constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int, @StyleRes defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
init {
controlBinding.videoControllerProgress.setOnSeekBarChangeListener(
object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (fromUser) {
controlBinding.timeCurrent.text = stringForTime(positionValue(progress))
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
removeCallbacks(hideAction)
dragging = true
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
player?.seekTo(positionValue(seekBar.progress))
hideAfterTimeout()
dragging = false
}
})
controlBinding.videoControllerProgress.max = progressBarMax
controlBinding.videoFullscreen.setOnClickListener {
val playerIntent = Intent(context, VideoPlayerActivity::class.java)
playerIntent.putExtra("uri", uri)
player?.let {
playerIntent.putExtra("position", it.currentPosition)
playerIntent.putExtra("windowIndex", it.currentWindowIndex)
}
playerIntent.putExtra("rotation", width > height)
context.startActivity(playerIntent)
disconnect()
}
videoView = TextureView(context)
val videoParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
videoView.layoutParams = videoParams
videoView.setOnClickListener {
if (isConnected) {
show()
} else {
connect()
}
}
thumbnailView = SimpleDraweeView(context)
val thumbParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
val hierarchy = GenericDraweeHierarchyBuilder(resources)
.setPlaceholderImage(R.color.loading_color)
.build()
thumbnailView.hierarchy = hierarchy
thumbnailView.layoutParams = thumbParams
loadingBar = ProgressBar(context, null, android.R.attr.progressBarStyle)
val loadingParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
loadingParams.gravity = Gravity.CENTER
loadingBar.layoutParams = loadingParams
loadingBar.visibility = View.GONE
playView = ImageView(context)
val playParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
playParams.gravity = Gravity.CENTER
playView.layoutParams = playParams
val padding = dp2Pixels(context, 24)
playView.setPadding(padding, padding, padding, padding)
playView.setOnClickListener {
player?.let {
if (it.playbackState == ExoPlayer.STATE_ENDED) {
it.seekTo(0)
it.playWhenReady = true
} else {
it.playWhenReady = !it.playWhenReady
}
}
}
leftTime = TextView(context)
val leftParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
leftParams.gravity = Gravity.BOTTOM
leftParams.bottomMargin = padding / 2
leftParams.leftMargin = padding / 2
leftTime.layoutParams = leftParams
leftTime.setTextColor(Color.WHITE)
leftTime.visibility = View.GONE
addView(videoView, 0)
addView(thumbnailView, 1)
addView(loadingBar, 2)
addView(playView, 3)
addView(leftTime, 4)
}
fun bindVideo(video: BaseVideoBean) {
uri = video.sourceUri
var params = layoutParams
if (params == null) {
params = LayoutParams(video.getWidth(), video.getHeight())
}
params.width = video.getWidth()
params.height = video.getHeight()
layoutParams = params
thumbnailView.setImageURI(video.getThumbnailUri(), context)
thumbnailView.visibility = View.VISIBLE
hide()
disconnect()
}
fun setPlayerClickable(enable: Boolean) {
videoView.isClickable = enable
}
fun performPlayerClick() {
if (isConnected) {
show()
} else {
connect()
}
}
private fun connect() {
val player = MyExoPlayer.preparePlayer(uri) {
disconnect()
}
player.setVideoTextureView(videoView)
player.addListener(eventListener)
player.addVideoListener(videoListener)
player.playWhenReady = true
this.player = player
isConnected = true
}
private fun disconnect() {
player?.let {
it.removeListener(eventListener)
it.removeVideoListener(videoListener)
it.stop()
player = null
}
thumbnailView.visibility = View.VISIBLE
loadingBar.visibility = View.GONE
isConnected = false
}
/**
* Shows the controller
*/
private fun show() {
if (isControllerVisible()) {
hide()
} else {
controlBinding.videoControlLayout.visibility = View.VISIBLE
playView.visibility = View.VISIBLE
leftTime.visibility = View.GONE
updateAll()
}
// Call hideAfterTimeout even if already visible to reset the timeout.
hideAfterTimeout()
}
private fun hide() {
if (isControllerVisible()) {
controlBinding.videoControlLayout.visibility = View.GONE
playView.visibility = View.GONE
removeCallbacks(updateProgressAction)
removeCallbacks(hideAction)
updateLeftTime()
}
}
private fun updateLeftTime() {
if (!isConnected || !isAttachedToWindow) {
leftTime.visibility = View.GONE
return
}
if (isControllerVisible()) {
return
}
val duration: Long = player?.duration ?: 0L
val position: Long = player?.currentPosition ?: 0L
if (duration == C.TIME_UNSET) {
return
}
leftTime.visibility = View.VISIBLE
leftTime.text = stringForTime(duration - position)
leftTime.postDelayed(updateTimeAction, 1000)
}
private fun hideAfterTimeout() {
removeCallbacks(hideAction)
if (isAttachedToWindow) {
postDelayed(hideAction, showTimeoutMs)
}
}
private fun updateAll() {
updatePlayPauseButton()
updateProgress()
}
private fun updatePlayPauseButton() {
if (!isControllerVisible() || !isAttachedToWindow) {
return
}
val playing: Boolean = player?.playWhenReady == true && player?.playbackState != ExoPlayer.STATE_ENDED
val contentDescription = resources.getString(
if (playing) R.string.exo_controls_pause_description else R.string.exo_controls_play_description)
playView.contentDescription = contentDescription
playView.setImageResource(if (playing) R.drawable.exo_controls_pause else R.drawable.exo_controls_play)
}
private fun updateProgress() {
if (!isControllerVisible() || !isAttachedToWindow) {
return
}
val duration = player?.duration ?: 0
val position = player?.currentPosition ?: 0
controlBinding.time.text = stringForTime(duration)
if (!dragging) {
controlBinding.timeCurrent.text = stringForTime(position)
}
if (!dragging) {
controlBinding.videoControllerProgress.progress = progressBarValue(position)
}
val bufferedPosition = player?.bufferedPosition ?: 0
controlBinding.videoControllerProgress.secondaryProgress = progressBarValue(bufferedPosition)
// Remove scheduled updates.
removeCallbacks(updateProgressAction)
// Schedule an update if necessary.
val playbackState = player?.playbackState ?: Player.STATE_IDLE
if (playbackState != Player.STATE_IDLE && playbackState != Player.STATE_ENDED) {
var delayMs: Long
if (player?.playWhenReady == true && playbackState == Player.STATE_READY) {
delayMs = 1000 - position % 1000
if (delayMs < 200) {
delayMs += 1000
}
} else {
delayMs = 1000
}
postDelayed(updateProgressAction, delayMs)
}
}
private fun isControllerVisible(): Boolean {
return controlBinding.videoControlLayout.visibility == View.VISIBLE
}
private fun stringForTime(timeMs: Long): String? {
var time = timeMs
if (time == C.TIME_UNSET) {
time = 0
}
val totalSeconds = (time + 500) / 1000
val seconds = totalSeconds % 60
val minutes = totalSeconds / 60 % 60
val hours = totalSeconds / 3600
formatBuilder.setLength(0)
return if (hours > 0)
formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString()
else
formatter.format("%02d:%02d", minutes, seconds).toString()
}
private fun progressBarValue(position: Long): Int {
val duration = player?.duration ?: C.TIME_UNSET
return if (duration == C.TIME_UNSET || duration == 0L) 0 else (position * progressBarMax / duration).toInt()
}
private fun positionValue(progress: Int): Long {
val duration = player?.duration ?: C.TIME_UNSET
return if (duration == C.TIME_UNSET || duration == 0L) 0 else (duration * progress / progressBarMax)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
hide()
disconnect()
}
} | app/src/main/java/com/nutrition/express/common/MyExoPlayerView.kt | 1734291058 |
package im.fdx.v2ex.utils.extensions
import android.app.Activity
import android.content.Context
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.elvishew.xlog.XLog
import com.google.android.material.snackbar.Snackbar
import im.fdx.v2ex.R
import im.fdx.v2ex.ui.LoginActivity
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
/**
* Created by fdx on 2017/6/14.
* fdx will maintain it
*/
fun Context.dealError(errorCode: Int = -1, swipe: androidx.swiperefreshlayout.widget.SwipeRefreshLayout? = null) {
when {
this is Activity -> runOnUiThread {
swipe?.isRefreshing = false
when (errorCode) {
-1 -> toast(getString(R.string.error_network))
302 -> toast(getString(R.string.error_auth_failure))
else -> toast(getString(R.string.error_network))
}
}
}
}
fun Fragment.toast(message : CharSequence): Toast? {
return activity?.let {
Toast.makeText(activity, message, Toast.LENGTH_SHORT)
.apply {
show()
}
}
}
fun Any.logv(msg: Any?) {
XLog.tag("v+" + this::class.java.simpleName).v(msg)
}
fun Any.logd(msg: Any?) {
XLog.tag("v+" + this::class.java.simpleName).d(msg)
}
fun Any.logi(msg: Any?) {
XLog.tag("v+" + this::class.java.simpleName).i(msg)
}
fun Any.logw(msg: Any?) {
XLog.tag("v+" + this::class.java.simpleName).w(msg)
}
fun Any.loge(msg: Any?) {
XLog.tag("v+" + this::class.java.simpleName).e(msg)
}
fun Activity.showLoginHint(view: View,message :String ="您还未登录,请登录后再试") {
Snackbar.make(view, message, Snackbar.LENGTH_LONG)
.setAction("登录") {
startActivity<LoginActivity>()
}.show()
} | app/src/main/java/im/fdx/v2ex/utils/extensions/Hint.kt | 3683036329 |
/****************************************************************************************
* Copyright (c) 2009 Casey Link <[email protected]> *
* Copyright (c) 2012 Norbert Nagold <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
@file:Suppress("DEPRECATION") // Migrate to AndroidX preferences #5019
package com.ichi2.anki
import android.app.AlarmManager
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.res.Configuration
import android.os.Bundle
import android.preference.CheckBoxPreference
import android.preference.ListPreference
import android.preference.Preference
import android.preference.PreferenceScreen
import android.text.TextUtils
import com.afollestad.materialdialogs.MaterialDialog
import com.ichi2.anim.ActivityTransitionAnimation
import com.ichi2.anim.ActivityTransitionAnimation.Direction.FADE
import com.ichi2.anki.CollectionManager.withCol
import com.ichi2.anki.exception.ConfirmModSchemaException
import com.ichi2.anki.services.ReminderService
import com.ichi2.annotations.NeedsTest
import com.ichi2.async.TaskListenerWithContext
import com.ichi2.async.changeDeckConfiguration
import com.ichi2.compat.CompatHelper
import com.ichi2.libanki.Collection
import com.ichi2.libanki.Consts
import com.ichi2.libanki.DeckConfig
import com.ichi2.libanki.utils.Time
import com.ichi2.libanki.utils.TimeManager
import com.ichi2.libanki.utils.set
import com.ichi2.preferences.NumberRangePreference
import com.ichi2.preferences.StepsPreference
import com.ichi2.preferences.TimePreference
import com.ichi2.themes.StyledProgressDialog
import com.ichi2.themes.Themes
import com.ichi2.themes.Themes.themeFollowsSystem
import com.ichi2.themes.Themes.updateCurrentTheme
import com.ichi2.ui.AppCompatPreferenceActivity
import com.ichi2.utils.KotlinCleanup
import com.ichi2.utils.NamedJSONComparator
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import timber.log.Timber
import java.util.*
@NeedsTest("onCreate - to be done after preference migration (5019)")
@KotlinCleanup("lateinit wherever possible")
@KotlinCleanup("IDE lint")
class DeckOptionsActivity :
AppCompatPreferenceActivity<DeckOptionsActivity.DeckPreferenceHack>() {
private lateinit var mOptions: DeckConfig
inner class DeckPreferenceHack : AppCompatPreferenceActivity<DeckOptionsActivity.DeckPreferenceHack>.AbstractPreferenceHack() {
@Suppress("Deprecation")
lateinit var progressDialog: android.app.ProgressDialog
private val mListeners: MutableList<SharedPreferences.OnSharedPreferenceChangeListener> = LinkedList()
val deckOptionsActivity: DeckOptionsActivity
get() = this@DeckOptionsActivity
override fun cacheValues() {
Timber.i("DeckOptions - CacheValues")
try {
mOptions = col.decks.confForDid(deck.getLong("id"))
mValues.apply {
set("name", deck.getString("name"))
set("desc", deck.getString("desc"))
set("deckConf", deck.getString("conf"))
// general
set("maxAnswerTime", mOptions.getString("maxTaken"))
set("showAnswerTimer", parseTimerValue(mOptions).toString())
set("autoPlayAudio", mOptions.getBoolean("autoplay").toString())
set("replayQuestion", mOptions.optBoolean("replayq", true).toString())
}
// new
val newOptions = mOptions.getJSONObject("new")
mValues.apply {
set("newSteps", StepsPreference.convertFromJSON(newOptions.getJSONArray("delays")))
set("newGradIvl", newOptions.getJSONArray("ints").getString(0))
set("newEasy", newOptions.getJSONArray("ints").getString(1))
set("newFactor", (newOptions.getInt("initialFactor") / 10).toString())
set("newOrder", newOptions.getString("order"))
set("newPerDay", newOptions.getString("perDay"))
set("newBury", newOptions.optBoolean("bury", true).toString())
}
// rev
val revOptions = mOptions.getJSONObject("rev")
mValues.apply {
set("revPerDay", revOptions.getString("perDay"))
set("easyBonus", String.format(Locale.ROOT, "%.0f", revOptions.getDouble("ease4") * 100))
set("hardFactor", String.format(Locale.ROOT, "%.0f", revOptions.optDouble("hardFactor", 1.2) * 100))
set("revIvlFct", String.format(Locale.ROOT, "%.0f", revOptions.getDouble("ivlFct") * 100))
set("revMaxIvl", revOptions.getString("maxIvl"))
set("revBury", revOptions.optBoolean("bury", true).toString())
set("revUseGeneralTimeoutSettings", revOptions.optBoolean("useGeneralTimeoutSettings", true).toString())
set("revTimeoutAnswer", revOptions.optBoolean("timeoutAnswer", false).toString())
set("revTimeoutAnswerSeconds", revOptions.optInt("timeoutAnswerSeconds", 6).toString())
set("revTimeoutQuestionSeconds", revOptions.optInt("timeoutQuestionSeconds", 60).toString())
}
// lapse
val lapOptions = mOptions.getJSONObject("lapse")
mValues.apply {
set("lapSteps", StepsPreference.convertFromJSON(lapOptions.getJSONArray("delays")))
set("lapNewIvl", String.format(Locale.ROOT, "%.0f", lapOptions.getDouble("mult") * 100))
set("lapMinIvl", lapOptions.getString("minInt"))
set("lapLeechThres", lapOptions.getString("leechFails"))
set("lapLeechAct", lapOptions.getString("leechAction"))
// options group management
set("currentConf", col.decks.getConf(deck.getLong("conf"))!!.getString("name"))
}
// reminders
if (mOptions.has("reminder")) {
val reminder = mOptions.getJSONObject("reminder")
val reminderTime = reminder.getJSONArray("time")
mValues["reminderEnabled"] = reminder.getBoolean("enabled").toString()
mValues["reminderTime"] = String.format(
"%1$02d:%2$02d", reminderTime.getLong(0), reminderTime.getLong(1)
)
} else {
mValues["reminderEnabled"] = "false"
mValues["reminderTime"] = TimePreference.DEFAULT_VALUE
}
} catch (e: JSONException) {
Timber.e(e, "DeckOptions - cacheValues")
CrashReportService.sendExceptionReport(e, "DeckOptions: cacheValues")
UIUtils.showThemedToast(this@DeckOptionsActivity, [email protected](R.string.deck_options_corrupt, e.localizedMessage), false)
finish()
}
}
private fun parseTimerValue(options: DeckConfig): Boolean {
return DeckConfig.parseTimerOpt(options, true)
}
fun confChangeHandler(timbering: String, block: Collection.() -> Unit) {
launch(getCoroutineExceptionHandler(this@DeckOptionsActivity)) {
preConfChange()
Timber.d(timbering)
try {
withCol(block)
} finally {
// need to call postConfChange in finally because if withCol{} throws an exception,
// postConfChange would never get called and progress-bar will never get dismissed
postConfChange()
}
}
}
fun preConfChange() {
val res = deckOptionsActivity.resources
progressDialog = StyledProgressDialog.show(
deckOptionsActivity as Context, null,
res?.getString(R.string.reordering_cards), false
)
}
fun postConfChange() {
cacheValues()
deckOptionsActivity.buildLists()
deckOptionsActivity.updateSummaries()
progressDialog.dismiss()
// Restart to reflect the new preference values
deckOptionsActivity.restartActivity()
}
inner class Editor : AppCompatPreferenceActivity<DeckOptionsActivity.DeckPreferenceHack>.AbstractPreferenceHack.Editor() {
override fun commit(): Boolean {
Timber.d("DeckOptions - commit() changes back to database")
try {
for ((key, value) in update.valueSet()) {
Timber.i("Change value for key '%s': %s", key, value)
when (key) {
"maxAnswerTime" -> mOptions.put("maxTaken", value)
"newFactor" -> mOptions.getJSONObject("new").put("initialFactor", value as Int * 10)
"newOrder" -> {
val newOrder: Int = (value as String).toInt()
// Sorting is slow, so only do it if we change order
val oldOrder = mOptions.getJSONObject("new").getInt("order")
if (oldOrder != newOrder) {
mOptions.getJSONObject("new").put("order", newOrder)
confChangeHandler("doInBackground - reorder") {
sched.resortConf(mOptions)
}
}
mOptions.getJSONObject("new").put("order", value.toInt())
}
"newPerDay" -> mOptions.getJSONObject("new").put("perDay", value)
"newGradIvl" -> {
val newInts = JSONArray() // [graduating, easy]
newInts.put(value)
newInts.put(mOptions.getJSONObject("new").getJSONArray("ints").getInt(1))
newInts.put(mOptions.getJSONObject("new").getJSONArray("ints").optInt(2, 7))
mOptions.getJSONObject("new").put("ints", newInts)
}
"newEasy" -> {
val newInts = JSONArray() // [graduating, easy]
newInts.put(mOptions.getJSONObject("new").getJSONArray("ints").getInt(0))
newInts.put(value)
newInts.put(mOptions.getJSONObject("new").getJSONArray("ints").optInt(2, 7))
mOptions.getJSONObject("new").put("ints", newInts)
}
"newBury" -> mOptions.getJSONObject("new").put("bury", value)
"revPerDay" -> mOptions.getJSONObject("rev").put("perDay", value)
"easyBonus" -> mOptions.getJSONObject("rev").put("ease4", (value as Int / 100.0f).toDouble())
"hardFactor" -> mOptions.getJSONObject("rev").put("hardFactor", (value as Int / 100.0f).toDouble())
"revIvlFct" -> mOptions.getJSONObject("rev").put("ivlFct", (value as Int / 100.0f).toDouble())
"revMaxIvl" -> mOptions.getJSONObject("rev").put("maxIvl", value)
"revBury" -> mOptions.getJSONObject("rev").put("bury", value)
"revUseGeneralTimeoutSettings" -> mOptions.getJSONObject("rev").put("useGeneralTimeoutSettings", value)
"revTimeoutAnswer" -> mOptions.getJSONObject("rev").put("timeoutAnswer", value)
"revTimeoutAnswerSeconds" -> mOptions.getJSONObject("rev").put("timeoutAnswerSeconds", value)
"revTimeoutQuestionSeconds" -> mOptions.getJSONObject("rev").put("timeoutQuestionSeconds", value)
"lapMinIvl" -> mOptions.getJSONObject("lapse").put("minInt", value)
"lapLeechThres" -> mOptions.getJSONObject("lapse").put("leechFails", value)
"lapLeechAct" -> mOptions.getJSONObject("lapse").put("leechAction", (value as String).toInt())
"lapNewIvl" -> mOptions.getJSONObject("lapse").put("mult", (value as Int / 100.0f).toDouble())
"showAnswerTimer" -> mOptions.put("timer", if (value as Boolean) 1 else 0)
"autoPlayAudio" -> mOptions.put("autoplay", value)
"replayQuestion" -> mOptions.put("replayq", value)
"desc" -> {
deck.put("desc", value)
col.decks.save(deck)
}
"newSteps" -> mOptions.getJSONObject("new").put("delays", StepsPreference.convertToJSON((value as String)))
"lapSteps" -> mOptions.getJSONObject("lapse").put("delays", StepsPreference.convertToJSON((value as String)))
// TODO: Extract out deckConf, confReset, remConf and confSetSubdecks to a function. They are overall similar.
"deckConf" -> {
val newConfId: Long = (value as String).toLong()
confChangeHandler("change Deck configuration") {
mOptions = decks.getConf(newConfId)!!
changeDeckConfiguration(deck, mOptions, this)
}
}
"confRename" -> {
val newName = value as String
if (!TextUtils.isEmpty(newName)) {
mOptions.put("name", newName)
}
}
"confReset" -> if (value as Boolean) {
// reset configuration
confChangeHandler("doInBackgroundConfReset") {
decks.restoreToDefault(mOptions)
save()
}
}
"confAdd" -> {
val newName = value as String
if (!TextUtils.isEmpty(newName)) {
// New config clones current config
val id = col.decks.confId(newName, mOptions.toString())
deck.put("conf", id)
col.decks.save(deck)
}
}
"confRemove" -> if (mOptions.getLong("id") == 1L) {
// Don't remove the options group if it's the default group
UIUtils.showThemedToast(
this@DeckOptionsActivity,
resources.getString(R.string.default_conf_delete_error), false
)
} else {
// Remove options group, handling the case where the user needs to confirm full sync
try {
remConf()
} catch (e: ConfirmModSchemaException) {
e.log()
// Libanki determined that a full sync will be required, so confirm with the user before proceeding
// TODO : Use ConfirmationDialog DialogFragment -- not compatible with PreferenceActivity
MaterialDialog(this@DeckOptionsActivity).show {
message(R.string.full_sync_confirmation)
positiveButton(R.string.dialog_ok) {
col.modSchemaNoCheck()
try {
remConf()
} catch (cmse: ConfirmModSchemaException) {
// This should never be reached as we just forced modSchema
throw RuntimeException(cmse)
}
}
negativeButton(R.string.dialog_cancel)
}
}
}
"confSetSubdecks" -> if (value as Boolean) {
launch(getCoroutineExceptionHandler(this@DeckOptionsActivity)) {
preConfChange()
try {
withCol {
Timber.d("confSetSubdecks")
val children = col.decks.children(deck.getLong("id"))
for (childDid in children.values) {
val child = col.decks.get(childDid)
if (child.isDyn) continue
changeDeckConfiguration(deck, mOptions, col)
}
}
} finally {
postConfChange()
}
}
}
"reminderEnabled" -> {
val reminder = JSONObject()
reminder.put("enabled", value)
if (mOptions.has("reminder")) {
reminder.put("time", mOptions.getJSONObject("reminder").getJSONArray("time"))
} else {
reminder.put(
"time",
JSONArray()
.put(TimePreference.parseHours(TimePreference.DEFAULT_VALUE))
.put(TimePreference.parseMinutes(TimePreference.DEFAULT_VALUE))
)
}
mOptions.put("reminder", reminder)
val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
val reminderIntent = CompatHelper.compat.getImmutableBroadcastIntent(
applicationContext,
mOptions.getLong("id").toInt(),
Intent(applicationContext, ReminderService::class.java).putExtra(
ReminderService.EXTRA_DECK_OPTION_ID, mOptions.getLong("id")
),
0
)
alarmManager.cancel(reminderIntent)
if (value as Boolean) {
val calendar = reminderToCalendar(TimeManager.time, reminder)
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
AlarmManager.INTERVAL_DAY,
reminderIntent
)
}
}
"reminderTime" -> {
val reminder = JSONObject()
reminder.put("enabled", true)
reminder.put(
"time",
JSONArray().put(TimePreference.parseHours((value as String)))
.put(TimePreference.parseMinutes(value))
)
mOptions.put("reminder", reminder)
val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
val reminderIntent = CompatHelper.compat.getImmutableBroadcastIntent(
applicationContext,
mOptions.getLong("id").toInt(),
Intent(
applicationContext,
ReminderService::class.java
).putExtra(
ReminderService.EXTRA_DECK_OPTION_ID,
mOptions.getLong("id")
),
0
)
alarmManager.cancel(reminderIntent)
val calendar = reminderToCalendar(TimeManager.time, reminder)
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
AlarmManager.INTERVAL_DAY,
reminderIntent
)
}
else -> Timber.w("Unknown key type: %s", key)
}
}
} catch (e: JSONException) {
throw RuntimeException(e)
}
// save conf
try {
col.decks.save(mOptions)
} catch (e: RuntimeException) {
Timber.e(e, "DeckOptions - RuntimeException on saving conf")
CrashReportService.sendExceptionReport(e, "DeckOptionsSaveConf")
setResult(DeckPicker.RESULT_DB_ERROR)
finish()
}
// make sure we refresh the parent cached values
cacheValues()
buildLists()
updateSummaries()
// and update any listeners
for (listener in mListeners) {
listener.onSharedPreferenceChanged(this@DeckPreferenceHack, null)
}
return true
}
/**
* Remove the currently selected options group
*/
@Throws(ConfirmModSchemaException::class)
private fun remConf() {
// Remove options group, asking user to confirm full sync if necessary
col.decks.remConf(mOptions.getLong("id"))
// Run the CPU intensive re-sort operation in a background thread
val conf = mOptions
confChangeHandler("Remove configuration") {
// Note: We do the actual removing of the options group in the main thread so that we
// can ask the user to confirm if they're happy to do a full sync, and just do the resorting here
// When a conf is deleted, all decks using it revert to the default conf.
// Cards must be reordered according to the default conf.
val order = conf.getJSONObject("new").getInt("order")
val defaultOrder =
col.decks.getConf(1)!!.getJSONObject("new").getInt("order")
if (order != defaultOrder) {
conf.getJSONObject("new").put("order", defaultOrder)
col.sched.resortConf(conf)
}
col.save()
}
deck.put("conf", 1)
}
private fun confChangeHandler(): ConfChangeHandler {
return ConfChangeHandler(this@DeckPreferenceHack)
}
}
override fun edit(): Editor {
return Editor()
}
}
class ConfChangeHandler(deckPreferenceHack: DeckPreferenceHack) :
TaskListenerWithContext<DeckPreferenceHack, Void?, Boolean?>(deckPreferenceHack) {
override fun actualOnPreExecute(context: DeckPreferenceHack) = context.preConfChange()
override fun actualOnPostExecute(context: DeckPreferenceHack, result: Boolean?) = context.postConfChange()
}
@KotlinCleanup("Remove this once DeckOptions is an AnkiActivity")
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
val newNightModeStatus = newConfig.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
// Check if theme should change
if (Themes.systemIsInNightMode != newNightModeStatus) {
Themes.systemIsInNightMode = newNightModeStatus
if (themeFollowsSystem()) {
updateCurrentTheme()
recreate()
}
}
}
// conversion to fragments tracked as #5019 in github
@Deprecated("Deprecated in Java")
override fun onCreate(savedInstanceState: Bundle?) {
Themes.setThemeLegacy(this)
super.onCreate(savedInstanceState)
if (!isColInitialized()) {
return
}
val extras = intent.extras
deck = if (extras != null && extras.containsKey("did")) {
col.decks.get(extras.getLong("did"))
} else {
col.decks.current()
}
registerExternalStorageListener()
pref = DeckPreferenceHack()
// #6068 - constructor can call finish()
if (this.isFinishing) {
return
}
pref.registerOnSharedPreferenceChangeListener(this)
addPreferencesFromResource(R.xml.deck_options)
if (isSchedV2) {
enableSchedV2Preferences()
}
buildLists()
updateSummaries()
// Set the activity title to include the name of the deck
var title = resources.getString(R.string.deckpreferences_title)
if (title.contains("XXX")) {
title = try {
title.replace("XXX", deck.getString("name"))
} catch (e: JSONException) {
Timber.w(e)
title.replace("XXX", "???")
}
}
setTitle(title)
// Add a home button to the actionbar
supportActionBar!!.setHomeButtonEnabled(true)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
}
// Workaround for bug 4611: http://code.google.com/p/android/issues/detail?id=4611
@Deprecated("Deprecated in Java") // TODO Tracked in https://github.com/ankidroid/Anki-Android/issues/5019
override fun onPreferenceTreeClick(preferenceScreen: PreferenceScreen, preference: Preference): Boolean {
super.onPreferenceTreeClick(preferenceScreen, preference)
if (preference is PreferenceScreen && preference.dialog != null) {
preference.dialog.window!!.decorView.setBackgroundDrawable(
this.window.decorView.background.constantState!!.newDrawable()
)
}
return false
}
override fun closeWithResult() {
if (prefChanged) {
setResult(RESULT_OK)
} else {
setResult(RESULT_CANCELED)
}
finish()
ActivityTransitionAnimation.slide(this, FADE)
}
// TODO Tracked in https://github.com/ankidroid/Anki-Android/issues/5019
@KotlinCleanup("remove reduntant val res = resources")
override fun updateSummaries() {
val res = resources
// for all text preferences, set summary as current database value
for (key in pref.mValues.keys) {
val pref = findPreference(key)
if ("deckConf" == key) {
var groupName = optionsGroupName
val count = optionsGroupCount
// Escape "%" in groupName as it's treated as a token
groupName = groupName.replace("%".toRegex(), "%%")
pref!!.summary = res.getQuantityString(R.plurals.deck_conf_group_summ, count, groupName, count)
continue
}
val value: String? = if (pref == null) {
continue
} else if (pref is CheckBoxPreference) {
continue
} else if (pref is ListPreference) {
val lp = pref
if (lp.entry != null) lp.entry.toString() else ""
} else {
this.pref.getString(key, "")
}
// update summary
if (!this.pref.mSummaries.containsKey(key)) {
this.pref.mSummaries[key] = pref.summary?.toString()
}
val summ = this.pref.mSummaries[key]
pref.summary = if (summ != null && summ.contains("XXX")) {
summ.replace("XXX", value!!)
} else {
value
}
}
// Update summaries of preference items that don't have values (aren't in mValues)
val subDeckCount = subdeckCount
findPreference("confSetSubdecks").summary = res.getQuantityString(R.plurals.deck_conf_set_subdecks_summ, subDeckCount, subDeckCount)
}
// TODO Tracked in https://github.com/ankidroid/Anki-Android/issues/5019
protected fun buildLists() {
val deckConfPref = findPreference("deckConf") as ListPreference
val confs = col.decks.allConf()
Collections.sort(confs, NamedJSONComparator.INSTANCE)
val confValues = arrayOfNulls<String>(confs.size)
val confLabels = arrayOfNulls<String>(confs.size)
confs.forEachIndexed { index, deckConfig ->
confValues[index] = deckConfig.getString("id")
confLabels[index] = deckConfig.getString("name")
}
deckConfPref.apply {
entries = confLabels
entryValues = confValues
value = pref.getString("deckConf", "0")
}
val newOrderPref = findPreference("newOrder") as ListPreference
newOrderPref.apply {
setEntries(R.array.new_order_labels)
setEntryValues(R.array.new_order_values)
value = pref.getString("newOrder", "0")
}
val leechActPref = findPreference("lapLeechAct") as ListPreference
leechActPref.apply {
setEntries(R.array.leech_action_labels)
setEntryValues(R.array.leech_action_values)
value = pref.getString(
"lapLeechAct",
Consts.LEECH_SUSPEND.toString()
)
}
}
private val isSchedV2: Boolean
get() = col.schedVer() == 2
/**
* Enable deck preferences that are only available with Scheduler V2.
*/
// TODO Tracked in https://github.com/ankidroid/Anki-Android/issues/5019
private fun enableSchedV2Preferences() {
val hardFactorPreference = findPreference("hardFactor") as NumberRangePreference
hardFactorPreference.isEnabled = true
}
/**
* Returns the number of decks using the options group of the current deck.
*/
private val optionsGroupCount: Int
get() {
var count = 0
val conf = deck.getLong("conf")
@KotlinCleanup("Join both if blocks")
for (deck in col.decks.all()) {
if (deck.isDyn) {
continue
}
if (deck.getLong("conf") == conf) {
count++
}
}
return count
}
/**
* Get the name of the currently set options group
*/
private val optionsGroupName: String
get() {
val confId = pref.getLong("deckConf", 0)
return col.decks.getConf(confId)!!.getString("name")
}
/**
* Get the number of (non-dynamic) subdecks for the current deck
*/
@KotlinCleanup("Use .count{}")
private val subdeckCount: Int
get() {
var count = 0
val did = deck.getLong("id")
val children = col.decks.children(did)
for (childDid in children.values) {
val child = col.decks.get(childDid)
if (child.isDyn) {
continue
}
count++
}
return count
}
private fun restartActivity() {
recreate()
}
companion object {
fun reminderToCalendar(time: Time, reminder: JSONObject): Calendar {
val calendar = time.calendar()
calendar[Calendar.HOUR_OF_DAY] = reminder.getJSONArray("time").getInt(0)
calendar[Calendar.MINUTE] = reminder.getJSONArray("time").getInt(1)
calendar[Calendar.SECOND] = 0
return calendar
}
}
}
| AnkiDroid/src/main/java/com/ichi2/anki/DeckOptionsActivity.kt | 3150091697 |
/*
* Copyright (c) 2021 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.libanki
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ichi2.anki.RobolectricTest
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
@RunWith(AndroidJUnit4::class)
class NoteWithColTest : RobolectricTest() {
@Test
@Config(qualifiers = "en")
fun newNoteTest() {
val note = col.newNote()
assertThat(note.model()["name"], equalTo("Basic"))
}
}
| AnkiDroid/src/test/java/com/ichi2/libanki/NoteWithColTest.kt | 3534722923 |
package io.gitlab.arturbosch.detekt.extensions
import org.gradle.api.Project
import org.gradle.api.file.RegularFile
import org.gradle.api.provider.Provider
import java.io.File
class DetektReport(val type: DetektReportType, private val project: Project) {
var enabled: Boolean? = null
var destination: File? = null
override fun toString(): String {
return "DetektReport(type='$type', enabled=$enabled, destination=$destination)"
}
fun getTargetFileProvider(reportsDir: Provider<File>): Provider<RegularFile> {
return project.provider {
if (enabled ?: DetektExtension.DEFAULT_REPORT_ENABLED_VALUE) {
getTargetFile(reportsDir.get())
} else {
null
}
}
}
private fun getTargetFile(reportsDir: File): RegularFile {
val prop = project.objects.fileProperty()
val customDestination = destination
if (customDestination != null) {
prop.set(customDestination)
} else {
prop.set(File(reportsDir, "$DEFAULT_FILENAME.${type.extension}"))
}
return prop.get()
}
companion object {
const val DEFAULT_FILENAME = "detekt"
}
}
| detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/extensions/DetektReport.kt | 3316001782 |
package org.needhamtrack.nytc.logging
import android.util.Log
import org.needhamtrack.nytc.BuildConfig
import timber.log.Timber
object TimberConfig {
fun init(crashReporter: CrashReporter) {
var tree: Timber.Tree? = null
if (BuildConfig.LOG_CONSOLE) {
if (BuildConfig.REPORT_CRASH) {
tree = object : Timber.DebugTree() {
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
if (priority >= Log.INFO) {
crashReporter.log(priority, tag, message)
} else {
super.log(priority, tag, message, t)
}
}
}
} else {
tree = Timber.DebugTree()
}
} else if (BuildConfig.REPORT_CRASH) {
tree = object : Timber.Tree() {
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
if (priority >= Log.INFO) {
crashReporter.log(priority, tag, message)
}
}
}
}
if (tree != null) {
Timber.plant(tree)
}
}
}
| app/src/main/kotlin/org/needhamtrack/nytc/logging/TimberConfig.kt | 2464069706 |
@file:JvmName("Sdk27ListenersListenersKt")
package org.jetbrains.anko.sdk27.listeners
inline fun android.view.View.onLayoutChange(noinline l: (v: android.view.View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) -> Unit) {
addOnLayoutChangeListener(l)
}
fun android.view.View.onAttachStateChangeListener(init: __View_OnAttachStateChangeListener.() -> Unit) {
val listener = __View_OnAttachStateChangeListener()
listener.init()
addOnAttachStateChangeListener(listener)
}
class __View_OnAttachStateChangeListener : android.view.View.OnAttachStateChangeListener {
private var _onViewAttachedToWindow: ((android.view.View) -> Unit)? = null
override fun onViewAttachedToWindow(v: android.view.View) {
_onViewAttachedToWindow?.invoke(v)
}
fun onViewAttachedToWindow(listener: (android.view.View) -> Unit) {
_onViewAttachedToWindow = listener
}
private var _onViewDetachedFromWindow: ((android.view.View) -> Unit)? = null
override fun onViewDetachedFromWindow(v: android.view.View) {
_onViewDetachedFromWindow?.invoke(v)
}
fun onViewDetachedFromWindow(listener: (android.view.View) -> Unit) {
_onViewDetachedFromWindow = listener
}
}
fun android.widget.TextView.textChangedListener(init: __TextWatcher.() -> Unit) {
val listener = __TextWatcher()
listener.init()
addTextChangedListener(listener)
}
class __TextWatcher : android.text.TextWatcher {
private var _beforeTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
_beforeTextChanged?.invoke(s, start, count, after)
}
fun beforeTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) {
_beforeTextChanged = listener
}
private var _onTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
_onTextChanged?.invoke(s, start, before, count)
}
fun onTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) {
_onTextChanged = listener
}
private var _afterTextChanged: ((android.text.Editable?) -> Unit)? = null
override fun afterTextChanged(s: android.text.Editable?) {
_afterTextChanged?.invoke(s)
}
fun afterTextChanged(listener: (android.text.Editable?) -> Unit) {
_afterTextChanged = listener
}
}
fun android.gesture.GestureOverlayView.onGestureListener(init: __GestureOverlayView_OnGestureListener.() -> Unit) {
val listener = __GestureOverlayView_OnGestureListener()
listener.init()
addOnGestureListener(listener)
}
class __GestureOverlayView_OnGestureListener : android.gesture.GestureOverlayView.OnGestureListener {
private var _onGestureStarted: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureStarted(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGestureStarted?.invoke(overlay, event)
}
fun onGestureStarted(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureStarted = listener
}
private var _onGesture: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGesture(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGesture?.invoke(overlay, event)
}
fun onGesture(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGesture = listener
}
private var _onGestureEnded: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureEnded(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGestureEnded?.invoke(overlay, event)
}
fun onGestureEnded(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureEnded = listener
}
private var _onGestureCancelled: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureCancelled(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGestureCancelled?.invoke(overlay, event)
}
fun onGestureCancelled(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureCancelled = listener
}
}
inline fun android.gesture.GestureOverlayView.onGesturePerformed(noinline l: (overlay: android.gesture.GestureOverlayView?, gesture: android.gesture.Gesture?) -> Unit) {
addOnGesturePerformedListener(l)
}
fun android.gesture.GestureOverlayView.onGesturingListener(init: __GestureOverlayView_OnGesturingListener.() -> Unit) {
val listener = __GestureOverlayView_OnGesturingListener()
listener.init()
addOnGesturingListener(listener)
}
class __GestureOverlayView_OnGesturingListener : android.gesture.GestureOverlayView.OnGesturingListener {
private var _onGesturingStarted: ((android.gesture.GestureOverlayView?) -> Unit)? = null
override fun onGesturingStarted(overlay: android.gesture.GestureOverlayView?) {
_onGesturingStarted?.invoke(overlay)
}
fun onGesturingStarted(listener: (android.gesture.GestureOverlayView?) -> Unit) {
_onGesturingStarted = listener
}
private var _onGesturingEnded: ((android.gesture.GestureOverlayView?) -> Unit)? = null
override fun onGesturingEnded(overlay: android.gesture.GestureOverlayView?) {
_onGesturingEnded?.invoke(overlay)
}
fun onGesturingEnded(listener: (android.gesture.GestureOverlayView?) -> Unit) {
_onGesturingEnded = listener
}
}
inline fun android.media.tv.TvView.onUnhandledInputEvent(noinline l: (event: android.view.InputEvent?) -> Boolean) {
setOnUnhandledInputEventListener(l)
}
inline fun android.view.View.onApplyWindowInsets(noinline l: (v: android.view.View?, insets: android.view.WindowInsets?) -> android.view.WindowInsets?) {
setOnApplyWindowInsetsListener(l)
}
inline fun android.view.View.onCapturedPointer(noinline l: (view: android.view.View?, event: android.view.MotionEvent?) -> Boolean) {
setOnCapturedPointerListener(l)
}
inline fun android.view.View.onClick(noinline l: (v: android.view.View?) -> Unit) {
setOnClickListener(l)
}
inline fun android.view.View.onContextClick(noinline l: (v: android.view.View?) -> Boolean) {
setOnContextClickListener(l)
}
inline fun android.view.View.onCreateContextMenu(noinline l: (menu: android.view.ContextMenu?, v: android.view.View?, menuInfo: android.view.ContextMenu.ContextMenuInfo?) -> Unit) {
setOnCreateContextMenuListener(l)
}
inline fun android.view.View.onDrag(noinline l: (v: android.view.View, event: android.view.DragEvent) -> Boolean) {
setOnDragListener(l)
}
inline fun android.view.View.onFocusChange(noinline l: (v: android.view.View, hasFocus: Boolean) -> Unit) {
setOnFocusChangeListener(l)
}
inline fun android.view.View.onGenericMotion(noinline l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) {
setOnGenericMotionListener(l)
}
inline fun android.view.View.onHover(noinline l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) {
setOnHoverListener(l)
}
inline fun android.view.View.onKey(noinline l: (v: android.view.View, keyCode: Int, event: android.view.KeyEvent?) -> Boolean) {
setOnKeyListener(l)
}
inline fun android.view.View.onLongClick(noinline l: (v: android.view.View?) -> Boolean) {
setOnLongClickListener(l)
}
inline fun android.view.View.onScrollChange(noinline l: (v: android.view.View?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) -> Unit) {
setOnScrollChangeListener(l)
}
inline fun android.view.View.onSystemUiVisibilityChange(noinline l: (visibility: Int) -> Unit) {
setOnSystemUiVisibilityChangeListener(l)
}
inline fun android.view.View.onTouch(noinline l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) {
setOnTouchListener(l)
}
fun android.view.ViewGroup.onHierarchyChangeListener(init: __ViewGroup_OnHierarchyChangeListener.() -> Unit) {
val listener = __ViewGroup_OnHierarchyChangeListener()
listener.init()
setOnHierarchyChangeListener(listener)
}
class __ViewGroup_OnHierarchyChangeListener : android.view.ViewGroup.OnHierarchyChangeListener {
private var _onChildViewAdded: ((android.view.View?, android.view.View?) -> Unit)? = null
override fun onChildViewAdded(parent: android.view.View?, child: android.view.View?) {
_onChildViewAdded?.invoke(parent, child)
}
fun onChildViewAdded(listener: (android.view.View?, android.view.View?) -> Unit) {
_onChildViewAdded = listener
}
private var _onChildViewRemoved: ((android.view.View?, android.view.View?) -> Unit)? = null
override fun onChildViewRemoved(parent: android.view.View?, child: android.view.View?) {
_onChildViewRemoved?.invoke(parent, child)
}
fun onChildViewRemoved(listener: (android.view.View?, android.view.View?) -> Unit) {
_onChildViewRemoved = listener
}
}
inline fun android.view.ViewStub.onInflate(noinline l: (stub: android.view.ViewStub?, inflated: android.view.View?) -> Unit) {
setOnInflateListener(l)
}
fun android.widget.AbsListView.onScrollListener(init: __AbsListView_OnScrollListener.() -> Unit) {
val listener = __AbsListView_OnScrollListener()
listener.init()
setOnScrollListener(listener)
}
class __AbsListView_OnScrollListener : android.widget.AbsListView.OnScrollListener {
private var _onScrollStateChanged: ((android.widget.AbsListView?, Int) -> Unit)? = null
override fun onScrollStateChanged(view: android.widget.AbsListView?, scrollState: Int) {
_onScrollStateChanged?.invoke(view, scrollState)
}
fun onScrollStateChanged(listener: (android.widget.AbsListView?, Int) -> Unit) {
_onScrollStateChanged = listener
}
private var _onScroll: ((android.widget.AbsListView?, Int, Int, Int) -> Unit)? = null
override fun onScroll(view: android.widget.AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
_onScroll?.invoke(view, firstVisibleItem, visibleItemCount, totalItemCount)
}
fun onScroll(listener: (android.widget.AbsListView?, Int, Int, Int) -> Unit) {
_onScroll = listener
}
}
inline fun android.widget.ActionMenuView.onMenuItemClick(noinline l: (item: android.view.MenuItem?) -> Boolean) {
setOnMenuItemClickListener(l)
}
inline fun android.widget.AdapterView<out android.widget.Adapter>.onItemClick(noinline l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit) {
setOnItemClickListener(l)
}
inline fun android.widget.AdapterView<out android.widget.Adapter>.onItemLongClick(noinline l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Boolean) {
setOnItemLongClickListener(l)
}
fun android.widget.AdapterView<out android.widget.Adapter>.onItemSelectedListener(init: __AdapterView_OnItemSelectedListener.() -> Unit) {
val listener = __AdapterView_OnItemSelectedListener()
listener.init()
setOnItemSelectedListener(listener)
}
class __AdapterView_OnItemSelectedListener : android.widget.AdapterView.OnItemSelectedListener {
private var _onItemSelected: ((android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit)? = null
override fun onItemSelected(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) {
_onItemSelected?.invoke(p0, p1, p2, p3)
}
fun onItemSelected(listener: (android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit) {
_onItemSelected = listener
}
private var _onNothingSelected: ((android.widget.AdapterView<*>?) -> Unit)? = null
override fun onNothingSelected(p0: android.widget.AdapterView<*>?) {
_onNothingSelected?.invoke(p0)
}
fun onNothingSelected(listener: (android.widget.AdapterView<*>?) -> Unit) {
_onNothingSelected = listener
}
}
inline fun android.widget.AutoCompleteTextView.onDismiss(noinline l: () -> Unit) {
setOnDismissListener(l)
}
inline fun android.widget.CalendarView.onDateChange(noinline l: (view: android.widget.CalendarView?, year: Int, month: Int, dayOfMonth: Int) -> Unit) {
setOnDateChangeListener(l)
}
inline fun android.widget.Chronometer.onChronometerTick(noinline l: (chronometer: android.widget.Chronometer?) -> Unit) {
setOnChronometerTickListener(l)
}
inline fun android.widget.CompoundButton.onCheckedChange(noinline l: (buttonView: android.widget.CompoundButton?, isChecked: Boolean) -> Unit) {
setOnCheckedChangeListener(l)
}
inline fun android.widget.DatePicker.onDateChanged(noinline l: (view: android.widget.DatePicker?, year: Int, monthOfYear: Int, dayOfMonth: Int) -> Unit) {
setOnDateChangedListener(l)
}
inline fun android.widget.ExpandableListView.onChildClick(noinline l: (parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, childPosition: Int, id: Long) -> Boolean) {
setOnChildClickListener(l)
}
inline fun android.widget.ExpandableListView.onGroupClick(noinline l: (parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, id: Long) -> Boolean) {
setOnGroupClickListener(l)
}
inline fun android.widget.ExpandableListView.onGroupCollapse(noinline l: (groupPosition: Int) -> Unit) {
setOnGroupCollapseListener(l)
}
inline fun android.widget.ExpandableListView.onGroupExpand(noinline l: (groupPosition: Int) -> Unit) {
setOnGroupExpandListener(l)
}
inline fun android.widget.NumberPicker.onScroll(noinline l: (view: android.widget.NumberPicker?, scrollState: Int) -> Unit) {
setOnScrollListener(l)
}
inline fun android.widget.NumberPicker.onValueChanged(noinline l: (picker: android.widget.NumberPicker?, oldVal: Int, newVal: Int) -> Unit) {
setOnValueChangedListener(l)
}
inline fun android.widget.RadioGroup.onCheckedChange(noinline l: (group: android.widget.RadioGroup?, checkedId: Int) -> Unit) {
setOnCheckedChangeListener(l)
}
inline fun android.widget.RatingBar.onRatingBarChange(noinline l: (ratingBar: android.widget.RatingBar?, rating: Float, fromUser: Boolean) -> Unit) {
setOnRatingBarChangeListener(l)
}
inline fun android.widget.SearchView.onClose(noinline l: () -> Boolean) {
setOnCloseListener(l)
}
inline fun android.widget.SearchView.onQueryTextFocusChange(noinline l: (v: android.view.View, hasFocus: Boolean) -> Unit) {
setOnQueryTextFocusChangeListener(l)
}
fun android.widget.SearchView.onQueryTextListener(init: __SearchView_OnQueryTextListener.() -> Unit) {
val listener = __SearchView_OnQueryTextListener()
listener.init()
setOnQueryTextListener(listener)
}
class __SearchView_OnQueryTextListener : android.widget.SearchView.OnQueryTextListener {
private var _onQueryTextSubmit: ((String?) -> Boolean)? = null
override fun onQueryTextSubmit(query: String?) = _onQueryTextSubmit?.invoke(query) ?: false
fun onQueryTextSubmit(listener: (String?) -> Boolean) {
_onQueryTextSubmit = listener
}
private var _onQueryTextChange: ((String?) -> Boolean)? = null
override fun onQueryTextChange(newText: String?) = _onQueryTextChange?.invoke(newText) ?: false
fun onQueryTextChange(listener: (String?) -> Boolean) {
_onQueryTextChange = listener
}
}
inline fun android.widget.SearchView.onSearchClick(noinline l: (v: android.view.View?) -> Unit) {
setOnSearchClickListener(l)
}
fun android.widget.SearchView.onSuggestionListener(init: __SearchView_OnSuggestionListener.() -> Unit) {
val listener = __SearchView_OnSuggestionListener()
listener.init()
setOnSuggestionListener(listener)
}
class __SearchView_OnSuggestionListener : android.widget.SearchView.OnSuggestionListener {
private var _onSuggestionSelect: ((Int) -> Boolean)? = null
override fun onSuggestionSelect(position: Int) = _onSuggestionSelect?.invoke(position) ?: false
fun onSuggestionSelect(listener: (Int) -> Boolean) {
_onSuggestionSelect = listener
}
private var _onSuggestionClick: ((Int) -> Boolean)? = null
override fun onSuggestionClick(position: Int) = _onSuggestionClick?.invoke(position) ?: false
fun onSuggestionClick(listener: (Int) -> Boolean) {
_onSuggestionClick = listener
}
}
fun android.widget.SeekBar.onSeekBarChangeListener(init: __SeekBar_OnSeekBarChangeListener.() -> Unit) {
val listener = __SeekBar_OnSeekBarChangeListener()
listener.init()
setOnSeekBarChangeListener(listener)
}
class __SeekBar_OnSeekBarChangeListener : android.widget.SeekBar.OnSeekBarChangeListener {
private var _onProgressChanged: ((android.widget.SeekBar?, Int, Boolean) -> Unit)? = null
override fun onProgressChanged(seekBar: android.widget.SeekBar?, progress: Int, fromUser: Boolean) {
_onProgressChanged?.invoke(seekBar, progress, fromUser)
}
fun onProgressChanged(listener: (android.widget.SeekBar?, Int, Boolean) -> Unit) {
_onProgressChanged = listener
}
private var _onStartTrackingTouch: ((android.widget.SeekBar?) -> Unit)? = null
override fun onStartTrackingTouch(seekBar: android.widget.SeekBar?) {
_onStartTrackingTouch?.invoke(seekBar)
}
fun onStartTrackingTouch(listener: (android.widget.SeekBar?) -> Unit) {
_onStartTrackingTouch = listener
}
private var _onStopTrackingTouch: ((android.widget.SeekBar?) -> Unit)? = null
override fun onStopTrackingTouch(seekBar: android.widget.SeekBar?) {
_onStopTrackingTouch?.invoke(seekBar)
}
fun onStopTrackingTouch(listener: (android.widget.SeekBar?) -> Unit) {
_onStopTrackingTouch = listener
}
}
inline fun android.widget.SlidingDrawer.onDrawerClose(noinline l: () -> Unit) {
setOnDrawerCloseListener(l)
}
inline fun android.widget.SlidingDrawer.onDrawerOpen(noinline l: () -> Unit) {
setOnDrawerOpenListener(l)
}
fun android.widget.SlidingDrawer.onDrawerScrollListener(init: __SlidingDrawer_OnDrawerScrollListener.() -> Unit) {
val listener = __SlidingDrawer_OnDrawerScrollListener()
listener.init()
setOnDrawerScrollListener(listener)
}
class __SlidingDrawer_OnDrawerScrollListener : android.widget.SlidingDrawer.OnDrawerScrollListener {
private var _onScrollStarted: (() -> Unit)? = null
override fun onScrollStarted() {
_onScrollStarted?.invoke()
}
fun onScrollStarted(listener: () -> Unit) {
_onScrollStarted = listener
}
private var _onScrollEnded: (() -> Unit)? = null
override fun onScrollEnded() {
_onScrollEnded?.invoke()
}
fun onScrollEnded(listener: () -> Unit) {
_onScrollEnded = listener
}
}
inline fun android.widget.TabHost.onTabChanged(noinline l: (tabId: String?) -> Unit) {
setOnTabChangedListener(l)
}
inline fun android.widget.TextView.onEditorAction(noinline l: (v: android.widget.TextView?, actionId: Int, event: android.view.KeyEvent?) -> Boolean) {
setOnEditorActionListener(l)
}
inline fun android.widget.TimePicker.onTimeChanged(noinline l: (view: android.widget.TimePicker?, hourOfDay: Int, minute: Int) -> Unit) {
setOnTimeChangedListener(l)
}
inline fun android.widget.Toolbar.onMenuItemClick(noinline l: (item: android.view.MenuItem?) -> Boolean) {
setOnMenuItemClickListener(l)
}
inline fun android.widget.VideoView.onCompletion(noinline l: (mp: android.media.MediaPlayer?) -> Unit) {
setOnCompletionListener(l)
}
inline fun android.widget.VideoView.onError(noinline l: (mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Boolean) {
setOnErrorListener(l)
}
inline fun android.widget.VideoView.onInfo(noinline l: (mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Boolean) {
setOnInfoListener(l)
}
inline fun android.widget.VideoView.onPrepared(noinline l: (mp: android.media.MediaPlayer?) -> Unit) {
setOnPreparedListener(l)
}
inline fun android.widget.ZoomControls.onZoomInClick(noinline l: (v: android.view.View?) -> Unit) {
setOnZoomInClickListener(l)
}
inline fun android.widget.ZoomControls.onZoomOutClick(noinline l: (v: android.view.View?) -> Unit) {
setOnZoomOutClickListener(l)
}
| anko/library/generated/sdk27-listeners/src/main/java/Listeners.kt | 3346014775 |
/*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.util.multiplatform
import java.util.UUID
import kotlin.reflect.KClass
actual typealias Class<T> = java.lang.Class<T>
actual val KClass<*>.name get() = java.name
actual typealias Throws = kotlin.jvm.Throws
actual typealias UUID = java.util.UUID
actual fun randomUUID(): UUID = UUID.randomUUID()
actual typealias JvmStatic = kotlin.jvm.JvmStatic
actual typealias JvmWildcard = kotlin.jvm.JvmWildcard
actual typealias JvmField = kotlin.jvm.JvmField
actual typealias JvmName = kotlin.jvm.JvmName
actual typealias JvmOverloads = kotlin.jvm.JvmOverloads
actual typealias JvmMultifileClass = kotlin.jvm.JvmMultifileClass
actual typealias URI = java.net.URI
@Suppress("NOTHING_TO_INLINE")
actual inline fun createUri(s: String): URI = URI.create(s)
actual fun String.toUUID(): UUID = UUID.fromString(this)
@Suppress("NOTHING_TO_INLINE")
actual fun <T> fill(array: Array<T>, element: T, fromIndex: Int, toIndex: Int) {
java.util.Arrays.fill(array, fromIndex, toIndex, element)
}
@Suppress("NOTHING_TO_INLINE")
actual fun arraycopy(src: Any, srcPos:Int, dest:Any, destPos:Int, length:Int) =
java.lang.System.arraycopy(src, srcPos, dest, destPos, length)
actual inline fun <reified T:Any> isTypeOf(value: Any):Boolean = value::class.java == T::class.java
actual fun Throwable.addSuppressedCompat(suppressed: Throwable): Unit = addSuppressed(suppressed)
actual fun Throwable.initCauseCompat(cause: Throwable): Throwable = initCause(cause)
| multiplatform/src/javaShared/kotlin/nl/adaptivity/util/multiplatform/javaMultiplatform.kt | 2032265615 |
package com.moviereel.di.qualifiers
import kotlin.annotation.Retention
import kotlin.annotation.AnnotationRetention.RUNTIME
import javax.inject.Qualifier
/**
* @author lusinabrian on 27/03/17
*/
@Qualifier
@Retention(RUNTIME)
annotation class ActivityContext
| app/src/main/kotlin/com/moviereel/di/qualifiers/ActivityContext.kt | 645115920 |
/*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.nativ.libEGL
import org.freedesktop.jaccall.Functor
import org.freedesktop.jaccall.Ptr
@Functor interface EglBindWaylandDisplayWL {
operator fun invoke(@Ptr dpy: Long,
@Ptr wlDisplay: Long): Int
}
| compositor/src/main/kotlin/org/westford/nativ/libEGL/EglBindWaylandDisplayWL.kt | 2582787968 |
package org.fossasia.openevent.general.settings
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import org.fossasia.openevent.general.BuildConfig
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.auth.AuthService
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.data.Preference
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers
import timber.log.Timber
const val API_URL = "apiUrl"
class SettingsViewModel(
private val authService: AuthService,
private val preference: Preference,
private val resource: Resource
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val mutableSnackBar = SingleLiveEvent<String>()
val snackBar: SingleLiveEvent<String> = mutableSnackBar
private val mutableUpdatedPassword = MutableLiveData<String>()
val updatedPassword: LiveData<String> = mutableUpdatedPassword
fun isLoggedIn() = authService.isLoggedIn()
fun logout() {
compositeDisposable += authService.logout()
.withDefaultSchedulers()
.subscribe({
Timber.d("Logged out!")
}) {
Timber.e(it, "Failure Logging out!")
}
}
fun getMarketAppLink(packageName: String): String {
return "market://details?id=" + packageName
}
fun getMarketWebLink(packageName: String): String {
return "https://play.google.com/store/apps/details?id=" + packageName
}
fun changePassword(oldPassword: String, newPassword: String) {
compositeDisposable += authService.changePassword(oldPassword, newPassword)
.withDefaultSchedulers()
.subscribe({
if (it.passwordChanged) {
mutableSnackBar.value = resource.getString(R.string.change_password_success_message)
mutableUpdatedPassword.value = newPassword
}
}, {
if (it.message.toString() == "HTTP 400 BAD REQUEST")
mutableSnackBar.value = resource.getString(R.string.incorrect_old_password_message)
else mutableSnackBar.value = resource.getString(R.string.change_password_fail_message)
})
}
fun getApiUrl(): String {
return preference.getString(API_URL) ?: BuildConfig.DEFAULT_BASE_URL
}
fun changeApiUrl(url: String) {
preference.putString(API_URL, url)
logout()
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
| app/src/main/java/org/fossasia/openevent/general/settings/SettingsViewModel.kt | 3077470606 |
package br.com.insanitech.spritekit.opengl.model
import br.com.insanitech.spritekit.core.ValueAssign
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* Created by anderson on 6/30/15.
*/
internal class GLColor() : ValueAssign<GLColor> {
internal val buffer by lazy {
val bb = ByteBuffer.allocateDirect(16 * 4)
bb.order(ByteOrder.nativeOrder())
bb.asFloatBuffer()
}
var r: Float
get() = this.get(0)
set(value) { this.set(0, value) }
var g: Float
get() = this.get(1)
set(value) { this.set(1, value) }
var b: Float
get() = this.get(2)
set(value) { this.set(2, value) }
var a: Float
get() = this.get(3)
set(value) { this.set(3, value) }
constructor(r: Float, g: Float, b: Float, a: Float) : this() {
this.r = r
this.g = g
this.b = b
this.a = a
}
private fun get(index: Int) : Float = this.buffer.get(index)
private fun set(index: Int, value: Float) {
this.buffer.put(index, value)
this.buffer.put(index + 4, value)
this.buffer.put(index + 8, value)
this.buffer.put(index + 12, value)
}
override fun assignByValue(other: GLColor) {
this.r = other.r
this.g = other.g
this.b = other.b
this.a = other.a
}
companion object {
fun rgb(r: Float, g: Float, b: Float): GLColor = rgba(r, g, b, 1.0f)
fun rgba(r: Float, g: Float, b: Float, a: Float): GLColor = GLColor(r, g, b, a)
}
}
| SpriteKitLib/src/main/java/br/com/insanitech/spritekit/opengl/model/GLColor.kt | 241755342 |
package ca.six.daily.biz.home.viewmodel
import ca.six.daily.R
import ca.six.daily.view.RvViewHolder
import ca.six.daily.view.ViewType
import java.text.SimpleDateFormat
import java.util.*
class ListTitleViewModel(val title: String) : ViewType<String> {
override fun getViewType(): Int {
return R.layout.item_title
}
override fun bind(holder: RvViewHolder) {
val formatterIn = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
val date = formatterIn.parse(title)
val formatterOut = SimpleDateFormat("MMM, dd yyyy", Locale.CANADA)
holder.setText(R.id.tvTitleItem, formatterOut.format(date))
}
override fun getData(): String {
return title
}
} | app/src/main/java/ca/six/daily/biz/home/viewmodel/ListTitleViewModel.kt | 663630545 |
/*
* Copyright (c) 2016. KESTI co, 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 debop4k.core.examples
import debop4k.core.AbstractCoreKotlinTest
import org.junit.Test
/**
* LiteralFunctionExamples
* @author [email protected]
*/
class LiteralFunctionExamples : AbstractCoreKotlinTest() {
@Test
fun makeIterate() {
val sequence = generateSequence(0) {
if (it < 100) {
Thread.sleep(100)
it + 1
} else
it
}
val list: Sequence<Int> = sequence.takeWhile { it < 100 }
list.forEach { println("$it") }
}
} | debop4k-core/src/test/kotlin/debop4k/core/examples/LiteralFunctionExamples.kt | 1131278839 |
/*
* Copyright (c) 2016. KESTI co, 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 debop4k.core.logback
import org.joda.time.DateTime
/**
* Kotlin 에서는 이런 Builder 패턴을 apply { } 메소드로 사용하는 것이 가장 좋다
*
* @author [email protected]
*/
class LogDocumentBuilder {
private var _serverName: String = "localhost"
private var _applicationName: String = ""
private var _logger: String = ""
private var _levelInt: Int = 0
private var _levelStr: String = ""
private var _threadName: String = ""
private var _message: String = ""
private var _timestamp: DateTime = DateTime.now()
private var _marker: String? = null
private var _exception: String? = null
private var _stackTrace: List<String> = emptyList()
/**
* Server name 설정
* @param serverName 설정할 server name
* *
* @return LogDocumentBuilder 인스턴스
*/
fun serverName(serverName: String): LogDocumentBuilder {
this._serverName = serverName
return this
}
/**
* Application name 설정
* @param applicationName 설정할 application name
* *
* @return LogDocumentBuilder 인스턴스
*/
fun applicationName(applicationName: String): LogDocumentBuilder {
this._applicationName = applicationName
return this
}
/**
* Logger 명 설정
* @param logger 설정할 logger 명
* *
* @return LogDocumentBuilder 인스턴스
*/
fun logger(logger: String): LogDocumentBuilder {
this._logger = logger
return this
}
/**
* Level 값 설정
* @param levelInt 설정할 레벨 값 (참고 : [ch.qos.logback.classic.Level] )
* *
* @return LogDocumentBuilder 인스턴스
*/
fun levelInt(levelInt: Int): LogDocumentBuilder {
this._levelInt = levelInt
return this
}
/**
* Level 설정
* @param levelStr 설정할 레벨 값 (참고 : [ch.qos.logback.classic.Level] )
* *
* @return LogDocumentBuilder 인스턴스
*/
fun levelStr(levelStr: String): LogDocumentBuilder {
this._levelStr = levelStr
return this
}
fun threadName(threadName: String): LogDocumentBuilder {
this._threadName = threadName
return this
}
fun message(message: String): LogDocumentBuilder {
this._message = message
return this
}
fun timestamp(timestamp: DateTime): LogDocumentBuilder {
this._timestamp = timestamp
return this
}
fun marker(marker: String): LogDocumentBuilder {
this._marker = marker
return this
}
fun exception(exception: String): LogDocumentBuilder {
this._exception = exception
return this
}
fun stackTrace(stackTrace: List<String>): LogDocumentBuilder {
this._stackTrace = stackTrace
return this
}
fun build(): LogDocument {
return LogDocument().apply {
serverName = _serverName
applicationName = _applicationName
logger = _logger
levelInt = _levelInt
levelStr = _levelStr
threadName = _threadName
message = _message
timestamp = _timestamp
marker = _marker
exception = _exception
stackTrace = _stackTrace
}
}
} | debop4k-core/src/main/kotlin/debop4k/core/logback/LogDocumentBuilder.kt | 416837366 |
/*
* Copyright (c) 2016. KESTI co, 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 debop4k.core.utils
import debop4k.core.AbstractCoreKotlinTest
import debop4k.core.collections.emptyCharArray
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Condition
import org.eclipse.collections.impl.factory.SortedMaps
import org.eclipse.collections.impl.list.mutable.FastList
import org.junit.Test
class StringExKotlinTest : AbstractCoreKotlinTest() {
internal val spaceTextt = " "
internal val whitespaceText = "\n \r \t "
@Test
fun testIsNull() {
assertThat(null.isNull()).isTrue()
assertThat("".isNull()).isFalse()
assertThat(null.isNotNull()).isFalse()
assertThat("".isNotNull()).isTrue()
}
@Test
fun testIsEmpty() {
assertThat(null.isEmpty()).isTrue()
assertThat("".isEmpty()).isTrue()
assertThat(spaceTextt.isEmpty()).isTrue()
assertThat(whitespaceText.isEmpty()).isTrue()
assertThat("null".isEmpty()).isFalse()
assertThat(null.isNotEmpty()).isFalse()
assertThat("".isNotEmpty()).isFalse()
assertThat(spaceTextt.isNotEmpty()).isFalse()
assertThat(whitespaceText.isNotEmpty()).isFalse()
assertThat("null".isNotEmpty()).isTrue()
}
@Test
fun testEllipsis() {
assertThat(sampleText.needEllipsis(sampleText.length * 2)).isFalse()
assertThat(sampleText.needEllipsis(sampleText.length / 2)).isTrue()
assertThat(sampleText.ellipsisEnd(10)).endsWith(TRIMMING)
assertThat(sampleText.ellipsisStart(10)).startsWith(TRIMMING)
assertThat(sampleText.ellipsisMid(10))
.`is`(object : Condition<CharSequence>() {
override fun matches(value: CharSequence): Boolean {
return !value.startsWith(TRIMMING)
}
})
.`is`(object : Condition<CharSequence>() {
override fun matches(value: CharSequence): Boolean {
return !value.endsWith(TRIMMING)
}
}).contains(TRIMMING)
}
@Test
fun covertToHexString() {
val text = "123 123"
val hexText = "31323320313233"
assertThat(byteArrayToHexString(text.toUtf8Bytes())).isEqualTo(hexText)
assertThat(hexStringToByteArray(hexText).toUtf8String()).isEqualTo(text)
}
@Test
fun convertToBase64String() {
val base64Str = byteArrayToBase64String(sampleBytes)
val bytes = base64StringToByteArray(base64Str)
val converted = bytes.toUtf8String()
assertThat(bytes).isEqualTo(sampleBytes)
assertThat(converted).isEqualTo(sampleText)
}
@Test
fun utf8StringToBytes() {
val bytes = sampleText.toUtf8Bytes()
val converted = bytes.toUtf8String()
assertThat(converted).isEqualTo(sampleText)
}
@Test
fun testDeleteChar() {
val text = "abcdefgh"
assertThat(text.deleteChar('c', 'f')).isEqualTo("abdegh")
assertThat(text.deleteChar('a', 'h')).isEqualTo("bcdefg")
}
@Test
fun testConcat() {
assertThat(concat(listOf("a", "b", "c"), ",")).isEqualTo("a,b,c")
}
@Test
fun stringSplitByCharacter() {
val attlStr = "37|75|95|107|133|141|142|147|148|178"
val atvlStr = "9 ||||2999999|||20091231|KR,KR,graph,c836|"
val attls = attlStr.splits('|')
val atvls = atvlStr.splits('|')
log.debug("attls size={}, {}", attls.size, attls)
log.debug("atvls size={}, {}", atvls.size, atvls)
}
@Test
fun stringSplit() {
val str = "동해,물 || 백두,산 a BaB"
val strList = str.splits(true, true, ",", "||", "A")
assertThat<String>(strList).contains("동해", "물", "백두", "산", "B", "B").hasSize(6)
val caseStrs = str.splits(false, true, ",", "||", "A")
assertThat<String>(caseStrs).contains("동해", "물", "백두", "산 a BaB").hasSize(4)
}
@Test
fun stringSplitIgnoreCase() {
val text = "Hello World! Hello java^^"
var result: List<String> = text.splits(true, true, "!")
assertThat<String>(result).contains("Hello World", "Hello java^^").hasSize(2)
result = text.splits(false, true, "hello")
assertThat<String>(result).contains(text).hasSize(1)
result = text.splits(true, true, "hello")
assertThat<String>(result).contains("World!", "java^^").hasSize(2)
result = text.splits(true, true, "hello", "java")
assertThat<String>(result).contains("World!", "^^").hasSize(2)
result = text.splits(true, true, "||")
assertThat<String>(result).contains(text).hasSize(1)
}
@Test
fun testWordCount() {
val text = sampleText.replicate(10)
assertThat(text.wordCount("동해")).isEqualTo(10)
}
@Test
fun testFirstLine() {
val text = listOf(sampleText, sampleText, sampleText).join(LINE_SEPARATOR)
assertThat(text.firstLine()).isEqualTo(sampleText)
assertThat(text.firstLine(LINE_SEPARATOR)).isEqualTo(sampleText)
}
@Test
fun testBetween() {
val text = "서울특별시 성북구 정릉동 현대아파트 107-301 서울특별시 성북구 정릉동 현대아파트 107-301"
assertThat(text.between("", "")).isEmpty()
assertThat(text.between("별", "동")).isEqualTo("시 성북구 정릉")
assertThat(text.between("", "특")).isEqualTo("서울")
assertThat(text.between("3", "")).isEqualTo("01 서울특별시 성북구 정릉동 현대아파트 107-301")
assertThat("abcdefg".between("c", "g")).isEqualTo("def")
assertThat("abcdefg".between("", "c")).isEqualTo("ab")
// NOTE: lastIndexOf 의 fromIndex 는 뒤에서부터 찾을 때이 index 값을 줘야 한다. (0 을 주면 항상 -1 이다)
val sample = "Hello World! Sunghyouk Bae Hello World"
assertThat(sample.lastIndexOf("Wor", 40)).isEqualTo(33)
assertThat(sample.lastIndexOf("Wor", 0)).isEqualTo(-1)
}
@Test
fun toCharArrayTest() {
assertThat(null.toCharArray()).isEqualTo(emptyCharArray)
assertThat("".toCharArray()).isEqualTo(emptyCharArray)
assertThat("abc".toCharArray()).hasSize(3).contains('a', 'b', 'c')
}
@Test
fun mkStringTest() {
assertThat(arrayOf("a", "bc", "def").mkString()).isEqualTo("a,bc,def")
assertThat(arrayOf("a", "bc", "def").mkString()).isEqualTo("a,bc,def")
assertThat(arrayOf("a", "bc", "def").mkString("|")).isEqualTo("a|bc|def")
assertThat(FastList.newListWith("a", "bc", "def").mkString()).isEqualTo("a,bc,def")
assertThat(FastList.newListWith("a", "bc", "def").mkString("|")).isEqualTo("a|bc|def")
val map = SortedMaps.mutable.of("a", 1, "b", 2, "c", 3)
assertThat(map.mkString<String, Int>()).isEqualTo("a=1,b=2,c=3")
assertThat(map.mkString<String, Int>("|")).isEqualTo("a=1|b=2|c=3")
}
@Test
fun joinString() {
assertThat(arrayOf("a", "bc", "def").join()).isEqualTo("a,bc,def")
assertThat(arrayOf("a", "bc", "def").join()).isEqualTo("a,bc,def")
assertThat(arrayOf("a", "bc", "def").join("|")).isEqualTo("a|bc|def")
assertThat(FastList.newListWith("a", "bc", "def").join()).isEqualTo("a,bc,def")
assertThat(FastList.newListWith("a", "bc", "def").join("|")).isEqualTo("a|bc|def")
val map = SortedMaps.mutable.of("a", 1, "b", 2, "c", 3)
assertThat(map.join<String, Int>()).isEqualTo("a=1,b=2,c=3")
assertThat(map.join<String, Int>("|")).isEqualTo("a=1|b=2|c=3")
}
}
| debop4k-core/src/test/kotlin/debop4k/core/utils/StringExKotlinTest.kt | 3183352432 |
/*
* Copyright (C) 2016 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.ui.suggestions.shows
import android.content.Context
import android.os.Bundle
import android.view.MenuItem
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import net.simonvt.cathode.R
import net.simonvt.cathode.common.ui.fragment.SwipeRefreshRecyclerFragment
import net.simonvt.cathode.entity.Show
import net.simonvt.cathode.provider.ProviderSchematic.Shows
import net.simonvt.cathode.settings.Settings
import net.simonvt.cathode.sync.scheduler.ShowTaskScheduler
import net.simonvt.cathode.ui.CathodeViewModelFactory
import net.simonvt.cathode.ui.LibraryType
import net.simonvt.cathode.ui.NavigationListener
import net.simonvt.cathode.ui.ShowsNavigationListener
import net.simonvt.cathode.ui.lists.ListDialog
import net.simonvt.cathode.ui.shows.ShowDescriptionAdapter
import javax.inject.Inject
class TrendingShowsFragment @Inject constructor(
private val viewModelFactory: CathodeViewModelFactory,
private val showScheduler: ShowTaskScheduler
) : SwipeRefreshRecyclerFragment<ShowDescriptionAdapter.ViewHolder>(), ListDialog.Callback,
ShowDescriptionAdapter.ShowCallbacks {
private lateinit var viewModel: TrendingShowsViewModel
private var showsAdapter: ShowDescriptionAdapter? = null
private lateinit var navigationListener: ShowsNavigationListener
private lateinit var sortBy: SortBy
private var columnCount: Int = 0
private var scrollToTop: Boolean = false
enum class SortBy(val key: String, val sortOrder: String) {
VIEWERS("viewers", Shows.SORT_VIEWERS), RATING("rating", Shows.SORT_RATING);
override fun toString(): String {
return key
}
companion object {
fun fromValue(value: String) = values().firstOrNull { it.key == value } ?: VIEWERS
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
navigationListener = requireActivity() as NavigationListener
}
override fun onCreate(inState: Bundle?) {
super.onCreate(inState)
sortBy = SortBy.fromValue(
Settings.get(requireContext()).getString(Settings.Sort.SHOW_TRENDING, SortBy.VIEWERS.key)!!
)
columnCount = resources.getInteger(R.integer.showsColumns)
setTitle(R.string.title_shows_trending)
setEmptyText(R.string.shows_loading_trending)
viewModel =
ViewModelProviders.of(this, viewModelFactory).get(TrendingShowsViewModel::class.java)
viewModel.loading.observe(this, Observer { loading -> setRefreshing(loading) })
viewModel.trending.observe(this, Observer { shows -> setShows(shows) })
}
override fun getColumnCount(): Int {
return columnCount
}
override fun onRefresh() {
viewModel.refresh()
}
override fun onMenuItemClick(item: MenuItem): Boolean {
when (item.itemId) {
R.id.sort_by -> {
val items = arrayListOf<ListDialog.Item>()
items.add(ListDialog.Item(R.id.sort_viewers, R.string.sort_viewers))
items.add(ListDialog.Item(R.id.sort_rating, R.string.sort_rating))
ListDialog.newInstance(requireFragmentManager(), R.string.action_sort_by, items, this)
.show(requireFragmentManager(), DIALOG_SORT)
return true
}
else -> return super.onMenuItemClick(item)
}
}
override fun onItemSelected(id: Int) {
when (id) {
R.id.sort_viewers -> if (sortBy != SortBy.VIEWERS) {
sortBy = SortBy.VIEWERS
Settings.get(requireContext())
.edit()
.putString(Settings.Sort.SHOW_TRENDING, SortBy.VIEWERS.key)
.apply()
viewModel.setSortBy(sortBy)
scrollToTop = true
}
R.id.sort_rating -> if (sortBy != SortBy.RATING) {
sortBy = SortBy.RATING
Settings.get(requireContext())
.edit()
.putString(Settings.Sort.SHOW_TRENDING, SortBy.RATING.key)
.apply()
viewModel.setSortBy(sortBy)
scrollToTop = true
}
}
}
override fun onShowClick(showId: Long, title: String?, overview: String?) {
navigationListener.onDisplayShow(showId, title, overview, LibraryType.WATCHED)
}
override fun setIsInWatchlist(showId: Long, inWatchlist: Boolean) {
showScheduler.setIsInWatchlist(showId, inWatchlist)
}
private fun setShows(shows: List<Show>) {
if (showsAdapter == null) {
showsAdapter = ShowDescriptionAdapter(requireContext(), this)
adapter = showsAdapter
}
showsAdapter!!.setList(shows)
if (scrollToTop) {
recyclerView.scrollToPosition(0)
scrollToTop = false
}
}
companion object {
private const val DIALOG_SORT =
"net.simonvt.cathode.ui.suggestions.shows.TrendingShowsFragment.sortDialog"
}
}
| cathode/src/main/java/net/simonvt/cathode/ui/suggestions/shows/TrendingShowsFragment.kt | 4044269408 |
package com.duopoints.android.logistics.upload
import com.google.firebase.storage.StorageReference
import java.io.File
data class UploadMedia(val ref: StorageReference, val mediaFile: File)
| app/src/main/java/com/duopoints/android/logistics/upload/UploadMedia.kt | 690097468 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.psi.impl
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiAnnotationMemberValue
import com.intellij.psi.PsiLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
fun PsiAnnotation.findDeclaredDetachedValue(attributeName: String?): PsiAnnotationMemberValue? {
return AnnotationUtil.findDeclaredAttribute(this, attributeName)?.detachedValue
}
fun PsiAnnotationMemberValue?.booleanValue() = (this as? PsiLiteral)?.value as? Boolean
fun PsiAnnotationMemberValue?.stringValue() = (this as? PsiLiteral)?.value as? String
fun GrModifierList.hasAnnotation(fqn: String) = annotations.any { it.qualifiedName == fqn }
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/grAnnotationUtil.kt | 1751442759 |
package com.hea3ven.dulcedeleche.modules.redstone.dispenser
import com.hea3ven.dulcedeleche.DulceDeLecheMod
import com.hea3ven.tools.commonutils.util.ItemStackUtil
import net.minecraft.block.DispenserBlock
import net.minecraft.block.dispenser.DispenserBehavior
import net.minecraft.entity.EquipmentSlot
import net.minecraft.item.ItemStack
import net.minecraft.util.math.BlockPointer
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
class DispenserPlantBehavior : DispenserBehavior {
override fun dispense(source: BlockPointer, stack: ItemStack): ItemStack {
val direction: Direction = source.blockState.get(DispenserBlock.FACING)
val position = source.blockPos.offset(direction)
val offset = if (source.world.isAir(position)) 1 else 0
val pos = BlockPos(position.x, position.y - offset, position.z)
val player = DulceDeLecheMod.mod.getFakePlayer(source.world)
player.setEquippedStack(EquipmentSlot.HAND_MAIN, stack)
ItemStackUtil.useItem(player, stack, pos, Direction.UP)
player.setEquippedStack(EquipmentSlot.HAND_MAIN, ItemStack.EMPTY)
return stack
}
} | src/main/kotlin/com/hea3ven/dulcedeleche/modules/redstone/dispenser/DispenserPlantBehavior.kt | 868993834 |
package com.lasthopesoftware.bluewater.client.connection.settings.changes.GivenALibrary
import androidx.test.core.app.ApplicationProvider
import com.lasthopesoftware.AndroidContext
import com.lasthopesoftware.bluewater.client.browsing.library.access.ILibraryStorage
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.connection.settings.ConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.settings.LookupConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.settings.changes.ObservableConnectionSettingsLibraryStorage
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.lasthopesoftware.resources.FakeMessageBus
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class WhenRemovingTheLibrary : AndroidContext() {
companion object {
private val libraryToRemove = Library(_id = 14)
private val messageBus = FakeMessageBus(ApplicationProvider.getApplicationContext())
private val libraryStorage = mockk<ILibraryStorage>()
}
override fun before() {
every { libraryStorage.removeLibrary(any()) } returns Unit.toPromise()
val connectionSettingsLookup = mockk<LookupConnectionSettings>()
every {
connectionSettingsLookup.lookupConnectionSettings(LibraryId(13))
} returns ConnectionSettings("codeOne").toPromise() andThen ConnectionSettings("codeOne").toPromise()
val connectionSettingsChangeDetectionLibraryStorage = ObservableConnectionSettingsLibraryStorage(
libraryStorage,
connectionSettingsLookup,
messageBus
)
connectionSettingsChangeDetectionLibraryStorage.removeLibrary(libraryToRemove).toFuture().get()
}
@Test
fun thenTheLibraryIsRemoved() {
verify { libraryStorage.removeLibrary(libraryToRemove) }
}
@Test
fun thenNoUpdatesAreSentOnTheMessageBus() {
assertThat(messageBus.recordedIntents).isEmpty()
}
}
| projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/connection/settings/changes/GivenALibrary/WhenRemovingTheLibrary.kt | 3627276341 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.remote.client
import com.intellij.openapi.diagnostic.Logger
import com.intellij.testGuiFramework.remote.transport.TransportMessage
import java.io.EOFException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.net.Socket
import java.util.*
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue
/**
* @author Sergey Karashevich
*/
class JUnitClientImpl(val host: String, val port: Int, initHandlers: Array<ClientHandler>? = null) : JUnitClient {
private val LOG = Logger.getInstance("#com.intellij.testGuiFramework.remote.client.JUnitClientImpl")
private val RECEIVE_THREAD = "JUnit Client Receive Thread"
private val SEND_THREAD = "JUnit Client Send Thread"
private val connection: Socket
private val clientReceiveThread: ClientReceiveThread
private val clientSendThread: ClientSendThread
private val poolOfMessages: BlockingQueue<TransportMessage> = LinkedBlockingQueue()
private val objectInputStream: ObjectInputStream
private val objectOutputStream: ObjectOutputStream
private val handlers: ArrayList<ClientHandler> = ArrayList()
init {
if (initHandlers != null) handlers.addAll(initHandlers)
LOG.info("Client connecting to Server($host, $port) ...")
connection = Socket(host, port)
LOG.info("Client connected to Server($host, $port) successfully")
objectOutputStream = ObjectOutputStream(connection.getOutputStream())
clientSendThread = ClientSendThread(connection, objectOutputStream)
clientSendThread.start()
objectInputStream = ObjectInputStream(connection.getInputStream())
clientReceiveThread = ClientReceiveThread(connection, objectInputStream)
clientReceiveThread.start()
}
override fun addHandler(handler: ClientHandler) {
handlers.add(handler)
}
override fun removeHandler(handler: ClientHandler) {
handlers.remove(handler)
}
override fun removeAllHandlers() {
handlers.clear()
}
override fun send(message: TransportMessage) {
poolOfMessages.add(message)
}
override fun stopClient() {
val clientPort = connection.port
LOG.info("Stopping client on port: $clientPort ...")
poolOfMessages.clear()
handlers.clear()
clientReceiveThread.objectInputStream.close()
clientReceiveThread.join()
clientSendThread.objectOutputStream.close()
clientSendThread.join()
connection.close()
LOG.info("Stopped client on port: $clientPort")
}
inner class ClientReceiveThread(val connection: Socket, val objectInputStream: ObjectInputStream) : Thread(RECEIVE_THREAD) {
override fun run() {
LOG.info("Starting Client Receive Thread")
try{
while (connection.isConnected) {
val obj = objectInputStream.readObject()
LOG.info("Received message: $obj")
obj as TransportMessage
handlers
.filter { it.accept(obj) }
.forEach { it.handle(obj) }
}
} catch (e: Exception) {
LOG.info("Transport receiving message exception: $e")
e.printStackTrace()
} finally {
objectInputStream.close()
}
}
}
inner class ClientSendThread(val connection: Socket, val objectOutputStream: ObjectOutputStream) : Thread(SEND_THREAD) {
override fun run() {
try {
LOG.info("Starting Client Send Thread")
while (connection.isConnected) {
val transportMessage = poolOfMessages.take()
LOG.info("Sending message: $transportMessage")
objectOutputStream.writeObject(transportMessage)
}
}
catch(e: InterruptedException) {
Thread.currentThread().interrupt()
}
finally {
objectOutputStream.close()
}
}
}
}
| platform/testGuiFramework/src/com/intellij/testGuiFramework/remote/client/JUnitClientImpl.kt | 2735192414 |
package com.quickblox.sample.conference.kotlin.presentation.screens.chat.adapters.attachment
import android.graphics.Bitmap
import com.quickblox.content.model.QBFile
/*
* Created by Injoit in 2021-09-30.
* Copyright © 2021 Quickblox. All rights reserved.
*/
data class AttachmentModel(var qbFile: QBFile? = null, val bitmap: Bitmap? = null, var progress: Int = 0) | sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/chat/adapters/attachment/AttachmentModel.kt | 1555874896 |
package io.casey.musikcube.remote.service.playback.impl.streaming.db
import androidx.room.Database
import androidx.room.RoomDatabase
import io.casey.musikcube.remote.Application
import io.casey.musikcube.remote.injection.DaggerDataComponent
import io.casey.musikcube.remote.service.playback.impl.remote.Metadata
import io.casey.musikcube.remote.service.playback.impl.streaming.StreamProxy
import io.casey.musikcube.remote.service.websocket.Messages
import io.casey.musikcube.remote.service.websocket.SocketMessage
import io.casey.musikcube.remote.service.websocket.WebSocketService
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.json.JSONArray
import org.json.JSONObject
import javax.inject.Inject
@Database(entities = [OfflineTrack::class], version = 1)
abstract class OfflineDb : RoomDatabase() {
@Inject lateinit var wss: WebSocketService
@Inject lateinit var streamProxy: StreamProxy
init {
DaggerDataComponent.builder()
.appComponent(Application.appComponent)
.build().inject(this)
wss.addInterceptor{ message, responder ->
var result = false
if (Messages.Request.QueryTracksByCategory.matches(message.name)) {
val category = message.getStringOption(Messages.Key.CATEGORY)
if (Metadata.Category.OFFLINE == category) {
queryTracks(message, responder)
result = true
}
}
result
}
prune()
}
abstract fun trackDao(): OfflineTrackDao
fun prune() {
@Suppress("unused")
Single.fromCallable {
val uris = trackDao().queryUris()
val toDelete = ArrayList<String>()
uris.forEach {
if (!streamProxy.isCached(it)) {
toDelete.add(it)
}
}
if (toDelete.size > 0) {
trackDao().deleteByUri(toDelete)
}
true
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ }, { })
}
private fun queryTracks(message: SocketMessage, responder: WebSocketService.Responder) {
Single.fromCallable {
val dao = trackDao()
val countOnly = message.getBooleanOption(Messages.Key.COUNT_ONLY, false)
val filter = message.getStringOption(Messages.Key.FILTER, "")
val tracks = JSONArray()
val options = JSONObject()
if (countOnly) {
val count = if (filter.isEmpty()) dao.countTracks() else dao.countTracks(filter)
options.put(Messages.Key.COUNT, count)
}
else {
val offset = message.getIntOption(Messages.Key.OFFSET, -1)
val limit = message.getIntOption(Messages.Key.LIMIT, -1)
val offlineTracks: List<OfflineTrack> =
if (filter.isEmpty()) {
if (offset == -1 || limit == -1)
dao.queryTracks() else dao.queryTracks(limit, offset)
}
else {
if (offset == -1 || limit == -1)
dao.queryTracks(filter) else dao.queryTracks(filter, limit, offset)
}
for (track in offlineTracks) {
tracks.put(track.toJSONObject())
}
options.put(Messages.Key.OFFSET, offset)
options.put(Messages.Key.LIMIT, limit)
}
options.put(Messages.Key.DATA, tracks)
val response = SocketMessage.Builder
.respondTo(message).withOptions(options).build()
responder.respond(response)
true
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()
}
}
| src/musikdroid/app/src/main/java/io/casey/musikcube/remote/service/playback/impl/streaming/db/OfflineDb.kt | 2307881227 |
fun main(args : Array<String>) {
println("Hello, world!")
}
| kotlin.kt | 2929209143 |
package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.test.TestConfig
import io.gitlab.arturbosch.detekt.test.lint
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
private const val IMPORTS = "imports"
private const val FORBIDDEN_PATTERNS = "forbiddenPatterns"
class ForbiddenImportSpec : Spek({
describe("ForbiddenImport rule") {
val code = """
package foo
import kotlin.jvm.JvmField
import kotlin.SinceKotlin
import com.example.R.string
import net.example.R.dimen
import net.example.R.dimension
"""
it("should report nothing by default") {
val findings = ForbiddenImport().lint(code)
assertThat(findings).isEmpty()
}
it("should report nothing when imports are blank") {
val findings = ForbiddenImport(TestConfig(mapOf(IMPORTS to " "))).lint(code)
assertThat(findings).isEmpty()
}
it("should report nothing when imports do not match") {
val findings = ForbiddenImport(TestConfig(mapOf(IMPORTS to "org.*"))).lint(code)
assertThat(findings).isEmpty()
}
it("should report kotlin.* when imports are kotlin.*") {
val findings = ForbiddenImport(TestConfig(mapOf(IMPORTS to "kotlin.*"))).lint(code)
assertThat(findings).hasSize(2)
}
it("should report kotlin.SinceKotlin when specified via fully qualified name") {
val findings =
ForbiddenImport(TestConfig(mapOf(IMPORTS to "kotlin.SinceKotlin"))).lint(code)
assertThat(findings).hasSize(1)
}
it("should report kotlin.SinceKotlin and kotlin.jvm.JvmField when specified via fully qualified names") {
val findings =
ForbiddenImport(TestConfig(mapOf(IMPORTS to "kotlin.SinceKotlin,kotlin.jvm.JvmField"))).lint(
code
)
assertThat(findings).hasSize(2)
}
it("should report kotlin.SinceKotlin and kotlin.jvm.JvmField when specified via fully qualified names list") {
val findings =
ForbiddenImport(
TestConfig(
mapOf(
IMPORTS to listOf("kotlin.SinceKotlin", "kotlin.jvm.JvmField")
)
)
).lint(code)
assertThat(findings).hasSize(2)
}
it("should report kotlin.SinceKotlin when specified via kotlin.Since*") {
val findings = ForbiddenImport(TestConfig(mapOf(IMPORTS to "kotlin.Since*"))).lint(code)
assertThat(findings).hasSize(1)
}
it("should report all of com.example.R.string, net.example.R.dimen, and net.example.R.dimension") {
val findings = ForbiddenImport(TestConfig(mapOf(IMPORTS to "*.R.*"))).lint(code)
assertThat(findings).hasSize(3)
}
it("should report net.example.R.dimen but not net.example.R.dimension") {
val findings =
ForbiddenImport(TestConfig(mapOf(IMPORTS to "net.example.R.dimen"))).lint(code)
assertThat(findings).hasSize(1)
}
it("should not report import when it does not match any pattern") {
val findings =
ForbiddenImport(TestConfig(mapOf(FORBIDDEN_PATTERNS to "nets.*R"))).lint(code)
assertThat(findings).isEmpty()
}
it("should report import when it matches the forbidden pattern") {
val findings =
ForbiddenImport(TestConfig(mapOf(FORBIDDEN_PATTERNS to "net.*R|com.*expiremental"))).lint(code)
assertThat(findings).hasSize(2)
}
}
})
| detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/ForbiddenImportSpec.kt | 659534364 |
package io.gitlab.arturbosch.detekt.rules.complexity
import io.github.detekt.metrics.linesOfCode
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Metric
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.ThresholdedCodeSmell
import io.gitlab.arturbosch.detekt.api.config
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import io.gitlab.arturbosch.detekt.api.internal.Configuration
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.utils.addToStdlib.flattenTo
import java.util.IdentityHashMap
/**
* This rule reports large classes. Classes should generally have one responsibility. Large classes can indicate that
* the class does instead handle multiple responsibilities. Instead of doing many things at once prefer to
* split up large classes into smaller classes. These smaller classes are then easier to understand and handle less
* things.
*/
@ActiveByDefault(since = "1.0.0")
class LargeClass(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(
"LargeClass",
Severity.Maintainability,
"One class should have one responsibility. Large classes tend to handle many things at once. " +
"Split up large classes into smaller classes that are easier to understand.",
Debt.TWENTY_MINS
)
@Configuration("the size of class required to trigger the rule")
private val threshold: Int by config(defaultValue = 600)
private val classToLinesCache = IdentityHashMap<KtClassOrObject, Int>()
private val nestedClassTracking = IdentityHashMap<KtClassOrObject, HashSet<KtClassOrObject>>()
override fun preVisit(root: KtFile) {
classToLinesCache.clear()
nestedClassTracking.clear()
}
override fun postVisit(root: KtFile) {
for ((clazz, lines) in classToLinesCache) {
if (lines >= threshold) {
report(
ThresholdedCodeSmell(
issue,
Entity.atName(clazz),
Metric("SIZE", lines, threshold),
"Class ${clazz.name} is too large. Consider splitting it into smaller pieces."
)
)
}
}
}
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
val lines = classOrObject.linesOfCode()
classToLinesCache[classOrObject] = lines
classOrObject.getStrictParentOfType<KtClassOrObject>()
?.let { nestedClassTracking.getOrPut(it) { HashSet() }.add(classOrObject) }
super.visitClassOrObject(classOrObject)
findAllNestedClasses(classOrObject)
.fold(0) { acc, next -> acc + (classToLinesCache[next] ?: 0) }
.takeIf { it > 0 }
?.let { classToLinesCache[classOrObject] = lines - it }
}
private fun findAllNestedClasses(startClass: KtClassOrObject): Sequence<KtClassOrObject> = sequence {
var nestedClasses = nestedClassTracking[startClass]
while (!nestedClasses.isNullOrEmpty()) {
yieldAll(nestedClasses)
nestedClasses = nestedClasses.mapNotNull { nestedClassTracking[it] }.flattenTo(HashSet())
}
}
}
| detekt-rules-complexity/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/LargeClass.kt | 273724669 |
/*
* Copyright (C) 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 com.example.android.kotlincoroutines.main
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Room
import androidx.room.RoomDatabase
/**
* Title represents the title fetched from the network
*/
@Entity
data class Title constructor(val title: String, @PrimaryKey val id: Int = 0)
/***
* Very small database that will hold one title
*/
@Dao
interface TitleDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertTitle(title: Title)
@get:Query("select * from Title where id = 0")
val titleLiveData: LiveData<Title?>
}
/**
* TitleDatabase provides a reference to the dao to repositories
*/
@Database(entities = [Title::class], version = 1, exportSchema = false)
abstract class TitleDatabase : RoomDatabase() {
abstract val titleDao: TitleDao
}
private lateinit var INSTANCE: TitleDatabase
/**
* Instantiate a database from a context.
*/
fun getDatabase(context: Context): TitleDatabase {
synchronized(TitleDatabase::class) {
if (!::INSTANCE.isInitialized) {
INSTANCE = Room
.databaseBuilder(
context.applicationContext,
TitleDatabase::class.java,
"titles_db"
)
.fallbackToDestructiveMigration()
.build()
}
}
return INSTANCE
}
| coroutines-codelab/start/src/main/java/com/example/android/kotlincoroutines/main/MainDatabase.kt | 412325288 |
package nl.sogeti.android.gpstracker.v2.sharedwear.messaging
import com.google.android.gms.wearable.DataEventBuffer
import com.google.android.gms.wearable.DataMap
import com.google.android.gms.wearable.MessageEvent
import com.google.android.gms.wearable.WearableListenerService
import nl.sogeti.android.gpstracker.v2.sharedwear.model.StatisticsMessage
import nl.sogeti.android.gpstracker.v2.sharedwear.model.StatisticsMessage.Companion.PATH_STATISTICS
import nl.sogeti.android.gpstracker.v2.sharedwear.model.StatusMessage
import nl.sogeti.android.gpstracker.v2.sharedwear.model.StatusMessage.Companion.PATH_STATUS
import timber.log.Timber
abstract class MessageListenerService : WearableListenerService() {
override fun onMessageReceived(messageEvent: MessageEvent?) {
Timber.d("onMessageReceived($messageEvent: MessageEvent?")
openMessage(messageEvent?.path, messageEvent?.data)
}
override fun onDataChanged(dataEvents: DataEventBuffer?) {
Timber.d("onDataChanged($dataEvents: DataEventBuffer?")
dataEvents?.forEach {
openMessage(it.dataItem.uri.path, it.dataItem.data)
}
}
private fun openMessage(path: String?, data: ByteArray?) {
if (path != null && data != null) {
val dataMap = DataMap.fromByteArray(data)
handleMessageEvents(path, dataMap)
} else {
Timber.w("message did not contain data")
}
}
private fun handleMessageEvents(path: String?, dataMap: DataMap) =
when (path) {
PATH_STATISTICS ->
updateStatistics(StatisticsMessage(dataMap))
PATH_STATUS ->
updateStatus(StatusMessage(dataMap))
else -> {
Timber.e("Failed to recognize path $path")
}
}
abstract fun updateStatus(status: StatusMessage)
abstract fun updateStatistics(statistics: StatisticsMessage)
}
| studio/wear-shared/src/main/java/nl/sogeti/android/gpstracker/v2/sharedwear/messaging/MessageListenerService.kt | 590843947 |
package io.gitlab.arturbosch.detekt.extensions
import org.gradle.api.Action
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.model.ObjectFactory
import org.gradle.api.plugins.quality.CodeQualityExtension
import java.io.File
import javax.inject.Inject
open class DetektExtension @Inject constructor(objects: ObjectFactory) : CodeQualityExtension() {
var ignoreFailures: Boolean
@JvmName("ignoreFailures_")
get() = isIgnoreFailures
@JvmName("ignoreFailures_")
set(value) {
isIgnoreFailures = value
}
@Deprecated("Use reportsDir which is equivalent", ReplaceWith("reportsDir"))
val customReportsDir: File?
get() = reportsDir
@Deprecated("Customise the reports on the Detekt task(s) instead.", level = DeprecationLevel.WARNING)
val reports: DetektReports = objects.newInstance(DetektReports::class.java)
@Deprecated(message = "Please use the source property instead.", replaceWith = ReplaceWith("source"))
var input: ConfigurableFileCollection
get() = source
set(value) {
source = value
}
var source: ConfigurableFileCollection = objects.fileCollection()
.from(
DEFAULT_SRC_DIR_JAVA,
DEFAULT_TEST_SRC_DIR_JAVA,
DEFAULT_SRC_DIR_KOTLIN,
DEFAULT_TEST_SRC_DIR_KOTLIN,
)
var baseline: File? = objects.fileProperty()
.fileValue(File("detekt-baseline.xml"))
.get().asFile
var basePath: String? = null
var config: ConfigurableFileCollection = objects.fileCollection()
var debug: Boolean = DEFAULT_DEBUG_VALUE
var parallel: Boolean = DEFAULT_PARALLEL_VALUE
@Deprecated("Please use the buildUponDefaultConfig and allRules flags instead.", ReplaceWith("allRules"))
var failFast: Boolean = DEFAULT_FAIL_FAST_VALUE
var allRules: Boolean = DEFAULT_ALL_RULES_VALUE
var buildUponDefaultConfig: Boolean = DEFAULT_BUILD_UPON_DEFAULT_CONFIG_VALUE
var disableDefaultRuleSets: Boolean = DEFAULT_DISABLE_RULESETS_VALUE
var autoCorrect: Boolean = DEFAULT_AUTO_CORRECT_VALUE
/**
* List of Android build variants for which no detekt task should be created.
*
* This is a combination of build types and flavors, such as fooDebug or barRelease.
*/
var ignoredVariants: List<String> = emptyList()
/**
* List of Android build types for which no detekt task should be created.
*/
var ignoredBuildTypes: List<String> = emptyList()
/**
* List of Android build flavors for which no detekt task should be created
*/
var ignoredFlavors: List<String> = emptyList()
@Suppress("DeprecatedCallableAddReplaceWith", "DEPRECATION")
@Deprecated("Customise the reports on the Detekt task(s) instead.", level = DeprecationLevel.WARNING)
fun reports(configure: Action<DetektReports>) {
configure.execute(reports)
}
companion object {
const val DEFAULT_SRC_DIR_JAVA = "src/main/java"
const val DEFAULT_TEST_SRC_DIR_JAVA = "src/test/java"
const val DEFAULT_SRC_DIR_KOTLIN = "src/main/kotlin"
const val DEFAULT_TEST_SRC_DIR_KOTLIN = "src/test/kotlin"
const val DEFAULT_DEBUG_VALUE = false
const val DEFAULT_PARALLEL_VALUE = false
const val DEFAULT_AUTO_CORRECT_VALUE = false
const val DEFAULT_DISABLE_RULESETS_VALUE = false
const val DEFAULT_REPORT_ENABLED_VALUE = true
const val DEFAULT_FAIL_FAST_VALUE = false
const val DEFAULT_ALL_RULES_VALUE = false
const val DEFAULT_BUILD_UPON_DEFAULT_CONFIG_VALUE = false
}
}
| detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/extensions/DetektExtension.kt | 1198637631 |
package uk.co.ribot.androidboilerplate.ui.main
import rx.Subscription
import javax.inject.Inject
import rx.android.schedulers.AndroidSchedulers
import rx.lang.kotlin.subscribeBy
import rx.schedulers.Schedulers
import timber.log.Timber
import uk.co.ribot.androidboilerplate.data.DataManager
import uk.co.ribot.androidboilerplate.injection.ConfigPersistent
@ConfigPersistent
class MainPresenter
@Inject
constructor(private val dataManager: DataManager) : MainContract.Presenter() {
private var subscription: Subscription? = null
override fun detachView() {
super.detachView()
subscription?.unsubscribe()
}
override fun loadRibots() {
subscription?.unsubscribe()
subscription = dataManager.getRibots()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribeBy(
onNext = { if (it.isEmpty()) view.showRibotsEmpty() else view.showRibots(it) },
onError = {
Timber.e(it, "There was an error loading the ribots.")
view.showError()
}
)
}
}
| app/src/main/kotlin/uk/co/ribot/androidboilerplate/ui/main/MainPresenter.kt | 2421179213 |
/*
* Copyright (C) 2017 Andrzej Ressel ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.jereksel.libresubstratum.dagger.modules
import com.jereksel.libresubstratum.activities.main.MainViewViewModel
import dagger.Binds
import dagger.multibindings.IntoMap
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import com.jereksel.libresubstratum.activities.main.MainViewModel
import dagger.Module
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(MainViewViewModel::class)
abstract fun bindUserViewModel(mainViewModel: MainViewViewModel): ViewModel
@Binds
abstract fun bindViewModelFactory(viewModelFactory: ViewModelFactory): ViewModelProvider.Factory
} | app/src/main/kotlin/com/jereksel/libresubstratum/dagger/modules/ViewModelModule.kt | 2721985448 |
/*
* Copyright (c) 2015 - 2022
*
* Maximilian Hille <[email protected]>
* Juliane Lehmann <[email protected]>
*
* This file is part of Watch Later.
*
* Watch Later 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.
*
* Watch Later 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 Watch Later. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lambdasoup.watchlater.ui.add
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.ContentAlpha
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.ColorPainter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImagePainter
import coil.compose.rememberAsyncImagePainter
import com.google.accompanist.placeholder.PlaceholderHighlight
import com.google.accompanist.placeholder.material.placeholder
import com.google.accompanist.placeholder.material.shimmer
import com.lambdasoup.watchlater.R
import com.lambdasoup.watchlater.data.YoutubeRepository
import com.lambdasoup.watchlater.util.formatDuration
import com.lambdasoup.watchlater.viewmodel.AddViewModel.VideoInfo
@Composable
fun VideoSnippet(
videoInfo: VideoInfo,
modifier: Modifier = Modifier,
) {
val loading = videoInfo is VideoInfo.Progress
val painter: Painter
val imageLoaded: Boolean
if (LocalInspectionMode.current) {
painter = painterResource(id = R.drawable.thumbnail)
imageLoaded = true
} else {
painter = when (videoInfo) {
is VideoInfo.Loaded -> rememberAsyncImagePainter(model = videoInfo.data.snippet.thumbnails.medium.url)
else -> remember { ColorPainter(Color.Transparent) }
}
imageLoaded = videoInfo is VideoInfo.Loaded &&
(painter as AsyncImagePainter).state is AsyncImagePainter.State.Success
}
val headerText = when (videoInfo) {
is VideoInfo.Loaded -> videoInfo.data.snippet.title
is VideoInfo.Error -> stringResource(id = R.string.video_error_title)
is VideoInfo.Progress -> "Lorem Ipsum"
}
val subheaderText = when (videoInfo) {
is VideoInfo.Loaded -> formatDuration(videoInfo.data.contentDetails.duration)
is VideoInfo.Progress -> "12:34"
is VideoInfo.Error -> ""
}
val bodyText = when (videoInfo) {
is VideoInfo.Loaded -> videoInfo.data.snippet.description
is VideoInfo.Error -> errorText(errorType = videoInfo.error)
is VideoInfo.Progress -> "Lorem ipsum dolor sit amet yadda yadda this is loading still"
}
Row(
modifier = modifier,
) {
AnimatedVisibility(
visible = videoInfo !is VideoInfo.Error,
) {
Image(
modifier = Modifier
.width(160.dp)
.height(90.dp)
.padding(end = 16.dp)
.placeholder(
visible = loading || !imageLoaded,
highlight = PlaceholderHighlight.shimmer()
),
painter = painter,
contentDescription = stringResource(id = R.string.thumbnail_cd)
)
}
Column(
modifier = Modifier.weight(1f),
) {
Text(
modifier = Modifier
.placeholder(
visible = loading,
highlight = PlaceholderHighlight.shimmer()
),
text = headerText,
style = MaterialTheme.typography.subtitle2,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
CompositionLocalProvider(LocalContentAlpha.provides(ContentAlpha.medium)) {
Text(
modifier = Modifier
.placeholder(
visible = loading,
highlight = PlaceholderHighlight.shimmer()
),
text = subheaderText,
maxLines = 1,
style = MaterialTheme.typography.body2,
fontStyle = FontStyle.Italic,
overflow = TextOverflow.Ellipsis,
)
Text(
modifier = Modifier
.placeholder(
visible = loading,
highlight = PlaceholderHighlight.shimmer()
),
text = bodyText,
style = MaterialTheme.typography.caption,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
@Composable
private fun errorText(
errorType: VideoInfo.ErrorType,
): String =
when (errorType) {
is VideoInfo.ErrorType.Youtube -> when (errorType.error) {
YoutubeRepository.ErrorType.Network -> stringResource(id = R.string.error_network)
YoutubeRepository.ErrorType.VideoNotFound -> stringResource(id = R.string.error_video_not_found)
else -> stringResource(
id = R.string.could_not_load,
errorType.toString()
)
}
is VideoInfo.ErrorType.InvalidVideoId -> stringResource(id = R.string.error_invalid_video_id)
is VideoInfo.ErrorType.NoAccount -> stringResource(id = R.string.error_video_info_no_account)
is VideoInfo.ErrorType.Network -> stringResource(id = R.string.error_network)
is VideoInfo.ErrorType.Other -> stringResource(id = R.string.error_general, errorType.msg)
}
@Preview(name = "Progress")
@Composable
fun VideoSnippetPreviewProgress() = VideoSnippet(
videoInfo = VideoInfo.Progress
)
@Preview(name = "Error")
@Composable
fun VideoSnippetPreviewError() = VideoSnippet(
videoInfo = VideoInfo.Error(error = VideoInfo.ErrorType.NoAccount)
)
@Preview(name = "Loaded")
@Composable
fun VideoSnippetPreviewLoaded() = VideoSnippet(
videoInfo = VideoInfo.Loaded(
data = YoutubeRepository.Videos.Item(
id = "video-id",
snippet = YoutubeRepository.Videos.Item.Snippet(
title = "Video Title",
description = "Video description",
thumbnails = YoutubeRepository.Videos.Item.Snippet.Thumbnails(
medium = YoutubeRepository.Videos.Item.Snippet.Thumbnails.Thumbnail("dummy-url ignore in preview"),
)
),
contentDetails = YoutubeRepository.Videos.Item.ContentDetails(duration = "time string"),
)
)
)
| app/src/main/java/com/lambdasoup/watchlater/ui/add/VideoSnippet.kt | 425941129 |
package net.nemerosa.ontrack.extension.github.model
import net.nemerosa.ontrack.extension.github.app.GitHubAppToken
import net.nemerosa.ontrack.extension.github.app.GitHubAppTokenService
import net.nemerosa.ontrack.extension.github.app.client.GitHubAppAccount
fun GitHubAppTokenService.getAppInstallationToken(configuration: GitHubEngineConfiguration): String? =
if (configuration.authenticationType() == GitHubAuthenticationType.APP) {
getAppInstallationToken(
configuration.name,
configuration.appId!!,
configuration.appPrivateKey!!,
configuration.appInstallationAccountName
)
} else {
error("This configuration is not using a GitHub App.")
}
fun GitHubAppTokenService.getAppInstallationTokenInformation(configuration: GitHubEngineConfiguration): GitHubAppToken? =
if (configuration.authenticationType() == GitHubAuthenticationType.APP) {
getAppInstallationTokenInformation(
configuration.name,
configuration.appId!!,
configuration.appPrivateKey!!,
configuration.appInstallationAccountName
)
} else {
null
}
fun GitHubAppTokenService.getAppInstallationAccount(configuration: GitHubEngineConfiguration): GitHubAppAccount? =
if (configuration.authenticationType() == GitHubAuthenticationType.APP) {
getAppInstallationAccount(
configuration.name,
configuration.appId!!,
configuration.appPrivateKey!!,
configuration.appInstallationAccountName
)
} else {
error("This configuration is not using a GitHub App.")
}
| ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/model/GitHubAppTokenServiceExtensions.kt | 1314448995 |
// Copyright (c) Akop Karapetyan
//
// 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 org.akop.ararat.io
class FormatException(message: String, cause: Throwable?) : RuntimeException(message, cause) {
constructor(message: String) : this(message, null)
}
| library/src/main/java/org/akop/ararat/io/FormatException.kt | 2727105319 |
package net.nemerosa.ontrack.extension.github.ingestion.payload
import net.nemerosa.ontrack.model.exceptions.NotFoundException
import java.util.*
class IngestionHookPayloadUUIDNotFoundException(uuid: UUID) : NotFoundException(
"Ingestion payload with UUID = $uuid not found."
) | ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/payload/IngestionHookPayloadUUIDNotFoundException.kt | 686164439 |
package org.tvheadend.tvhclient.service
import android.app.Service
import android.content.Intent
import android.content.SharedPreferences
import android.os.IBinder
import org.tvheadend.data.AppRepository
import org.tvheadend.data.entity.Connection
import org.tvheadend.tvhclient.MainApplication
import org.tvheadend.tvhclient.service.htsp.HtspServiceHandler
import timber.log.Timber
import javax.inject.Inject
class ConnectionService : Service() {
@Inject
lateinit var appRepository: AppRepository
@Inject
lateinit var sharedPreferences: SharedPreferences
private lateinit var connection: Connection
private lateinit var serviceHandler: ServiceInterface
override fun onCreate() {
Timber.d("Starting service")
MainApplication.component.inject(this)
connection = appRepository.connectionData.activeItem
serviceHandler = HtspServiceHandler(this, appRepository, connection)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return serviceHandler.onStartCommand(intent)
}
override fun onDestroy() {
serviceHandler.onDestroy()
}
override fun onBind(intent: Intent): IBinder? {
return null
}
interface ServiceInterface {
fun onStartCommand(intent: Intent?): Int
fun onDestroy()
}
}
| app/src/main/java/org/tvheadend/tvhclient/service/ConnectionService.kt | 3268547317 |
package net.nemerosa.ontrack.extension.indicators.model
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.model.extension.Extension
import net.nemerosa.ontrack.model.form.Form
interface IndicatorValueType<T, C> : Extension {
/**
* Display name
*/
val name: String
fun form(config: C, value: T?): Form
fun status(config: C, value: T): IndicatorCompliance
fun toClientJson(config: C, value: T): JsonNode
fun fromClientJson(config: C, value: JsonNode): T?
/**
* Gets a string representation for the value
*/
fun toClientString(config: C, value: T): String = value.toString()
fun fromStoredJson(valueConfig: C, value: JsonNode): T?
fun toStoredJson(config: C, value: T): JsonNode
fun configForm(config: C?): Form
fun toConfigForm(config: C): JsonNode
fun fromConfigForm(config: JsonNode): C
fun toConfigClientJson(config: C): JsonNode
fun toConfigStoredJson(config: C): JsonNode
fun fromConfigStoredJson(config: JsonNode): C
}
/**
* ID if the FQCN of the value type.
*/
val IndicatorValueType<*, *>.id: String get() = this::class.java.name
| ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/model/IndicatorValueType.kt | 2915096229 |
/*
* 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.jetbrains.kotlin
import org.gradle.api.Action
import groovy.lang.Closure
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.process.ExecResult
import org.gradle.process.ExecSpec
import org.gradle.util.ConfigureUtil
import org.jetbrains.kotlin.konan.target.*
import org.jetbrains.kotlin.konan.file.*
class ExecClang(private val project: Project) {
private val platformManager = project.rootProject.findProperty("platformManager") as PlatformManager
private fun konanArgs(target: KonanTarget): List<String> {
return platformManager.platform(target).clang.clangArgsForKonanSources.asList()
}
fun konanArgs(targetName: String?): List<String> {
val target = platformManager.targetManager(targetName).target
return konanArgs(target)
}
fun resolveExecutable(executable: String?): String {
val executable = executable ?: "clang"
if (listOf("clang", "clang++").contains(executable)) {
val llvmDir = project.findProperty("llvmDir")
return "${llvmDir}/bin/$executable"
} else {
throw GradleException("unsupported clang executable: $executable")
}
}
// The bare ones invoke clang with system default sysroot.
fun execBareClang(action: Action<in ExecSpec>): ExecResult {
return this.execClang(emptyList<String>(), action)
}
fun execBareClang(closure: Closure<in ExecSpec>): ExecResult {
return this.execClang(emptyList<String>(), closure)
}
// The konan ones invoke clang with konan provided sysroots.
// So they require a target or assume it to be the host.
// The target can be specified as KonanTarget or as a
// (nullable, which means host) target name.
fun execKonanClang(target: String?, action: Action<in ExecSpec>): ExecResult {
return this.execClang(konanArgs(target), action)
}
fun execKonanClang(target: KonanTarget, action: Action<in ExecSpec>): ExecResult {
return this.execClang(konanArgs(target), action)
}
fun execKonanClang(target: String?, closure: Closure<in ExecSpec>): ExecResult {
return this.execClang(konanArgs(target), closure)
}
fun execKonanClang(target: KonanTarget, closure: Closure<in ExecSpec>): ExecResult {
return this.execClang(konanArgs(target), closure)
}
// These ones are private, so one has to choose either Bare or Konan.
private fun execClang(defaultArgs: List<String>, closure: Closure<in ExecSpec>): ExecResult {
return this.execClang(defaultArgs, ConfigureUtil.configureUsing(closure))
}
private fun execClang(defaultArgs: List<String>, action: Action<in ExecSpec>): ExecResult {
val extendedAction = object : Action<ExecSpec> {
override fun execute(execSpec: ExecSpec) {
action.execute(execSpec)
execSpec.apply {
executable = resolveExecutable(executable)
val hostPlatform = project.findProperty("hostPlatform") as Platform
environment["PATH"] = project.files(hostPlatform.clang.clangPaths).asPath +
java.io.File.pathSeparator + environment["PATH"]
args(defaultArgs)
}
}
}
return project.exec(extendedAction)
}
}
| build-tools/src/main/kotlin/org/jetbrains/kotlin/ExecClang.kt | 290059669 |
/*
* Nextcloud Android client application
*
* @author Felix Nüsse
*
* Copyright (C) 2022 Felix Nüsse
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or 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 AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.utils
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.core.graphics.drawable.toBitmap
import com.owncloud.android.R
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.ThumbnailsCacheManager
import com.owncloud.android.ui.activity.FileActivity
import com.owncloud.android.ui.activity.FileDisplayActivity
import com.owncloud.android.utils.MimeTypeUtil
import com.owncloud.android.utils.theme.ViewThemeUtils
import javax.inject.Inject
class ShortcutUtil @Inject constructor(private val mContext: Context) {
/**
* Adds a pinned shortcut to the home screen that points to the passed file/folder.
*
* @param file The file/folder to which a pinned shortcut should be added to the home screen.
*/
fun addShortcutToHomescreen(file: OCFile, viewThemeUtils: ViewThemeUtils) {
if (ShortcutManagerCompat.isRequestPinShortcutSupported(mContext)) {
val intent = Intent(mContext, FileDisplayActivity::class.java)
intent.action = FileDisplayActivity.OPEN_FILE
intent.putExtra(FileActivity.EXTRA_FILE, file.remotePath)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val shortcutId = "nextcloud_shortcut_" + file.remoteId
val icon: IconCompat
var thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(
ThumbnailsCacheManager.PREFIX_THUMBNAIL + file.remoteId
)
if (thumbnail != null) {
thumbnail = bitmapToAdaptiveBitmap(thumbnail)
icon = IconCompat.createWithAdaptiveBitmap(thumbnail)
} else if (file.isFolder) {
val bitmapIcon = MimeTypeUtil.getFolderTypeIcon(
file.isSharedWithMe || file.isSharedWithSharee,
file.isSharedViaLink,
file.isEncrypted,
file.isGroupFolder,
file.mountType,
mContext,
viewThemeUtils
).toBitmap()
icon = IconCompat.createWithBitmap(bitmapIcon)
} else {
icon = IconCompat.createWithResource(
mContext,
MimeTypeUtil.getFileTypeIconId(file.mimeType, file.fileName)
)
}
val longLabel = mContext.getString(R.string.pin_shortcut_label, file.fileName)
val pinShortcutInfo = ShortcutInfoCompat.Builder(mContext, shortcutId)
.setShortLabel(file.fileName)
.setLongLabel(longLabel)
.setIcon(icon)
.setIntent(intent)
.build()
val pinnedShortcutCallbackIntent =
ShortcutManagerCompat.createShortcutResultIntent(mContext, pinShortcutInfo)
val successCallback = PendingIntent.getBroadcast(
mContext,
0,
pinnedShortcutCallbackIntent,
FLAG_IMMUTABLE
)
ShortcutManagerCompat.requestPinShortcut(
mContext,
pinShortcutInfo,
successCallback.intentSender
)
}
}
private fun bitmapToAdaptiveBitmap(orig: Bitmap): Bitmap {
val adaptiveIconSize = mContext.resources.getDimensionPixelSize(R.dimen.adaptive_icon_size)
val adaptiveIconOuterSides = mContext.resources.getDimensionPixelSize(R.dimen.adaptive_icon_padding)
val drawable: Drawable = BitmapDrawable(mContext.resources, orig)
val bitmap = Bitmap.createBitmap(adaptiveIconSize, adaptiveIconSize, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(
adaptiveIconOuterSides,
adaptiveIconOuterSides,
adaptiveIconSize - adaptiveIconOuterSides,
adaptiveIconSize - adaptiveIconOuterSides
)
drawable.draw(canvas)
return bitmap
}
}
| app/src/main/java/com/nextcloud/utils/ShortcutUtil.kt | 1974240178 |
/*
* 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
*
* 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.producthunt.data.api.model
import io.plaidapp.core.data.PlaidItem
/**
* Models a post on Product Hunt.
*/
class Post(
override val id: Long,
override val title: String,
override var url: String? = null,
val tagline: String,
val discussionUrl: String,
val redirectUrl: String,
val commentsCount: Int,
val votesCount: Int
) : PlaidItem(id, title, url, 0)
| core/src/main/java/io/plaidapp/core/producthunt/data/api/model/Post.kt | 3066452985 |
/*
* Copyright (C) 2016 Mihály Szabó
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.libreplicator.core.model
import java.lang.Math.max
data class TimeTable(private val table: MutableMap<String, MutableMap<String, Long>> = mutableMapOf()) {
operator fun get(sourceNodeId: String, targetNodeId: String): Long {
return table.getOrElse(sourceNodeId, { mapOf<String, Long>() })
.getOrElse(targetNodeId, { 0 })
}
operator fun set(sourceNodeId: String, targetNodeId: String, time: Long) {
if (time > 0) {
table.getOrPut(sourceNodeId, { mutableMapOf() })[targetNodeId] = time
}
}
fun merge(sourceNodeId: String, payload: ReplicatorPayload) {
mergeRow(sourceNodeId, payload)
merge(payload)
}
private fun mergeRow(sourceNodeId: String, payload: ReplicatorPayload) {
val sourceRow = table.getOrPut(sourceNodeId, { mutableMapOf() })
val targetRow = payload.timeTable.table.getOrPut(payload.nodeId, { mutableMapOf() })
sourceRow.keys + targetRow.keys.forEach {
val maxValue = max(sourceRow.getOrElse(it, { 0 }), targetRow.getOrElse(it, { 0 }))
sourceRow[it] = maxValue
}
}
private fun merge(payload: ReplicatorPayload) {
val rowKeys2 = table.keys + payload.timeTable.table.keys
val columnKeys2 = (table.values.map { it.keys } + payload.timeTable.table.values.map { it.keys }).flatten()
rowKeys2.forEach { rowKey ->
columnKeys2.forEach { columnKey ->
val maxValue = max(get(rowKey, columnKey), payload.timeTable[rowKey, columnKey])
set(rowKey, columnKey, maxValue)
}
}
}
// Do not change or call. It's here for serialization/deserialization purposes.
private fun getTable() = table
}
| libreplicator-core/src/main/kotlin/org/libreplicator/core/model/TimeTable.kt | 449821063 |
package io.mockk.impl.platform
interface Disposable {
fun dispose()
} | modules/mockk/src/commonMain/kotlin/io/mockk/impl/platform/Disposable.kt | 483006610 |
package eu.corvus.corax.scene.assets
import eu.corvus.corax.app.storage.StorageAccess
import eu.corvus.corax.graphics.material.textures.Texture
import eu.corvus.corax.graphics.material.textures.Texture2D_PC
import eu.corvus.corax.platforms.desktop.assets.loaders.AssimpLoader
import eu.corvus.corax.platforms.desktop.assets.loaders.TextureLoader
import eu.corvus.corax.scene.Object
import eu.corvus.corax.scene.Spatial
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.nio.file.FileSystems
import java.nio.file.StandardWatchEventKinds
import java.nio.file.WatchKey
import kotlin.properties.Delegates
class AssetManagerImpl(
private val storageAccess: StorageAccess
) : Object(), AssetManager {
private val loaders = mutableMapOf<String, AssetManager.AssetLoader>()
init {
addLoader("png", TextureLoader())
addLoader("jpg", TextureLoader())
addLoader("*", AssimpLoader())
}
override fun addLoader(suffix: String, assetLoader: AssetManager.AssetLoader) {
loaders[suffix] = assetLoader
}
override fun removeLoader(suffix: String) {
loaders.remove(suffix)
}
override suspend fun loadSpatial(assetName: String): Spatial = withContext(Dispatchers.IO) {
val suffix = assetName.substringAfterLast('.')
val assetLoader = loaders[suffix] ?: loaders["*"]!!
assetLoader.load(this@AssetManagerImpl, storageAccess, assetName) as Spatial
}
override suspend fun loadTexture(assetName: String): Texture = withContext(Dispatchers.IO) {
val suffix = assetName.substringAfterLast('.')
val assetLoader = loaders[suffix] ?: throw RuntimeException("Cannot find asset loader for $assetName")
assetLoader.load(this@AssetManagerImpl, storageAccess, assetName) as Texture2D_PC
}
override suspend fun loadRaw(assetPath: String): ByteArray = withContext(Dispatchers.IO) { // this is not cache-able
var data: ByteArray by Delegates.notNull()
storageAccess.readFrom(assetPath) {
data = it.readBytes()
}
data
}
override fun watch(assetPath: File, callback: () -> Unit): WatchKey {
val watchService = FileSystems.getDefault().newWatchService()
val pathToWatch = assetPath.toPath()
val pathKey = pathToWatch.register(watchService,
StandardWatchEventKinds.ENTRY_MODIFY)
while (true) {
val watchKey = watchService.take()
for (event in watchKey.pollEvents()) {
callback()
}
if (!watchKey.reset()) {
watchKey.cancel()
watchService.close()
break
}
}
return pathKey
}
override fun unload(assetName: String) {
}
override fun free() {
super.free()
loaders.clear()
}
}
| src/main/kotlin/eu/corvus/corax/scene/assets/AssetManagerImpl.kt | 608411130 |
// Copyright 2000-2017 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.copyright
import com.intellij.configurationStore.SchemeManagerFactoryBase
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.testFramework.rules.InMemoryFsRule
import com.intellij.util.io.write
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
internal class CopyrightManagerTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
@JvmField
@Rule
val fsRule = InMemoryFsRule()
@Test
fun loadSchemes() {
val schemeFile = fsRule.fs.getPath("copyright/openapi.xml")
val schemeData = """
<component name="CopyrightManager">
<copyright>
<option name="notice" value="Copyright 2000-&#36;today.year 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." />
<option name="keyword" value="Copyright" />
<option name="allowReplaceKeyword" value="JetBrains" />
<option name="myName" value="openapi" />
<option name="myLocal" value="true" />
</copyright>
</component>""".trimIndent()
schemeFile.write(schemeData)
val schemeManagerFactory = SchemeManagerFactoryBase.TestSchemeManagerFactory(fsRule.fs.getPath(""))
val profileManager = CopyrightManager(projectRule.project, schemeManagerFactory,
isSupportIprProjects = false /* otherwise scheme will be not loaded from our memory fs */)
profileManager.loadSchemes()
val copyrights = profileManager.getCopyrights()
assertThat(copyrights).hasSize(1)
val scheme = copyrights.first()
assertThat(scheme.schemeState).isEqualTo(null)
assertThat(scheme.name).isEqualTo("openapi")
}
} | plugins/copyright/testSrc/com/intellij/copyright/CopyrightManagerTest.kt | 1231664801 |
package com.bennyhuo.github.view.fragments
import com.bennyhuo.github.view.common.CommonViewPagerFragment
import com.bennyhuo.github.view.config.FragmentPage
import com.bennyhuo.github.view.fragments.subfragments.MyIssueListFragment
/**
* Created by benny on 7/16/17.
*/
class MyIssueFragment : CommonViewPagerFragment() {
override fun getFragmentPagesNotLoggedIn()
= listOf(
FragmentPage(MyIssueListFragment(), "My")
)
override fun getFragmentPagesLoggedIn(): List<FragmentPage>
= listOf(
FragmentPage(MyIssueListFragment(), "My")
)
} | Kotlin/Kotlin-github/app/src/main/java/com/bennyhuo/github/view/fragments/MyIssueFragment.kt | 39517574 |
package permissions.dispatcher.processor.exception
import permissions.dispatcher.processor.RuntimePermissionsElement
class NoAnnotatedMethodsException(rpe: RuntimePermissionsElement, type: Class<*>) : RuntimeException("Annotated class '${rpe.inputClassName}' doesn't have any method annotated with '@${type.simpleName}'") | processor/src/main/kotlin/permissions/dispatcher/processor/exception/NoAnnotatedMethodsException.kt | 418144019 |
//
// (C) Copyright 2017-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package /*js*/x.katydid.vdom.dom
import org.w3c.dom.Element
fun Element.removeAttributeAndProperty(key: String) {
this.removeAttribute(key)
this.asDynamic()[key] = null
}
fun Element.setAttributeAndProperty(key: String, value: String) {
this.setAttribute(key, value)
this.asDynamic()[key] = value
}
fun Element.setBooleanAttributeAndProperty(key: String) {
this.setAttribute(key, "")
this.asDynamic()[key] = true
}
| Katydid-VDOM-JS/src/main/kotlin/x/katydid/vdom/dom/ElementExtensions.kt | 3640281773 |
package permissions.dispatcher.test
import android.Manifest
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import permissions.dispatcher.ktx.Fun
import permissions.dispatcher.ktx.PermissionRequestViewModel
import permissions.dispatcher.ktx.PermissionResult
import java.lang.ref.WeakReference
class PermissionRequestViewModelTest {
@Rule
@JvmField
val instantTaskExecutorRule = InstantTaskExecutorRule()
private val permission = arrayOf(Manifest.permission.CAMERA).contentToString()
private lateinit var viewModel: PermissionRequestViewModel
private lateinit var lifecycleOwner: LifecycleOwner
private lateinit var requiresPermission: Fun
private lateinit var onPermissionDenied: Fun
private lateinit var onNeverAskAgain: Fun
@Before
fun setup() {
viewModel = PermissionRequestViewModel()
lifecycleOwner = mock()
val lifecycle = LifecycleRegistry(mock())
lifecycle.markState(Lifecycle.State.RESUMED)
whenever(lifecycleOwner.lifecycle).thenReturn(lifecycle)
onPermissionDenied = mock()
requiresPermission = mock()
onNeverAskAgain = mock()
}
@After
fun cleanup() {
viewModel.removeObservers(lifecycleOwner)
}
@Test
fun `GRANTED emits requiresPermission`() {
viewModel.observe(
lifecycleOwner,
permission,
WeakReference(requiresPermission),
WeakReference(onPermissionDenied),
WeakReference(onNeverAskAgain)
)
viewModel.postPermissionRequestResult(permission, PermissionResult.GRANTED)
verify(requiresPermission).invoke()
verify(onPermissionDenied, never()).invoke()
verify(onNeverAskAgain, never()).invoke()
}
@Test
fun `DENIED emits onPermissionDenied`() {
viewModel.observe(
lifecycleOwner,
permission,
WeakReference(requiresPermission),
WeakReference(onPermissionDenied),
WeakReference(onNeverAskAgain)
)
viewModel.postPermissionRequestResult(permission, PermissionResult.DENIED)
verify(requiresPermission, never()).invoke()
verify(onPermissionDenied).invoke()
verify(onNeverAskAgain, never()).invoke()
}
@Test
fun `DENIED_AND_DISABLED emits onNeverAskAgain`() {
viewModel.observe(
lifecycleOwner,
permission,
WeakReference(requiresPermission),
WeakReference(onPermissionDenied),
WeakReference(onNeverAskAgain)
)
viewModel.postPermissionRequestResult(permission, PermissionResult.DENIED_AND_DISABLED)
verify(requiresPermission, never()).invoke()
verify(onPermissionDenied, never()).invoke()
verify(onNeverAskAgain).invoke()
}
}
| ktx/src/test/java/permissions/dispatcher/test/PermissionRequestViewModelTest.kt | 1370554542 |
/*
* Copyright 2017 Ali Moghnieh
*
* 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.blurengine.blur
import com.blurengine.blur.utils.allMaxBy
import org.junit.Assert
import org.junit.Test
class CollectionsExtensionsTest {
@Test
fun testAllMaxBy() {
val values = listOf(1, 2, 2, 3, 4, 4 )
Assert.assertEquals(values.allMaxBy { it }, listOf(4, 4))
}
}
| src/test/java/com/blurengine/blur/CollectionsExtensionsTest.kt | 613426180 |
package app.cash.sqldelight.intellij.run
internal data class SqlParameter(
val name: String,
val value: String = "",
val range: IntRange,
)
| sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/run/SqlParameter.kt | 1892729641 |
/*
* Copyright 2020 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.pasterino.service.monitor
sealed class ServiceEvent {
data class PasteEvent(val isDeepSearchEnabled: Boolean) : ServiceEvent()
}
| app/src/main/java/com/pyamsoft/pasterino/service/monitor/ServiceEvent.kt | 2367590880 |
package net.dean.gbs.web.db
import io.dropwizard.hibernate.AbstractDAO
import net.dean.gbs.web.models.Model
import net.dean.gbs.web.models.ProjectModel
import org.hibernate.SessionFactory
import java.io.Serializable
import java.util.*
/**
* Provides a standard interface for retrieving models from the database
*
* M: Model type
*/
public interface DataAccessObject<M : Model> {
public fun get(id: UUID): M?
public fun getAll(): List<M>
public fun insert(model: M)
public fun update(model: M)
}
public open class BaseDao<M : Model>(sessionFactory: SessionFactory) : DataAccessObject<M>, AbstractDAO<M>(sessionFactory) {
override fun get(id: UUID): M? = get(id as Serializable)
override fun getAll(): List<M> {
return list(criteria())
}
override fun insert(model: M) {
currentSession().save(model)
}
override fun update(model: M) {
currentSession().update(model)
}
}
public class ProjectDao(sessionFactory: SessionFactory) :
BaseDao<ProjectModel>(sessionFactory)
| service/src/main/kotlin/net/dean/gbs/web/db/Database.kt | 275049616 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.preference
import android.content.Context
import android.support.v4.app.FragmentActivity
import android.support.v7.preference.Preference
import android.util.AttributeSet
import org.mariotaku.chameleon.ChameleonUtils
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.TwittnukerConstants.REQUEST_PURCHASE_EXTRA_FEATURES
import de.vanita5.twittnuker.extension.findParent
import de.vanita5.twittnuker.fragment.ExtraFeaturesIntroductionDialogFragment
import de.vanita5.twittnuker.util.dagger.GeneralComponent
import de.vanita5.twittnuker.util.premium.ExtraFeaturesService
import javax.inject.Inject
class PremiumEntryPreference(context: Context, attrs: AttributeSet) : Preference(context, attrs) {
@Inject
internal lateinit var extraFeaturesService: ExtraFeaturesService
init {
GeneralComponent.get(context).inject(this)
val a = context.obtainStyledAttributes(attrs, R.styleable.PremiumEntryPreference)
val requiredFeature: String = a.getString(R.styleable.PremiumEntryPreference_requiredFeature)
a.recycle()
isEnabled = extraFeaturesService.isSupported()
setOnPreferenceClickListener {
if (!extraFeaturesService.isEnabled(requiredFeature)) {
val activity = ChameleonUtils.getActivity(context)
if (activity is FragmentActivity) {
ExtraFeaturesIntroductionDialogFragment.show(fm = activity.supportFragmentManager,
feature = requiredFeature, source = "preference:${key}",
requestCode = REQUEST_PURCHASE_EXTRA_FEATURES)
}
return@setOnPreferenceClickListener true
}
return@setOnPreferenceClickListener false
}
}
override fun onAttached() {
super.onAttached()
if (!extraFeaturesService.isSupported()) {
preferenceManager.preferenceScreen?.let { screen ->
findParent(screen)?.removePreference(this)
}
}
}
} | twittnuker/src/main/kotlin/de/vanita5/twittnuker/preference/PremiumEntryPreference.kt | 3108659340 |
package com.stripe.android.networking
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import androidx.annotation.RestrictTo
import androidx.annotation.VisibleForTesting
import com.stripe.android.core.injection.PUBLISHABLE_KEY
import com.stripe.android.core.networking.AnalyticsRequest
import com.stripe.android.core.networking.AnalyticsRequestFactory
import com.stripe.android.core.utils.ContextUtils.packageInfo
import com.stripe.android.model.PaymentMethodCode
import com.stripe.android.model.Source
import com.stripe.android.model.Token
import com.stripe.android.payments.core.injection.PRODUCT_USAGE
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Provider
/**
* Factory for [AnalyticsRequest] objects.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class PaymentAnalyticsRequestFactory @VisibleForTesting internal constructor(
packageManager: PackageManager?,
packageInfo: PackageInfo?,
packageName: String,
publishableKeyProvider: Provider<String>,
internal val defaultProductUsageTokens: Set<String> = emptySet()
) : AnalyticsRequestFactory(
packageManager,
packageInfo,
packageName,
publishableKeyProvider
) {
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
constructor(
context: Context,
publishableKey: String,
defaultProductUsageTokens: Set<String> = emptySet()
) : this(
context,
{ publishableKey },
defaultProductUsageTokens
)
internal constructor(
context: Context,
publishableKeyProvider: Provider<String>
) : this(
context.applicationContext.packageManager,
context.applicationContext.packageInfo,
context.applicationContext.packageName.orEmpty(),
publishableKeyProvider,
emptySet()
)
@Inject
internal constructor(
context: Context,
@Named(PUBLISHABLE_KEY) publishableKeyProvider: () -> String,
@Named(PRODUCT_USAGE) defaultProductUsageTokens: Set<String>
) : this(
context.applicationContext.packageManager,
context.applicationContext.packageInfo,
context.applicationContext.packageName.orEmpty(),
publishableKeyProvider,
defaultProductUsageTokens
)
@JvmSynthetic
internal fun create3ds2Challenge(
event: PaymentAnalyticsEvent,
uiTypeCode: String?
): AnalyticsRequest {
return createRequest(
event,
threeDS2UiType = ThreeDS2UiType.fromUiTypeCode(uiTypeCode)
)
}
@JvmSynthetic
internal fun createTokenCreation(
productUsageTokens: Set<String>,
tokenType: Token.Type
): AnalyticsRequest {
return createRequest(
PaymentAnalyticsEvent.TokenCreate,
productUsageTokens = productUsageTokens,
tokenType = tokenType
)
}
@JvmSynthetic
internal fun createPaymentMethodCreation(
paymentMethodCode: PaymentMethodCode?,
productUsageTokens: Set<String>
): AnalyticsRequest {
return createRequest(
PaymentAnalyticsEvent.PaymentMethodCreate,
sourceType = paymentMethodCode,
productUsageTokens = productUsageTokens
)
}
@JvmSynthetic
internal fun createSourceCreation(
@Source.SourceType sourceType: String,
productUsageTokens: Set<String> = emptySet()
): AnalyticsRequest {
return createRequest(
PaymentAnalyticsEvent.SourceCreate,
productUsageTokens = productUsageTokens,
sourceType = sourceType
)
}
@JvmSynthetic
internal fun createAddSource(
productUsageTokens: Set<String> = emptySet(),
@Source.SourceType sourceType: String
): AnalyticsRequest {
return createRequest(
PaymentAnalyticsEvent.CustomerAddSource,
productUsageTokens = productUsageTokens,
sourceType = sourceType
)
}
@JvmSynthetic
internal fun createDeleteSource(
productUsageTokens: Set<String>
): AnalyticsRequest {
return createRequest(
PaymentAnalyticsEvent.CustomerDeleteSource,
productUsageTokens = productUsageTokens
)
}
@JvmSynthetic
internal fun createAttachPaymentMethod(
productUsageTokens: Set<String>
): AnalyticsRequest {
return createRequest(
PaymentAnalyticsEvent.CustomerAttachPaymentMethod,
productUsageTokens = productUsageTokens
)
}
@JvmSynthetic
internal fun createDetachPaymentMethod(
productUsageTokens: Set<String>
): AnalyticsRequest {
return createRequest(
PaymentAnalyticsEvent.CustomerDetachPaymentMethod,
productUsageTokens = productUsageTokens
)
}
@JvmSynthetic
internal fun createPaymentIntentConfirmation(
paymentMethodType: String? = null
): AnalyticsRequest {
return createRequest(
PaymentAnalyticsEvent.PaymentIntentConfirm,
sourceType = paymentMethodType
)
}
@JvmSynthetic
internal fun createSetupIntentConfirmation(
paymentMethodType: String?
): AnalyticsRequest {
return createRequest(
PaymentAnalyticsEvent.SetupIntentConfirm,
sourceType = paymentMethodType
)
}
@JvmSynthetic
internal fun createRequest(
event: PaymentAnalyticsEvent,
productUsageTokens: Set<String> = emptySet(),
@Source.SourceType sourceType: String? = null,
tokenType: Token.Type? = null,
threeDS2UiType: ThreeDS2UiType? = null
): AnalyticsRequest {
return createRequest(
event,
additionalParams(
productUsageTokens = productUsageTokens,
sourceType = sourceType,
tokenType = tokenType,
threeDS2UiType = threeDS2UiType
)
)
}
private fun additionalParams(
productUsageTokens: Set<String> = emptySet(),
@Source.SourceType sourceType: String? = null,
tokenType: Token.Type? = null,
threeDS2UiType: ThreeDS2UiType? = null
): Map<String, Any> {
return defaultProductUsageTokens
.plus(productUsageTokens)
.takeUnless { it.isEmpty() }?.let { mapOf(FIELD_PRODUCT_USAGE to it.toList()) }
.orEmpty()
.plus(sourceType?.let { mapOf(FIELD_SOURCE_TYPE to it) }.orEmpty())
.plus(createTokenTypeParam(sourceType, tokenType))
.plus(threeDS2UiType?.let { mapOf(FIELD_3DS2_UI_TYPE to it.toString()) }.orEmpty())
}
private fun createTokenTypeParam(
@Source.SourceType sourceType: String? = null,
tokenType: Token.Type? = null
): Map<String, String> {
val value = when {
tokenType != null -> tokenType.code
// This is not a source event, so to match iOS we log a token without type
// as type "unknown"
sourceType == null -> "unknown"
else -> null
}
return value?.let {
mapOf(FIELD_TOKEN_TYPE to it)
}.orEmpty()
}
internal enum class ThreeDS2UiType(
private val code: String?,
private val typeName: String
) {
None(null, "none"),
Text("01", "text"),
SingleSelect("02", "single_select"),
MultiSelect("03", "multi_select"),
Oob("04", "oob"),
Html("05", "html");
override fun toString(): String = typeName
companion object {
fun fromUiTypeCode(uiTypeCode: String?) = values().firstOrNull {
it.code == uiTypeCode
} ?: None
}
}
internal companion object {
internal const val FIELD_TOKEN_TYPE = "token_type"
internal const val FIELD_PRODUCT_USAGE = "product_usage"
internal const val FIELD_SOURCE_TYPE = "source_type"
internal const val FIELD_3DS2_UI_TYPE = "3ds2_ui_type"
}
}
| payments-core/src/main/java/com/stripe/android/networking/PaymentAnalyticsRequestFactory.kt | 2381065047 |
package com.ivaneye.ktjvm.model
import com.ivaneye.ktjvm.model.attr.Attribute
import com.ivaneye.ktjvm.type.U2
/**
* Created by wangyifan on 2017/5/17.
*/
class MethodInfo(val accFlag: U2, val nameIdx: U2, val descIdx: U2, val attrCount: U2, val attrs: Array<Attribute>, val classInfo: ClassInfo) {
override fun toString(): String {
var str = ""
for(attr in attrs){
str += attr.toString()
}
return "MethodInfo(accFlag=${accFlag.toHexString()},name=${classInfo.cpInfos[nameIdx.toInt()]!!.value()}," +
"desc=${classInfo.cpInfos[descIdx.toInt()]!!.value()},attrCount=${attrCount.toInt()
},attrs=[$str])"
}
} | src/com/ivaneye/ktjvm/model/MethodInfo.kt | 4160841291 |
package androidx.room.integration.kotlintestapp.vo
import androidx.room.TypeConverter
import androidx.room.util.joinIntoString
import androidx.room.util.splitToIntList
object StringToIntListConverters {
@TypeConverter
// Specifying that a static method should be generated. Otherwise, the compiler looks for the
// constructor of the class, and a object has a private constructor.
@JvmStatic
fun stringToIntList(data: String?): List<Int>? =
if (data == null) null else splitToIntList(data)
@TypeConverter
@JvmStatic
fun intListToString(ints: List<Int>?): String? =
if (ints == null) null else joinIntoString(ints)
}
| room/integration-tests/kotlintestapp/src/androidTest/java/androidx/room/integration/kotlintestapp/vo/StringToIntListConverters.kt | 3710158586 |
package au.com.codeka.warworlds.server.admin.handlers
import au.com.codeka.warworlds.common.proto.AdminRole
import au.com.codeka.warworlds.common.proto.AdminUser
import au.com.codeka.warworlds.server.store.DataStore
import com.google.common.collect.ImmutableMap
import java.util.*
/**
* Handler for /admin/users/create, which is used to create new users.
*/
class UsersCreateHandler : AdminHandler() {
public override fun get() {
render("users/create.html", ImmutableMap.builder<String, Any>()
.put("all_roles", AdminRole.values())
.build())
}
public override fun post() {
val emailAddr = request.getParameter("email_addr")
val roles = ArrayList<AdminRole>()
for (role in AdminRole.values()) {
if (request.getParameter(role.toString()) != null) {
roles.add(role)
}
}
if (emailAddr == null || emailAddr.isEmpty()) {
render("users/create.html", ImmutableMap.builder<String, Any>()
.put("error", "Email address must not be empty.")
.build())
return
}
DataStore.i.adminUsers().put(emailAddr, AdminUser(
email_addr = emailAddr,
roles = roles))
redirect("/admin/users")
}
} | server/src/main/kotlin/au/com/codeka/warworlds/server/admin/handlers/UsersCreateHandler.kt | 79083357 |
package expo.modules.webbrowser
import android.content.Intent
import androidx.browser.customtabs.CustomTabsIntent
import expo.modules.webbrowser.error.PackageManagerNotFoundException
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.unimodules.test.core.PromiseMock
import org.unimodules.test.core.assertListsEqual
import org.unimodules.test.core.assertSetsEqual
import org.unimodules.test.core.assertStringValueNull
import org.unimodules.test.core.mockInternalModule
import org.unimodules.test.core.mockkInternalModule
import org.unimodules.test.core.moduleRegistryMock
import org.unimodules.test.core.promiseRejected
import org.unimodules.test.core.promiseResolved
@RunWith(RobolectricTestRunner::class)
internal class WebBrowserModuleTest {
private var moduleRegistry = moduleRegistryMock()
private lateinit var promise: PromiseMock
private lateinit var module: WebBrowserModule
@Before
fun initializeMock() {
promise = PromiseMock()
module = WebBrowserModule(mockk())
}
@Test
fun testOpenBrowserAsync() {
// given
val mock = mockkCustomTabsActivitiesHelper()
every { mock.canResolveIntent(any()) } returns true
initialize(mock)
// when
module.openBrowserAsync("http://expo.io", browserArguments(), promise)
// then
promiseResolved(promise) {
assertSetsEqual(setOf("type"), it.keySet())
assertEquals("opened", it.getString("type"))
}
}
@Test
fun `test browser not opened when no resolving activity found`() {
// given
val mock = mockkCustomTabsActivitiesHelper()
every { mock.canResolveIntent(any()) } returns false
initialize(mock)
// when
module.openBrowserAsync("http://expo.io", browserArguments(), promise)
// then
promiseRejected(promise) {
assertTrue(it.rejectCodeSet)
assertEquals(it.rejectCode, "EXWebBrowser")
assertTrue(it.rejectMessageSet)
assertEquals(it.rejectMessage, "No matching activity!")
}
}
@Test
fun `test no exception thrown when no package manager found`() {
// given
val mock = mockkCustomTabsActivitiesHelper()
every { mock.canResolveIntent(any()) } throws PackageManagerNotFoundException()
initialize(mock)
// when
module.openBrowserAsync("http://expo.io", browserArguments(), promise)
// then
promiseRejected(promise) {
assertFalse(it.rejectCodeSet)
assertFalse(it.rejectMessageSet)
assertTrue(it.rejectThrowableSet)
assertTrue(it.rejectThrowable is PackageManagerNotFoundException)
}
}
@Test
fun testArgumentsCorrectlyPassedToIntent() {
// given
val intentSlot = slot<Intent>()
val mock = mockkCustomTabsActivitiesHelper(defaultCanResolveIntent = true, startIntentSlot = intentSlot)
initialize(mock)
// when
module.openBrowserAsync(
"http://expo.io",
browserArguments(
toolbarColor = "#000000",
browserPackage = "com.browser.package",
enableBarCollapsing = true,
enableDefaultShareMenuItem = true,
showInRecents = true,
createTask = true,
showTitle = true
),
promise
)
intentSlot.captured.let {
assertEquals("com.browser.package", it.`package`)
}
}
@Test
fun testTrueFlagsCorrectlyPassedToIntent() {
// given
val intentSlot = slot<Intent>()
val mock = mockkCustomTabsActivitiesHelper(defaultCanResolveIntent = true, startIntentSlot = intentSlot)
initialize(mock)
// when
module.openBrowserAsync(
"http://expo.io",
browserArguments(
toolbarColor = "#000000",
browserPackage = "com.browser.package",
enableBarCollapsing = true,
enableDefaultShareMenuItem = true,
showInRecents = true,
showTitle = true
),
promise
)
intentSlot.captured.let {
assertTrue(it.hasExtra(CustomTabsIntent.EXTRA_ENABLE_URLBAR_HIDING))
assertTrue(it.getBooleanExtra(CustomTabsIntent.EXTRA_ENABLE_URLBAR_HIDING, false))
assertTrue((it.flags and Intent.FLAG_ACTIVITY_NEW_TASK) > 0)
assertFalse((it.flags and Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) > 0)
assertFalse((it.flags and Intent.FLAG_ACTIVITY_NO_HISTORY) > 0)
}
}
@Test
fun testFalseFlagsCorrectlyPassedToIntent() {
// given
val intentSlot = slot<Intent>()
val mock = mockkCustomTabsActivitiesHelper(defaultCanResolveIntent = true, startIntentSlot = intentSlot)
initialize(mock)
// when
module.openBrowserAsync(
"http://expo.io",
browserArguments(
toolbarColor = "#000000",
browserPackage = "com.browser.package",
enableBarCollapsing = false,
enableDefaultShareMenuItem = false,
showInRecents = false,
showTitle = false
),
promise
)
intentSlot.captured.let {
assertFalse(it.getBooleanExtra(CustomTabsIntent.EXTRA_ENABLE_URLBAR_HIDING, true))
assertTrue((it.flags and Intent.FLAG_ACTIVITY_NEW_TASK) > 0)
assertTrue((it.flags and Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) > 0)
assertTrue((it.flags and Intent.FLAG_ACTIVITY_NO_HISTORY) > 0)
}
}
@Test
fun testCreateTaskFalseCorrectlyPassedToIntent() {
// given
val intentSlot = slot<Intent>()
val mock = mockkCustomTabsActivitiesHelper(defaultCanResolveIntent = true, startIntentSlot = intentSlot)
initialize(mock)
// when
module.openBrowserAsync(
"http://expo.io",
browserArguments(
toolbarColor = "#000000",
browserPackage = "com.browser.package",
createTask = false
),
promise
)
intentSlot.captured.let {
assertFalse((it.flags and Intent.FLAG_ACTIVITY_NEW_TASK) > 0)
assertFalse((it.flags and Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) > 0)
assertFalse((it.flags and Intent.FLAG_ACTIVITY_NO_HISTORY) > 0)
}
}
@Test
fun testActivitiesAndServicesReturnedForValidKeys() {
// given
val services = arrayListOf("service1", "service2")
val activities = arrayListOf("activity1", "activity2")
initialize(mockkCustomTabsActivitiesHelper(services, activities))
// when
module.getCustomTabsSupportingBrowsersAsync(promise)
// then
promiseResolved(promise) {
assertSetsEqual(setOf("browserPackages", "servicePackages", "preferredBrowserPackage", "defaultBrowserPackage"), it.keySet())
assertListsEqual(activities, it.getStringArrayList("browserPackages"))
assertListsEqual(services, it.getStringArrayList("servicePackages"))
assertStringValueNull(it, "preferredBrowserPackage")
assertStringValueNull(it, "defaultBrowserPackage")
}
}
@Test
fun testActivitiesAndServicesWorkForNulls() {
// given
initialize()
// when
module.getCustomTabsSupportingBrowsersAsync(promise)
// then
promiseResolved(promise) {
assertSetsEqual(setOf("browserPackages", "servicePackages", "preferredBrowserPackage", "defaultBrowserPackage"), it.keySet())
assertListsEqual(emptyList<String>(), it.getStringArrayList("browserPackages"))
assertListsEqual(emptyList<String>(), it.getStringArrayList("servicePackages"))
assertStringValueNull(it, "preferredBrowserPackage")
assertStringValueNull(it, "defaultBrowserPackage")
}
}
@Test
fun testWarmUpWithGivenPackage() {
// given
val connectionHelper: CustomTabsConnectionHelper = mockkCustomTabsConnectionHelper()
initialize(customTabsConnectionHelper = connectionHelper)
// when
module.warmUpAsync("com.browser.package", promise)
// then
verify(exactly = 1) {
connectionHelper.warmUp(any())
}
verify {
connectionHelper.warmUp(eq("com.browser.package"))
}
}
@Test
fun testWarmUpWithoutPackage() {
// given
val connectionHelper: CustomTabsConnectionHelper = mockkCustomTabsConnectionHelper()
val customTabsHelper = mockkCustomTabsActivitiesHelper(preferredActivity = "com.browser.package")
initialize(customTabsConnectionHelper = connectionHelper, customTabsActivitiesHelper = customTabsHelper)
// when
module.warmUpAsync(null, promise)
// then
verify(exactly = 1) {
connectionHelper.warmUp(any())
}
verify {
connectionHelper.warmUp(eq("com.browser.package"))
}
}
@Test
fun testCoolDownWithGivenPackage() {
// given
val connectionHelper: CustomTabsConnectionHelper = mockkCustomTabsConnectionHelper()
initialize(customTabsConnectionHelper = connectionHelper)
// when
module.coolDownAsync("com.browser.package", promise)
// then
verify(exactly = 1) {
connectionHelper.coolDown(any())
}
verify {
connectionHelper.coolDown(eq("com.browser.package"))
}
}
@Test
fun testCoolDownWithoutPackage() {
// given
val connectionHelper: CustomTabsConnectionHelper = mockkInternalModule(relaxed = true)
val customTabsHelper = mockkCustomTabsActivitiesHelper(preferredActivity = "com.browser.package")
initialize(customTabsConnectionHelper = connectionHelper, customTabsActivitiesHelper = customTabsHelper)
// when
module.coolDownAsync(null, promise)
// then
verify(exactly = 1) {
connectionHelper.coolDown(any())
}
verify {
connectionHelper.coolDown(eq("com.browser.package"))
}
}
private fun initialize(
customTabsActivitiesHelper: CustomTabsActivitiesHelper = mockkCustomTabsActivitiesHelper(),
customTabsConnectionHelper: CustomTabsConnectionHelper? = null
) {
if (customTabsConnectionHelper != null) {
moduleRegistry.mockInternalModule(customTabsConnectionHelper)
}
moduleRegistry.mockInternalModule(customTabsActivitiesHelper)
module.onCreate(moduleRegistry)
}
}
| packages/expo-web-browser/android/src/test/java/expo/modules/webbrowser/WebBrowserModuleTest.kt | 171379019 |
package host.exp.exponent.notifications
import android.content.Context
import expo.modules.notifications.service.NotificationsService
import expo.modules.notifications.service.interfaces.PresentationDelegate
import host.exp.exponent.notifications.delegates.ScopedExpoPresentationDelegate
class ExpoNotificationsService : NotificationsService() {
override fun getPresentationDelegate(context: Context): PresentationDelegate =
ScopedExpoPresentationDelegate(context)
}
| android/expoview/src/main/java/host/exp/exponent/notifications/ExpoNotificationsService.kt | 4231124199 |
package monaco.editor
external interface ITextModel {
fun findMatches(searchString: String, searchOnlyEditableRange: Boolean, isRegex: Boolean, matchCase: Boolean, wordSeparatos: String, captureMatches: Boolean, limitResultCount: Number = definedExternally): Any // FindMatch[]
fun findNextMatch(searchString: String, searchStart: Any, isRegex: Boolean, matchCase: Boolean, wordSeparators: String, captureMatches: Boolean): Any // IPosition FindMatch
fun findPreviousMatch(searchString: String, searchStart: Any, isRegex: Boolean, matchCase: Boolean, wordSeparators: String, captureMatches: Boolean): Any // IPosition FindMatch
fun getAlternativeVersionId(): Number
fun getEOL(): String
fun getFullModelRange(): Any // Range
fun getLineContent(lineNumber: Number): String
fun getLineCount(): Number
fun getLineFirstNonWhitespaceColumn(lineNumber: Number): Number
fun getLineLastNonWhitespaceColumn(lineNumber: Number): Number
fun getLineMaxColumn(lineNumber: Number): Number
fun getLineMinColumn(lineNumber: Number): Number
fun getLinesContent(): Array<String>
fun getOffsetAt(position: Any): Number // IPosition
fun getOptions(): Any // TextModelResolvedOptions
fun getPositionAt(offset: Number): Any // Position
fun getValue(eol: Any = definedExternally, preserveBOM: Boolean = definedExternally): String // EndOfLinePreference
fun getValueInRange(range: Any, eol: Any = definedExternally): String // IRange, EndOfLinePreference
fun getValueLength(eol: Any = definedExternally, preserveBOM: Boolean = definedExternally): Number // EndOfLinePreference
fun getValueLengthInRange(range: Any): Number // IRange
fun getVersionId(): Number
fun isDisposed(): Boolean
fun modifyPosition(position: Any, offset: Number): Any // IPosition Position
fun setEOL(eol: Any) // EndOfLineSequence
fun setValue(newValue: String)
fun validatePosition(position: Any): Any // IPosition Position
fun validateRange(range: Any): Any // IRange Range
} | src/main/kotlin/monaco/editor/ITextModel.kt | 4106943944 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.