content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
// "Create secondary constructor" "true"
// ERROR: Too many arguments for public/*package*/ constructor J() defined in J
internal fun test() = J(<caret>1) | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createSecondaryConstructor/javaConstructor.before.Main.kt | 3612455501 |
<fold text='/** Kdoc licence ...*/'>/**
* Kdoc licence
*/</fold>
package some
<fold text='/** Some Kdoc comment ...*/'>/**
* Some Kdoc comment
*/</fold>
class A | plugins/kotlin/idea/tests/testData/folding/noCollapse/kdocComments.kt | 4151533007 |
package dependency
fun xxx_topLevelFun(){}
val xxx_topLevelVal: Int = 1
fun CharSequence.xxx_extFun(){}
| plugins/kotlin/completion/tests/testData/basic/multifile/CallableReferenceNotImported/CallableReferenceNotImported.dependency.kt | 1166333610 |
package net.coding.program.common.event
import org.greenrobot.eventbus.EventBus
class EventLoginSuccess {
companion object {
fun sendMessage() {
EventBus.getDefault().post(EventLoginSuccess())
}
}
}
| common-coding/src/main/java/net/coding/program/common/event/EventLoginSuccess.kt | 1329249848 |
package com.cognifide.gradle.aem.common.bundle
import com.cognifide.gradle.aem.AemException
class BundleException : AemException {
constructor(message: String, cause: Throwable) : super(message, cause)
constructor(message: String) : super(message)
}
| src/main/kotlin/com/cognifide/gradle/aem/common/bundle/BundleException.kt | 745019260 |
/*
* Copyright 2018 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.util
enum class AutoCompletionMode {
USER_MODE,
COMMAND_MODE;
companion object {
/**
* It's important to start with " " to enter USER_MODE even if text starts with "/"
*/
fun getWithText(text: String) = when {
text.startsWith("@") || text.contains(" ") -> USER_MODE
text.startsWith("/") -> COMMAND_MODE
else -> USER_MODE
}
}
} | vector/src/main/java/im/vector/util/AutoCompletionMode.kt | 377425220 |
package com.dreampany.framework.misc
import javax.inject.Qualifier
/**
* Created by roman on 2019-07-09
* Copyright (c) 2019 bjit. All rights reserved.
* [email protected]
* Last modified $file.lastModified
*/
@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class Room | frame/src/main/kotlin/com/dreampany/framework/misc/Room.kt | 2486230238 |
package run.smt.karafrunner.util
sealed class Filter<T> {
companion object {
fun <T> all(): Filter<T> = All()
fun <T> none(): Filter<T> = None()
fun <T> some(indexes: Iterable<Int>) = SomeIndexes<T>(indexes)
fun <T> first() = SomeIndexes<T>(listOf(0))
}
abstract fun applyTo(someList: Iterable<T>): Iterable<T>
class All<T>: Filter<T>() {
override fun applyTo(someList: Iterable<T>): Iterable<T> {
return someList
}
}
class None<T>: Filter<T>() {
override fun applyTo(someList: Iterable<T>): Iterable<T> {
return emptyList()
}
}
class SomeIndexes<T>(private val some: Iterable<Int>): Filter<T>() {
override fun applyTo(someList: Iterable<T>): Iterable<T> {
return someList.filterIndexed { index, value -> some.contains(index) }
}
}
} | src/main/java/run/smt/karafrunner/util/Filter.kt | 652150238 |
package com.mikepenz.materialdrawer.model
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem
/**
* Describes the main [IDrawerItem] bing used as primary item, offering a toggle.
*/
open class ToggleDrawerItem : AbstractToggleableDrawerItem<ToggleDrawerItem>()
| materialdrawer/src/main/java/com/mikepenz/materialdrawer/model/ToggleDrawerItem.kt | 3680103782 |
package com.qfleng.um.database
import android.content.Context
import androidx.room.Room
/**
* Created by Duke
*/
class AppDbHelper private constructor(ctx: Context) {
val appDataBase = Room
.databaseBuilder(ctx, AppDb::class.java, DbConst.APP_DB_NAME)
.build()
companion object {
@Volatile
private var instance: AppDbHelper? = null
fun getInstance(context: Context) = instance ?: synchronized(AppDbHelper::class) {
instance ?: AppDbHelper(context.applicationContext).also { instance = it }
}
}
} | UnrealMedia/app/src/main/java/com/qfleng/um/database/AppDbHelper.kt | 1281360449 |
package org.ak80.bdp
import org.ak80.bdp.annotations.MappedByte
import org.ak80.bdp.annotations.MappedEnum
import org.ak80.bdp.annotations.MappedFlag
import org.ak80.bdp.annotations.MappedWord
import javax.annotation.processing.Messager
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.element.Element
import javax.lang.model.element.ElementKind
import javax.lang.model.element.TypeElement
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
import javax.tools.Diagnostic
/**
* Processor for annotations
*/
interface BdpProcessor {
/**
* Init the processor with the environment
*
* @param processingEnvironment the processing environment
*/
fun init(processingEnvironment: ProcessingEnvironment)
/**
* Process an annotation
*
* @param annotations the registered annotations
* @param roundEnv the information for this round
*/
fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean
}
/**
* Core Processor
*
* @property mappedClasses the registry of mapped classes
* @property generator the generator that generated and writes Java files
*/
class CoreProcessor(private val mappedClasses: MappedClasses, private val generator: Generator) : BdpProcessor {
var fieldMappingAnnotations = setOf(
MappedByte::class.java,
MappedWord::class.java,
MappedFlag::class.java,
MappedEnum::class.java
)
var processingEnvironment: ProcessingEnvironment? = null
private val messager: Messager by lazy {
processingEnvironment?.messager ?: throw IllegalStateException("the CoreProcessor was not initialized")
}
override fun init(processingEnvironment: ProcessingEnvironment) {
this.processingEnvironment = processingEnvironment
}
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
var exit: Boolean;
for (annotatedElement in roundEnv.getElementsAnnotatedWith(MappedByte::class.java)) {
exit = processMappedField(annotatedElement)
if (exit) break
}
for (annotatedElement in roundEnv.getElementsAnnotatedWith(MappedWord::class.java)) {
exit = processMappedField(annotatedElement)
if (exit) break
}
for (annotatedElement in roundEnv.getElementsAnnotatedWith(MappedFlag::class.java)) {
exit = processMappedField(annotatedElement)
if (exit) break
}
for (annotatedElement in roundEnv.getElementsAnnotatedWith(MappedEnum::class.java)) {
exit = processMappedField(annotatedElement)
if (exit) break
}
for (byteMappedClass in mappedClasses.getClasses()) {
generator.generateFor(byteMappedClass)
}
mappedClasses.clear()
return true
}
private fun processMappedField(element: Element): Boolean {
if (element.kind != ElementKind.FIELD) {
error(element, "Only fields can be annotated with mapping annotation");
return true;
}
val mappedClass = getMappedClass(element)
val fieldName = element.simpleName.toString()
val typeMirror = element.asType()
val fieldType = getType(typeMirror)
val annotation = getAnnotation(element)
mappedClass.addMapping(fieldName, fieldType, annotation)
return false
}
private fun getType(typeMirror: TypeMirror): String {
if (typeMirror.kind.equals(TypeKind.DECLARED)) {
return typeMirror.toString();
} else {
return typeMirror.kind.name.toString()
}
}
private fun getMappedClass(element: Element): MappedClass {
val classFullName = getClassFullName(element)
val classSimpleName = getClassSimpleName(element)
val classPackage = getClassPackage(classFullName, classSimpleName)
val parentType = element.enclosingElement.asType()
return mappedClasses.get(classSimpleName, classPackage, parentType)
}
private fun getAnnotation(element: Element): Annotation {
var annotations: Set<Annotation> = mutableSetOf()
for (annotationClass in fieldMappingAnnotations) {
var annotation = element.getAnnotation(annotationClass)
if (annotation != null) {
annotations = annotations.plus(annotation)
}
}
if (annotations.size > 1) {
throw IllegalStateException("Only one mapping annotation allowed for element ${element.simpleName} but found: $annotations")
}
return annotations.single()
}
private fun getClassFullName(element: Element): String {
val parentTypeElement = element.enclosingElement as TypeElement
return parentTypeElement.qualifiedName.toString()
}
private fun getClassSimpleName(element: Element): String {
val parentTypeElement = element.enclosingElement as TypeElement
return parentTypeElement.simpleName.toString()
}
private fun getClassPackage(fullName: String, simpleName: String): String {
return fullName.subSequence(0, fullName.length - simpleName.length - 1).toString()
}
private fun error(element: Element, message: String) {
messager.printMessage(Diagnostic.Kind.ERROR, message, element)
}
} | bdp-processor/src/main/java/org/ak80/bdp/CoreProcessor.kt | 2564379995 |
package samples
import net.onedaybeard.transducers.*
typealias Sample = org.junit.Test
class Samples {
@Sample
fun branch_a() {
intoList(xf = copy<Int>() +
branch(test = { it % 4 == 0 },
xfTrue = map { i: Int -> i * 100 },
xfFalse = map { i: Int -> i / 4 } +
distinct() +
map(Int::toString)),
input = (1..9)
) assertEquals listOf("0", 400, 400, "1", 800, 800, "2")
}
@Sample
fun collect_a() {
// using collect for sorting input
transduce(xf = map { i: Int -> i / 3 } +
distinct() +
collect(sort = { a, b -> a.compareTo(b) * -1 }),
rf = { _, input -> input.toList() },
init = listOf<Int>(),
input = (0..20)
) assertEquals listOf(6, 5, 4, 3, 2, 1, 0)
}
@Sample
fun collect_b() {
// collecting into a set, releasing sorted iterable
transduce(xf = map { i: Int -> i / 3 } +
collect(sort = { a, b -> a.compareTo(b) * -1 },
collector = { mutableSetOf<Int>() }),
rf = { _, input -> input.toList() },
init = listOf<Int>(),
input = (0..20)
) assertEquals listOf(6, 5, 4, 3, 2, 1, 0)
}
@Sample
fun mux_a() {
listOf(xf = mux(isEven@ // labels only for readability
{ i: Int -> i % 2 == 0 }
wires map { i: Int -> i * 100 } +
filter { it != 400 },
leetify@
{ i: Int -> i == 3 }
wires map { _: Int -> 1337 } +
collect() + // releases on final result
cat()),
input = (0..9)
) assertEquals listOf(0, 200, 600, 800, 1337)
}
@Sample
fun mux_b() {
// promiscuous = true: input goes through all applicable transducers
listOf(xf = mux({ i: Int -> i % 1 == 0 }
wires map { i: Int -> i / 2 } +
distinct(),
{ i: Int -> i % 2 == 0 }
wires map { it },
{ i: Int -> i % 3 == 0 }
wires map { i: Int -> i * 100 } +
copy(),
promiscuous = true),
input = (0..6)
) assertEquals listOf(0, 0, 0, 0, // input: 0
// input: 1
1, 2, // input: 2
300, 300, // input: 3
2, 4, // input: 4
// input: 5
3, 6, 600, 600) // input: 6
}
@Sample
fun sum_a() {
// collecting single result into list
listOf(xf = filter<Int> { 4 > it } + sum<Int>(),
input = (0..10)
) assertEquals listOf(1 + 2 + 3)
}
@Sample
fun sum_b() {
val xf = filter { i: Int -> i % 5 == 0 } +
sum { i: Int -> i / 5 }
transduce(xf = xf,
rf = { result, input -> result + input },
init = 0,
input = (0..20)
) assertEquals (1 + 2 + 3 + 4)
}
} | src/test/kotlin/samples/samples.kt | 421591241 |
/*
* Copyright 2016 Ross Binden
*
* 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.rpkit.characters.bukkit.command.character.card
import com.rpkit.characters.bukkit.RPKCharactersBukkit
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
/**
* Character card command.
* Displays the character card of the active character of either the player running the command or the specified player.
*/
class CharacterCardCommand(private val plugin: RPKCharactersBukkit): CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (sender is Player) {
if (sender.hasPermission("rpkit.characters.command.character.card.self")) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
var minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender)
if (sender.hasPermission("rpkit.characters.command.character.card.other")) {
if (args.isNotEmpty()) {
val bukkitPlayer = plugin.server.getPlayer(args[0])
if (bukkitPlayer != null) {
minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer)
}
}
}
if (minecraftProfile != null) {
val character = characterProvider.getActiveCharacter(minecraftProfile)
if (character != null) {
val senderMinecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender)
if (senderMinecraftProfile != null) {
character.showCharacterCard(senderMinecraftProfile)
} else {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
}
} else {
sender.sendMessage(plugin.messages["no-character"])
}
} else {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
}
} else {
sender.sendMessage(plugin.messages["no-permission-character-card-self"])
}
} else {
sender.sendMessage(plugin.messages["not-from-console"])
}
return true
}
}
| bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/card/CharacterCardCommand.kt | 238313357 |
/*
* Copyright 2016 Ross Binden
*
* 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.rpkit.auctions.bukkit.database.table
import com.rpkit.auctions.bukkit.RPKAuctionsBukkit
import com.rpkit.auctions.bukkit.auction.RPKAuction
import com.rpkit.auctions.bukkit.auction.RPKAuctionImpl
import com.rpkit.auctions.bukkit.database.jooq.rpkit.Tables.RPKIT_AUCTION
import com.rpkit.auctions.bukkit.database.jooq.rpkit.Tables.RPKIT_BID
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.core.bukkit.util.toByteArray
import com.rpkit.core.bukkit.util.toItemStack
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.economy.bukkit.currency.RPKCurrencyProvider
import org.bukkit.Location
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.jooq.impl.DSL.constraint
import org.jooq.impl.SQLDataType
/**
* Represents the auction table.
*/
class RPKAuctionTable(database: Database, private val plugin: RPKAuctionsBukkit): Table<RPKAuction>(database, RPKAuction::class) {
private val cache = if (plugin.config.getBoolean("caching.rpkit_auction.id.enabled")) {
database.cacheManager.createCache("rpk-auctions-bukkit.rpkit_auction.id", CacheConfigurationBuilder
.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKAuction::class.java,
ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_auction.id.size"))).build())
} else {
null
}
override fun create() {
database.create
.createTableIfNotExists(RPKIT_AUCTION)
.column(RPKIT_AUCTION.ID, SQLDataType.INTEGER.identity(true))
.column(RPKIT_AUCTION.ITEM, SQLDataType.BLOB)
.column(RPKIT_AUCTION.CURRENCY_ID, SQLDataType.INTEGER)
.column(RPKIT_AUCTION.WORLD, SQLDataType.VARCHAR(256))
.column(RPKIT_AUCTION.X, SQLDataType.DOUBLE)
.column(RPKIT_AUCTION.Y, SQLDataType.DOUBLE)
.column(RPKIT_AUCTION.Z, SQLDataType.DOUBLE)
.column(RPKIT_AUCTION.YAW, SQLDataType.DOUBLE)
.column(RPKIT_AUCTION.PITCH, SQLDataType.DOUBLE)
.column(RPKIT_AUCTION.CHARACTER_ID, SQLDataType.INTEGER)
.column(RPKIT_AUCTION.DURATION, SQLDataType.BIGINT)
.column(RPKIT_AUCTION.END_TIME, SQLDataType.BIGINT)
.column(RPKIT_AUCTION.START_PRICE, SQLDataType.INTEGER)
.column(RPKIT_AUCTION.BUY_OUT_PRICE, SQLDataType.INTEGER)
.column(RPKIT_AUCTION.NO_SELL_PRICE, SQLDataType.INTEGER)
.column(RPKIT_AUCTION.MINIMUM_BID_INCREMENT, SQLDataType.INTEGER)
.column(RPKIT_AUCTION.BIDDING_OPEN, SQLDataType.TINYINT.length(1))
.constraints(
constraint("pk_rpkit_auction").primaryKey(RPKIT_AUCTION.ID)
)
.execute()
}
override fun applyMigrations() {
if (database.getTableVersion(this) == null) {
database.setTableVersion(this, "0.4.0")
}
}
override fun insert(entity: RPKAuction): Int {
database.create
.insertInto(
RPKIT_AUCTION,
RPKIT_AUCTION.ITEM,
RPKIT_AUCTION.CURRENCY_ID,
RPKIT_AUCTION.WORLD,
RPKIT_AUCTION.X,
RPKIT_AUCTION.Y,
RPKIT_AUCTION.Z,
RPKIT_AUCTION.YAW,
RPKIT_AUCTION.PITCH,
RPKIT_AUCTION.CHARACTER_ID,
RPKIT_AUCTION.DURATION,
RPKIT_AUCTION.END_TIME,
RPKIT_AUCTION.START_PRICE,
RPKIT_AUCTION.BUY_OUT_PRICE,
RPKIT_AUCTION.NO_SELL_PRICE,
RPKIT_AUCTION.MINIMUM_BID_INCREMENT,
RPKIT_AUCTION.BIDDING_OPEN
)
.values(
entity.item.toByteArray(),
entity.currency.id,
entity.location?.world?.name,
entity.location?.x,
entity.location?.y,
entity.location?.z,
entity.location?.yaw?.toDouble(),
entity.location?.pitch?.toDouble(),
entity.character.id,
entity.duration,
entity.endTime,
entity.startPrice,
entity.buyOutPrice,
entity.noSellPrice,
entity.minimumBidIncrement,
if (entity.isBiddingOpen) 1.toByte() else 0.toByte()
)
.execute()
val id = database.create.lastID().toInt()
entity.id = id
cache?.put(id, entity)
return id
}
override fun update(entity: RPKAuction) {
database.create
.update(RPKIT_AUCTION)
.set(RPKIT_AUCTION.ITEM, entity.item.toByteArray())
.set(RPKIT_AUCTION.CURRENCY_ID, entity.currency.id)
.set(RPKIT_AUCTION.WORLD, entity.location?.world?.name)
.set(RPKIT_AUCTION.X, entity.location?.x)
.set(RPKIT_AUCTION.Y, entity.location?.y)
.set(RPKIT_AUCTION.Z, entity.location?.z)
.set(RPKIT_AUCTION.YAW, entity.location?.yaw?.toDouble())
.set(RPKIT_AUCTION.PITCH, entity.location?.pitch?.toDouble())
.set(RPKIT_AUCTION.CHARACTER_ID, entity.character.id)
.set(RPKIT_AUCTION.DURATION, entity.duration)
.set(RPKIT_AUCTION.END_TIME, entity.endTime)
.set(RPKIT_AUCTION.START_PRICE, entity.startPrice)
.set(RPKIT_AUCTION.BUY_OUT_PRICE, entity.buyOutPrice)
.set(RPKIT_AUCTION.NO_SELL_PRICE, entity.noSellPrice)
.set(RPKIT_AUCTION.MINIMUM_BID_INCREMENT, entity.minimumBidIncrement)
.set(RPKIT_AUCTION.BIDDING_OPEN, if (entity.isBiddingOpen) 1.toByte() else 0.toByte())
.where(RPKIT_AUCTION.ID.eq(entity.id))
.execute()
cache?.put(entity.id, entity)
}
override fun get(id: Int): RPKAuction? {
if (cache?.containsKey(id) == true) {
return cache.get(id)
} else {
val result = database.create
.select(
RPKIT_AUCTION.ITEM,
RPKIT_AUCTION.CURRENCY_ID,
RPKIT_AUCTION.WORLD,
RPKIT_AUCTION.X,
RPKIT_AUCTION.Y,
RPKIT_AUCTION.Z,
RPKIT_AUCTION.YAW,
RPKIT_AUCTION.PITCH,
RPKIT_AUCTION.CHARACTER_ID,
RPKIT_AUCTION.DURATION,
RPKIT_AUCTION.END_TIME,
RPKIT_AUCTION.START_PRICE,
RPKIT_AUCTION.BUY_OUT_PRICE,
RPKIT_AUCTION.NO_SELL_PRICE,
RPKIT_AUCTION.MINIMUM_BID_INCREMENT,
RPKIT_AUCTION.BIDDING_OPEN
)
.from(RPKIT_AUCTION)
.where(RPKIT_AUCTION.ID.eq(id))
.fetchOne() ?: return null
val currencyProvider = plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class)
val currencyId = result.get(RPKIT_AUCTION.CURRENCY_ID)
val currency = currencyProvider.getCurrency(currencyId)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val characterId = result.get(RPKIT_AUCTION.CHARACTER_ID)
val character = characterProvider.getCharacter(characterId)
if (currency != null && character != null) {
val auction = RPKAuctionImpl(
plugin,
id,
result.get(RPKIT_AUCTION.ITEM).toItemStack(),
currency,
Location(
plugin.server.getWorld(result.get(RPKIT_AUCTION.WORLD)),
result.get(RPKIT_AUCTION.X),
result.get(RPKIT_AUCTION.Y),
result.get(RPKIT_AUCTION.Z),
result.get(RPKIT_AUCTION.YAW).toFloat(),
result.get(RPKIT_AUCTION.PITCH).toFloat()
),
character,
result.get(RPKIT_AUCTION.DURATION),
result.get(RPKIT_AUCTION.END_TIME),
result.get(RPKIT_AUCTION.START_PRICE),
result.get(RPKIT_AUCTION.BUY_OUT_PRICE),
result.get(RPKIT_AUCTION.NO_SELL_PRICE),
result.get(RPKIT_AUCTION.MINIMUM_BID_INCREMENT),
result.get(RPKIT_AUCTION.BIDDING_OPEN) == 1.toByte()
)
cache?.put(id, auction)
return auction
} else {
val bidTable = database.getTable(RPKBidTable::class)
database.create
.select(RPKIT_BID.ID)
.from(RPKIT_BID)
.where(RPKIT_BID.AUCTION_ID.eq(id))
.fetch()
.map { it[RPKIT_BID.ID] }
.mapNotNull { bidId -> bidTable[bidId] }
.forEach { bid -> bidTable.delete(bid) }
database.create
.deleteFrom(RPKIT_AUCTION)
.where(RPKIT_AUCTION.ID.eq(id))
.execute()
return null
}
}
}
/**
* Gets a list of all auctions
*
* @return A list containing all auctions
*/
fun getAll(): List<RPKAuction> {
val results = database.create
.select(RPKIT_AUCTION.ID)
.from(RPKIT_AUCTION)
.fetch()
return results.map { result ->
get(result.get(RPKIT_AUCTION.ID))
}.filterNotNull()
}
override fun delete(entity: RPKAuction) {
for (bid in entity.bids) {
database.getTable(RPKBidTable::class).delete(bid)
}
database.create
.deleteFrom(RPKIT_AUCTION)
.where(RPKIT_AUCTION.ID.eq(entity.id))
.execute()
cache?.remove(entity.id)
}
} | bukkit/rpk-auctions-bukkit/src/main/kotlin/com/rpkit/auctions/bukkit/database/table/RPKAuctionTable.kt | 3097381446 |
package pt.orgmir.budgetandroid.localstorage.wrapers
import io.realm.Realm
import pt.orgmir.budgetandroid.BAApplication
import pt.orgmir.budgetandroid.localstorage.model.BAExpenseModel
/**
* Created by Luis Ramos on 7/26/2015.
*/
public class BAExpense(public var model: BAExpenseModel) {
public constructor() : this(BAExpenseModel())
companion object{
public fun findAll() : List<BAExpense> {
val findAll = BAApplication.realm.where(javaClass<BAExpenseModel>()).findAll()
return findAll.map { BAExpense(it) }
}
public fun findAllOrderedByDate() : List<BAExpense> {
val findAll = BAApplication.realm.where(javaClass<BAExpenseModel>()).findAllSorted("createdAt", false)
return findAll.map { BAExpense(it) }
}
}
public var id : String
get() = model.getId()
set(value) { model.setId(value) }
public var value : Double
get() = model.getValue()
set(value) { model.setValue(value) }
public var category: String
get() = model.getCategory()
set(value) { model.setCategory(value) }
public var title : String
get() = model.getTitle()
set(value) { model.setTitle(value)}
public var description : String?
get() = model.getDescription()
set(value) { model.setDescription(description) }
/**
* QUERIES
*/
public fun create() {
saveData {
model = it.copyToRealm(model)
}
}
} | app/src/main/kotlin/pt/orgmir/budgetandroid/localstorage/wrapers/BAExpense.kt | 3338523148 |
package com.foo.graphql.unionInternal
import com.foo.graphql.SpringController
class UnionInternalController : SpringController(GQLUnionInternalApplication::class.java) {
override fun schemaName() = GQLUnionInternalApplication.SCHEMA_NAME
}
| e2e-tests/spring-graphql/src/test/kotlin/com/foo/graphql/unionInternal/UnionInternalController.kt | 3091918599 |
package com.soywiz.kpspemu.hle.modules
import com.soywiz.kpspemu.*
import com.soywiz.kpspemu.hle.*
import com.soywiz.kpspemu.hle.error.*
import com.soywiz.kpspemu.mem.*
class sceDmac(emulator: Emulator) : SceModule(emulator, "sceDmac", 0x40010011, "lowio.prx", "sceLowIO_Driver") {
fun _sceDmacMemcpy(src: Int, dst: Int, size: Int): Int {
if (size == 0) return SceKernelErrors.ERROR_INVALID_SIZE
if (src == 0 || dst == 0) return SceKernelErrors.ERROR_INVALID_POINTER
mem.copy(dst, src, size)
return 0
}
fun sceDmacMemcpy(src: Int, dst: Int, size: Int): Int = _sceDmacMemcpy(src, dst, size)
fun sceDmacTryMemcpy(src: Int, dst: Int, size: Int): Int = _sceDmacMemcpy(src, dst, size)
override fun registerModule() {
registerFunctionInt("sceDmacMemcpy", 0x617F3FE6, since = 150) { sceDmacMemcpy(int, int, int) }
registerFunctionInt("sceDmacTryMemcpy", 0xD97F94D8, since = 150) { sceDmacTryMemcpy(int, int, int) }
}
}
| src/commonMain/kotlin/com/soywiz/kpspemu/hle/modules/sceDmac.kt | 767762347 |
package kscript.app
import kscript.app.code.Templates
import kscript.app.model.Config
import kscript.app.util.Logger
import kscript.app.util.Logger.errorMsg
import kscript.app.shell.ShellUtils.evalBash
import kscript.app.shell.ShellUtils.quit
import kscript.app.util.VersionChecker
import org.docopt.DocOptWrapper
/**
* A kscript - Scripting enhancements for Kotlin
*
* For details and license see https://github.com/holgerbrandl/kscript
*
* @author Holger Brandl
* @author Marcin Kuszczak
*/
const val KSCRIPT_VERSION = "4.1.0"
fun main(args: Array<String>) {
try {
val config = Config.builder().apply { osType = args[0] }.build()
val remainingArgs = args.drop(1)
// skip org.docopt for version and help to allow for lazy version-check
val usage = Templates.createUsageOptions(config.osConfig.selfName, KSCRIPT_VERSION)
if (remainingArgs.size == 1 && listOf("--help", "-h", "--version", "-v").contains(remainingArgs[0])) {
Logger.info(usage)
VersionChecker.versionCheck(KSCRIPT_VERSION)
val systemInfo = evalBash(config.osConfig.osType, "kotlin -version").stdout.split('(')
Logger.info("Kotlin : " + systemInfo[0].removePrefix("Kotlin version").trim())
Logger.info("Java : " + systemInfo[1].split('-', ')')[0].trim())
return
}
// note: with current implementation we still don't support `kscript -1` where "-1" is a valid kotlin expression
val userArgs = remainingArgs.dropWhile { it.startsWith("-") && it != "-" }.drop(1)
val kscriptArgs = remainingArgs.take(remainingArgs.size - userArgs.size)
val docopt = DocOptWrapper(kscriptArgs, usage)
KscriptHandler(config, docopt).handle(kscriptArgs, userArgs)
} catch (e: Exception) {
errorMsg(e)
quit(1)
}
}
| src/main/kotlin/kscript/app/Kscript.kt | 890294389 |
package com.xwray.groupie.example
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.xwray.groupie.ExpandableGroup
import com.xwray.groupie.Group
import com.xwray.groupie.GroupieAdapter
import com.xwray.groupie.OnItemClickListener
import com.xwray.groupie.OnItemLongClickListener
import com.xwray.groupie.Section
import com.xwray.groupie.example.core.InfiniteScrollListener
import com.xwray.groupie.example.core.Prefs
import com.xwray.groupie.example.core.SettingsActivity
import com.xwray.groupie.example.core.decoration.CarouselItemDecoration
import com.xwray.groupie.example.core.decoration.DebugItemDecoration
import com.xwray.groupie.example.core.decoration.SwipeTouchCallback
import com.xwray.groupie.example.item.*
import com.xwray.groupie.groupiex.plusAssign
import kotlinx.android.synthetic.main.activity_main.*
const val INSET_TYPE_KEY = "inset_type"
const val INSET = "inset"
class MainActivity : AppCompatActivity() {
private val groupAdapter = GroupieAdapter()
private lateinit var groupLayoutManager: GridLayoutManager
private val prefs by lazy { Prefs.get(this) }
private val handler = Handler()
private val gray: Int by lazy { ContextCompat.getColor(this, R.color.background) }
private val betweenPadding: Int by lazy { resources.getDimensionPixelSize(R.dimen.padding_small) }
private val rainbow200: IntArray by lazy { resources.getIntArray(R.array.rainbow_200) }
private val rainbow500: IntArray by lazy { resources.getIntArray(R.array.rainbow_500) }
private val infiniteLoadingSection = Section(HeaderItem(R.string.infinite_loading))
private val swipeSection = Section(HeaderItem(R.string.swipe_to_delete))
private val dragSection = Section(HeaderItem(R.string.drag_to_reorder))
// Normally there's no need to hold onto a reference to this list, but for demonstration
// purposes, we'll shuffle this list and post an update periodically
private val updatableItems: ArrayList<UpdatableItem> by lazy {
ArrayList<UpdatableItem>().apply {
for (i in 1..12) {
add(UpdatableItem(rainbow200[i], i))
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.refresh) {
recreateAdapter()
return true
}
return super.onOptionsItemSelected(item)
}
// Hold a reference to the updating group, so we can, well, update it
private var updatingGroup = Section()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
groupAdapter.apply {
setOnItemClickListener(onItemClickListener)
setOnItemLongClickListener(onItemLongClickListener)
spanCount = 12
}
recreateAdapter()
groupLayoutManager = GridLayoutManager(this, groupAdapter.spanCount).apply {
spanSizeLookup = groupAdapter.spanSizeLookup
}
recyclerView.apply {
layoutManager = groupLayoutManager
addItemDecoration(HeaderItemDecoration(gray, betweenPadding))
addItemDecoration(InsetItemDecoration(gray, betweenPadding))
addItemDecoration(DebugItemDecoration(context))
adapter = groupAdapter
addOnScrollListener(object : InfiniteScrollListener(groupLayoutManager) {
override fun onLoadMore(currentPage: Int) {
val color = rainbow200[currentPage % rainbow200.size]
for (i in 0..4) {
infiniteLoadingSection.add(CardItem(color))
}
}
})
}
ItemTouchHelper(touchCallback).attachToRecyclerView(recyclerView)
fab.setOnClickListener { startActivity(Intent(this@MainActivity, SettingsActivity::class.java)) }
prefs.registerListener(onSharedPrefChangeListener)
}
private fun recreateAdapter() {
groupAdapter.clear()
val groups = createGroups()
if (prefs.useAsync) {
groupAdapter.updateAsync(groups)
} else {
groupAdapter.update(groups)
}
}
private fun createGroups(): List<Group> = mutableListOf<Group>().apply {
// Full bleed item
this += Section(HeaderItem(R.string.full_bleed_item)).apply {
add(FullBleedCardItem(R.color.purple_200))
}
// Update in place group
this += Section().apply {
val updatingHeader = HeaderItem(
R.string.updating_group,
R.string.updating_group_subtitle,
R.drawable.shuffle,
onShuffleClicked)
setHeader(updatingHeader)
updatingGroup.update(updatableItems)
add(updatingGroup)
}
// Expandable group
val expandableHeaderItem = ExpandableHeaderItem(R.string.expanding_group, R.string.expanding_group_subtitle)
this += ExpandableGroup(expandableHeaderItem).apply {
for (i in 0..1) {
add(CardItem(rainbow200[1]))
}
}
// Reordering a Section of Expandable Groups
val section = Section(HeaderItem(R.string.reorderable_section))
val swappableExpandableGroup = mutableListOf<ExpandableGroup>()
var colorIndex = 0
for (i in 0..2) {
val header = ExpandableHeaderItem(R.string.reorderable_item_title, R.string.reorderable_item_subtitle)
val group = ExpandableGroup(header).apply {
val numChildren= i * 2 // groups will continue to grow by 2
for (j in 0..numChildren) {
add(CardItem(rainbow200[colorIndex]))
if (colorIndex + 1 >= rainbow200.size) {
colorIndex = 0
} else {
colorIndex += 1
}
}
}
header.clickListener = {
swappableExpandableGroup.remove(group)
swappableExpandableGroup.add(group)
section.update(swappableExpandableGroup)
}
swappableExpandableGroup.add(group)
}
section.addAll(swappableExpandableGroup)
this += section
// Columns
fun makeColumnGroup(): ColumnGroup {
val columnItems = ArrayList<ColumnItem>()
for (i in 1..5) {
// First five items are red -- they'll end up in a vertical column
columnItems += ColumnItem(rainbow200[0], i)
}
for (i in 6..10) {
// Next five items are pink
columnItems += ColumnItem(rainbow200[1], i)
}
return ColumnGroup(columnItems)
}
this += Section(HeaderItem(R.string.vertical_columns)).apply {
add(makeColumnGroup())
}
// Group showing even spacing with multiple columns
this += Section(HeaderItem(R.string.multiple_columns)).apply {
for (i in 0..11) {
add(SmallCardItem(rainbow200[5]))
}
}
// Swipe to delete (with add button in header)
swipeSection.clear()
for (i in 0..2) {
swipeSection += SwipeToDeleteItem(rainbow200[i])
}
this += swipeSection
dragSection.clear()
for (i in 0..4) {
dragSection += DraggableItem(rainbow500[i])
}
this += dragSection
// Horizontal carousel
fun makeCarouselItem(): CarouselItem {
val carouselDecoration = CarouselItemDecoration(gray, betweenPadding)
val carouselAdapter = GroupieAdapter()
for (i in 0..29) {
carouselAdapter += CarouselCardItem(rainbow200[7])
}
return CarouselItem(carouselDecoration, carouselAdapter)
}
this += Section(HeaderItem(R.string.carousel, R.string.carousel_subtitle)).apply {
add(makeCarouselItem())
}
// Update with payload
this += Section(HeaderItem(R.string.update_with_payload, R.string.update_with_payload_subtitle)).apply {
rainbow500.indices.forEach { i ->
add(HeartCardItem(rainbow200[i], i.toLong()) { item, favorite ->
// Pretend to make a network request
handler.postDelayed({
// Network request was successful!
item.setFavorite(favorite)
item.notifyChanged(FAVORITE)
}, 1000)
})
}
}
// Infinite loading section
this += infiniteLoadingSection
}
private val onItemClickListener = OnItemClickListener { item, _ ->
if (item is CardItem && !TextUtils.isEmpty(item.text)) {
Toast.makeText(this@MainActivity, item.text, Toast.LENGTH_SHORT).show()
}
}
private val onItemLongClickListener = OnItemLongClickListener { item, _ ->
if (item is CardItem && !item.text.isNullOrBlank()) {
Toast.makeText(this@MainActivity, "Long clicked: " + item.text, Toast.LENGTH_SHORT).show()
return@OnItemLongClickListener true
}
false
}
private val onShuffleClicked = View.OnClickListener {
ArrayList(updatableItems).apply {
shuffle()
updatingGroup.update(this)
}
// You can also do this by forcing a change with payload
recyclerView.post { recyclerView.invalidateItemDecorations() }
}
override fun onDestroy() {
prefs.unregisterListener(onSharedPrefChangeListener)
super.onDestroy()
}
private val touchCallback: SwipeTouchCallback by lazy {
object : SwipeTouchCallback() {
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder): Boolean {
val item = groupAdapter.getItem(viewHolder.bindingAdapterPosition)
val targetItem = groupAdapter.getItem(target.bindingAdapterPosition)
val dragItems = dragSection.groups
var targetIndex = dragItems.indexOf(targetItem)
dragItems.remove(item)
// if item gets moved out of the boundary
if (targetIndex == -1) {
targetIndex = if (target.bindingAdapterPosition < viewHolder.bindingAdapterPosition) {
0
} else {
dragItems.size - 1
}
}
dragItems.add(targetIndex, item)
dragSection.update(dragItems)
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val item = groupAdapter.getItem(viewHolder.bindingAdapterPosition)
// Change notification to the adapter happens automatically when the section is
// changed.
swipeSection.remove(item)
}
}
}
private val onSharedPrefChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ ->
recreateAdapter()
}
}
| example/src/main/java/com/xwray/groupie/example/MainActivity.kt | 709762752 |
/*
* Copyright (C) 2014 Contentful GmbH
*
* 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.contentful.java.cma.lib
import org.apache.commons.io.FileUtils
import java.io.File
import kotlin.test.assertEquals
class TestUtils {
companion object {
fun fileToString(fileName: String): String =
FileUtils.readFileToString(File("src/test/resources/${fileName}"), "UTF-8")
}
}
class ModuleTestUtils {
companion object {
fun assertUpdateWithoutVersion(method: () -> Unit) {
try {
method()
} catch (e: IllegalArgumentException) {
val msg = "Cannot perform update action on a " +
"resource that has no version associated."
assertEquals(msg, e.getMessage())
throw e
}
}
}
}
| src/test/kotlin/com/contentful/java/cma/lib/TestUtils.kt | 3110207759 |
package org.eurofurence.connavigator.ui.fragments
import android.animation.LayoutTransition
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.RecyclerView
import com.joanzapata.iconify.widget.IconTextView
import io.reactivex.disposables.Disposables
import org.eurofurence.connavigator.BuildConfig
import org.eurofurence.connavigator.R
import org.eurofurence.connavigator.database.HasDb
import org.eurofurence.connavigator.database.lazyLocateDb
import org.eurofurence.connavigator.ui.views.NonScrollingLinearLayout
import org.eurofurence.connavigator.util.delegators.view
import org.eurofurence.connavigator.util.extensions.*
import org.eurofurence.connavigator.util.v2.compatAppearance
import org.eurofurence.connavigator.util.v2.plus
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.UI
import java.util.*
/**
* Renders an info group element and displays it's individual items
*/
class InfoGroupFragment : DisposingFragment(), HasDb, AnkoLogger {
inner class InfoItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val layout: LinearLayout by view("layout")
val name: TextView by view("title")
}
inner class DataAdapter : RecyclerView.Adapter<InfoItemViewHolder>() {
override fun getItemCount() = infoItems.count()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
InfoItemViewHolder(UI { SingleInfoUi().createView(this) }.view)
override fun onBindViewHolder(holder: InfoItemViewHolder, position: Int) {
val item = infoItems[position]
holder.name.text = item.title
holder.layout.setOnClickListener {
val action = InfoListFragmentDirections.actionInfoListFragmentToInfoItemFragment(item.id.toString(), BuildConfig.CONVENTION_IDENTIFIER)
findNavController().navigate(action)
}
holder.layout.setOnLongClickListener {
context?.let {
context?.share(item.shareString(it), "Share Info")
} != null
}
}
}
override val db by lazyLocateDb()
private val infoGroupId: UUID? get() = UUID.fromString(arguments!!.getString("id"))
private val infoGroup by lazy { db.knowledgeGroups[infoGroupId] }
val infoItems by lazy {
db.knowledgeEntries.items
.filter { it.knowledgeGroupId == infoGroupId }
.sortedBy { it.order }
}
val ui = InfoGroupUi()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
UI { ui.createView(this) }.view
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fillUi()
db.subscribe {
fillUi()
}
.collectOnDestroyView()
}
private fun fillUi() {
ui.apply {
infoGroup?.let {
title.text = it.name
mainIcon.text = it.fontAwesomeIconCharacterUnicodeAddress?.toUnicode() ?: ""
description.text = it.description
groupLayout.setOnClickListener {
setDropdown()
}
recycler.apply {
adapter = DataAdapter()
layoutManager = NonScrollingLinearLayout(activity)
itemAnimator = DefaultItemAnimator()
}
} ?: run {
warn { "Info group initialized on non-existent ID." }
groupLayout.visibility = View.GONE
}
}
}
private fun setDropdown() {
if (ui.recyclerLayout.visibility == View.GONE) {
ui.recyclerLayout.visibility = View.VISIBLE
ui.dropdownCaret.text = "{fa-chevron-up 24sp}"
} else {
ui.recyclerLayout.visibility = View.GONE
ui.dropdownCaret.text = "{fa-chevron-down 24sp}"
}
}
}
class InfoGroupUi : AnkoComponent<Fragment> {
lateinit var title: TextView
lateinit var description: TextView
lateinit var recycler: RecyclerView
lateinit var groupLayout: LinearLayout
lateinit var dropdownCaret: IconTextView
lateinit var mainIcon: TextView
lateinit var recyclerLayout: LinearLayout
override fun createView(ui: AnkoContext<Fragment>) = with(ui) {
verticalLayout {
groupLayout = linearLayout {
isClickable = true
weightSum = 20F
backgroundResource = R.color.lightBackground
layoutTransition = LayoutTransition().apply {
enableTransitionType(LayoutTransition.APPEARING)
enableTransitionType(LayoutTransition.CHANGE_APPEARING)
enableTransitionType(LayoutTransition.CHANGING)
}
verticalLayout {
mainIcon = fontAwesomeTextView {
gravity = Gravity.CENTER
textColor = ContextCompat.getColor(context, R.color.primary)
textSize = 24f
}.lparams(matchParent, matchParent)
}.lparams(dip(0), matchParent) {
weight = 4F
}
verticalLayout {
verticalPadding = dip(15)
title = textView {
textResource = R.string.misc_title
compatAppearance = android.R.style.TextAppearance_DeviceDefault_Large
}
description = textView {
textResource = R.string.misc_description
compatAppearance = android.R.style.TextAppearance_DeviceDefault_Small
}
}.lparams(dip(0), wrapContent) {
weight = 13F
}
verticalLayout {
dropdownCaret = fontAwesomeView {
gravity = Gravity.CENTER
text = "{fa-chevron-down 24sp}"
}.lparams(matchParent, matchParent)
}.lparams(dip(0), matchParent) {
weight = 3F
}
}
recyclerLayout = verticalLayout {
recycler = recycler {
}.lparams(matchParent, wrapContent)
visibility = View.GONE
}
}
}
}
class SingleInfoUi : AnkoComponent<Fragment> {
override fun createView(ui: AnkoContext<Fragment>) = with(ui) {
linearLayout {
topPadding = dip(10)
bottomPadding = dip(10)
id = R.id.layout
weightSum = 20F
lparams(matchParent, wrapContent)
view {
// Sneaky view to pad stuff
}.lparams(dip(0), wrapContent) {
weight = 4F
}
textView {
textResource = R.string.misc_name
id = R.id.title
compatAppearance = android.R.style.TextAppearance_DeviceDefault_Medium
textColor = ContextCompat.getColor(context, R.color.textBlack)
}.lparams(dip(0), wrapContent) {
weight = 13F
}
fontAwesomeView {
text = "{fa-chevron-right 24sp}"
gravity = Gravity.CENTER
}.lparams(dip(0), matchParent) {
weight = 3F
}
}
}
} | app/src/main/kotlin/org/eurofurence/connavigator/ui/fragments/InfoGroupFragment.kt | 697024335 |
package com.petrulak.cleankotlin.platform.extensions
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableCompletableObserver
import io.reactivex.observers.DisposableObserver
import io.reactivex.observers.DisposableSingleObserver
import io.reactivex.schedulers.Schedulers
import io.reactivex.subscribers.DisposableSubscriber
import timber.log.Timber
fun <T1> subscribeOnIo(observable: Flowable<T1>, onNext: (T1) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable {
return observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableSubscriber<T1>() {
override fun onNext(t: T1) {
onNext.invoke(t)
}
override fun onComplete() {
}
override fun onError(e: Throwable) {
Timber.e(e)
onError.invoke(e)
}
})
}
fun <T1> subscribeOnIo(observable: Observable<T1>, onNext: (T1) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable {
return observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableObserver<T1>() {
override fun onNext(t: T1) {
onNext.invoke(t)
}
override fun onComplete() {
}
override fun onError(e: Throwable) {
onError.invoke(e)
}
})
}
fun <T1> subscribeOnIo(single: Single<T1>, onSuccess: (T1) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable {
return single
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableSingleObserver<T1>() {
override fun onSuccess(t: T1) {
onSuccess.invoke(t)
}
override fun onError(e: Throwable) {
Timber.e(e)
onError.invoke(e)
}
})
}
fun subscribeOnIo(completable: Completable, onCompleted: () -> Unit, onError: (Throwable) -> Unit) {
return completable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : DisposableCompletableObserver() {
override fun onComplete() {
onCompleted.invoke()
}
override fun onError(e: Throwable) {
onError.invoke(e)
}
})
}
fun <T> getDisposableSingleObserver(onNext: (T) -> Unit, onError: (Throwable) -> Unit = {}): DisposableSingleObserver<T> {
return object : DisposableSingleObserver<T>() {
override fun onSuccess(value: T) {
onNext.invoke(value)
}
override fun onError(e: Throwable) {
Timber.e(e, "DisposableSingleObserver error")
onError.invoke(e)
}
}
}
fun <T> getDisposableCompletableObserver(onComplete: () -> Unit, onError: (Throwable) -> Unit = {}): DisposableCompletableObserver {
return object : DisposableCompletableObserver() {
override fun onComplete() {
onComplete.invoke()
}
override fun onError(e: Throwable) {
Timber.e(e, "DisposableCompletableObserver error")
onError.invoke(e)
}
}
}
fun <T> getDisposableSubscriber(onNext: (T) -> Unit, onError: (Throwable) -> Unit = {}): DisposableSubscriber<T> {
return object : DisposableSubscriber<T>() {
override fun onNext(value: T) {
onNext.invoke(value)
}
override fun onComplete() {
}
override fun onError(e: Throwable) {
Timber.e(e, "DisposableSubscriber error")
onError.invoke(e)
}
}
} | app/src/main/java/com/petrulak/cleankotlin/platform/extensions/RxExtensions.kt | 1335718007 |
package me.proxer.library.entity.messenger
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import me.proxer.library.entity.ProxerDateItem
import me.proxer.library.entity.ProxerIdItem
import me.proxer.library.enums.Device
import me.proxer.library.enums.MessageAction
import java.util.Date
/**
* Entity representing a single message.
*
* @property conferenceId The id of the associated [Conference].
* @property userId The id of the associated user.
* @property username The username of the author.
* @property message The actual content of the message.
* @property action The action of this message. If the action is not [MessageAction.NONE],
* [message] returns associated information, like the name of the user, performing the action.
* @property device The device, the message was sent from.
*
* @author Ruben Gees
*/
@JsonClass(generateAdapter = true)
data class Message(
@Json(name = "message_id") override val id: String,
@Json(name = "conference_id") val conferenceId: String,
@Json(name = "user_id") val userId: String,
@Json(name = "username") val username: String,
@Json(name = "message") val message: String,
@Json(name = "action") val action: MessageAction,
@Json(name = "timestamp") override val date: Date,
@Json(name = "device") val device: Device
) : ProxerIdItem, ProxerDateItem
| library/src/main/kotlin/me/proxer/library/entity/messenger/Message.kt | 186501071 |
package com.hadihariri.markcode
import com.hadihariri.markcode.ExampleLanguage
import com.hadihariri.markcode.startsWithAny
object KotlinLanguage : ExampleLanguage {
override fun getPackageName(dirName: String, fileName: String): String {
if (fileName[0] in '0'..'9')
return dirName + ".ex" + fileName.substringAfter('.').removeSuffix(".kt").replace('.', '_')
return dirName + "." + fileName.removeSuffix(".kt")
}
override fun formatPackageStatement(packageName: String) = "package $packageName"
override fun formatImportStatement(importName: String) = "import $importName"
override fun formatMainFunction(fileName: String) = "fun main(args: Array<String>) {"
override fun formatMainFunctionIndent() = " "
override fun formatMainFunctionEnd() = "}"
override fun hasAnyDeclarations(lines: Collection<String>) = lines.any {
it.startsWithAny("fun", "inline fun", "operator fun", "class", "enum class", "interface", "open class", "data class", "abstract class")
}
} | src/main/kotlin/com/hadihariri/markcode/KotlinLanguage.kt | 1814409573 |
package chat.rocket.android.emoji.internal.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import chat.rocket.android.emoji.Emoji
import chat.rocket.android.emoji.EmojiDao
@Database(entities = [Emoji::class], version = 1)
@TypeConverters(StringListConverter::class)
abstract class EmojiDatabase : RoomDatabase() {
abstract fun emojiDao(): EmojiDao
companion object : SingletonHolder<EmojiDatabase, Context>({
Room.databaseBuilder(it.applicationContext,
EmojiDatabase::class.java, "emoji.db")
.fallbackToDestructiveMigration()
.build()
})
}
open class SingletonHolder<out T, in A>(creator: (A) -> T) {
private var creator: ((A) -> T)? = creator
@kotlin.jvm.Volatile
private var instance: T? = null
fun getInstance(arg: A): T {
val i = instance
if (i != null) {
return i
}
return synchronized(this) {
val i2 = instance
if (i2 != null) {
i2
} else {
val created = creator!!(arg)
instance = created
creator = null
created
}
}
}
}
| emoji/src/main/java/chat/rocket/android/emoji/internal/db/EmojiDatabase.kt | 1127907867 |
package com.theostanton.lfgss.huddles
import com.theostanton.lfgss.api.LFGSS
import com.theostanton.lfgss.listitem.ListItemPresenter
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import timber.log.Timber
/**
* Created by theostanton on 28/02/16.
*/
class HuddlesPresenter : ListItemPresenter() {
init {
Timber.tag("HuddlesPresenter")
}
override fun load() {
super.load()
cancelIfRunning()
subscription = LFGSS.api
.getHuddles()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe (
{ setData(it.data.huddles.items) },
{ Timber.e("error ${it.message}", it) }
)
}
} | app/src/main/java/com/theostanton/lfgss/huddles/HuddlesPresenter.kt | 2021582957 |
package org.nield.kotlinstatistics
import org.junit.Assert.assertTrue
import org.junit.Test
import java.math.BigDecimal
import java.util.*
class NumberStatisticsTest {
val doubleVector = sequenceOf(1.0, 3.0, 5.0, 11.0)
val intVector = doubleVector.map { it.toInt() }
val longVector = intVector.map { it.toLong() }
val bigDecimalVector = doubleVector.map(BigDecimal::valueOf)
val groups = sequenceOf("A","A","B", "B")
@Test
fun descriptiveStatistics() {
assertTrue(doubleVector.descriptiveStatistics.mean == 5.0)
assertTrue(intVector.descriptiveStatistics.mean == 5.0)
assertTrue(longVector.descriptiveStatistics.mean == 5.0)
assertTrue(bigDecimalVector.descriptiveStatistics.mean == 5.0)
assertTrue(doubleVector.descriptiveStatistics.min == 1.0)
assertTrue(intVector.descriptiveStatistics.min == 1.0)
assertTrue(longVector.descriptiveStatistics.min == 1.0)
assertTrue(bigDecimalVector.descriptiveStatistics.min == 1.0)
assertTrue(doubleVector.descriptiveStatistics.max == 11.0)
assertTrue(intVector.descriptiveStatistics.max == 11.0)
assertTrue(longVector.descriptiveStatistics.max == 11.0)
assertTrue(bigDecimalVector.descriptiveStatistics.max == 11.0)
assertTrue(doubleVector.descriptiveStatistics.size == 4L)
assertTrue(intVector.descriptiveStatistics.size == 4L)
assertTrue(longVector.descriptiveStatistics.size == 4L)
assertTrue(bigDecimalVector.descriptiveStatistics.size == 4L)
}
@Test
fun descriptiveBy() {
groups.zip(doubleVector).descriptiveStatisticsBy()
.let {
assertTrue(it["A"]!!.mean == 2.0 && it["B"]!!.mean == 8.0)
}
groups.zip(intVector).descriptiveStatisticsBy()
.let {
assertTrue(it["A"]!!.mean == 2.0 && it["B"]!!.mean == 8.0)
}
groups.zip(longVector).descriptiveStatisticsBy()
.let {
assertTrue(it["A"]!!.mean == 2.0 && it["B"]!!.mean == 8.0)
}
groups.zip(bigDecimalVector).descriptiveStatisticsBy()
.let {
assertTrue(it["A"]!!.mean == 2.0 && it["B"]!!.mean == 8.0)
}
groups.zip(doubleVector).descriptiveStatisticsBy(
keySelector = { it.first },
valueSelector = {it.second}
)
.let {
assertTrue(it["A"]!!.mean == 2.0 && it["B"]!!.mean == 8.0)
}
}
@Test
fun geometricMean() {
doubleVector.asSequence().geometricMean().let { assertTrue(it == 3.584024634215721) }
intVector.asSequence().geometricMean().let { assertTrue(it == 3.584024634215721) }
longVector.asSequence().geometricMean().let { assertTrue(it == 3.584024634215721) }
bigDecimalVector.asSequence().geometricMean().let { assertTrue(it == 3.584024634215721) }
}
@Test
fun median() {
doubleVector.asSequence().median().let { assertTrue(it == 4.0) }
doubleVector.asSequence().take(3).median().let { assertTrue(it == 3.0) }
intVector.asSequence().median().let { assertTrue(it == 4.0) }
longVector.asSequence().median().let { assertTrue(it == 4.0) }
bigDecimalVector.asSequence().median().let { assertTrue(it == 4.0) }
}
@Test
fun medianBy() {
groups.zip(doubleVector).medianBy()
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0)
}
groups.zip(intVector).medianBy()
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0)
}
groups.zip(longVector).medianBy()
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0)
}
groups.zip(bigDecimalVector).medianBy()
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0)
}
groups.zip(doubleVector).medianBy(
keySelector = {it.first},
valueSelector = {it.second}
)
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0)
}
}
@Test
fun percentile() {
doubleVector.asSequence().percentile(50.0).let { assertTrue(it == 4.0) }
intVector.asSequence().percentile(50.0).let { assertTrue(it == 4.0) }
longVector.asSequence().percentile(50.0).let { assertTrue(it == 4.0) }
bigDecimalVector.asSequence().percentile(50.0).let { assertTrue(it == 4.0) }
}
@Test
fun percentileBy() {
groups.zip(doubleVector).percentileBy(50.0)
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0)
}
groups.zip(intVector).percentileBy(50.0)
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0)
}
groups.zip(longVector).percentileBy(50.0)
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0)
}
groups.zip(bigDecimalVector).percentileBy(50.0)
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0)
}
groups.zip(bigDecimalVector).percentileBy(
percentile = 50.0,
keySelector = {it.first},
valueSelector = {it.second}
)
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0)
}
}
@Test
fun variance() {
val r = 18.666666666666668
doubleVector.asSequence().variance().let { assertTrue(it == r) }
intVector.asSequence().variance().let { assertTrue(it == r) }
longVector.asSequence().variance().let { assertTrue(it == r) }
bigDecimalVector.asSequence().variance().let { assertTrue(it == r) }
}
@Test
fun varianceBy() {
groups.zip(doubleVector).varianceBy()
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 18.0)
}
groups.zip(intVector).varianceBy()
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 18.0)
}
groups.zip(longVector).varianceBy()
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 18.0)
}
groups.zip(bigDecimalVector).varianceBy()
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 18.0)
}
groups.zip(bigDecimalVector).varianceBy(
keySelector = {it.first},
valueSelector = {it.second}
)
.let {
assertTrue(it["A"]!! == 2.0 && it["B"]!! == 18.0)
}
}
@Test
fun sumOfSquares() {
val r = 156.0
doubleVector.asSequence().sumOfSquares().let { assertTrue(it == r) }
intVector.asSequence().sumOfSquares().let { assertTrue(it == r) }
longVector.asSequence().sumOfSquares().let { assertTrue(it == r) }
bigDecimalVector.asSequence().sumOfSquares().let { assertTrue(it == r) }
}
@Test
fun standardDeviation() {
val r = 4.320493798938574
doubleVector.asSequence().standardDeviation().let { assertTrue(it == r) }
intVector.asSequence().standardDeviation().let { assertTrue(it == r) }
longVector.asSequence().standardDeviation().let { assertTrue(it == r) }
bigDecimalVector.asSequence().standardDeviation().let { assertTrue(it == r) }
}
@Test
fun standardDeviationBy() {
val r = mapOf("A" to 1.4142135623730951, "B" to 4.242640687119285)
groups.zip(doubleVector).standardDeviationBy()
.let {
assertTrue(it == r)
}
groups.zip(intVector).standardDeviationBy()
.let {
assertTrue(it == r)
}
groups.zip(longVector).standardDeviationBy()
.let {
assertTrue(it == r)
}
groups.zip(bigDecimalVector).standardDeviationBy()
.let {
assertTrue(it == r)
}
groups.zip(bigDecimalVector).standardDeviationBy(
keySelector = {it.first},
valueSelector = {it.second}
)
.let {
assertTrue(it == r)
}
}
@Test
fun normalize() {
val r = doubleArrayOf(
-0.9258200997725514,
-0.4629100498862757,
0.0,
1.3887301496588271
)
doubleVector.asSequence().normalize().let { assertTrue(Arrays.equals(it, r)) }
intVector.asSequence().normalize().let { assertTrue(Arrays.equals(it, r)) }
longVector.asSequence().normalize().let { assertTrue(Arrays.equals(it, r)) }
bigDecimalVector.asSequence().normalize().let { assertTrue(Arrays.equals(it, r)) }
}
@Test
fun kurtosis() {
val r = 1.4999999999999947
assertTrue(doubleVector.kurtosis == r)
assertTrue(intVector.kurtosis == r)
assertTrue(longVector.kurtosis == r)
assertTrue(bigDecimalVector.kurtosis == r)
}
@Test
fun skewness() {
val r = 1.1903401282789945
assertTrue(doubleVector.skewness == r)
assertTrue(intVector.skewness == r)
assertTrue(longVector.skewness == r)
assertTrue(bigDecimalVector.skewness == r)
}
@Test
fun geometricMeanBy() {
val r = mapOf("A" to 1.7320508075688774, "B" to 7.416198487095664)
groups.zip(doubleVector).geometricMeanBy()
.let {
assertTrue(it == r)
}
groups.zip(intVector).geometricMeanBy()
.let {
assertTrue(it == r)
}
groups.zip(longVector).geometricMeanBy()
.let {
assertTrue(it == r)
}
groups.zip(bigDecimalVector).geometricMeanBy()
.let {
assertTrue(it == r)
}
groups.zip(bigDecimalVector).geometricMeanBy(
keySelector = {it.first},
valueSelector = {it.second}
)
.let {
assertTrue(it == r)
}
}
@Test
fun simpleRegression() {
doubleVector.zip(doubleVector.map { it * 2 })
.simpleRegression()
.let { assertTrue(it.slope == 2.0) }
intVector.zip(intVector.map { it * 2 })
.simpleRegression()
.let { assertTrue(it.slope == 2.0) }
longVector.zip(longVector.map { it * 2 })
.simpleRegression()
.let { assertTrue(it.slope == 2.0) }
bigDecimalVector.zip(bigDecimalVector.map { it * BigDecimal.valueOf(2L) })
.simpleRegression()
.let { assertTrue(it.slope == 2.0) }
intVector.zip(intVector.map { it * 2 })
.simpleRegression(
xSelector = {it.first},
ySelector = {it.second}
)
.let { assertTrue(it.slope == 2.0) }
}
} | src/test/kotlin/org/nield/kotlinstatistics/NumberStatisticsTest.kt | 2699623461 |
/*
* 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
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.DependencyConstraint
import org.gradle.api.artifacts.dsl.DependencyConstraintHandler
import org.gradle.kotlin.dsl.support.delegates.DependencyConstraintHandlerDelegate
/**
* Receiver for `dependencies.constraints` block providing convenient utilities for configuring dependency constraints.
*
* @see [DependencyConstraintHandler]
* @since 5.0
*/
class DependencyConstraintHandlerScope
private constructor(
val constraints: DependencyConstraintHandler
) : DependencyConstraintHandlerDelegate() {
companion object {
fun of(constraints: DependencyConstraintHandler) =
DependencyConstraintHandlerScope(constraints)
}
override val delegate: DependencyConstraintHandler
get() = constraints
/**
* Adds a dependency constraint to the given configuration.
*
* @param dependencyConstraintNotation notation for the dependency constraint to be added.
* @return The dependency constraint.
* @see [DependencyConstraintHandler.add]
*/
operator fun String.invoke(dependencyConstraintNotation: Any): DependencyConstraint? =
constraints.add(this, dependencyConstraintNotation)
/**
* Adds a dependency constraint to the given configuration.
*
* @param dependencyConstraintNotation notation for the dependency constraint to be added.
* @param configuration expression to use to configure the dependency constraint.
* @return The dependency constraint.
* @see [DependencyConstraintHandler.add]
*/
operator fun String.invoke(dependencyConstraintNotation: String, configuration: DependencyConstraint.() -> Unit): DependencyConstraint =
constraints.add(this, dependencyConstraintNotation, configuration)
/**
* Adds a dependency constraint to the given configuration.
*
* @param dependencyConstraintNotation notation for the dependency constraint to be added.
* @return The dependency constraint.
* @see [DependencyConstraintHandler.add]
*/
operator fun Configuration.invoke(dependencyConstraintNotation: Any): DependencyConstraint? =
add(name, dependencyConstraintNotation)
/**
* Adds a dependency constraint to the given configuration.
*
* @param dependencyConstraintNotation notation for the dependency constraint to be added.
* @param configuration expression to use to configure the dependency constraint.
* @return The dependency constraint.
* @see [DependencyConstraintHandler.add]
*/
operator fun Configuration.invoke(dependencyConstraintNotation: String, configuration: DependencyConstraint.() -> Unit): DependencyConstraint =
add(name, dependencyConstraintNotation, configuration)
/**
* Configures the dependency constraints.
*/
inline operator fun invoke(configuration: DependencyConstraintHandlerScope.() -> Unit) =
this.configuration()
}
| subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/DependencyConstraintHandlerScope.kt | 3886426643 |
/*
* Copyright 2022 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.google.android.libraries.pcc.chronicle.api.integration
import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptor
import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptorSet
import com.google.android.libraries.pcc.chronicle.api.FieldType
import java.time.Duration
import java.time.Instant
import kotlin.reflect.KClass
/** Default implementation of [DataTypeDescriptorSet]. */
class DefaultDataTypeDescriptorSet(private val dtds: Set<DataTypeDescriptor>) :
DataTypeDescriptorSet {
private val dtdsByName: Map<String, DataTypeDescriptor> =
dtds.flatMap { collectNestedDataTypeDescriptors(it) }.associateBy { it.name }
private val dtdsByKClass: Map<KClass<*>, DataTypeDescriptor> =
dtdsByName.values.associateBy { it.cls }
private fun collectNestedDataTypeDescriptors(dtd: DataTypeDescriptor): List<DataTypeDescriptor> {
return dtd.innerTypes.fold(listOf(dtd)) { acc, t -> acc + collectNestedDataTypeDescriptors(t) }
}
override fun getOrNull(name: String): DataTypeDescriptor? = dtdsByName[name]
override tailrec fun findFieldTypeOrThrow(
dtd: DataTypeDescriptor,
accessPath: List<String>,
): FieldType {
require(accessPath.isNotEmpty()) { "Cannot find field type for empty access path." }
val field = accessPath[0]
val fieldType =
requireNotNull(dtd.fields[field]) { "Field \"$field\" not found in ${dtd.name}" }
if (accessPath.size == 1) return fieldType
val nextDtd = requireNotNull(findDataTypeDescriptor(fieldType))
return findFieldTypeOrThrow(nextDtd, accessPath.drop(1))
}
override fun findDataTypeDescriptor(fieldType: FieldType): DataTypeDescriptor? {
return when (fieldType) {
is FieldType.Array -> findDataTypeDescriptor(fieldType.itemFieldType)
is FieldType.List -> findDataTypeDescriptor(fieldType.itemFieldType)
is FieldType.Nullable -> findDataTypeDescriptor(fieldType.itemFieldType)
is FieldType.Nested -> getOrNull(fieldType.name)
is FieldType.Reference -> getOrNull(fieldType.name)
FieldType.Boolean,
FieldType.Byte,
FieldType.ByteArray,
FieldType.Char,
FieldType.Double,
FieldType.Duration,
FieldType.Float,
FieldType.Instant,
FieldType.Integer,
FieldType.Long,
FieldType.Short,
FieldType.String,
is FieldType.Enum,
is FieldType.Opaque,
// We would need to know which item within the tuple we are interested in.
is FieldType.Tuple -> null
}
}
override fun findDataTypeDescriptor(cls: KClass<*>): DataTypeDescriptor? = dtdsByKClass[cls]
override fun fieldTypeAsClass(fieldType: FieldType): Class<*> {
return when (fieldType) {
FieldType.Boolean -> Boolean::class.javaObjectType
FieldType.Byte -> Byte::class.javaObjectType
FieldType.ByteArray -> ByteArray::class.java
FieldType.Char -> Char::class.javaObjectType
FieldType.Double -> Double::class.javaObjectType
FieldType.Duration -> Duration::class.java
FieldType.Float -> Float::class.javaObjectType
FieldType.Instant -> Instant::class.java
FieldType.Integer -> Int::class.javaObjectType
FieldType.Long -> Long::class.javaObjectType
FieldType.Short -> Short::class.javaObjectType
FieldType.String -> String::class.java
is FieldType.Enum -> Enum::class.java
is FieldType.Array -> Array::class.java
is FieldType.List -> List::class.java
is FieldType.Reference -> this[fieldType.name].cls.java
is FieldType.Nested -> this[fieldType.name].cls.java
is FieldType.Opaque -> Class.forName(fieldType.name)
is FieldType.Nullable -> fieldTypeAsClass(fieldType.itemFieldType)
is FieldType.Tuple ->
// TODO(b/208662121): Tuples could be android.util.Pair or kotlin.Pair (or similar)
throw IllegalArgumentException("Tuple is too ambiguous to return a field type.")
}
}
override fun toSet(): Set<DataTypeDescriptor> = dtds
}
| java/com/google/android/libraries/pcc/chronicle/api/integration/DefaultDataTypeDescriptorSet.kt | 1965656820 |
/*
* Copyright 2020 Ren Binden
*
* 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.rpkit.chat.bukkit.event.chatgroup
import com.rpkit.chat.bukkit.chatgroup.RPKChatGroup
import com.rpkit.core.event.RPKEvent
interface RPKChatGroupEvent : RPKEvent {
val chatGroup: RPKChatGroup
} | bukkit/rpk-chat-lib-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/event/chatgroup/RPKChatGroupEvent.kt | 780740396 |
package tech.summerly.quiet.ui.activity.netease
import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.SeekBar
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.activity_personal_fm.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.toast
import org.jetbrains.anko.uiThread
import tech.summerly.quiet.R
import tech.summerly.quiet.bus.FetchMusicErrorEvent
import tech.summerly.quiet.bus.OnMusicLikedEvent
import tech.summerly.quiet.data.netease.NeteaseCloudMusicApi
import tech.summerly.quiet.extensions.*
import tech.summerly.quiet.extensions.lib.GlideApp
import tech.summerly.quiet.module.common.bean.Music
import tech.summerly.quiet.module.common.bus.RxBus
import tech.summerly.quiet.module.common.bus.event.MusicPlayerEvent
import tech.summerly.quiet.module.common.player.MusicPlayerWrapper
@Suppress("UNUSED_PARAMETER")
class PersonalFmActivity : AppCompatActivity(), SeekBar.OnSeekBarChangeListener {
private val compositeDisposable = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_personal_fm)
setSupportActionBar(toolbar)
toolbar.setNavigationOnClickListener {
onBackPressed()
}
seekBar.setOnSeekBarChangeListener(this)
startListenEvent()
lyricView.setOnPlayIndicatorClickListener {
MusicPlayerWrapper.seekToPosition(it.toLong())
}
lyricView.setOnClickListener {
if (lyricView.visibility == View.VISIBLE) {
changeMusicInfoState()
}
}
playerInfo.setOnClickListener {
changeMusicInfoState()
}
}
/**
* 显示歌词与显示歌曲图片相互切换
*/
private fun changeMusicInfoState(showLyric: Boolean = lyricView.visibility != View.VISIBLE) {
if (showLyric) {
lyricView.visibility = View.VISIBLE
imageArtwork.visibility = View.INVISIBLE
textArtist.visibility = View.INVISIBLE
textMusicName.visibility = View.INVISIBLE
} else {
lyricView.visibility = View.INVISIBLE
imageArtwork.visibility = View.VISIBLE
textArtist.visibility = View.VISIBLE
textMusicName.visibility = View.VISIBLE
}
}
private val currentPlayingMusic: Music?
get() = MusicPlayerWrapper.currentPlaying()
private val isPlaying: Boolean
get() = MusicPlayerWrapper.isPlaying()
private fun startListenEvent() {
RxBus.listen(FetchMusicErrorEvent::class.java)
.subscribe {
freezeViewState()
toast("出错 : ${it.throwable.message}")
it.throwable.printStackTrace()
}.addTo(compositeDisposable)
RxBus.listen(this, MusicPlayerEvent.OnPlayerStateChange::class) {
resetViewState()
setPlayingState(isPlaying)
setLikeState(currentPlayingMusic!!.isFavorite)
setMusicInfo(currentPlayingMusic)
setImage(currentPlayingMusic?.picUrl)
}.addTo(compositeDisposable)
RxBus.listen(OnMusicLikedEvent::class.java)
.subscribe { (music, liked) ->
if (currentPlayingMusic == music) {
setLikeState(liked)
}
}
RxBus.listen(this, MusicPlayerEvent.OnMusicProgressChangeEvent::class) {
setProgress(it.currentPosition, it.total)
}
// RxBus.listen<MusicPlayerEvent.OnMusicPrepareEvent> {
// setMusicInfo(it.music)
// setImage(it.music.picModel)
// //TODO setPrepareState
// setLikeState(it.music.isFavorite)
// currentPlayingMusic = it.music
// }
// RxBus.listen<NeteaseFmPlayerEvent.OnMusicPlayerErrorEvent> {
// setPlayingState(false)
// }.addTo(compositeDisposable)
}
override fun onDestroy() {
super.onDestroy()
compositeDisposable.clear()
}
fun onDeleteButtonClick(view: View) {
currentPlayingMusic?.let {
MusicPlayerWrapper.remove(it)
}
}
fun onLikeButtonClick(view: View) {
RxBus.publish(MusicPlayerEvent.Like(currentPlayingMusic))
}
fun onPlayButtonClick(view: View) {
RxBus.publish(MusicPlayerEvent.PlayPause())
}
fun onNextButtonClick(view: View) {
RxBus.publish(MusicPlayerEvent.PlayNext())
}
private fun setImage(model: Any?) {
model ?: return
//设置图片宽高上限.
val width = getScreenWidthHeight().first / 2
val target = GlideApp.with(this)
.asBitmap()
.load(model)
.submit(width, width)
//取得图片,进行高斯模糊,然后显示为背景
doAsync {
val bitmap = target.get() ?: return@doAsync
log("artWork :height :${bitmap.height} width : ${bitmap.width}")
uiThread { imageArtwork.setImageBitmap(bitmap) }
bitmap.blur(canReuseInBitmap = false).let { blued ->
uiThread { imageBackground.setImageBitmap(blued) }
}
}
}
private fun setPlayingState(isPlaying: Boolean) {
val indicator =
if (!isPlaying) R.drawable.ic_play_arrow_black_24dp
else R.drawable.ic_pause_black_24dp
buttonPlay.setImageResource(indicator)
}
private fun setLikeState(like: Boolean) {
if (like) {
buttonLike.setColorFilter(Color.RED)
} else {
buttonLike.setColorFilter(Color.WHITE)
}
}
private fun setCommentState(any: Any) {
toast("not implemented!")
}
private fun setMusicInfo(music: Music?) {
music ?: return
textMusicName.text = music.title
textArtist.text = music.artistString()
NeteaseCloudMusicApi.instance
.lyric(music.id)
.observeOn(AndroidSchedulers.mainThread())
.subscribeK {
onNext {
if (it.lrc.lyric != null) {
lyricView.setLyricText(it.lrc.lyric)
} else {
lyricView.setLyricError(string(R.string.netease_player_message_lyric_not_found))
}
}
onError {
lyricView.setLyricError(string(R.string.netease_error_can_not_fetch_lyric))
}
}
}
private fun setProgress(current: Long, total: Long) {
textCurrentPosition.text = current.toMusicTimeStamp()
textDuration.text = total.toMusicTimeStamp()
seekBar.max = total.toInt()
if (!isUserSeeking) {
seekBar.progress = current.toInt()
}
lyricView.scrollLyricTo(current.toInt())
}
private fun freezeViewState() {
buttonLike.isClickable = false
buttonPlay.setImageResource(R.drawable.ic_play_arrow_black_24dp)
buttonDelete.isClickable = false
buttonComment.isClickable = false
}
private fun resetViewState() {
buttonLike.isClickable = true
buttonDelete.isClickable = true
buttonComment.isClickable = true
}
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
}
private var isUserSeeking = false
override fun onStartTrackingTouch(seekBar: SeekBar) {
isUserSeeking = true
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
MusicPlayerWrapper.seekToPosition(seekBar.progress.toLong())
isUserSeeking = false
}
}
| app/src/main/java/tech/summerly/quiet/ui/activity/netease/PersonalFmActivity.kt | 2840922489 |
package test.assertk.assertions
import assertk.all
import assertk.assertAll
import assertk.assertThat
import assertk.assertions.*
import org.junit.Test
import java.time.LocalDate
import java.time.Month
import java.util.*
import kotlin.test.assertEquals
import kotlin.test.assertFails
internal class OptionalTest {
@Test fun isPresent_passes() {
assertThat(Optional.of("test")).isPresent()
}
@Test
fun isPresent_fails() {
val error = assertFails {
assertThat(Optional.empty<Any>()).isPresent()
}
assertEquals(
"expected optional to not be empty",
error.message
)
}
@Test fun isEmpty_passes() {
assertThat(Optional.empty<Any>()).isEmpty()
}
@Test fun isEmpty_fails() {
val error = assertFails {
assertThat(Optional.of("test")).isEmpty()
}
assertEquals(
"expected optional to be empty but was:<\"test\">",
error.message
)
}
@Test fun hasValue_passes() {
assertThat(Optional.of("test")).hasValue("test")
}
@Test fun hasValue_empty_fails() {
val error = assertFails {
assertThat(Optional.empty<String>()).hasValue("test")
}
assertEquals(
"expected optional to not be empty",
error.message
)
}
@Test fun hasValue_wrong_value_fails() {
val error = assertFails {
assertThat(Optional.of("test")).hasValue("wrong")
}
assertEquals(
"expected:<\"[wrong]\"> but was:<\"[test]\"> (Optional[test])",
error.message
)
}
@Test
fun test_envisioned_usage() {
// Data Access Logic - eg. Repository, DAO etc..
val personId = 1L
val personName = "person name"
val personDateCreated = LocalDate.of(2021, Month.JANUARY, 16)
val personStore = mapOf(
personId to Person(
id = personId,
name = personName,
dateCreated = personDateCreated
)
)
fun findPersonById(id: Long): Optional<Person> {
return Optional.ofNullable(personStore[id])
}
// Asserting against findPersonById in data access logic:
assertAll {
assertThat(findPersonById(0)).isEmpty()
assertThat(findPersonById(personId)).isPresent().all {
prop(Person::id).isEqualTo(personId)
prop(Person::name).isEqualTo(personName)
prop(Person::dateCreated).all {
isEqualTo(personDateCreated)
transform("dateCreated.year") { it.year }.isGreaterThan(2020)
}
}
}
}
private data class Person(val id: Long, val name: String, val dateCreated: LocalDate)
} | assertk/src/jvmTest/kotlin/test/assertk/assertions/OptionalTest.kt | 1957020410 |
@file:Suppress("unused")
package cn.yiiguxing.plugin.translate.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import com.intellij.uiDesigner.core.GridConstraints
import com.intellij.uiDesigner.core.GridLayoutManager
import com.intellij.util.ui.AnimatedIcon
import com.intellij.util.ui.JBUI
import java.awt.Insets
import javax.swing.JPanel
/**
* ProcessComponent
*/
class ProcessComponent(private val icon: AnimatedIcon, insets: Insets = JBUI.emptyInsets()) : JPanel(), Disposable {
val isRunning: Boolean get() = icon.isRunning
init {
isOpaque = false
layout = GridLayoutManager(1, 1, insets, 0, 0)
add(icon, GridConstraints().apply {
column = 0
hSizePolicy = GridConstraints.SIZEPOLICY_FIXED
vSizePolicy = GridConstraints.SIZEPOLICY_FIXED
anchor = GridConstraints.ANCHOR_CENTER
})
}
fun resume() = icon.resume()
fun suspend() = icon.suspend()
override fun dispose() {
Disposer.dispose(icon)
}
}
| src/main/kotlin/cn/yiiguxing/plugin/translate/ui/ProcessComponent.kt | 2107764777 |
package com.fuyoul.sanwenseller.structure.presenter
import android.app.Activity
import android.content.Context
import android.util.Log
import com.alibaba.fastjson.JSON
import com.fuyoul.sanwenseller.base.BaseP
import com.fuyoul.sanwenseller.bean.reqhttp.ReqEditUserInfo
import com.fuyoul.sanwenseller.bean.reshttp.ResHttpResult
import com.fuyoul.sanwenseller.bean.reshttp.ResLoginInfoBean
import com.fuyoul.sanwenseller.bean.reshttp.ResQiNiuBean
import com.fuyoul.sanwenseller.configs.UrlInfo.EDITUSERINFO
import com.fuyoul.sanwenseller.helper.HttpDialogHelper
import com.fuyoul.sanwenseller.helper.MsgDialogHelper
import com.fuyoul.sanwenseller.helper.QiNiuHelper
import com.fuyoul.sanwenseller.listener.HttpReqListener
import com.fuyoul.sanwenseller.listener.QiNiuUpLoadListener
import com.fuyoul.sanwenseller.structure.model.EditUserInfoM
import com.fuyoul.sanwenseller.structure.view.EditUserInfoV
import com.fuyoul.sanwenseller.utils.NormalFunUtils
import com.lzy.okgo.OkGo
import org.litepal.crud.DataSupport
/**
* @author: chen
* @CreatDate: 2017\10\28 0028
* @Desc:
*/
class EditUserInfoP(editUserInfoV: EditUserInfoV) : BaseP<EditUserInfoM, EditUserInfoV>(editUserInfoV) {
override fun getModelImpl(): EditUserInfoM = EditUserInfoM()
fun upInfo(activity: Activity, info: ResLoginInfoBean) {
HttpDialogHelper.showDialog(activity, true, false)
//如果是本地图片,先上传到七牛
if (info.avatar != null && !info.avatar.startsWith("http")) {
val imgs = ArrayList<String>()
imgs.add(info.avatar)
QiNiuHelper.multQiNiuUpLoad(activity, imgs, object : QiNiuUpLoadListener {
override fun complete(path: List<ResQiNiuBean>) {
doReq(activity, info, path[0].key)
}
override fun error(error: String) {
HttpDialogHelper.dismisss()
NormalFunUtils.showToast(activity, error)
}
})
} else {
doReq(activity, info, null)
}
}
private fun doReq(activity: Activity, info: ResLoginInfoBean, avatar: String?) {
val data = ReqEditUserInfo()
data.avatar = avatar ?: info.avatar
data.nickname = info.nickname
data.gender = info.gender
data.provinces = info.provinces
data.city = info.city
data.selfExp = info.selfExp
data.selfInfo = info.selfInfo
Log.e("csl", "更新个人资料:${JSON.toJSONString(data)}")
OkGo.post<ResHttpResult>(EDITUSERINFO)
.upJson(JSON.toJSONString(data))
.execute(object : HttpReqListener(activity) {
override fun reqOk(result: ResHttpResult) {
val backInfo = JSON.parseObject(result.data.toString(), ResLoginInfoBean::class.java)
backInfo.updateAll()
MsgDialogHelper.showStateDialog(activity, "资料更新成功", true, object : MsgDialogHelper.DialogOndismissListener {
override fun onDismiss(context: Context) {
activity.setResult(Activity.RESULT_OK)
activity.finish()
}
})
}
override fun withoutData(code: Int, msg: String) {
NormalFunUtils.showToast(activity, msg)
}
override fun error(errorInfo: String) {
NormalFunUtils.showToast(activity, errorInfo)
}
})
}
} | app/src/main/java/com/fuyoul/sanwenseller/structure/presenter/EditUserInfoP.kt | 377275054 |
package cn.yiiguxing.plugin.translate.diagnostic.github
class TranslationGitHubAppException(
override val message: String,
cause: Throwable? = null
) : Exception(message, cause) | src/main/kotlin/cn/yiiguxing/plugin/translate/diagnostic/github/TranslationGitHubAppException.kt | 2270133091 |
/*
*
* * Copyright (C) 2018 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.background
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.util.Log
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SdkSuppress
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import androidx.work.Configuration
import androidx.work.WorkManager
import androidx.work.testing.SynchronousExecutor
import androidx.work.testing.WorkManagerTestInitHelper
import com.example.background.Constants.KEY_IMAGE_URI
import com.example.background.Constants.TAG_OUTPUT
import com.example.background.workers.BaseFilterWorker
import com.example.background.workers.BaseFilterWorker.Companion.inputStreamFor
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@RunWith(AndroidJUnit4::class)
@SmallTest
class ImageOperationsTest {
companion object {
// Maximum wait time for a test.
private const val TEST_TIMEOUT = 5L
// Making the input image to the ImageOperationsBuilder look like a URI.
// However the underlying image is loaded using AssetManager. For more information
// look at BaseFilterWorker#inputStreamFor(...).
private const val JETPACK = "${BaseFilterWorker.ASSET_PREFIX}images/jetpack.png"
private const val JETPACK_GRAYSCALED =
"${BaseFilterWorker.ASSET_PREFIX}test_outputs/grayscale.png"
private val IMAGE = Uri.parse(JETPACK)
private val IMAGE_GRAYSCALE = Uri.parse(JETPACK_GRAYSCALED) // grayscale
private val DEFAULT_IMAGE_URI = Uri.EMPTY.toString()
}
private lateinit var mContext: Context
private lateinit var mTargetContext: Context
private lateinit var mLifeCycleOwner: LifecycleOwner
private lateinit var mConfiguration: Configuration
private var mWorkManager: WorkManager? = null
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp() {
mContext = InstrumentationRegistry.getInstrumentation().context
mTargetContext = InstrumentationRegistry.getInstrumentation().targetContext
mLifeCycleOwner = TestLifeCycleOwner()
mConfiguration = Configuration.Builder()
.setExecutor(SynchronousExecutor())
.setMinimumLoggingLevel(Log.DEBUG)
.build()
// Initialize WorkManager using the WorkManagerTestInitHelper.
WorkManagerTestInitHelper.initializeTestWorkManager(mTargetContext, mConfiguration)
mWorkManager = WorkManager.getInstance(mTargetContext)
}
@Test
fun testImageOperations() {
val imageOperations = ImageOperations.Builder(mTargetContext, IMAGE)
.setApplyGrayScale(true)
.build()
imageOperations.continuation
.enqueue()
.result
.get()
val latch = CountDownLatch(1)
val outputs: MutableList<Uri> = mutableListOf()
imageOperations.continuation.workInfosLiveData.observe(mLifeCycleOwner, Observer { workInfos ->
val statuses = workInfos ?: return@Observer
val finished = statuses.all { it.state.isFinished }
if (finished) {
val outputUris = statuses.map {
val output = it.outputData.getString(KEY_IMAGE_URI) ?: DEFAULT_IMAGE_URI
Uri.parse(output)
}.filter {
it != Uri.EMPTY
}
outputs.addAll(outputUris)
latch.countDown()
}
})
assertTrue(latch.await(TEST_TIMEOUT, TimeUnit.SECONDS))
assertEquals(outputs.size, 1)
assertTrue(sameBitmaps(outputs[0], IMAGE_GRAYSCALE))
}
@Test
@SdkSuppress(maxSdkVersion = 22)
fun testImageOperationsChain() {
val imageOperations = ImageOperations.Builder(mTargetContext, IMAGE)
.setApplyWaterColor(true)
.setApplyGrayScale(true)
.setApplyBlur(true)
.setApplySave(true)
.build()
imageOperations.continuation
.enqueue()
.result
.get()
val latch = CountDownLatch(2)
val outputs: MutableList<Uri> = mutableListOf()
imageOperations.continuation.workInfosLiveData.observe(mLifeCycleOwner, Observer { workInfos ->
val statuses = workInfos ?: return@Observer
val finished = statuses.all { it.state.isFinished }
if (finished) {
val outputUris = statuses.map {
val output = it.outputData.getString(KEY_IMAGE_URI) ?: DEFAULT_IMAGE_URI
Uri.parse(output)
}.filter {
it != Uri.EMPTY
}
outputs.addAll(outputUris)
latch.countDown()
}
})
var outputUri: Uri? = null
mWorkManager?.getWorkInfosByTagLiveData(TAG_OUTPUT)?.observe(mLifeCycleOwner, Observer { workInfos ->
val statuses = workInfos ?: return@Observer
val finished = statuses.all { it.state.isFinished }
if (finished) {
outputUri =
statuses.firstOrNull()
?.outputData?.getString(KEY_IMAGE_URI)
?.let { Uri.parse(it) }
latch.countDown()
}
})
assertTrue(latch.await(TEST_TIMEOUT, TimeUnit.SECONDS))
assertEquals(outputs.size, 4)
assertNotNull(outputUri)
}
private fun sameBitmaps(outputUri: Uri, compareWith: Uri): Boolean {
val outputBitmap: Bitmap = BitmapFactory.decodeStream(
inputStreamFor(mContext, outputUri.toString()))
val compareBitmap: Bitmap = BitmapFactory.decodeStream(
inputStreamFor(mContext, compareWith.toString()))
return outputBitmap.sameAs(compareBitmap)
}
}
| WorkManager/app/src/androidTest/java/com/example/background/ImageOperationsTest.kt | 2789098533 |
package app.cash.inject.inflation.processor
import app.cash.inject.inflation.processor.internal.applyEach
import app.cash.inject.inflation.processor.internal.joinToCode
import app.cash.inject.inflation.processor.internal.peerClassWithReflectionNesting
import app.cash.inject.inflation.processor.internal.rawClassName
import com.squareup.javapoet.AnnotationSpec
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import com.squareup.javapoet.TypeVariableName
import javax.lang.model.element.Modifier.FINAL
import javax.lang.model.element.Modifier.PRIVATE
import javax.lang.model.element.Modifier.PUBLIC
private val JAVAX_INJECT = ClassName.get("javax.inject", "Inject")
internal val JAVAX_PROVIDER = ClassName.get("javax.inject", "Provider")
/** The structure of an assisted injection factory. */
data class AssistedInjection(
/** The type which will be instantiated inside the factory. */
val targetType: TypeName,
/** TODO */
val dependencyRequests: List<DependencyRequest>,
/** The factory interface type. */
val factoryType: TypeName,
/** Name of the factory's only method. */
val factoryMethod: String,
/** The factory method return type. [targetType] must be assignable to this type. */
val returnType: TypeName = targetType,
/**
* The factory method keys. These default to the keys of the assisted [dependencyRequests]
* and when supplied must always match them, but the order is allowed to be different.
*/
val assistedKeys: List<Key> = dependencyRequests.filter { it.isAssisted }.map { it.key },
/** An optional `@Generated` annotation marker. */
val generatedAnnotation: AnnotationSpec? = null
) {
private val keyToRequest = dependencyRequests.filter { it.isAssisted }.associateBy { it.key }
init {
check(keyToRequest.keys == assistedKeys.toSet()) {
"""
assistedKeys must contain the same elements as the assisted dependencyRequests.
* assistedKeys:
$assistedKeys
* assisted dependencyRequests:
${keyToRequest.keys}
""".trimIndent()
}
}
/** The type generated from [brewJava]. */
val generatedType = targetType.rawClassName().assistedInjectFactoryName()
private val providedKeys = dependencyRequests.filterNot { it.isAssisted }
fun brewJava(): TypeSpec {
return TypeSpec.classBuilder(generatedType)
.addModifiers(PUBLIC, FINAL)
.addSuperinterface(factoryType)
.apply {
if (generatedAnnotation != null) {
addAnnotation(generatedAnnotation)
}
}
.applyEach(providedKeys) {
addField(it.providerType.withoutAnnotations(), it.name, PRIVATE, FINAL)
}
.addMethod(MethodSpec.constructorBuilder()
.addModifiers(PUBLIC)
.addAnnotation(JAVAX_INJECT)
.applyEach(providedKeys) {
addParameter(it.providerType, it.name)
addStatement("this.$1N = $1N", it.name)
}
.build())
.addMethod(MethodSpec.methodBuilder(factoryMethod)
.addAnnotation(Override::class.java)
.addModifiers(PUBLIC)
.returns(returnType)
.apply {
if (targetType is ParameterizedTypeName) {
addTypeVariables(targetType.typeArguments.filterIsInstance<TypeVariableName>())
}
}
.applyEach(assistedKeys) { key ->
val parameterName = keyToRequest.getValue(key).name
addParameter(key.type, parameterName)
}
.addStatement("return new \$T(\n\$L)", targetType,
dependencyRequests.map { it.argumentProvider }.joinToCode(",\n"))
.build())
.build()
}
}
private val DependencyRequest.providerType: TypeName
get() {
val type = if (key.useProvider) {
ParameterizedTypeName.get(JAVAX_PROVIDER, key.type.box())
} else {
key.type
}
key.qualifier?.let {
return type.annotated(it)
}
return type
}
private val DependencyRequest.argumentProvider
get() = CodeBlock.of(if (isAssisted || !key.useProvider) "\$N" else "\$N.get()", name)
fun ClassName.assistedInjectFactoryName(): ClassName =
peerClassWithReflectionNesting(simpleName() + "_InflationFactory")
| inflation-inject-processor/src/main/java/app/cash/inject/inflation/processor/AssistedInjection.kt | 1945670462 |
// DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2016 Konrad Jamrozik
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// email: [email protected]
// web: www.droidmate.org
package org.droidmate.report
import com.google.common.jimfs.Jimfs
import java.nio.file.FileSystem
fun mockFs(): FileSystem = Jimfs.newFileSystem(com.google.common.jimfs.Configuration.unix()) | dev/droidmate/projects/reporter/src/test/kotlin/org/droidmate/report/functions_for_testing.kt | 1411047399 |
package com.blankj.utilcode.pkg.feature
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import com.blankj.common.activity.CommonActivity
import com.blankj.common.item.CommonItem
import com.blankj.common.item.CommonItemClick
import com.blankj.utilcode.pkg.R
import com.blankj.utilcode.pkg.feature.activity.ActivityActivity
import com.blankj.utilcode.pkg.feature.adaptScreen.AdaptScreenActivity
import com.blankj.utilcode.pkg.feature.api.ApiActivity
import com.blankj.utilcode.pkg.feature.app.AppActivity
import com.blankj.utilcode.pkg.feature.bar.BarActivity
import com.blankj.utilcode.pkg.feature.brightness.BrightnessActivity
import com.blankj.utilcode.pkg.feature.bus.BusActivity
import com.blankj.utilcode.pkg.feature.clean.CleanActivity
import com.blankj.utilcode.pkg.feature.click.ClickActivity
import com.blankj.utilcode.pkg.feature.clipboard.ClipboardActivity
import com.blankj.utilcode.pkg.feature.device.DeviceActivity
import com.blankj.utilcode.pkg.feature.file.FileActivity
import com.blankj.utilcode.pkg.feature.flashlight.FlashlightActivity
import com.blankj.utilcode.pkg.feature.fragment.FragmentActivity
import com.blankj.utilcode.pkg.feature.image.ImageActivity
import com.blankj.utilcode.pkg.feature.intent.IntentActivity
import com.blankj.utilcode.pkg.feature.keyboard.KeyboardActivity
import com.blankj.utilcode.pkg.feature.language.LanguageActivity
import com.blankj.utilcode.pkg.feature.log.LogActivity
import com.blankj.utilcode.pkg.feature.messenger.MessengerActivity
import com.blankj.utilcode.pkg.feature.metaData.MetaDataActivity
import com.blankj.utilcode.pkg.feature.mvp.MvpActivity
import com.blankj.utilcode.pkg.feature.network.NetworkActivity
import com.blankj.utilcode.pkg.feature.notification.NotificationActivity
import com.blankj.utilcode.pkg.feature.path.PathActivity
import com.blankj.utilcode.pkg.feature.permission.PermissionActivity
import com.blankj.utilcode.pkg.feature.phone.PhoneActivity
import com.blankj.utilcode.pkg.feature.process.ProcessActivity
import com.blankj.utilcode.pkg.feature.reflect.ReflectActivity
import com.blankj.utilcode.pkg.feature.resource.ResourceActivity
import com.blankj.utilcode.pkg.feature.rom.RomActivity
import com.blankj.utilcode.pkg.feature.screen.ScreenActivity
import com.blankj.utilcode.pkg.feature.sdcard.SDCardActivity
import com.blankj.utilcode.pkg.feature.shadow.ShadowActivity
import com.blankj.utilcode.pkg.feature.snackbar.SnackbarActivity
import com.blankj.utilcode.pkg.feature.spStatic.SPStaticActivity
import com.blankj.utilcode.pkg.feature.span.SpanActivity
import com.blankj.utilcode.pkg.feature.toast.ToastActivity
import com.blankj.utilcode.pkg.feature.uiMessage.UiMessageActivity
import com.blankj.utilcode.pkg.feature.vibrate.VibrateActivity
import com.blankj.utilcode.pkg.feature.volume.VolumeActivity
import com.blankj.utilcode.pkg.helper.DialogHelper
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.UtilsTransActivity
/**
* ```
* author: Blankj
* blog : http://blankj.com
* time : 2016/09/29
* desc :
* ```
*/
class CoreUtilActivity : CommonActivity() {
companion object {
fun start(context: Context) {
val starter = Intent(context, CoreUtilActivity::class.java)
context.startActivity(starter)
}
}
override fun bindTitleRes(): Int {
return R.string.core_util
}
override fun bindItems(): MutableList<CommonItem<*>> {
return CollectionUtils.newArrayList(
CommonItemClick(R.string.demo_activity, true) {
ActivityActivity.start(this)
ThreadUtils.runOnUiThreadDelayed(Runnable {
}, 2000)
},
CommonItemClick(R.string.demo_adapt_screen, true) {
AdaptScreenActivity.start(this)
},
CommonItemClick(R.string.demo_api, true) {
ApiActivity.start(this)
},
CommonItemClick(R.string.demo_app, true) {
AppActivity.start(this)
},
CommonItemClick(R.string.demo_bar, true) {
BarActivity.start(this)
},
CommonItemClick(R.string.demo_brightness, true) {
BrightnessActivity.start(this)
},
CommonItemClick(R.string.demo_bus, true) {
BusActivity.start(this)
},
CommonItemClick(R.string.demo_clean, true) {
CleanActivity.start(this)
},
CommonItemClick(R.string.demo_click, true) {
ClickActivity.start(this)
},
CommonItemClick(R.string.demo_clipboard, true) {
ClipboardActivity.start(this)
},
CommonItemClick(R.string.demo_crash) {
throw NullPointerException("crash test")
},
CommonItemClick(R.string.demo_device, true) {
DeviceActivity.start(this)
},
CommonItemClick(R.string.demo_file, true) {
FileActivity.start(this)
},
CommonItemClick(R.string.demo_flashlight, true) {
FlashlightActivity.start(this)
},
CommonItemClick(R.string.demo_fragment, true) {
FragmentActivity.start(this)
},
CommonItemClick(R.string.demo_image, true) {
ImageActivity.start(this)
},
CommonItemClick(R.string.demo_intent, true) {
IntentActivity.start(this)
},
CommonItemClick(R.string.demo_keyboard, true) {
KeyboardActivity.start(this)
},
CommonItemClick(R.string.demo_language, true) {
LanguageActivity.start(this)
},
CommonItemClick(R.string.demo_log, true) {
LogActivity.start(this)
},
CommonItemClick(R.string.demo_messenger, true) {
MessengerActivity.start(this)
},
CommonItemClick(R.string.demo_meta_data, true) {
MetaDataActivity.start(this)
},
CommonItemClick(R.string.demo_mvp, true) {
MvpActivity.start(this)
},
CommonItemClick(R.string.demo_network, true) {
NetworkActivity.start(this)
},
CommonItemClick(R.string.demo_notification, true) {
NotificationActivity.start(this)
},
CommonItemClick(R.string.demo_path, true) {
PathActivity.start(this)
},
CommonItemClick(R.string.demo_permission, true) {
PermissionActivity.start(this)
},
CommonItemClick(R.string.demo_phone, true) {
PhoneActivity.start(this)
},
CommonItemClick(R.string.demo_process, true) {
ProcessActivity.start(this)
},
CommonItemClick(R.string.demo_reflect, true) {
ReflectActivity.start(this)
},
CommonItemClick(R.string.demo_resource, true) {
ResourceActivity.start(this)
},
CommonItemClick(R.string.demo_rom, true) {
RomActivity.start(this)
},
CommonItemClick(R.string.demo_screen, true) {
ScreenActivity.start(this)
},
CommonItemClick(R.string.demo_sdcard, true) {
SDCardActivity.start(this)
},
CommonItemClick(R.string.demo_shadow, true) {
ShadowActivity.start(this)
},
CommonItemClick(R.string.demo_snackbar, true) {
SnackbarActivity.start(this)
},
CommonItemClick(R.string.demo_spStatic, true) {
SPStaticActivity.start(this)
},
CommonItemClick(R.string.demo_span, true) {
SpanActivity.start(this)
},
CommonItemClick(R.string.demo_toast, true) {
ToastActivity.start(this)
},
CommonItemClick(R.string.demo_trans_activity, true) {
UtilsTransActivity.start(this, object : UtilsTransActivity.TransActivityDelegate() {
override fun onCreated(activity: UtilsTransActivity, savedInstanceState: Bundle?) {
super.onCreated(activity, savedInstanceState)
activity.setContentView(R.layout.common_dialog_loading)
activity.findViewById<TextView>(R.id.utilActionLoadingMsgTv).text = "Trans Activity is showing..."
}
})
},
CommonItemClick(R.string.demo_uiMessage, true) {
UiMessageActivity.start(this)
},
CommonItemClick(R.string.demo_vibrate, true) {
VibrateActivity.start(this)
},
CommonItemClick(R.string.demo_volume, true) {
VolumeActivity.start(this)
}
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
LogUtils.e(requestCode, requestCode)
}
}
| feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/CoreUtilActivity.kt | 3000947938 |
package sst.com.anouncements.feed.model
import android.os.Parcelable
import android.text.format.DateUtils
import kotlinx.android.parcel.Parcelize
import org.apache.commons.text.StringEscapeUtils
import java.text.SimpleDateFormat
import java.util.*
@Parcelize
data class Entry(
val id: String,
val publishedDate: Date,
val updatedDate: Date,
val authorName: String,
val url: String,
val title: String,
val content: String
) : Parcelable {
val relativePublishedDate: String by lazy { relativeDate(publishedDate) }
val contentWithoutHTML: String by lazy {
// Remove any content in style tags
var content = this.content.replace("<style[^>]*>.*</style>".toRegex(), "")
// Remove HTML tags
content = content.replace("<[^>]*>".toRegex(), "")
// Unescape characters, e.g. converting < to <
StringEscapeUtils.unescapeHtml4(content).trim()
}
private fun relativeDate(date: Date): String {
return DateUtils.getRelativeTimeSpanString(date.time).toString()
}
override fun equals(other: Any?) =
other is Entry &&
id == other.id &&
updatedDate.compareTo(other.updatedDate) == 0
override fun hashCode() = (id + updatedDate).hashCode()
} | sstannouncer/app/src/main/java/sst/com/anouncements/feed/model/Entry.kt | 378808662 |
package org.owntracks.android.ui.preferences
import android.os.Bundle
import dagger.hilt.android.AndroidEntryPoint
import org.owntracks.android.R
import javax.inject.Inject
@AndroidEntryPoint
class MapFragment @Inject constructor() : AbstractPreferenceFragment() {
override fun onCreatePreferencesFix(savedInstanceState: Bundle?, rootKey: String?) {
super.onCreatePreferencesFix(savedInstanceState, rootKey)
setPreferencesFromResource(R.xml.preferences_map, rootKey)
}
}
| project/app/src/main/java/org/owntracks/android/ui/preferences/MapFragment.kt | 2729569870 |
package de.maibornwolff.codecharta.importer.sourcemonitor
import de.maibornwolff.codecharta.importer.csv.CSVProjectBuilder
import de.maibornwolff.codecharta.serialization.ProjectSerializer
import de.maibornwolff.codecharta.tools.interactiveparser.InteractiveParser
import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface
import de.maibornwolff.codecharta.translator.MetricNameTranslator
import picocli.CommandLine
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.PrintStream
import java.util.concurrent.Callable
@CommandLine.Command(
name = "sourcemonitorimport",
description = ["generates cc.json from sourcemonitor csv"],
footer = ["Copyright(c) 2020, MaibornWolff GmbH"]
)
class SourceMonitorImporter(
private val output: PrintStream = System.out
) : Callable<Void>, InteractiveParser {
@CommandLine.Option(names = ["-h", "--help"], usageHelp = true, description = ["displays this help and exits"])
private var help = false
@CommandLine.Option(names = ["-nc", "--not-compressed"], description = ["save uncompressed output File"])
private var compress = true
@CommandLine.Option(names = ["-o", "--output-file"], description = ["output File"])
private var outputFile: String? = null
@CommandLine.Parameters(arity = "1..*", paramLabel = "FILE", description = ["sourcemonitor csv files"])
private var files: List<File> = mutableListOf()
private val pathSeparator = '\\'
private val csvDelimiter = ','
@Throws(IOException::class)
override fun call(): Void? {
val csvProjectBuilder =
CSVProjectBuilder(pathSeparator, csvDelimiter, "File Name", sourceMonitorReplacement, getAttributeDescriptors())
files.map { it.inputStream() }.forEach<InputStream> { csvProjectBuilder.parseCSVStream(it) }
val project = csvProjectBuilder.build(true)
ProjectSerializer.serializeToFileOrStream(project, outputFile, output, compress)
return null
}
private val sourceMonitorReplacement: MetricNameTranslator
get() {
val prefix = "sm_"
val replacementMap = mutableMapOf<String, String>()
replacementMap["Project Name"] = ""
replacementMap["Checkpoint Name"] = ""
replacementMap["Created On"] = ""
replacementMap["Lines"] = "loc"
replacementMap["Statements"] = "statements"
replacementMap["Classes and Interfaces"] = "classes"
replacementMap["Methods per Class"] = "functions_per_class"
replacementMap["Average Statements per Method"] = "average_statements_per_function"
replacementMap["Line Number of Most Complex Method*"] = ""
replacementMap["Name of Most Complex Method*"] = ""
replacementMap["Maximum Complexity*"] = "max_function_mcc"
replacementMap["Line Number of Deepest Block"] = ""
replacementMap["Maximum Block Depth"] = "max_block_depth"
replacementMap["Average Block Depth"] = "average_block_depth"
replacementMap["Average Complexity*"] = "average_function_mcc"
for (i in 0..9) {
replacementMap["Statements at block level $i"] = "statements_at_level_$i"
}
return MetricNameTranslator(replacementMap.toMap(), prefix)
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
CommandLine(SourceMonitorImporter()).execute(*args)
}
}
override fun getDialog(): ParserDialogInterface = ParserDialog
}
| analysis/import/CSVImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/sourcemonitor/SourceMonitorImporter.kt | 2938262626 |
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.morse
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.common.utils.text.MorseUtils
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.declarations.MorseCommand
class MorseToExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val textArgument = string("text", MorseCommand.I18N_PREFIX.Options.FromTextToMorse)
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
val text = args[options.textArgument]
when (val toMorseResult = MorseUtils.toMorse(text)) {
is MorseUtils.ValidToMorseConversionResult -> {
val toMorse = toMorseResult.morse
val unknownCharacters = toMorseResult.unknownCharacters
context.sendMessage {
styled(
content = "`$toMorse`",
prefix = Emotes.Radio.toString()
)
if (unknownCharacters.isNotEmpty()) {
styled(
content = context.i18nContext.get(
MorseCommand.I18N_PREFIX.ToMorseWarningUnknownCharacters(
unknownCharacters.joinToString("")
)
),
prefix = Emotes.LoriSob
)
}
}
}
is MorseUtils.InvalidToMorseConversionResult -> {
context.failEphemerally(
prefix = Emotes.Error.asMention,
content = context.i18nContext.get(
MorseCommand.I18N_PREFIX.ToMorseFailUnknownCharacters
)
)
}
}
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/morse/MorseToExecutor.kt | 4233220551 |
package com.ghstudios.android.features.wishlist.list
import android.app.Activity
import androidx.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.ItemTouchHelper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import com.ghstudios.android.ClickListeners.WishlistClickListener
import com.ghstudios.android.RecyclerViewFragment
import com.ghstudios.android.adapter.common.SimpleDiffRecyclerViewAdapter
import com.ghstudios.android.adapter.common.SimpleViewHolder
import com.ghstudios.android.adapter.common.SwipeReorderTouchHelper
import com.ghstudios.android.data.classes.Wishlist
import com.ghstudios.android.features.wishlist.detail.WishlistRenameDialogFragment
import com.ghstudios.android.mhgendatabase.R
import com.ghstudios.android.util.createSnackbarWithUndo
/** Adapter used to render wishlists in a recyclerview */
class WishlistAdapter: SimpleDiffRecyclerViewAdapter<Wishlist>() {
override fun areItemsTheSame(oldItem: Wishlist, newItem: Wishlist): Boolean {
return oldItem.id == newItem.id
}
override fun onCreateView(parent: ViewGroup): View {
val inflater = LayoutInflater.from(parent.context)
return inflater.inflate(R.layout.fragment_wishlistmain_listitem, parent, false)
}
override fun bindView(viewHolder: SimpleViewHolder, data: Wishlist) {
val view = viewHolder.itemView
val wishlist = data
// Set up the views
val itemLayout = view.findViewById<View>(R.id.listitem) as LinearLayout
val wishlistNameTextView = view.findViewById<View>(R.id.item_name) as TextView
view.findViewById<View>(R.id.item_image).visibility = View.GONE
// Bind views
val cellText = wishlist.name
wishlistNameTextView.text = cellText
// Assign view tag and listeners
view.tag = wishlist.id
itemLayout.tag = wishlist.id
itemLayout.setOnClickListener(WishlistClickListener(viewHolder.context, wishlist.id))
}
}
/**
* Fragment used to display and manage a collection of wishlists
*/
class WishlistListFragment : RecyclerViewFragment() {
companion object {
const val DIALOG_WISHLIST_ADD = "wishlist_add"
const val DIALOG_WISHLIST_COPY = "wishlist_copy"
const val DIALOG_WISHLIST_DELETE = "wishlist_delete"
const val DIALOG_WISHLIST_RENAME = "wishlist_rename"
const val REQUEST_ADD = 0
const val REQUEST_RENAME = 1
const val REQUEST_COPY = 2
const val REQUEST_DELETE = 3
}
val viewModel by lazy {
ViewModelProvider(this).get(WishlistListViewModel::class.java)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
enableDivider()
enableFab {
showAddDialog()
}
val adapter = WishlistAdapter()
setAdapter(adapter)
val handler = ItemTouchHelper(SwipeReorderTouchHelper(
afterSwiped = {
val wishlistId = it.itemView.tag as Long
val message = getString(R.string.wishlist_deleted)
val operation = viewModel.startDeleteWishlist(wishlistId)
val containerView = view.findViewById<ViewGroup>(R.id.recyclerview_container_main)
containerView.createSnackbarWithUndo(message, operation)
}
))
handler.attachToRecyclerView(recyclerView)
viewModel.wishlistData.observe(viewLifecycleOwner, Observer {
if (it == null) return@Observer
adapter.setItems(it)
showEmptyView(show = it.isEmpty())
})
}
private fun showAddDialog() {
val dialog = WishlistAddDialogFragment()
dialog.setTargetFragment(this@WishlistListFragment, REQUEST_ADD)
dialog.show(parentFragmentManager, DIALOG_WISHLIST_ADD)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode != Activity.RESULT_OK) return
if (requestCode == REQUEST_ADD) {
if (data!!.getBooleanExtra(WishlistAddDialogFragment.EXTRA_ADD, false)) {
updateUI()
}
} else if (requestCode == REQUEST_RENAME) { // not used here
if (data!!.getBooleanExtra(WishlistRenameDialogFragment.EXTRA_RENAME, false)) {
updateUI()
}
} else if (requestCode == REQUEST_COPY) { // might be used here
if (data!!.getBooleanExtra(WishlistCopyDialogFragment.EXTRA_COPY, false)) {
updateUI()
}
}
}
override fun onResume() {
super.onResume()
// Check for dataset changes when the activity is resumed.
// Not the best practice but the list will always be small.
viewModel.reload()
}
private fun updateUI() {
viewModel.reload()
}
}
| app/src/main/java/com/ghstudios/android/features/wishlist/list/WishlistListFragment.kt | 302855562 |
package com.pinterest.ktlint.internal
import com.pinterest.ktlint.KtlintCommandLine
import com.pinterest.ktlint.core.KtLint
import com.pinterest.ktlint.core.api.FeatureInAlphaState
import picocli.CommandLine
@CommandLine.Command(
description = [
"EXPERIMENTAL!!! Generate kotlin style section for '.editorconfig' file.",
"Add output content into '.editorconfig' file"
],
mixinStandardHelpOptions = true,
versionProvider = KtlintVersionProvider::class
)
class GenerateEditorConfigSubCommand : Runnable {
@CommandLine.ParentCommand
private lateinit var ktlintCommand: KtlintCommandLine
@CommandLine.Spec
private lateinit var commandSpec: CommandLine.Model.CommandSpec
@OptIn(FeatureInAlphaState::class)
override fun run() {
commandSpec.commandLine().printHelpOrVersionUsage()
// For now we are using CLI invocation dir as path to load existing '.editorconfig'
val generatedEditorConfig = KtLint.generateKotlinEditorConfigSection(
KtLint.ExperimentalParams(
fileName = "./test.kt",
text = "",
ruleSets = ktlintCommand.rulesets
.loadRulesets(
ktlintCommand.experimental,
ktlintCommand.debug,
ktlintCommand.disabledRules
)
.map { it.value.get() },
userData = mapOf(
"android" to ktlintCommand.android.toString()
),
debug = ktlintCommand.debug,
cb = { _, _ -> Unit }
)
)
if (generatedEditorConfig.isNotBlank()) {
println(
"""
[*.{kt,kts}]
$generatedEditorConfig
""".trimIndent()
)
} else {
println("Nothing to add to .editorconfig file")
}
}
companion object {
internal const val COMMAND_NAME = "generateEditorConfig"
}
}
| ktlint/src/main/kotlin/com/pinterest/ktlint/internal/GenerateEditorConfigSubCommand.kt | 1042733265 |
package mogul.kobx
// Stuff currently missing in Kotlin Native
public inline fun <T> T.takeUnless(predicate: (T) -> Boolean): T? = if (!predicate(this)) this else null
| native/src/mogul/kobx/NativeExtra.kt | 3779488609 |
package net.yested.core.utils
import org.w3c.dom.HTMLElement
interface Effect {
fun apply(htmlElement: HTMLElement, callback: Function0<Unit>? = null)
}
object NoEffect : Effect, BiDirectionEffect {
override fun apply(htmlElement: HTMLElement, callback: (() -> Unit)?) {
callback?.invoke()
}
override fun applyIn(htmlElement: HTMLElement, callback: (() -> Unit)?) {
callback?.invoke()
}
override fun applyOut(htmlElement: HTMLElement, callback: (() -> Unit)?) {
callback?.invoke()
}
}
/**
* @param effectIn the effect to make the element come in to view (aka appear).
* @param effectOut the effect to make the element go out of view (aka disappear).
*/
open class SimpleBiDirectionEffect(val effectIn: Effect, val effectOut: Effect): BiDirectionEffect {
override fun applyIn(htmlElement: HTMLElement, callback: (() -> Unit)?) {
effectIn.apply(htmlElement, callback)
}
override fun applyOut(htmlElement: HTMLElement, callback: (() -> Unit)?) {
effectOut.apply(htmlElement, callback)
}
}
interface BiDirectionEffect {
fun applyIn(htmlElement: HTMLElement, callback: Function0<Unit>? = null)
fun applyOut(htmlElement: HTMLElement, callback: Function0<Unit>? = null)
}
| src/jsMain/kotlin/net/yested/core/utils/htmleffects.kt | 2540053404 |
// Generated from "com/google/j2cl/benchmarks/octane/richards/Task.java"
package com.google.j2cl.benchmarks.octane.richards
import javaemul.lang.*
import kotlin.jvm.*
fun interface Task {
fun run(packet: com.google.j2cl.benchmarks.octane.richards.Packet?): com.google.j2cl.benchmarks.octane.richards.TaskControlBlock?
}
| kmpbench/gencode_snapshot/octane/richards/Task.kt | 2806181317 |
/*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* 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.vanniktech.emoji.search
/**
* Interface for providing some custom implementation for searching emojis.
*
* @since 0.10.0
*/
interface SearchEmoji {
/**
* Return the emojis that match your search algorithm for the given query as a list of [SearchEmojiResult].
*
* @since 0.10.0
*/
fun search(query: String): List<SearchEmojiResult>
}
| emoji/src/commonMain/kotlin/com/vanniktech/emoji/search/SearchEmoji.kt | 1964323647 |
package uk.co.appsbystudio.geoshare.friends.manager.pages.current
interface FriendsPresenter {
fun friends()
fun removeFriend(uid: String)
fun stop()
} | mobile/src/main/java/uk/co/appsbystudio/geoshare/friends/manager/pages/current/FriendsPresenter.kt | 3495066340 |
/*
* Copyright 2017 juntaki
*
* 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.juntaki.springfennec.util
import io.swagger.models.properties.*
import javax.lang.model.element.ElementKind
import javax.lang.model.element.VariableElement
import javax.lang.model.type.ArrayType
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.TypeMirror
import javax.lang.model.util.ElementFilter
import javax.lang.model.util.Elements
import javax.lang.model.util.Types
class PropertyUtil(
private val elementUtils: Elements,
private val typeUtils: Types
) {
fun doEachClassField(className: String, fn: (VariableElement) -> Unit) {
val typeElement = elementUtils.getTypeElement(className) ?: return
ElementFilter.fieldsIn(typeElement.enclosedElements).forEach {
it ?: return@forEach
// enum class cannot converted to swagger spec automatically.
// ApiParam.allowableValues should be used, but not implemented.
if (elementUtils.getTypeElement(it.asType().toString())?.kind == ElementKind.ENUM) return@forEach
fn(it)
}
}
// return null only if tm is Void type
fun getProperty(tm: TypeMirror): Property? {
fun isAssignable(tm: TypeMirror, className: String): Boolean {
return typeUtils.isAssignable(tm, elementUtils.getTypeElement(className).asType())
}
fun isSameClassName(tm: TypeMirror, className: String): Boolean {
return tm.toString() == className
}
if (isAssignable(tm, "java.time.LocalDateTime") ||
isAssignable(tm, "java.time.ZonedDateTime") ||
isAssignable(tm, "java.time.OffsetDateTime") ||
isAssignable(tm, "java.util.Date") ||
isSameClassName(tm, "org.joda.time.DateTime")
) {
return DateTimeProperty()
}
if (isAssignable(tm, "java.time.LocalDate")) {
return DateProperty()
}
if (isAssignable(tm, "java.lang.Boolean")) {
return BooleanProperty()
}
if (isAssignable(tm, "java.lang.Byte")) {
return ByteArrayProperty()
}
if (isAssignable(tm, "java.lang.Integer")) {
return IntegerProperty()
}
if (isAssignable(tm, "java.lang.Long")) {
return LongProperty()
}
if (isAssignable(tm, "java.lang.Float")) {
return FloatProperty()
}
if (isAssignable(tm, "java.lang.Double")) {
return DoubleProperty()
}
if (isAssignable(tm, "java.lang.String")) {
return StringProperty()
}
if (isSameClassName(tm, "org.springframework.web.multipart.MultipartFile")) {
return FileProperty()
}
// Array
val listRegex = Regex("""^java.util.List|^java.util.ArrayList""")
if (tm is DeclaredType && listRegex.containsMatchIn(tm.toString())) {
val arrayProperty = ArrayProperty()
arrayProperty.items = getProperty(tm.typeArguments[0])
return arrayProperty
}
if (tm is ArrayType) {
val arrayProperty = ArrayProperty()
arrayProperty.items = getProperty(tm.componentType)
return arrayProperty
}
// Map
val mapRegex = Regex("""^java.util.Map""")
if (tm is DeclaredType && mapRegex.containsMatchIn(tm.toString())) {
if (!isAssignable(tm.typeArguments[0], "java.lang.String")) {
// TODO: I believe this is not implemented... but output is the same as springfox. is it correct?
// TODO: Read JSON Schema and https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responses-definitions-object
}
val mapProperty = MapProperty()
mapProperty.additionalProperties = getProperty(tm.typeArguments[1])
return mapProperty
}
// Void
if (tm.toString() == "java.lang.Void") {
return null
}
// Class
val refProperty = RefProperty()
refProperty.`$ref` = tm.toString()
return refProperty
}
} | src/main/kotlin/com/juntaki/springfennec/util/PropertyUtil.kt | 714357536 |
package mil.nga.giat.mage.network.api
import mil.nga.giat.mage.sdk.datastore.user.Role
import retrofit2.Response
import retrofit2.http.GET
interface RoleService {
@GET("/api/roles")
suspend fun getRoles(): Response<Collection<Role>>
} | mage/src/main/java/mil/nga/giat/mage/network/api/RoleService.kt | 3604013265 |
package com.fk.fuckoffer.domain.interactor
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.ShareCompat
import com.fk.fuckoffer.R
import com.fk.fuckoffer.injection.InjectionHelper
import com.fk.fuckoffer.ui.preview.PreviewPresenter
import com.fk.fuckoffer.ui.preview.PreviewView
import kotlinx.android.synthetic.main.activity_preview.*
import javax.inject.Inject
import android.content.Intent
import com.fk.fuckoffer.ui.main.MainActivity
class PreviewActivity : AppCompatActivity(), PreviewView {
@Inject
lateinit var presenter: PreviewPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_preview)
setup()
}
private fun setup() {
setupUi()
InjectionHelper.buildViewComponent().inject(this)
presenter.attach(this)
presenter.loadOffence(
intent.getStringExtra(PARAM_OPERATION_NAME),
intent.getStringArrayListExtra(PARAM_LIST_OF_VALUES))
}
private fun setupUi() {
setTitle(R.string.preview)
previewCloseBtn.setOnClickListener { hardClose() }
}
private fun hardClose() {
val intent = Intent(applicationContext,
MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(intent)
}
override fun loadPreview(url: String) {
previewWebView.loadUrl(url)
previewShareBtn.setOnClickListener {
ShareCompat.IntentBuilder
.from(this)
.setText(url)
.setType("text/plain")
.startChooser()
}
}
companion object {
val PARAM_OPERATION_NAME = "PARAM_OPERATION_NAME"
val PARAM_LIST_OF_VALUES = "PARAM_LIST_OF_VALUES"
}
}
| app/src/main/java/com/fk/fuckoffer/domain/interactor/PreviewActivity.kt | 4239904275 |
/*
* Copyright (c) 2016 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.
*/
package nl.komponents.kovenant.rx
import nl.komponents.kovenant.Promise
import rx.Observable
import rx.Producer
import rx.Subscriber
import rx.exceptions.Exceptions
import java.util.concurrent.atomic.AtomicInteger
/**
* Turns an existing `Promise<V, E : Exception>` into an `Observable<V>`.
* Note that by default the `Observable` is observed on the callback `Dispatcher`
* of the `Promise` in question.
*
* @return The Observable backed by the Promise
*/
fun <V, E : Exception> Promise<V, E>.toObservable(): Observable<V> = Observable.create(PromiseOnSubscribe(this))
private class PromiseOnSubscribe<V, E : Exception>(private val promise: Promise<V, E>) : Observable.OnSubscribe<V> {
override fun call(subscriber: Subscriber<in V>) {
val producer = PromiseProducer<V, E>(subscriber)
subscriber.setProducer(producer)
if (promise.isDone()) {
if (promise.isSuccess()) producer.setValue(promise.get())
else if (promise.isFailure()) producer.setError(promise.getError())
} else {
promise success { producer.setValue(it) }
promise fail { producer.setError(it) }
}
}
private class PromiseProducer<V, E : Exception>(private val subscriber: Subscriber<in V>) : Producer {
companion object {
val error_result = 4
val value_result = 2
val has_request = 1
}
private @Volatile var value: Any? = null
private val state = AtomicInteger(0)
override fun request(n: Long) {
if (n < 0) throw IllegalArgumentException("n >= 0 required")
if (n > 0) {
while (true) {
val oldState = state.get()
if (oldState.isRequestSet()) return // request is already set, so return
val newState = oldState or has_request
if (state.compareAndSet(oldState, newState)) {
if (oldState.isResolved()) emit()
return // we are done
}
}
}
}
private fun Int.isError() = hasFlag(error_result)
private fun Int.isValue() = hasFlag(value_result)
private fun Int.isResolved() = this >= value_result // yeah nasty right ;-)
private fun Int.isRequestSet() = hasFlag(has_request)
private fun Int.hasFlag(flag: Int) = this and flag == flag
fun setError(error: E) {
value = error
setResolvedState(error_result)
}
fun setValue(value: V) {
this.value = value
setResolvedState(value_result)
}
private fun setResolvedState(flag: Int) {
while (true) {
val oldState = state.get()
val newState = oldState or flag
if (state.compareAndSet(oldState, newState)) {
if (oldState.isRequestSet()) emit()
return // we are done
}
if (oldState.isResolved()) {
//sanity check against poor implemented Promises
throw IllegalStateException("It shouldn't happen, but did...")
}
}
}
//This behaviour is mimicked from SingleDelayedProducer
private fun emit() {
val s = state.get()
when {
s.isValue() -> emitValue()
s.isError() -> emitError()
else -> throw IllegalStateException("It shouldn't happen, but did...")
}
}
private fun emitError() {
@Suppress("UNCHECKED_CAST")
val e = value as E
Exceptions.throwIfFatal(e)
subscriber.onError(e)
}
//This behaviour is mimicked from SingleDelayedProducer
private fun emitValue() {
if (!subscriber.isUnsubscribed) {
@Suppress("UNCHECKED_CAST")
val v = value as V
try {
subscriber.onNext(v)
} catch (e: Throwable) {
Exceptions.throwOrReport(e, subscriber, v)
return
}
}
if (!subscriber.isUnsubscribed) {
subscriber.onCompleted()
}
}
}
}
| projects/rx/src/main/kotlin/promises.kt | 3664586172 |
package com.bl_lia.kirakiratter.data.repository.datasource.account
import com.bl_lia.kirakiratter.data.cache.AccountCache
import com.bl_lia.kirakiratter.domain.entity.Account
import com.bl_lia.kirakiratter.domain.entity.Relationship
import com.bl_lia.kirakiratter.domain.entity.Status
import io.reactivex.Single
class ApiAccountDataStore(
private val accountService: AccountService,
private val accountCache: AccountCache
) : AccountDataStore {
override fun status(id: Int): Single<List<Status>> = accountService.status(id)
override fun moreStatus(id: Int, maxId: Int?, sinceId: Int?): Single<List<Status>> = accountService.status(id, maxId, sinceId)
override fun relationship(id: Int): Single<Relationship> =
accountService.relationships(id)
.flatMap { Single.just(it.first()) }
override fun follow(id: Int): Single<Relationship> = accountService.follow(id)
override fun unfollow(id: Int): Single<Relationship> = accountService.unfollow(id)
override fun verifyCredentials(): Single<Account> =
accountService.verifyCredentials()
.doAfterSuccess { account ->
accountCache.credentials = account
}
} | app/src/main/kotlin/com/bl_lia/kirakiratter/data/repository/datasource/account/ApiAccountDataStore.kt | 3332737537 |
/*
* Copyright 2017 Fantasy Fang
*
* 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.fantasy1022.fancytrendapp.data.remote
import android.support.v4.util.ArrayMap
import kotlinx.coroutines.Deferred
import retrofit2.http.GET
/**
* Created by fantasy1022 on 2017/2/7.
*/
interface FancyTrendRestService {
@get:GET("internal/data")
val googleTrendNew: Deferred<ArrayMap<String, List<String>>>
}
| app/src/main/java/com/fantasy1022/fancytrendapp/data/remote/FancyTrendRestService.kt | 213912187 |
package io.particle.android.sdk.cloud
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType
import io.particle.android.sdk.cloud.ParticleDevice.VariableType
const val DEVICE_ID_0 = "d34db33f52ca40bd34db33f0"
const val DEVICE_ID_1 = "d34db33f52ca40bd34db33f1"
internal val DEVICE_STATE_0 = DeviceState(
DEVICE_ID_0,
ParticleDeviceType.XENON.intValue,
ParticleDeviceType.XENON.intValue,
"64.124.183.01",
null,
"normal",
"device0",
true,
false,
null,
null,
"1.4.0",
"1.4.4",
setOf(),
mapOf(),
ParticleDeviceType.XENON,
null,
"XENKAB8D34DB33F",
"ABCDEFG01234567",
null,
"1.4.0",
null
)
internal val DEVICE_STATE_1 = DeviceState(
DEVICE_ID_1,
ParticleDeviceType.ARGON.intValue,
ParticleDeviceType.ARGON.intValue,
"64.124.183.02",
null,
"normal",
"device1",
true,
false,
null,
null,
"1.4.2",
"1.4.4",
setOf(),
mapOf(),
ParticleDeviceType.ARGON,
null,
"ARGHABD34DB33F1",
"ABCDEFG01234567",
null,
"1.4.2",
null
)
internal val DEVICE_STATE_1_FULL = DEVICE_STATE_1.copy(
functions = setOf("digitalread", "digitalwrite", "analogread", "analogwrite"),
variables = mapOf(
"somebool" to VariableType.BOOLEAN,
"someint" to VariableType.INT,
"somedouble" to VariableType.DOUBLE,
"somestring" to VariableType.STRING
)
)
val DEVICE_0_JSON = """
{
"id":"$DEVICE_ID_0",
"name":"device0",
"last_app":null,
"last_ip_address":"64.124.183.01",
"last_heard":null,
"product_id":14,
"connected":true,
"platform_id":14,
"cellular":false,
"notes":null,
"status":"normal",
"serial_number":"XENKAB8D34DB33F",
"mobile_secret":"ABCDEFG01234567",
"current_build_target":"1.4.0",
"system_firmware_version":"1.4.0",
"default_build_target":"1.4.4"
}
""".trimIndent()
val DEVICE_1_JSON = """
{
"id":"$DEVICE_ID_1",
"name":"device1",
"last_app":null,
"last_ip_address":"64.124.183.02",
"last_heard":null,
"product_id":12,
"connected":true,
"platform_id":12,
"cellular":false,
"notes":null,
"status":"normal",
"serial_number":"ARGHABD34DB33F1",
"mobile_secret":"ABCDEFG01234567",
"current_build_target":"1.4.2",
"system_firmware_version":"1.4.2",
"default_build_target":"1.4.4"
}
""".trimIndent()
val DEVICE_1_FULL_JSON = """
{
"id":"$DEVICE_ID_1",
"name":"device1",
"last_app":null,
"last_ip_address":"64.124.183.02",
"last_heard":null,
"product_id":12,
"connected":true,
"platform_id":12,
"cellular":false,
"notes":null,
"network": {
"id":"d34db33fd34db33f0123456A",
"name":"fakenet",
"type":"micro_wifi",
"role":{
"gateway":true,
"state":"confirmed"
}
},
"status":"normal",
"serial_number":"ARGHABD34DB33F1",
"mobile_secret":"ABCDEFG01234567",
"current_build_target":"1.4.2",
"system_firmware_version":"1.4.2",
"default_build_target":"1.4.4",
"variables":{
"somebool":"bool",
"someint":"int32",
"somedouble":"double",
"somestring":"string"
},
"functions":[
"digitalread",
"digitalwrite",
"analogread",
"analogwrite"
],
"firmware_updates_enabled":true,
"firmware_updates_forced":false
}
""".trimIndent()
val DEVICE_LIST_JSON = """
[
$DEVICE_0_JSON,
$DEVICE_1_JSON
]
""".trimIndent()
| cloudsdk/src/test/java/io/particle/android/sdk/cloud/TestData.kt | 2701617191 |
package com.example.fragnums
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import android.view.View
import android.view.animation.AnimationUtils.loadAnimation
import android.widget.FrameLayout
import com.squareup.enumsbatter.R
import java.util.ArrayList
import kotlin.properties.Delegates.notNull
class MainActivity : AppCompatActivity() {
private var backstack: ArrayList<BackstackFrame> = ArrayList()
private var currentScreen: Screen = Screen.values.first()
private val container by lazy { findViewById(R.id.main_container) as FrameLayout }
private var currentView: View by notNull()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState != null) {
currentScreen = Screen.values[savedInstanceState.getInt("currentScreen")]
backstack = savedInstanceState.getParcelableArrayList<BackstackFrame>("backstack")
}
currentView = currentScreen.inflate(container)
container.addView(currentView)
currentScreen.bind(currentView)
updateActionBar()
}
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("currentScreen", currentScreen.ordinal)
outState.putParcelableArrayList("backstack", backstack)
}
override fun onDestroy() {
super.onDestroy()
currentScreen.unbind()
}
override fun onBackPressed() {
if (backstack.size > 0) {
goBack()
return
}
super.onBackPressed()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
goBack()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
fun goTo(screen: Screen) {
currentScreen.unbind()
currentView.startAnimation(loadAnimation(this, R.anim.exit_forward))
container.removeView(currentView)
val backstackFrame = backstackFrame(currentScreen, currentView)
backstack.add(backstackFrame)
currentScreen = screen
currentView = currentScreen.inflate(container)
currentView.startAnimation(loadAnimation(this, R.anim.enter_forward))
container.addView(currentView)
currentScreen.bind(currentView)
updateActionBar()
}
fun goBack() {
currentScreen.unbind()
currentView.startAnimation(loadAnimation(this, R.anim.exit_backward))
container.removeView(currentView)
val latest = backstack.removeAt(backstack.size - 1)
currentScreen = latest.screen
currentView = currentScreen.inflate(container)
currentView.startAnimation(loadAnimation(this, R.anim.enter_backward))
container.addView(currentView, 0)
latest.restore(currentView)
currentScreen.bind(currentView)
updateActionBar()
}
private fun updateActionBar() {
val actionBar = supportActionBar
actionBar.setDisplayHomeAsUpEnabled(backstack.size != 0)
var title: CharSequence? = currentScreen.title
if (title == null) {
title = getTitle()
}
actionBar.title = title
}
}
| app/src/main/kotlin/com/example/fragnums/MainActivity.kt | 131027330 |
package jp.wasabeef.example.recyclerview
import androidx.recyclerview.widget.RecyclerView
import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter
class MyAnimatorAdapter constructor(
adapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>,
from: Float = 0.5f
) : AlphaInAnimationAdapter(adapter, from) {
}
| example/src/main/java/jp/wasabeef/example/recyclerview/MyAnimationAdapter.kt | 3253259947 |
package `in`.shabhushan.cp_trials.math.primes
import `in`.shabhushan.cp_trials.math.primes.StepsInPrime.isPrime
import `in`.shabhushan.cp_trials.math.primes.StepsInPrime.step2
import org.junit.Test
import java.util.*
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class StepsInPrimeTest {
@Test
fun testPrime() {
assertTrue(isPrime(2))
assertTrue(isPrime(5))
assertTrue(isPrime(7))
assertFalse(isPrime(9))
assertTrue(isPrime(13))
assertFalse(isPrime(12))
assertFalse(isPrime(30148))
}
//--------------
@Test
fun test() {
println("Fixed Tests")
assertEquals("[101, 103]", Arrays.toString(step2(2, 100, 110)))
assertEquals("[103, 107]", Arrays.toString(step2(4, 100, 110)))
assertEquals("[101, 107]", Arrays.toString(step2(6, 100, 110)))
assertEquals("[]", Arrays.toString(step2(11, 30000, 100000)))
}
}
| cp-trials/src/test/kotlin/in/shabhushan/cp_trials/math/primes/StepsInPrimeTest.kt | 553556118 |
package io.dev.temperature.model
import io.vertx.core.buffer.Buffer
import io.vertx.core.eventbus.MessageCodec
import io.vertx.core.json.JsonObject
import java.time.Instant
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.format.DateTimeFormatter
data class Temperature(val value: Float, val temperatureSet: Float, val heating: Boolean, val date: Instant = Instant.now()) {
companion object {
fun fromJson(jsonObject: JsonObject): Temperature {
return Temperature(
jsonObject.getFloat("value"),
jsonObject.getFloat("setTemp"),
jsonObject.getBoolean("heating"),
Instant.parse(jsonObject.getString("date")))
}
}
fun toJson(): String {
val json = toJsonObject()
return json.encodePrettily()
}
fun toJsonObject(): JsonObject {
return JsonObject().put("value", value)
.put("setTemp", temperatureSet)
.put("heating", heating)
.put("date", date.toString())
}
}
data class Schedule(val active: Boolean = false, val days: List<ScheduleDay>) {
companion object {
fun fromJson(jsonObject: JsonObject): Schedule {
val active = jsonObject.getBoolean("active")
val days = jsonObject.getJsonArray("days").map { ScheduleDay.fromJson(it as JsonObject) }
return Schedule(active, days)
}
}
private fun flattenListOfScheduledHoursOfDays(dateTime: LocalDateTime, tillTheEndOfWeek: List<ScheduleDay>): List<NextScheduledTemp> {
return tillTheEndOfWeek.mapIndexed { index, scheduleDay ->
val date = dateTime.plusDays(index.toLong()).toLocalDate()
scheduleDay.hours.map { hour ->
NextScheduledTemp(LocalDateTime.of(date, hour.time), hour.temp)
}
}.flatMap { it }
}
private fun dateOfNextWeekMonday(dateTime: LocalDateTime): LocalDateTime {
val daysToAdd = 8 - dateTime.dayOfWeek.value
return dateTime.plusDays(daysToAdd.toLong())
}
fun nextScheduledTemp(dateTime: LocalDateTime): NextScheduledTemp? {
val flattenedHours = days.flatMap { it.hours }
if (flattenedHours.size == 0) return null
val dayIndex = dateTime.dayOfWeek.value - 1
val tillTheEndOfWeek = days.subList(dayIndex, days.size)
val mappedRestOfTheWeek = flattenListOfScheduledHoursOfDays(dateTime, tillTheEndOfWeek)
val nextPossibleSchedule = mappedRestOfTheWeek.find { it.time.isAfter(dateTime) }
if (nextPossibleSchedule == null) {
val nextWeeksDate = dateOfNextWeekMonday(dateTime)
return flattenListOfScheduledHoursOfDays(nextWeeksDate, days).first()
}
return nextPossibleSchedule
}
}
data class ScheduleDay(val name: String, val hours: List<ScheduleHour>) {
companion object {
fun fromJson(jsonObject: JsonObject): ScheduleDay {
val name = jsonObject.getString("name")
val hours = jsonObject.getJsonArray("hours").map { ScheduleHour.fromJson(it as JsonObject) }
return ScheduleDay(name, hours)
}
}
}
data class ScheduleHour(val time: LocalTime, val temp: Float) {
companion object {
fun fromJson(jsonObject: JsonObject): ScheduleHour {
val timeParts = jsonObject.getString("time").split(":")
val temp = jsonObject.getFloat("temp")
return ScheduleHour(LocalTime.of(timeParts[0].toInt(), timeParts[1].toInt()), temp)
}
}
}
data class NextScheduledTemp(val time: LocalDateTime, val temp: Float) {
fun toJson(): JsonObject {
return JsonObject()
.put("time", time.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm")))
.put("temp", temp)
}
}
class TemperatureCodec : MessageCodec<Temperature, Temperature> {
override fun systemCodecID(): Byte {
return -1
}
override fun name(): String? {
return Temperature::class.java.canonicalName
}
override fun transform(p0: Temperature?): Temperature? {
return p0
}
override fun decodeFromWire(p0: Int, p1: Buffer?): Temperature? {
val value = p1?.getFloat(p0)
val setTemp = p1?.getFloat(p0 + 4)
val heating: Boolean = if (p1?.getByte(p0 + 8) == Byte.MIN_VALUE ) false else true
val date = Instant.ofEpochMilli(p1?.getLong(p0 + 9)!!)
return Temperature(value!!, setTemp!!, heating, date)
}
override fun encodeToWire(p0: Buffer?, p1: Temperature?) {
p0?.appendFloat(p1?.value!!)
p0?.appendFloat(p1?.temperatureSet!!)
p0?.appendByte(if (p1?.heating!!) 0 else 1)
p0?.appendLong(p1?.date?.toEpochMilli()!!)
}
} | temperature-sensor-and-rest/src/main/kotlin/io/dev/temperature/model/Model.kt | 346884166 |
package com.supercilex.robotscouter.core.ui.views
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.widget.LinearLayout
import com.supercilex.robotscouter.core.ui.CardMetric
import com.supercilex.robotscouter.core.ui.CardMetricHelper
class CardMetricLinearLayout : LinearLayout, CardMetric {
override val helper = CardMetricHelper(this)
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) :
super(context, attrs, defStyleAttr)
init {
helper.init()
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super<LinearLayout>.onLayout(changed, left, top, right, bottom)
super<CardMetric>.onLayout(changed, left, top, right, bottom)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) =
super<CardMetric>.onSizeChanged(w, h, oldw, oldh)
override fun onDraw(canvas: Canvas) {
super<LinearLayout>.onDraw(canvas)
super<CardMetric>.onDraw(canvas)
}
}
| library/core-ui/src/main/java/com/supercilex/robotscouter/core/ui/views/CardMetricLinearLayout.kt | 3936464168 |
package com.eden.orchid.posts.pages
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.options.annotations.Archetype
import com.eden.orchid.api.options.annotations.Archetypes
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.archetypes.ConfigArchetype
import com.eden.orchid.api.resources.resource.OrchidResource
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.impl.relations.AssetRelation
import com.eden.orchid.posts.PostCategoryArchetype
import com.eden.orchid.posts.PostsGenerator
import com.eden.orchid.posts.model.Author
import com.eden.orchid.posts.model.CategoryModel
@Archetypes(
Archetype(value = PostCategoryArchetype::class, key = PostsGenerator.GENERATOR_KEY),
Archetype(value = ConfigArchetype::class, key = "${PostsGenerator.GENERATOR_KEY}.postPages")
)
@Description(value = "A blog post.", name = "Blog Post")
class PostPage(resource: OrchidResource, val categoryModel: CategoryModel, title: String)
: OrchidPage(resource, "post", title) {
@Option
@Description("The posts author. May be the `name` of a known author, or an anonymous Author config, only " +
"used for this post, which is considered as a guest author."
)
var author: Author? = null
@Option
@Description("A list of tags for this post, for basic taxonomic purposes. More complex taxonomic relationships " +
"may be managed by other plugins, which may take post tags into consideration."
)
lateinit var tags: Array<String>
@Option
@Description("A 'type' of post, such as 'gallery', 'video', or 'blog', which is used to determine the specific" +
"post template to use for the Page Content."
)
lateinit var postType: String
@Option
@Description("A fully-specified URL to a post's featured image, or a relative path to an Orchid image.")
lateinit var featuredImage: AssetRelation
@Option
@Description("The permalink structure to use only for this blog post. This overrides the permalink structure set " +
"in the category configuration."
)
lateinit var permalink: String
val category: String?
get() {
return categoryModel.key
}
val categories: Array<String>
get() {
return categoryModel.path.split("/").toTypedArray()
}
val year: Int get() { return publishDate.year }
val month: Int get() { return publishDate.monthValue }
val monthName: String get() { return publishDate.month.toString() }
val day: Int get() { return publishDate.dayOfMonth }
init {
this.extractOptions(this.context, data)
postInitialize(title)
}
override fun initialize(title: String?) {
}
override fun getTemplates(): List<String> {
val templates = ArrayList<String>()
if(!EdenUtils.isEmpty(postType)) {
templates.add(0, "$key-type-$postType")
}
if(!EdenUtils.isEmpty(categoryModel.key)) {
templates.add(0, "$key-${categoryModel.key!!}")
}
return templates
}
}
| plugins/OrchidPosts/src/main/kotlin/com/eden/orchid/posts/pages/PostPage.kt | 887008400 |
package com.supercilex.robotscouter.core.data.model
import android.net.Uri
import android.util.Patterns
import com.firebase.ui.firestore.SnapshotParser
import com.google.firebase.Timestamp
import com.google.firebase.appindexing.Action
import com.google.firebase.appindexing.FirebaseAppIndex
import com.google.firebase.appindexing.FirebaseUserActions
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.SetOptions
import com.google.firebase.firestore.ktx.toObject
import com.supercilex.robotscouter.common.FIRESTORE_NUMBER
import com.supercilex.robotscouter.common.FIRESTORE_OWNERS
import com.supercilex.robotscouter.common.FIRESTORE_POSITION
import com.supercilex.robotscouter.common.FIRESTORE_TEMPLATE_ID
import com.supercilex.robotscouter.common.FIRESTORE_TIMESTAMP
import com.supercilex.robotscouter.common.isSingleton
import com.supercilex.robotscouter.common.second
import com.supercilex.robotscouter.core.InvocationMarker
import com.supercilex.robotscouter.core.data.QueryGenerator
import com.supercilex.robotscouter.core.data.QueuedDeletion
import com.supercilex.robotscouter.core.data.client.retrieveLocalMedia
import com.supercilex.robotscouter.core.data.client.saveLocalMedia
import com.supercilex.robotscouter.core.data.deepLink
import com.supercilex.robotscouter.core.data.defaultTemplateId
import com.supercilex.robotscouter.core.data.firestoreBatch
import com.supercilex.robotscouter.core.data.getInBatches
import com.supercilex.robotscouter.core.data.logAdd
import com.supercilex.robotscouter.core.data.logFailures
import com.supercilex.robotscouter.core.data.share
import com.supercilex.robotscouter.core.data.teamDuplicatesRef
import com.supercilex.robotscouter.core.data.teamsRef
import com.supercilex.robotscouter.core.data.uid
import com.supercilex.robotscouter.core.logBreadcrumb
import com.supercilex.robotscouter.core.model.Scout
import com.supercilex.robotscouter.core.model.Team
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.invoke
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import java.io.File
import java.util.Calendar
import java.util.Date
import java.util.concurrent.TimeUnit
import kotlin.math.abs
val teamParser = SnapshotParser { checkNotNull(it.toObject<Team>()) }
val teamWithSafeDefaults: (number: Long, id: String) -> Team = { number, id ->
Team().apply {
this.id = id
this.number = number
owners = mapOf(checkNotNull(uid) to number)
templateId = defaultTemplateId
}
}
internal val teamsQueryGenerator: QueryGenerator = {
"$FIRESTORE_OWNERS.${it.uid}".let {
teamsRef.whereGreaterThanOrEqualTo(it, 0).orderBy(it)
}
}
val Team.ref: DocumentReference get() = teamsRef.document(id)
val Team.isOutdatedMedia: Boolean
get() = retrieveLocalMedia() == null &&
(mediaYear < Calendar.getInstance().get(Calendar.YEAR) || media.isNullOrBlank())
val Team.displayableMedia get() = retrieveLocalMedia() ?: media
private const val TEAM_FRESHNESS_DAYS = 4
internal val Team.isStale: Boolean
get() = TimeUnit.MILLISECONDS.toDays(
System.currentTimeMillis() - timestamp.time
) >= TEAM_FRESHNESS_DAYS
fun Collection<Team>.getNames(): String {
val sortedTeams = toMutableList()
sortedTeams.sort()
return when {
sortedTeams.isSingleton -> sortedTeams.single().toString()
sortedTeams.size == 2 -> "${sortedTeams.first()} and ${sortedTeams.second()}"
else -> {
val teamsMaxedOut = sortedTeams.size > 10
val size = if (teamsMaxedOut) 10 else sortedTeams.size
val names = StringBuilder(4 * size)
for (i in 0 until size) {
names.append(sortedTeams[i].number)
if (i < size - 1) names.append(", ")
if (i == size - 2 && !teamsMaxedOut) names.append("and ")
}
if (teamsMaxedOut) names.append(" and more")
names.toString()
}
}
}
internal fun Team.add() {
id = teamsRef.document().id
rawSet(refresh = true, new = true)
logAdd()
FirebaseUserActions.getInstance().end(
Action.Builder(Action.Builder.ADD_ACTION)
.setObject(toString(), deepLink)
.setActionStatus(Action.Builder.STATUS_TYPE_COMPLETED)
.build()
).logFailures("addTeam:addAction")
}
internal fun Team.update(newTeam: Team) {
if (this == newTeam) {
val timestamp = Timestamp.now()
ref.update(FIRESTORE_TIMESTAMP, timestamp).logFailures("updateTeam", ref, timestamp)
return
}
if (name == newTeam.name) {
hasCustomName = false
} else if (!hasCustomName) {
name = newTeam.name
}
if (media == newTeam.media) {
hasCustomMedia = false
} else if (!hasCustomMedia) {
media = newTeam.media
}
mediaYear = newTeam.mediaYear
if (website == newTeam.website) {
hasCustomWebsite = false
} else if (!hasCustomWebsite) {
website = newTeam.website
}
forceUpdate()
}
internal fun Team.updateTemplateId(id: String) {
if (id == templateId) return
templateId = id
ref.update(FIRESTORE_TEMPLATE_ID, templateId).logFailures("updateTeamTemplate", ref, templateId)
}
fun Team.forceUpdate(refresh: Boolean = false) {
rawSet(refresh, false)
}
suspend fun List<DocumentReference>.shareTeams(
block: Boolean = false
) = share(block) { token, ids ->
QueuedDeletion.ShareToken.Team(token, ids)
}
fun Team.copyMediaInfo(image: Uri, shouldUpload: Boolean) {
media = image.path
hasCustomMedia = true
shouldUploadMediaToTba = shouldUpload
mediaYear = Calendar.getInstance().get(Calendar.YEAR)
}
suspend fun Team.processPotentialMediaUpload() = Dispatchers.IO {
val url = media
if (url == null || !File(url).exists()) return@IO
saveLocalMedia()
media = null
hasCustomMedia = false
}
fun Team.trash() {
FirebaseAppIndex.getInstance().remove(deepLink).logFailures("trashTeam:delIndex")
firestoreBatch {
val newNumber = if (number == 0L) {
-1 // Fatal flaw in our trashing architecture: -0 isn't a thing.
} else {
-abs(number)
}
update(ref, "$FIRESTORE_OWNERS.${checkNotNull(uid)}", newNumber)
set(teamDuplicatesRef.document(checkNotNull(uid)),
mapOf(id to newNumber),
SetOptions.merge())
set(userDeletionQueue, QueuedDeletion.Team(ref.id).data, SetOptions.merge())
}.logFailures("trashTeam", ref, this)
}
fun untrashTeam(id: String) {
GlobalScope.launch {
val ref = teamsRef.document(id)
val snapshot = try {
ref.get().await()
} catch (e: Exception) {
logBreadcrumb("untrashTeam:get: ${ref.path}")
throw InvocationMarker(e)
}
val newNumber = abs(checkNotNull(snapshot.getLong(FIRESTORE_NUMBER)))
firestoreBatch {
update(ref, "$FIRESTORE_OWNERS.${checkNotNull(uid)}", newNumber)
update(teamDuplicatesRef.document(checkNotNull(uid)), id, newNumber)
update(userDeletionQueue, id, FieldValue.delete())
}.logFailures("untrashTeam:set", id)
}
}
internal fun Team.fetchLatestData() {
if (!isStale || timestamp.time == 0L) return
ref.update(FIRESTORE_TIMESTAMP, Date(0)).logFailures("fetchLatestData", ref)
}
suspend fun Team.getScouts(): List<Scout> = coroutineScope {
val scouts = getScoutsQuery().getInBatches().map { scoutParser.parseSnapshot(it) }
val metricsForScouts = scouts.map {
async { getScoutMetricsRef(it.id).orderBy(FIRESTORE_POSITION).getInBatches() }
}.awaitAll()
scouts.mapIndexed { index, scout ->
scout.copy(metrics = metricsForScouts[index].map { metricParser.parseSnapshot(it) })
}
}
suspend fun CharSequence.isValidTeamUri(): Boolean {
val uri = toString().formatAsTeamUri() ?: return true
if (Patterns.WEB_URL.matcher(uri).matches()) return true
if (Dispatchers.IO { File(uri).exists() }) return true
return false
}
suspend fun String.formatAsTeamUri(): String? {
val trimmedUrl = trim()
if (trimmedUrl.isBlank()) return null
if (Dispatchers.IO { File(this@formatAsTeamUri).exists() }) return this
return if (trimmedUrl.contains("http://") || trimmedUrl.contains("https://")) {
trimmedUrl
} else {
"http://$trimmedUrl"
}
}
private fun Team.rawSet(refresh: Boolean, new: Boolean) {
timestamp = if (refresh) Date(0) else Date()
if (new) {
firestoreBatch {
set(ref, this@rawSet)
set(teamDuplicatesRef.document(checkNotNull(uid)),
mapOf(id to number),
SetOptions.merge())
}
} else {
ref.set(this)
}.logFailures("setTeam", ref, this)
}
| library/core-data/src/main/java/com/supercilex/robotscouter/core/data/model/Teams.kt | 545273021 |
package net.resonious.talker
import marytts.LocalMaryInterface
import net.dv8tion.jda.core.audio.AudioSendHandler
import net.dv8tion.jda.core.entities.Message
import javax.sound.sampled.AudioInputStream
import javax.sound.sampled.AudioSystem
const val SEGMENT_SIZE = 3840
class Speech(
val mary: LocalMaryInterface,
val message: Message,
val voice: Data.Voice,
val onDone: (Speech) -> Unit
) : AudioSendHandler {
val text: String = message.contentStripped
var originalInputStream = generateAudio()
var inputStream = originalInputStream
var done = false
val guild = message.guild
private var ranCallback = false
private var nextSegment = ByteArray(SEGMENT_SIZE)
private val myFormat get() = inputStream.format
private val inputFormat get() = AudioSendHandler.INPUT_FORMAT
init {
println("Received message: \"$text\"")
// Convert input
try {
if (myFormat != inputFormat) {
inputStream = AudioSystem.getAudioInputStream(inputFormat, inputStream)
}
}
catch (e: Exception) {
done = true
throw e
}
}
fun generateAudio(): AudioInputStream {
mary.voice = voice.maryVoice
mary.audioEffects = voice.maryEffects
var inputText = text
if (!inputText.endsWith('.')) inputText += '.'
// TODO do more processing, maybe generate ssml doc
return mary.generateAudio(inputText)
}
fun advanceSegment(): Boolean {
if (done) return false
nextSegment.fill(0)
val bytesRead = inputStream.read(nextSegment)
if (bytesRead < nextSegment.size) {
done = true
return bytesRead > 0
}
else
return true
}
override fun canProvide(): Boolean {
if (!done) return advanceSegment()
else if (!ranCallback) { ranCallback = true; onDone(this); return false }
else return false
}
override fun provide20MsAudio(): ByteArray? {
return nextSegment
}
} | src/main/kotlin/net/resonious/talker/Speech.kt | 246970161 |
package com.github.siosio.upsource.internal
import com.github.siosio.upsource.*
import com.github.siosio.upsource.bean.*
import com.jayway.jsonpath.matchers.*
import com.jayway.jsonpath.matchers.JsonPathMatchers.*
import org.hamcrest.CoreMatchers.*
import org.junit.*
import org.junit.Assert.*
import org.mockito.*
internal class RemoveReviewCommandTest : UpsourceApiTestSupport() {
@Test
fun removeReview() {
// -------------------------------------------------- setup
Mockito.`when`(mockResponse.entity).thenReturn(
TestData("testdata/upsourceapi/voidMessageResult.json").getStringEntity()
)
// -------------------------------------------------- execute
val result = sut.send(RemoveReviewCommand(ReviewId("demo", "demo-2")))
// -------------------------------------------------- assert
assertThat(httpPost.value.uri.toASCIIString(), `is`("http://testserver/~rpc/removeReview"))
assertThat(httpPost.value.entity.content.readText(),
allOf(
hasJsonPath("projectId", equalTo("demo")),
hasJsonPath("reviewId", equalTo("demo-2"))
)
)
assertThat(result, `is`(instanceOf(VoidMessage::class.java)))
}
}
| src/test/java/com/github/siosio/upsource/internal/RemoveReviewCommandTest.kt | 3206687551 |
package com.github.shynixn.blockball.api.bukkit.event
import com.github.shynixn.blockball.api.business.proxy.BallProxy
class BallSpawnEvent(ball: BallProxy) : BallEvent(ball)
| blockball-bukkit-api/src/main/java/com/github/shynixn/blockball/api/bukkit/event/BallSpawnEvent.kt | 2771634992 |
package com.github.shynixn.blockball.api.bukkit.event
import com.github.shynixn.blockball.api.persistence.entity.Game
/**
* Base Event for all game events.
*/
open class GameEvent(
/**
* Game firing this event.
*/
val game: Game
) : BlockBallEvent()
| blockball-bukkit-api/src/main/java/com/github/shynixn/blockball/api/bukkit/event/GameEvent.kt | 1873520271 |
import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.*
import java.io.OutputStreamWriter
class TestProcessor(
val codeGenerator: CodeGenerator,
val logger: KSPLogger
) : SymbolProcessor {
var rounds = 0
override fun process(resolver: Resolver): List<KSAnnotated> {
if (++rounds == 1) {
codeGenerator.createNewFile(Dependencies(false), "com.example", "Bar", "kt").use { output ->
OutputStreamWriter(output).use { writer ->
writer.write("package com.example\n\n")
writer.write("interface Bar\n")
}
}
}
return emptyList()
}
}
class TestProcessorProvider : SymbolProcessorProvider {
override fun create(
environment: SymbolProcessorEnvironment
): SymbolProcessor {
return TestProcessor(environment.codeGenerator, environment.logger)
}
}
| integration-tests/src/test/resources/java-only/test-processor/src/main/kotlin/TestProcessor.kt | 456802549 |
package io.jentz.winter.testing
import io.jentz.winter.*
import io.jentz.winter.inject.ApplicationScope
import io.jentz.winter.plugin.SimplePlugin
typealias WinterTestSessionBlock = WinterTestSession.Builder.() -> Unit
typealias OnGraphInitializedCallback = (Graph) -> Unit
typealias OnGraphCloseCallback = (Graph) -> Unit
/**
* [WinterTestSession] helps to write cleaner tests that require `Winter` by eliminating
* boilerplate code.
*
* This is used by the Winter JUnit4 and JUnit5 modules but can also be used directly with other
* test frameworks.
*
* Example:
*
* ```
* class ExampleTest {
*
* private lateinit val session: WinterTestSession
*
* @Mock service: Service = mock()
*
* @Before fun setup() {
* session = WinterTestSession.session(this) {
* application = MyWinterApp
* bindAllMocks()
* testGraph("activity")
* }
* session.start()
* }
*
* @After fun teardown() {
* session.stop()
* }
*
* }
* ```
*
* @see WinterTestSession.Builder for more details about the possible configurations.
*/
@Suppress("MaxLineLength") // maybe I should get rid of Detekt...
class WinterTestSession private constructor(
private val application: WinterApplication,
private val testInstances: List<Any>,
private val graphExtenders: List<Pair<ComponentMatcher, ComponentBuilderBlock>>,
private val onGraphInitializedCallbacks: List<Pair<ComponentMatcher, OnGraphInitializedCallback>>,
private val onGraphCloseCallbacks: List<Pair<ComponentMatcher, OnGraphCloseCallback>>,
private val testGraphComponentMatcher: ComponentMatcher,
private val autoCloseMode: AutoCloseMode,
private val bindAllMocksMatcher: ComponentMatcher?
) {
/**
* The test graph if open otherwise null.
*/
var testGraph: Graph? = null
private set
/**
* The test graph.
*
* @throws IllegalStateException If graph is not open.
*/
val requireTestGraph: Graph
get() = checkNotNull(testGraph) {
"Test graph is not open."
}
private val _allGraphs = mutableListOf<Graph>()
/**
* A list of all graphs that where opened after calling [start].
*/
val allGraphs: List<Graph> get() = _allGraphs.toList()
private val plugin = object : SimplePlugin() {
override fun graphInitializing(parentGraph: Graph?, builder: Component.Builder) {
for ((matcher, block) in graphExtenders) {
if (matcher.matches(builder)) {
builder.apply(block)
}
}
if (bindAllMocksMatcher?.matches(builder) == true) {
testInstances.forEach { builder.bindAllMocks(it) }
}
}
override fun graphInitialized(graph: Graph) {
_allGraphs += graph
if (testGraphComponentMatcher.matches(graph)) {
[email protected] = graph
testInstances.forEach { graph.inject(it) }
}
for ((matcher, callback) in onGraphInitializedCallbacks) {
if (matcher.matches(graph)) {
callback(graph)
}
}
}
override fun graphClose(graph: Graph) {
_allGraphs -= graph
for ((matcher, callback) in onGraphCloseCallbacks) {
if (matcher.matches(graph)) {
callback(graph)
}
}
if (testGraph == graph) {
testGraph = null
}
}
}
/**
* Call this to start the session.
*/
fun start() {
application.plugins += plugin
}
/**
* Call this to stop the session.
*/
fun stop() {
application.plugins -= plugin
testGraph?.let { graph ->
this.testGraph = null
if (graph.isClosed) {
return
}
when (autoCloseMode) {
AutoCloseMode.NoAutoClose -> {
}
AutoCloseMode.Graph -> {
graph.close()
}
AutoCloseMode.GraphAndAncestors -> {
var graphToClose: Graph? = graph
while (graphToClose != null && !graphToClose.isClosed) {
val parent = graphToClose.parent
graphToClose.close()
graphToClose = parent
}
}
AutoCloseMode.AllGraphs -> {
allGraphs.forEach(Graph::close)
}
}
}
}
/**
* Resolve an instance of [type] with optional [qualifier].
*
* @param type The Java type.
* @param qualifier The optional qualifier.
*
* @return The requested type or null if not found.
*/
fun resolve(type: Class<*>, qualifier: Any? = null): Any =
requireTestGraph.instanceByKey(ClassTypeKey(type.kotlin.javaObjectType, qualifier))
internal enum class AutoCloseMode { NoAutoClose, Graph, GraphAndAncestors, AllGraphs }
internal class ComponentMatcher(private val qualifier: Any) {
fun matches(graph: Graph): Boolean = qualifier == graph.component.qualifier
fun matches(builder: Component.Builder): Boolean = qualifier == builder.qualifier
}
class Builder {
var application: WinterApplication = Winter
private var autoCloseMode: AutoCloseMode = AutoCloseMode.NoAutoClose
private var testGraphComponentMatcher = ComponentMatcher(ApplicationScope::class)
private var bindAllMocksMatcher: ComponentMatcher? = null
private val graphExtenders = mutableListOf<Pair<ComponentMatcher, ComponentBuilderBlock>>()
private val onGraphInitializedCallbacks =
mutableListOf<Pair<ComponentMatcher, OnGraphInitializedCallback>>()
private val onGraphCloseCallbacks =
mutableListOf<Pair<ComponentMatcher, OnGraphCloseCallback>>()
/**
* Use the graph with component [qualifier] as test graph.
*
* Default: Uses the application graph.
*/
fun testGraph(qualifier: Any) {
testGraphComponentMatcher = ComponentMatcher(qualifier)
}
/**
* Auto-close the test graph when [stop] is called.
*
* Default: No auto-close.
*/
fun autoCloseTestGraph() {
autoCloseMode = AutoCloseMode.Graph
}
/**
* Auto-close the test graph and all its ancestors when [stop] is called.
*
* Default: No auto-close.
*/
fun autoCloseTestGraphAndAncestors() {
autoCloseMode = AutoCloseMode.GraphAndAncestors
}
/**
* Auto-close all graphs that where opened after [start] was called when [stop] is
* called.
*
* Default: No auto-close.
*/
fun autoCloseAllGraphs() {
autoCloseMode = AutoCloseMode.AllGraphs
}
/**
* Extend the graph with the component qualifier [qualifier] with the given [block].
*
* @param qualifier The qualifier of the graph component.
* @param block The block to apply to the graph component builder.
*/
fun extend(qualifier: Any = ApplicationScope::class, block: ComponentBuilderBlock) {
graphExtenders += ComponentMatcher(qualifier) to block
}
/**
* Add callback that gets invoked when a graph with the component [qualifier] got created.
*
* @param qualifier The qualifier of the graph component.
* @param callback The callback that gets invoked with the graph.
*/
fun onGraphInitialized(
qualifier: Any = ApplicationScope::class,
callback: OnGraphInitializedCallback
) {
onGraphInitializedCallbacks += ComponentMatcher(qualifier) to callback
}
/**
* Add callback that gets invoked when a graph with the component [qualifier] gets closed.
*
* @param qualifier The qualifier of the graph component.
* @param callback The callback that gets invoked with the graph.
*/
fun onGraphClose(
qualifier: Any = ApplicationScope::class,
callback: OnGraphCloseCallback
) {
onGraphCloseCallbacks += ComponentMatcher(qualifier) to callback
}
/**
* Automatically bind all mocks found in the test instances to the graph with given
* component [qualifier].
*
* @param qualifier The qualifier of the graph component.
*/
fun bindAllMocks(qualifier: Any = ApplicationScope::class) {
bindAllMocksMatcher = ComponentMatcher(qualifier)
}
fun build(testInstances: List<Any>) = WinterTestSession(
application = application,
testInstances = testInstances,
graphExtenders = graphExtenders,
onGraphInitializedCallbacks = onGraphInitializedCallbacks,
onGraphCloseCallbacks = onGraphCloseCallbacks,
testGraphComponentMatcher = testGraphComponentMatcher,
autoCloseMode = autoCloseMode,
bindAllMocksMatcher = bindAllMocksMatcher
)
}
companion object {
fun session(
vararg testInstances: Any,
block: WinterTestSessionBlock
): WinterTestSession = Builder().apply(block).build(testInstances.toList())
}
}
| winter-testing/src/main/kotlin/io/jentz/winter/testing/WinterTestSession.kt | 2230350323 |
package io.jentz.winter.delegate
import io.jentz.winter.Graph
import java.util.*
/**
* Holds a map of instances to a list of [injected properties][InjectedProperty] until
* [Graph.inject] with the instance is called which will trigger [notify].
*
* Inspired by Toothpick KTP.
*/
internal object DelegateNotifier {
private val delegates =
Collections.synchronizedMap(WeakHashMap<Any, MutableList<InjectedProperty<*>>>())
fun register(owner: Any, property: InjectedProperty<*>) {
delegates
.getOrPut(owner) { mutableListOf() }
.add(property)
}
fun notify(owner: Any, graph: Graph): Boolean {
return delegates.remove(owner)?.onEach { it.inject(graph) } != null
}
}
| winter/src/main/kotlin/io/jentz/winter/delegate/DelegateNotifier.kt | 3619362839 |
package unittest
import com.github.shynixn.blockball.api.business.enumeration.ScoreboardDisplaySlot
import com.github.shynixn.blockball.api.business.service.ScoreboardService
import com.github.shynixn.blockball.bukkit.logic.business.service.ScoreboardServiceImpl
import org.bukkit.scoreboard.*
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class ScoreboardServiceTest {
/**
* Given
* a valid configuration as parameter
* When
* setConfiguration is called
* Then
* a new objective should be registered.
*/
@Test
fun setConfiguration_ValidScoreboardDisplaySlotTitle_ShouldRegisterObjective() {
// Arrange
val classUnderTest = createWithDependencies()
val scoreboard = mock(Scoreboard::class.java)
val displaySlot = ScoreboardDisplaySlot.SIDEBAR
val title = "Custom"
var called = false
// Act
`when`(scoreboard.registerNewObjective(any(), any())).then {
called = true
mock(Objective::class.java)
}
classUnderTest.setConfiguration(scoreboard, displaySlot, title)
// Assert
Assertions.assertTrue(called)
}
/**
* Given
* a valid configuration as parameter and no valid scoreboard
* When
* setConfiguration is called
* Then
* Exception should be thrown.
*/
@Test
fun setConfiguration_ValidScoreboardNoDisplaySlotTitle_ShouldRegisterObjective() {
// Arrange
val classUnderTest = createWithDependencies()
val displaySlot = ScoreboardDisplaySlot.SIDEBAR
val title = "Custom"
// Act
assertThrows(IllegalArgumentException::class.java) {
classUnderTest.setConfiguration("wrong parameter", displaySlot, title)
}
}
/**
* Given
* a valid line as parameter
* When
* setLine is called
* Then
* a new line should be added regardless of the state.
*/
@Test
fun setLine_ValidLineText_ShouldAddLine() {
// Arrange
val classUnderTest = createWithDependencies()
val scoreboard = mock(Scoreboard::class.java)
var called = false
// Act
`when`(scoreboard.registerNewTeam(any())).then {
val team = mock(Team::class.java)
`when`(team.addEntry(any())).then {
called = true
""
}
team
}
`when`(scoreboard.getObjective(any(String::class.java))).then {
val objective = mock(Objective::class.java)
`when`(objective.getScore(any(String::class.java))).then {
mock(Score::class.java)
}
objective
}
classUnderTest.setLine(scoreboard, 0, "SampleText")
// Assert
Assertions.assertTrue(called)
}
/**
* Given
* a valid line as parameter but invalid scoreboard
* When
* setLine is called
* Then
* Exception should be thrown.
*/
@Test
fun setLine_ValidLineTextInvalidScoreboard_ShouldAddLine() {
// Arrange
val classUnderTest = createWithDependencies()
// Act
assertThrows(IllegalArgumentException::class.java) {
classUnderTest.setLine("wrong parameter", 0, "SampleText")
}
}
companion object {
fun createWithDependencies(): ScoreboardService {
return ScoreboardServiceImpl()
}
}
} | blockball-bukkit-plugin/src/test/java/unittest/ScoreboardServiceTest.kt | 308620227 |
// Copyright (c) 2017-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.flex.psi
import com.intellij.lang.ASTNode
import com.vladsch.md.nav.psi.util.MdPsiBundle
open class FlexmarkExampleAstImpl(node: ASTNode) : FlexmarkExampleSectionImpl(node), FlexmarkExampleAst {
override fun getLanguageNode(): ASTNode? {
return null
}
override fun getFlexmarkExampleParams(example: FlexmarkExample, content: String?): FlexmarkExampleParams {
return FlexmarkExampleParams(example).withAst(content)
}
override fun getSectionDescription(): String = "Flexmark spec example HTML block"
override fun getSectionIndex(): Int = 3
override fun getBreadcrumbInfo(): String {
return MdPsiBundle.message("flexmark-ast")
}
}
| src/main/java/com/vladsch/md/nav/flex/psi/FlexmarkExampleAstImpl.kt | 1209781424 |
package org.stt.gui.jfx
import javafx.scene.Node
import javafx.scene.control.Tooltip
internal object Tooltips {
fun install(node: Node, tooltip: String) {
Tooltip.install(node, Tooltip(tooltip))
}
}
| src/main/kotlin/org/stt/gui/jfx/Tooltips.kt | 2669146140 |
package org.roylance.yaorm.services.mysql.myisam
import org.junit.Test
import org.roylance.yaorm.utilities.ConnectionUtilities
import org.roylance.yaorm.utilities.common.EntityMessageServiceTestUtilities
import org.roylance.yaorm.utilities.common.IEntityMessageServiceTest
class MySQLEntityMessageServiceTest: MySQLISAMBase(), IEntityMessageServiceTest {
@Test
override fun simpleCreateTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.simpleCreateTest(buildEntityService(), cleanup())
}
@Test
override fun simpleLoadAndCreateTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.simpleLoadAndCreateTest(buildEntityService(), cleanup())
}
@Test
override fun complexLoadAndCreateTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.complexLoadAndCreateTest(buildEntityService(), cleanup())
}
@Test
override fun complexLoadAndCreate2Test() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.complexLoadAndCreate2Test(buildEntityService(), cleanup())
}
@Test
override fun complexLoadAndCreateProtectedTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.complexLoadAndCreateProtectedTest(buildEntityService(), cleanup())
}
@Test
override fun simpleGetTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.simpleGetTest(buildEntityService(), cleanup())
}
@Test
override fun bulkInsert1Test() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.bulkInsert1Test(buildEntityService(), cleanup())
}
@Test
override fun simplePassThroughWithReportTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.simplePassThroughWithReportTest(buildEntityService(), cleanup())
}
@Test
override fun simplePassThroughTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
// arrange
EntityMessageServiceTestUtilities.simplePassThroughTest(buildEntityService(), cleanup())
}
@Test
override fun childAddThenDeleteTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.childAddThenDeleteTest(buildEntityService(), cleanup())
}
@Test
override fun verifyChildSerializedProperly() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.verifyChildSerializedProperly(buildEntityService(), cleanup())
}
@Test
override fun verifyChildChangedAfterMergeProperly() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.verifyChildChangedAfterMergeProperly(buildEntityService(), cleanup())
}
@Test
override fun additionalAddRemoveTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.additionalAddRemoveTest(buildEntityService(), cleanup())
}
@Test
override fun simplePersonTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.simplePersonTest(buildEntityService(), cleanup())
}
@Test
override fun simplePersonFriendsTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.simplePersonFriendsTest(buildEntityService(), cleanup())
}
@Test
override fun simpleDagTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.simpleDagTest(buildEntityService(), cleanup())
}
@Test
override fun moreComplexDagTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.moreComplexDagTest(buildEntityService(), cleanup())
}
@Test
override fun simpleUserAndUserDeviceTestTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.simpleUserAndUserDeviceTestTest(buildEntityService(), cleanup())
}
@Test
override fun simpleIndexTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.simpleIndexTest(buildEntityService(), cleanup())
}
@Test
override fun bulkInsertTest() {
if (!ConnectionUtilities.runMySQLTests()) {
return
}
EntityMessageServiceTestUtilities.bulkInsertTest(buildEntityService(), cleanup())
}
}
| yaorm/src/test/java/org/roylance/yaorm/services/mysql/myisam/MySQLEntityMessageServiceTest.kt | 1812533669 |
package com.garpr.android.data.converters
import com.garpr.android.data.models.SimpleDate
import com.garpr.android.extensions.require
import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.ToJson
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
object SimpleDateConverter {
private val UTC = TimeZone.getTimeZone("UTC")
private val FORMAT = object : ThreadLocal<SimpleDateFormat>() {
override fun initialValue(): SimpleDateFormat? {
val format = SimpleDateFormat("MM/dd/yy", Locale.US)
format.isLenient = false
format.timeZone = UTC
return format
}
}
@FromJson
fun fromJson(reader: JsonReader): SimpleDate? {
when (val token = reader.peek()) {
JsonReader.Token.NULL -> {
return reader.nextNull()
}
JsonReader.Token.NUMBER -> {
val timeLong = reader.nextLong()
return SimpleDate(Date(timeLong))
}
JsonReader.Token.STRING -> {
val string = reader.nextString()
val format = FORMAT.require()
val date: Date? = try {
format.parse(string)
} catch (e: ParseException) {
// this Exception can be safely ignored
null
}
if (date != null) {
return SimpleDate(date)
}
throw JsonDataException("Can't parse SimpleDate, unsupported format: \"$string\"")
}
else -> {
throw JsonDataException("Can't parse SimpleDate, unsupported token: \"$token\"")
}
}
}
@ToJson
fun toJson(writer: JsonWriter, value: SimpleDate?) {
if (value != null) {
writer.value(value.date.time)
}
}
}
| smash-ranks-android/app/src/main/java/com/garpr/android/data/converters/SimpleDateConverter.kt | 2065531908 |
/*
* Copyright (C) 2021. Uber Technologies
*
* 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.uber.rib.compose.root.main.logged_in.off_game
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.uber.rib.compose.util.CustomButton
import com.uber.rib.compose.util.EventStream
@Composable
fun OffGameView(viewModel: State<OffGameViewModel>, eventStream: EventStream<OffGameEvent>) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, alignment = Alignment.Bottom),
) {
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text(text = viewModel.value.playerOne)
Text(text = "Win Count: ${viewModel.value.playerOneWins}")
}
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text(text = viewModel.value.playerTwo)
Text(text = "Win Count: ${viewModel.value.playerTwoWins}")
}
CustomButton(
analyticsId = "26882559-fc45",
onClick = { eventStream.notify(OffGameEvent.StartGame) },
modifier = Modifier.fillMaxWidth()
) {
Text(text = "START GAME")
}
}
}
@Preview
@Composable
fun OffGameViewPreview() {
val viewModel = remember { mutableStateOf(OffGameViewModel("James", "Alejandro", 3, 0)) }
OffGameView(viewModel, EventStream())
}
| android/demos/compose/src/main/kotlin/com/uber/rib/compose/root/main/logged_in/off_game/OffGameView.kt | 1630970099 |
package com.abdodaoud.merlin.data.db
import java.util.*
import kotlin.properties.getValue
import kotlin.properties.setValue
class MainFacts(val map: MutableMap<String, Any?>, val dailyFact: List<DayFact>) {
var _id: Long by map
constructor(id: Long, dailyFact: List<DayFact>) : this(HashMap(), dailyFact) {
this._id = id
}
}
class DayFact(var map: MutableMap<String, Any?>) {
var _id: Long by map
var factsId: Long by map
var date: Long by map
var title: String by map
var url: String by map
constructor(factsId: Long, date: Long, title: String, url: String)
: this(HashMap()) {
this.factsId = factsId
this.date = date
this.title = title
this.url = url
}
} | app/src/main/java/com/abdodaoud/merlin/data/db/DbClasses.kt | 3335665508 |
package edu.cs4730.listfragmentdemo_kt
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
/**
* This is an example using the listfragment. There is very little code here that is not default
* except the callbacks for the listfragment named titlefrag.
*
* see the two fragments textFrag and titlefrag for the bulk of the code.
*/
class MainActivity : AppCompatActivity(), titlefrag.OnFragmentInteractionListener {
lateinit var myTextFrag: textFrag
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//get the textFrag from the support manager;
myTextFrag = supportFragmentManager.findFragmentById(R.id.frag_text) as textFrag
}
override fun onItemSelected(id: Int) {
//use the setter in textFrag to change the text.
myTextFrag.setText(id)
}
} | ListViews/ListFragmentDemo_kt/app/src/main/java/edu/cs4730/listfragmentdemo_kt/MainActivity.kt | 84274360 |
package org.http4k.filter.cookie
import org.http4k.core.cookie.Cookie
import java.time.Duration
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.util.concurrent.ConcurrentHashMap
data class LocalCookie(val cookie: Cookie, private val created: Instant) {
@Deprecated("use main constructor", ReplaceWith("LocalCookie(cookie, created.toInstant(java.time.ZoneOffset.UTC))"))
constructor(cookie: Cookie, created: LocalDateTime) : this(cookie, created.toInstant(ZoneOffset.UTC))
@Deprecated("use instant version", ReplaceWith("isExpired(now.toInstant(java.time.ZoneOffset.UTC))"))
fun isExpired(now: LocalDateTime) = isExpired(now.toInstant(java.time.ZoneOffset.UTC))
fun isExpired(now: Instant) =
(cookie.maxAge
?.let { maxAge -> Duration.between(created, now).seconds >= maxAge }
?: cookie.expires?.let { expires ->
Duration.between(created, now).seconds > Duration.between(
created,
expires
).seconds
}) == true
}
interface CookieStorage {
fun store(cookies: List<LocalCookie>)
fun remove(name: String)
fun retrieve(): List<LocalCookie>
}
class BasicCookieStorage : CookieStorage {
private val storage = ConcurrentHashMap<String, LocalCookie>()
override fun store(cookies: List<LocalCookie>) = cookies.forEach { storage[it.cookie.name] = it }
override fun retrieve(): List<LocalCookie> = storage.values.toList()
override fun remove(name: String) {
storage.remove(name)
}
}
| http4k-core/src/main/kotlin/org/http4k/filter/cookie/clientCookies.kt | 1428546368 |
package org.http4k.security.oauth.server.request
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import dev.forkhandles.result4k.Failure
import dev.forkhandles.result4k.Result
import dev.forkhandles.result4k.Success
import org.apache.commons.codec.binary.Base64
import org.http4k.core.Uri
import org.http4k.format.Jackson
import org.http4k.security.ResponseMode.Query
import org.http4k.security.ResponseType.CodeIdToken
import org.http4k.security.State
import org.http4k.security.oauth.server.ClientId
import org.http4k.security.oauth.server.InvalidRequestObject
import org.http4k.security.oauth.server.request.RequestObjectExtractor.extractRequestJwtClaimsAsMap
import org.junit.jupiter.api.Test
import java.time.Instant
internal class RequestObjectExtractorTest {
@Test
fun `if not three parts then failure`() {
assertThat(extractRequestJwtClaimsAsMap("kasdjflksadjfsjdfaksjdf"), equalTo(failure()))
assertThat(extractRequestJwtClaimsAsMap("kasdjflksadj.fsjdfaksjdf"), equalTo(failure()))
assertThat(extractRequestJwtClaimsAsMap("kasdjfl.ksadj.fsjdfa.ksjdf"), equalTo(failure()))
}
@Test
fun `if has three parts but middle part is not valid base64 encoded`() {
assertThat(extractRequestJwtClaimsAsMap("kasdjfl.ksadjfsjd.faksjdf"), equalTo(failure()))
}
@Test
fun `if middle part is correctly base64 encoded but not json then error`() {
assertThat(extractRequestJwtClaimsAsMap("kasdjfl.${Base64.encodeBase64String("something not json".toByteArray())}.faksjdf"),
equalTo(failure()))
}
@Test
fun `if middle part is correctly base64 encoded json then success`() {
assertThat(extractRequestJwtClaimsAsMap("kasdjfl.${Base64.encodeBase64String("{\"foo\":\"bar\"}".toByteArray())}.faksjdf"),
equalTo(success(mapOf("foo" to "bar") as Map<*, *>)))
}
@Test
fun `parses 'full' object correctly`() {
val expiry = Instant.now().epochSecond
val rawData = mapOf(
"iss" to "s6BhdRkqt3",
"aud" to "https://server.example.com",
"response_mode" to "query",
"response_type" to "code id_token",
"client_id" to "s6BhdRkqt3",
"redirect_uri" to "https://client.example.org/cb",
"scope" to "openid",
"state" to "af0ifjsldkj",
"nonce" to "n-0S6_WzA2Mj",
"max_age" to 86400,
"exp" to expiry,
"claims" to mapOf(
"userinfo" to mapOf(
"given_name" to mapOf("essential" to true),
"email" to mapOf("essential" to true),
"email_verified" to mapOf("essential" to true),
"someThingCustomer" to mapOf("value" to "someCustomerValue", "essential" to true)
),
"id_token" to mapOf(
"birthdate" to mapOf("essential" to true),
"acr" to mapOf("values" to listOf("urn:mace:incommon:iap:silver"))
)
)
)
val correspondingExpectedRequestObject = RequestObject(
issuer = "s6BhdRkqt3",
audience = listOf("https://server.example.com"),
responseMode = Query,
responseType = CodeIdToken,
client = ClientId("s6BhdRkqt3"),
redirectUri = Uri.of("https://client.example.org/cb"),
scope = listOf("openid"),
state = State("af0ifjsldkj"),
nonce = org.http4k.security.Nonce("n-0S6_WzA2Mj"),
magAge = 86400,
expiry = expiry,
claims = Claims(
userinfo = mapOf(
"given_name" to Claim(true),
"email" to Claim(true),
"email_verified" to Claim(true),
"someThingCustomer" to Claim(true, value = "someCustomerValue")
),
id_token = mapOf(
"birthdate" to Claim(true),
"acr" to Claim(false, values = listOf("urn:mace:incommon:iap:silver"))
)
)
)
val requestJwt = "someHeader.${Base64.encodeBase64URLSafeString(Jackson.asFormatString(rawData).toByteArray()).replace("=", "")}.someSignature"
assertThat(RequestObjectExtractor.extractRequestObjectFromJwt(requestJwt), equalTo(success(correspondingExpectedRequestObject)))
}
@Test
fun `if has unknown fields ignore them, and parse known ones`() {
val rawData = mapOf(
"iss" to "s6BhdRkqt3",
"foo" to "bar")
val correspondingExpectedRequestObject = RequestObject(
issuer = "s6BhdRkqt3",
audience = emptyList(),
scope = emptyList(),
claims = Claims()
)
val requestJwt = "someHeader.${Base64.encodeBase64URLSafeString(Jackson.asFormatString(rawData).toByteArray()).replace("=", "")}.someSignature"
assertThat(RequestObjectExtractor.extractRequestObjectFromJwt(requestJwt), equalTo(success(correspondingExpectedRequestObject)))
}
@Test
fun `multiple audiences are supported`() {
val rawData = mapOf(
"aud" to listOf("https://audience1", "https://audience2", "https://audience3")
)
val correspondingExpectedRequestObject = RequestObject(
audience = listOf("https://audience1", "https://audience2", "https://audience3"),
scope = emptyList()
)
val requestJwt = "someHeader.${Base64.encodeBase64URLSafeString(Jackson.asFormatString(rawData).toByteArray()).replace("=", "")}.someSignature"
assertThat(RequestObjectExtractor.extractRequestObjectFromJwt(requestJwt), equalTo(success(correspondingExpectedRequestObject)))
}
private fun failure(): Result<Map<*, *>, InvalidRequestObject> = Failure(InvalidRequestObject)
private fun <T> success(data: T): Result<T, InvalidRequestObject> = Success(data)
}
| http4k-security/oauth/src/test/kotlin/org/http4k/security/oauth/server/request/RequestObjectExtractorTest.kt | 2614427609 |
package com.christianbahl.swapico
import android.app.Application
import android.content.Context
import com.christianbahl.swapico.api.SwapiApi
import com.squareup.okhttp.Cache
import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.logging.HttpLoggingInterceptor
import dagger.Module
import dagger.Provides
import retrofit.GsonConverterFactory
import retrofit.Retrofit
import retrofit.RxJavaCallAdapterFactory
import java.io.File
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
/**
* @author Christian Bahl
*/
@Module class AppModule(private val application: Application) {
companion object {
val HTTP_RESPONSE_DISK_CACHE_MAX_SIZE: Long = 10 * 1024 * 1024
val DEFAULT_CONNECT_TIMEOUT_MILLIS: Long = 15 * 1000
val DEFAULT_READ_TIMEOUT_MILLIS: Long = 20 * 1000
val DEFAULT_WRITE_TIMEOUT_MILLIS: Long = 20 * 1000
}
@Provides @Singleton fun provideApplicationContext() = application
@Provides @Singleton fun provideContext(): Context = application
@Provides @Singleton fun provideSwapiApi(okHttpClient: OkHttpClient) =
Retrofit.Builder().baseUrl("http://swapi.co/api/").addConverterFactory(
GsonConverterFactory.create()).addCallAdapterFactory(
RxJavaCallAdapterFactory.create()).client(okHttpClient).build().create(SwapiApi::class.java)
@Provides @Singleton fun provideOkHttpClient(context: Context): OkHttpClient {
val logging = HttpLoggingInterceptor()
logging.setLevel(HttpLoggingInterceptor.Level.BODY)
val okHttpClient = OkHttpClient()
okHttpClient.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
okHttpClient.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
okHttpClient.setWriteTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
okHttpClient.interceptors().add(logging)
val baseDir = context.cacheDir;
if (baseDir != null) {
val cacheDir = File(baseDir, "HttpResponseCache")
okHttpClient.setCache(Cache(cacheDir, HTTP_RESPONSE_DISK_CACHE_MAX_SIZE))
}
return okHttpClient;
}
} | app/src/main/java/com/christianbahl/swapico/AppModule.kt | 3020937550 |
package com.github.mikegehard
import java.math.BigDecimal
import java.math.MathContext
fun main(args: Array<String>) {
val sqFeetToSqMeters = 0.09290304
// This will get you 5 digits, not always 3 decimal places.
val precision = 5
val length = getNumber("What is the length of room in feet?")
val width = getNumber("What is the width of room in feet?")
val areaFeet = length * width
val areaMeters = BigDecimal(areaFeet * sqFeetToSqMeters).round(MathContext(precision))
println("You entered dimensions of $length by $width feet.")
println("The area is:")
println("$areaFeet square feet")
println("$areaMeters square meters")
}
| src/main/com/github/mikegehard/roomSize.kt | 2778143815 |
package org.droidplanner.android.proxy.mission.item.fragments
import com.o3dr.services.android.lib.drone.mission.MissionItemType
import org.droidplanner.android.R
/**
* Created by Fredia Huya-Kouadio on 10/20/15.
*/
class MissionResetROIFragment : MissionDetailFragment() {
override fun getResource() = R.layout.fragment_editor_detail_reset_roi
override fun onApiConnected(){
super.onApiConnected()
typeSpinner.setSelection(commandAdapter.getPosition(MissionItemType.RESET_ROI))
}
} | Android/src/org/droidplanner/android/proxy/mission/item/fragments/MissionResetROIFragment.kt | 2755999975 |
package components.message
import java.awt.Frame
import javax.swing.ImageIcon
import javax.swing.JOptionPane
/**
* Created by vicboma on 10/12/16.
*/
class MessageImpl internal constructor( val frame : Frame, val pair : Pair<String,String>, val option : EnumMessage, val icon : ImageIcon?) : Message {
companion object {
fun create(frame: Frame, pair: Pair<String, String>, option: EnumMessage): Message {
return MessageImpl(frame, pair, option, null)
}
fun create(frame: Frame, pair: Pair<String, String>, option: EnumMessage, icon: ImageIcon): Message {
return MessageImpl(frame, pair, option, icon)
}
}
init {
show()
}
fun show() = JOptionPane.showMessageDialog(frame, pair.second, pair.first, option.value, icon)
} | 04-start-async-dialog-application/src/main/kotlin/components/message/MessageImpl.kt | 145591786 |
/*
* Copyright (C) 2021, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.datmusic.data.db
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import tm.alashow.data.db.BaseTypeConverters
import tm.alashow.datmusic.data.db.daos.AlbumsDao
import tm.alashow.datmusic.data.db.daos.ArtistsDao
import tm.alashow.datmusic.data.db.daos.AudiosDao
import tm.alashow.datmusic.data.db.daos.DownloadRequestsDao
import tm.alashow.datmusic.data.db.daos.PlaylistsDao
import tm.alashow.datmusic.data.db.daos.PlaylistsWithAudiosDao
import tm.alashow.datmusic.domain.entities.Album
import tm.alashow.datmusic.domain.entities.Artist
import tm.alashow.datmusic.domain.entities.Audio
import tm.alashow.datmusic.domain.entities.DownloadRequest
import tm.alashow.datmusic.domain.entities.Playlist
import tm.alashow.datmusic.domain.entities.PlaylistAudio
@Database(
version = 3,
entities = [
Audio::class,
Artist::class,
Album::class,
DownloadRequest::class,
Playlist::class,
PlaylistAudio::class,
],
autoMigrations = [
AutoMigration(from = 1, to = 2),
AutoMigration(from = 2, to = 3),
]
)
@TypeConverters(BaseTypeConverters::class, AppTypeConverters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun audiosDao(): AudiosDao
abstract fun artistsDao(): ArtistsDao
abstract fun albumsDao(): AlbumsDao
abstract fun playlistsDao(): PlaylistsDao
abstract fun playlistsWithAudiosDao(): PlaylistsWithAudiosDao
abstract fun downloadRequestsDao(): DownloadRequestsDao
}
| modules/data/src/main/java/tm/alashow/datmusic/data/db/AppDatabase.kt | 1365412692 |
package pl.mareklangiewicz.ktjvmsample
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestFactory
import pl.mareklangiewicz.uspek.*
import java.util.Locale
/** micro debugging ;-) */
private fun ud(s: String) =
println("ud [${Thread.currentThread().name.padEnd(40).substring(0, 40)}] [${getCurrentTimeString()}] $s")
private val ud get() = ud("")
private fun getCurrentTimeString() = System.currentTimeMillis().let { String.format(Locale.US, "%tT:%tL", it, it) }
private const val maxLoopShort = 9000
private const val maxLoopLong = 50_000_000
class ConcurrentTest {
@Test fun tests_sequential_slowly() = runBlocking(Dispatchers.Default) {
uspekLog = { }
ud("start")
val d1 = suspekAsync { checkAddSlowly(1, 1, 9000); ud("in1") }; ud("out1"); d1.await(); ud("after1")
val d2 = suspekAsync { checkAddSlowly(2, 1, 9000); ud("in2") }; ud("out2"); d2.await(); ud("after2")
ud("end")
}
@Test fun tests_concurrent_slowly() = runBlocking(Dispatchers.Default) {
uspekLog = { }
ud("start")
val d1 = suspekAsync { checkAddSlowly(1, 1, maxLoopShort); ud("in1") }; ud("out1")
val d2 = suspekAsync { checkAddSlowly(2, 1, maxLoopShort); ud("in2") }; ud("out2")
d1.await(); ud("after1")
d2.await(); ud("after2")
ud("end")
}
@Test fun tests_simple_massively() { suspekBlocking {
ud("start")
checkAddFaster(100, 199, 1, maxLoopLong); ud("1")
checkAddFaster(200, 299, 1, maxLoopLong); ud("2")
checkAddFaster(300, 399, 1, maxLoopLong); ud("3")
checkAddFaster(400, 499, 1, maxLoopLong); ud("4")
ud("end")
} }
@Test fun tests_sequential_massively() = runBlocking(Dispatchers.Default) {
ud("start")
val d1 = suspekAsync { checkAddFaster(100, 199, 1, maxLoopLong); ud("in1") }; ud("out1"); d1.await(); ud("after1")
val d2 = suspekAsync { checkAddFaster(200, 299, 1, maxLoopLong); ud("in2") }; ud("out2"); d2.await(); ud("after2")
val d3 = suspekAsync { checkAddFaster(300, 399, 1, maxLoopLong); ud("in3") }; ud("out3"); d3.await(); ud("after3")
val d4 = suspekAsync { checkAddFaster(400, 499, 1, maxLoopLong); ud("in4") }; ud("out4"); d4.await(); ud("after4")
ud("end")
}
@Test fun tests_concurrent_massively() = runBlocking(Dispatchers.Default) {
ud("start")
val d1 = suspekAsync { checkAddFaster(100, 199, 1, maxLoopLong); ud("in1") }; ud("out1")
val d2 = suspekAsync { checkAddFaster(200, 299, 1, maxLoopLong); ud("in2") }; ud("out2")
val d3 = suspekAsync { checkAddFaster(300, 399, 1, maxLoopLong); ud("in3") }; ud("out3")
val d4 = suspekAsync { checkAddFaster(400, 499, 1, maxLoopLong); ud("in4") }; ud("out4")
d1.await(); ud("after1")
d2.await(); ud("after2")
d3.await(); ud("after3")
d4.await(); ud("after4")
ud("end")
}
@TestFactory fun exampleFactory() = suspekTestFactory {
checkAddSlowly(666, 10, 20)
checkAddSlowly(999, 50, 60)
}
suspend fun checkAddSlowly(addArg: Int, resultFrom: Int, resultTo: Int) {
"create SUT for adding $addArg + $resultFrom..$resultTo" so {
val sut = MicroCalc(666)
"check add $addArg" so {
for (i in resultFrom..resultTo) {
// generating tests in a loop is slow because it starts the loop
// again and again just to find and run first not-finished test
"check add $addArg to $i" so {
sut.result = i
sut.add(addArg)
sut.result eq i + addArg
// require(i < resultTo - 3) // this should fail three times
}
}
}
}
}
suspend fun checkAddFaster(addArgFrom: Int, addArgTo: Int, resultFrom: Int, resultTo: Int) {
"create SUT and check add $addArgFrom .. $addArgTo" so {
val sut = MicroCalc(666)
for (addArg in addArgFrom..addArgTo)
for (i in resultFrom..resultTo) {
sut.result = i
sut.add(addArg)
sut.result eq i + addArg
}
// require(false) // enable to test failing
}
}
}
| ktjunit5sample/src/test/kotlin/ConcurrentTest.kt | 2060356774 |
package io.javalin.http
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class HttpCodeTest {
@Test
fun `fetching http codes by code should get the right code`() {
HttpCode.values().forEach {
assertThat(HttpCode.forStatus(it.status)).isEqualTo(it)
}
}
@Test
fun `fetching http codes by code outside of range should not throw errors`() {
assertThat(HttpCode.forStatus(512)).isNull()
assertThat(HttpCode.forStatus(-1)).isNull()
assertThat(HttpCode.forStatus(542345)).isNull()
}
@Test
fun `http code provides formatted implementation of toString() method`() {
HttpCode.values().forEach {
assertThat("${it.status} ${it.message}").isEqualTo(it.toString())
}
}
}
| javalin/src/test/java/io/javalin/http/HttpCodeTest.kt | 1003446445 |
package com.infinum.dbinspector.domain.settings.interactors
import com.infinum.dbinspector.data.Sources
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.koin.core.module.Module
import org.koin.dsl.module
import org.koin.test.get
import org.mockito.kotlin.any
@DisplayName("GetSettingsInteractor tests")
internal class GetSettingsInteractorTest : BaseTest() {
override fun modules(): List<Module> = listOf(
module {
factory { mockk<Sources.Local.Settings>() }
}
)
@Test
fun `Invoking interactor invokes source current`() {
val source: Sources.Local.Settings = get()
val interactor = GetSettingsInteractor(source)
coEvery { source.current() } returns mockk()
test {
interactor.invoke(any())
}
coVerify(exactly = 1) { source.current() }
}
}
| dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/settings/interactors/GetSettingsInteractorTest.kt | 3304958384 |
package io.gitlab.arturbosch.detekt.api.internal
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.test.resource
import io.gitlab.arturbosch.detekt.test.yamlConfig
import org.assertj.core.api.Assertions
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatIllegalStateException
import org.assertj.core.api.Assertions.fail
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.nio.file.Paths
@Suppress("DEPRECATION")
class YamlConfigSpec : Spek({
describe("load yaml config") {
val config by memoized { yamlConfig("detekt.yml") }
it("should create a sub config") {
try {
val subConfig = config.subConfig("style")
assertThat(subConfig.valueOrDefault("WildcardImport", mapOf<String, Any>())).isNotEmpty
assertThat(subConfig.valueOrDefault("WildcardImport", mapOf<String, Any>())["active"].toString()).isEqualTo("true")
assertThat(subConfig.valueOrDefault("WildcardImport", mapOf<String, Any>())["active"] as Boolean).isTrue()
assertThat(subConfig.valueOrDefault("NotFound", mapOf<String, Any>())).isEmpty()
assertThat(subConfig.valueOrDefault("NotFound", "")).isEmpty()
} catch (ignored: Config.InvalidConfigurationError) {
fail("Creating a sub config should work for test resources config!")
}
}
it("should create a sub sub config") {
try {
val subConfig = config.subConfig("style")
val subSubConfig = subConfig.subConfig("WildcardImport")
assertThat(subSubConfig.valueOrDefault("active", false)).isTrue()
assertThat(subSubConfig.valueOrDefault("NotFound", true)).isTrue()
} catch (ignored: Config.InvalidConfigurationError) {
fail("Creating a sub config should work for test resources config!")
}
}
it("tests wrong sub config conversion") {
assertThatIllegalStateException().isThrownBy {
@Suppress("UNUSED_VARIABLE")
val ignored = config.valueOrDefault("style", "")
}.withMessage("Value \"{WildcardImport={active=true}, NoElseInWhenExpression={active=true}, MagicNumber={active=true, ignoreNumbers=[-1, 0, 1, 2]}}\" set for config parameter \"style\" is not of required type String.")
}
}
describe("loading empty configurations") {
it("empty yaml file is equivalent to empty config") {
YamlConfig.loadResource(javaClass.getResource("/empty.yml"))
}
it("single item in yaml file is valid") {
YamlConfig.loadResource(javaClass.getResource("/oneitem.yml"))
}
}
describe("meaningful error messages") {
val config by memoized { yamlConfig("wrong-property-type.yml") }
it("only accepts true and false boolean values") {
assertThatIllegalStateException()
.isThrownBy { config.valueOrDefault("bool", false) }
.withMessage("""Value "fasle" set for config parameter "bool" is not of required type Boolean.""")
}
it("prints whole config-key path for NumberFormatException") {
assertThatIllegalStateException().isThrownBy {
config.subConfig("RuleSet")
.subConfig("Rule")
.valueOrDefault("threshold", 6)
}.withMessage("Value \"v5.7\" set for config parameter \"RuleSet > Rule > threshold\" is not of required type Int.")
}
it("prints whole config-key path for ClassCastException") {
assertThatIllegalStateException().isThrownBy {
@Suppress("UNUSED_VARIABLE")
val bool: Int = config.subConfig("RuleSet")
.subConfig("Rule")
.valueOrDefault("active", 1)
}.withMessage("Value \"[]\" set for config parameter \"RuleSet > Rule > active\" is not of required type Int.")
}
}
describe("yaml config") {
it("loads the config from a given yaml file") {
val path = Paths.get(resource("detekt.yml"))
val config = YamlConfig.load(path)
assertThat(config).isNotNull
}
it("loads the config from a given text file") {
val path = Paths.get(resource("detekt.txt"))
val config = YamlConfig.load(path)
assertThat(config).isNotNull
}
it("throws an exception on an non-existing file") {
val path = Paths.get("doesNotExist.yml")
Assertions.assertThatIllegalArgumentException()
.isThrownBy { YamlConfig.load(path) }
.withMessageStartingWith("Configuration does not exist")
}
it("throws an exception on a directory") {
val path = Paths.get(resource("/config_validation"))
Assertions.assertThatIllegalArgumentException()
.isThrownBy { YamlConfig.load(path) }
.withMessageStartingWith("Configuration must be a file")
}
}
})
| detekt-api/src/test/kotlin/io/gitlab/arturbosch/detekt/api/internal/YamlConfigSpec.kt | 2013664221 |
package com.example.aleckstina.wespeakandroid.fragment
import android.annotation.TargetApi
import android.app.DialogFragment
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.example.aleckstina.wespeakandroid.R
import com.example.aleckstina.wespeakandroid.activities.ReviewActivity
/**
* Created by aleckstina on 10/12/17.
*/
class PopupDialogFragment() : DialogFragment() {
companion object {
public fun newInstance(title: String) : PopupDialogFragment {
val dialog = PopupDialogFragment()
val args = Bundle()
args.putString("title", title)
dialog.arguments = args
return dialog
}
}
@TargetApi(Build.VERSION_CODES.M)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val dialogView = inflater.inflate(R.layout.popup_fragment, container, false)
setAvatar(dialogView)
Handler().postDelayed(Runnable {
activateScreen(context)
}, 3000)
return dialogView
}
private fun activateScreen(context: Context) {
startActivity(Intent(context, ReviewActivity::class.java))
}
private fun setAvatar(view: View) {
Glide
.with(this)
.load(R.mipmap.avatar_test)
.apply(RequestOptions.circleCropTransform())
.into(view.findViewById(R.id.avatar))
Glide
.with(this)
.load(R.mipmap.flag_test)
.into(view.findViewById(R.id.flag))
}
}
| app/src/main/java/com/example/aleckstina/wespeakandroid/fragment/PopupDialogFragment.kt | 4027889145 |
/*
* 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.anki
import android.content.Context
import android.content.SharedPreferences
import androidx.annotation.CheckResult
import androidx.core.content.edit
import com.ichi2.anki.servicelayer.PreferenceUpgradeService
import com.ichi2.anki.servicelayer.PreferenceUpgradeService.setPreferencesUpToDate
import com.ichi2.utils.VersionUtils.pkgVersionName
import timber.log.Timber
/** Utilities for launching the first activity (currently the DeckPicker) */
object InitialActivity {
/** Returns null on success */
@CheckResult
fun getStartupFailureType(context: Context): StartupFailure? {
// A WebView failure means that we skip `AnkiDroidApp`, and therefore haven't loaded the collection
if (AnkiDroidApp.webViewFailedToLoad()) {
return StartupFailure.WEBVIEW_FAILED
}
// If we're OK, return null
if (CollectionHelper.instance.getColSafe(context, reportException = false) != null) {
return null
}
if (!AnkiDroidApp.isSdCardMounted) {
return StartupFailure.SD_CARD_NOT_MOUNTED
} else if (!CollectionHelper.isCurrentAnkiDroidDirAccessible(context)) {
return StartupFailure.DIRECTORY_NOT_ACCESSIBLE
}
return when (CollectionHelper.lastOpenFailure) {
CollectionHelper.CollectionOpenFailure.FILE_TOO_NEW -> StartupFailure.FUTURE_ANKIDROID_VERSION
CollectionHelper.CollectionOpenFailure.CORRUPT -> StartupFailure.DB_ERROR
CollectionHelper.CollectionOpenFailure.LOCKED -> StartupFailure.DATABASE_LOCKED
null -> {
// if getColSafe returned null, this should never happen
null
}
}
}
/** @return Whether any preferences were upgraded
*/
fun upgradePreferences(context: Context?, previousVersionCode: Long): Boolean {
return PreferenceUpgradeService.upgradePreferences(context, previousVersionCode)
}
/**
* @return Whether a fresh install occurred and a "fresh install" setup for preferences was performed
* This only refers to a fresh install from the preferences perspective, not from the Anki data perspective.
*
* NOTE: A user can wipe app data, which will mean this returns true WITHOUT deleting their collection.
* The above note will need to be reevaluated after scoped storage migration takes place
*
*
* On the other hand, restoring an app backup can cause this to return true before the Anki collection is created
* in practice, this doesn't occur due to CollectionHelper.getCol creating a new collection, and it's called before
* this in the startup script
*/
@CheckResult
fun performSetupFromFreshInstallOrClearedPreferences(preferences: SharedPreferences): Boolean {
if (!wasFreshInstall(preferences)) {
Timber.d("Not a fresh install [preferences]")
return false
}
Timber.i("Fresh install")
setPreferencesUpToDate(preferences)
setUpgradedToLatestVersion(preferences)
return true
}
/**
* true if the app was launched the first time
* false if the app was launched for the second time after a successful initialisation
* false if the app was launched after an update
*/
fun wasFreshInstall(preferences: SharedPreferences) =
"" == preferences.getString("lastVersion", "")
/** Sets the preference stating that the latest version has been applied */
fun setUpgradedToLatestVersion(preferences: SharedPreferences) {
Timber.i("Marked prefs as upgraded to latest version: %s", pkgVersionName)
preferences.edit { putString("lastVersion", pkgVersionName) }
}
/** @return false: The app has been upgraded since the last launch OR the app was launched for the first time.
* Implementation detail:
* This is not called in the case of performSetupFromFreshInstall returning true.
* So this should not use the default value
*/
fun isLatestVersion(preferences: SharedPreferences): Boolean {
return preferences.getString("lastVersion", "") == pkgVersionName
}
enum class StartupFailure {
SD_CARD_NOT_MOUNTED, DIRECTORY_NOT_ACCESSIBLE, FUTURE_ANKIDROID_VERSION,
DB_ERROR, DATABASE_LOCKED, WEBVIEW_FAILED
}
}
| AnkiDroid/src/main/java/com/ichi2/anki/InitialActivity.kt | 3879342553 |
package io.gitlab.arturbosch.detekt.rules.exceptions
import io.gitlab.arturbosch.detekt.api.CodeSmell
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.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.valueOrDefaultCommaSeparated
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtThrowExpression
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
/**
* This rule allows to define functions which should never throw an exception. If a function exists that does throw
* an exception it will be reported. By default this rule is checking for `toString`, `hashCode`, `equals` and
* `finalize`. This rule is configurable via the `methodNames` configuration to change the list of functions which
* should not throw any exceptions.
*
* <noncompliant>
* class Foo {
*
* override fun toString(): String {
* throw IllegalStateException() // exception should not be thrown here
* }
* }
* </noncompliant>
*
* @configuration methodNames - methods which should not throw exceptions
* (default: `[toString, hashCode, equals, finalize]`)
*/
class ExceptionRaisedInUnexpectedLocation(config: Config = Config.empty) : Rule(config) {
override val issue = Issue("ExceptionRaisedInUnexpectedLocation", Severity.CodeSmell,
"This method is not expected to throw exceptions. This can cause weird behavior.",
Debt.TWENTY_MINS)
private val methods = valueOrDefaultCommaSeparated(
METHOD_NAMES,
listOf("toString", "hashCode", "equals", "finalize"))
override fun visitNamedFunction(function: KtNamedFunction) {
if (isPotentialMethod(function) && hasThrowExpression(function.bodyExpression)) {
report(CodeSmell(issue, Entity.from(function), issue.description))
}
}
private fun isPotentialMethod(function: KtNamedFunction) = methods.any { function.name == it }
private fun hasThrowExpression(declaration: KtExpression?) =
declaration?.anyDescendantOfType<KtThrowExpression>() == true
companion object {
const val METHOD_NAMES = "methodNames"
}
}
| detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/ExceptionRaisedInUnexpectedLocation.kt | 2404981679 |
/****************************************************************************************
* Copyright (c) 2011 Kostas Spyropoulos <[email protected]> *
* Copyright (c) 2014 Houssam Salem <[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 android.database.SQLException
import android.net.Uri
import android.text.TextUtils
import com.ichi2.anki.CrashReportService
import com.ichi2.libanki.exception.EmptyMediaException
import com.ichi2.libanki.template.TemplateFilters
import com.ichi2.utils.*
import com.ichi2.utils.HashUtil.HashMapInit
import org.json.JSONArray
import org.json.JSONObject
import timber.log.Timber
import java.io.*
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import java.util.zip.ZipOutputStream
import kotlin.math.min
/**
* Media manager - handles the addition and removal of media files from the media directory (collection.media) and
* maintains the media database (collection.media.ad.db2) which is used to determine the state of files for syncing.
* Note that the media database has an additional prefix for AnkiDroid (.ad) to avoid any potential issues caused by
* users copying the file to the desktop client and vice versa.
*
*
* Unlike the python version of this module, we do not (and cannot) modify the current working directory (CWD) before
* performing operations on media files. In python, the CWD is changed to the media directory, allowing it to easily
* refer to the files in the media directory by name only. In Java, we must be cautious about when to specify the full
* path to the file and when we need to use the filename only. In general, when we refer to a file on disk (i.e.,
* creating a new File() object), we must include the full path. Use the dir() method to make this step easier.
*
* E.g: new File(dir(), "filename.jpg")
*/
@KotlinCleanup("IDE Lint")
open class Media(private val col: Collection, server: Boolean) {
private var mDir: String?
/**
* Used by unit tests only.
*/
@KotlinCleanup("non-null + exception if used after .close()")
var db: DB? = null
private set
open fun connect() {
if (col.server) {
return
}
// NOTE: We use a custom prefix for AnkiDroid to avoid issues caused by copying
// the db to the desktop or vice versa.
val path = dir() + ".ad.db2"
val dbFile = File(path)
val create = !dbFile.exists()
db = DB.withAndroidFramework(col.context, path)
if (create) {
_initDB()
}
maybeUpgrade()
}
fun _initDB() {
val sql = """create table media (
fname text not null primary key,
csum text, -- null indicates deleted file
mtime int not null, -- zero if deleted
dirty int not null
);
create index idx_media_dirty on media (dirty);
create table meta (dirMod int, lastUsn int); insert into meta values (0, 0);"""
db!!.executeScript(sql)
}
private fun maybeUpgrade() {
val oldPath = dir() + ".db"
val oldDbFile = File(oldPath)
if (oldDbFile.exists()) {
db!!.execute(String.format(Locale.US, "attach \"%s\" as old", oldPath))
try {
val sql = """insert into media
select m.fname, csum, mod, ifnull((select 1 from log l2 where l2.fname=m.fname), 0) as dirty
from old.media m
left outer join old.log l using (fname)
union
select fname, null, 0, 1 from old.log where type=${Consts.CARD_TYPE_LRN};"""
db!!.apply {
execute(sql)
execute("delete from meta")
execute("insert into meta select dirMod, usn from old.meta")
commit()
}
} catch (e: Exception) {
// if we couldn't import the old db for some reason, just start anew
val sw = StringWriter()
e.printStackTrace(PrintWriter(sw))
col.log("failed to import old media db:$sw")
}
db!!.execute("detach old")
val newDbFile = File("$oldPath.old")
if (newDbFile.exists()) {
newDbFile.delete()
}
oldDbFile.renameTo(newDbFile)
}
}
open fun close() {
if (col.server) {
return
}
db!!.close()
db = null
}
private fun _deleteDB() {
val path = db!!.path
close()
File(path).delete()
connect()
}
@KotlinCleanup("nullable if server == true, we don't do this in AnkiDroid so should be fine")
fun dir(): String = mDir!!
/*
Adding media
***********************************************************
*/
/**
* In AnkiDroid, adding a media file will not only copy it to the media directory, but will also insert an entry
* into the media database marking it as a new addition.
*/
@Throws(IOException::class, EmptyMediaException::class)
@KotlinCleanup("scope function: fname")
fun addFile(oFile: File?): String {
if (oFile == null || oFile.length() == 0L) {
throw EmptyMediaException()
}
val fname = writeData(oFile)
markFileAdd(fname)
return fname
}
/**
* Copy a file to the media directory and return the filename it was stored as.
*
*
* Unlike the python version of this method, we don't read the file into memory as a string. All our operations are
* done on streams opened on the file, so there is no second parameter for the string object here.
*/
@Throws(IOException::class)
private fun writeData(oFile: File): String {
// get the file name
var fname = oFile.name
// make sure we write it in NFC form and return an NFC-encoded reference
fname = Utils.nfcNormalized(fname)
// ensure it's a valid filename
val base = cleanFilename(fname)
val split = Utils.splitFilename(base)
var root = split[0]
val ext = split[1]
// find the first available name
val csum = Utils.fileChecksum(oFile)
while (true) {
fname = root + ext
val path = File(dir(), fname)
// if it doesn't exist, copy it directly
if (!path.exists()) {
Utils.copyFile(oFile, path)
return fname
}
// if it's identical, reuse
if (Utils.fileChecksum(path) == csum) {
return fname
}
// otherwise, increment the checksum in the filename
root = "$root-$csum"
}
}
/**
* Extract media filenames from an HTML string.
*
* @param string The string to scan for media filenames ([sound:...] or <img...>).
* @param includeRemote If true will also include external http/https/ftp urls.
* @return A list containing all the sound and image filenames found in the input string.
*/
/**
* String manipulation
* ***********************************************************
*/
fun filesInStr(mid: Long?, string: String, includeRemote: Boolean = false): List<String> {
val l: MutableList<String> = ArrayList()
val model = col.models.get(mid!!)
var strings: MutableList<String?> = ArrayList()
if (model!!.isCloze && string.contains("{{c")) {
// if the field has clozes in it, we'll need to expand the
// possibilities so we can render latex
strings = _expandClozes(string)
} else {
strings.add(string)
}
for (s in strings) {
@Suppress("NAME_SHADOWING")
var s = s
// handle latex
@KotlinCleanup("change to .map { }")
val svg = model.optBoolean("latexsvg", false)
s = LaTeX.mungeQA(s!!, col, svg)
// extract filenames
var m: Matcher
for (p in REGEXPS) {
// NOTE: python uses the named group 'fname'. Java doesn't have named groups, so we have to determine
// the index based on which pattern we are using
val fnameIdx = if (p == fSoundRegexps) 2 else if (p == fImgAudioRegExpU) 2 else 3
m = p.matcher(s)
while (m.find()) {
val fname = m.group(fnameIdx)!!
val isLocal =
!fRemotePattern.matcher(fname.lowercase(Locale.getDefault())).find()
if (isLocal || includeRemote) {
l.add(fname)
}
}
}
}
return l
}
private fun _expandClozes(string: String): MutableList<String?> {
val ords: MutableSet<String> = TreeSet()
var m = // In Android, } should be escaped
Pattern.compile("\\{\\{c(\\d+)::.+?\\}\\}").matcher(string)
while (m.find()) {
ords.add(m.group(1)!!)
}
val strings = ArrayList<String?>(ords.size + 1)
val clozeReg = TemplateFilters.CLOZE_REG
for (ord in ords) {
val buf = StringBuffer()
m = Pattern.compile(String.format(Locale.US, clozeReg, ord)).matcher(string)
while (m.find()) {
if (!TextUtils.isEmpty(m.group(4))) {
m.appendReplacement(buf, "[$4]")
} else {
m.appendReplacement(buf, TemplateFilters.CLOZE_DELETION_REPLACEMENT)
}
}
m.appendTail(buf)
val s =
buf.toString().replace(String.format(Locale.US, clozeReg, ".+?").toRegex(), "$2")
strings.add(s)
}
strings.add(string.replace(String.format(Locale.US, clozeReg, ".+?").toRegex(), "$2"))
return strings
}
/**
* Strips a string from media references.
*
* @param txt The string to be cleared of media references.
* @return The media-free string.
*/
@KotlinCleanup("return early and remove var")
fun strip(txt: String): String {
@Suppress("NAME_SHADOWING")
var txt = txt
for (p in REGEXPS) {
txt = p.matcher(txt).replaceAll("")
}
return txt
}
/*
Rebuilding DB
***********************************************************
*/
/**
* Finds missing, unused and invalid media files
*
* @return A list containing three lists of files (missingFiles, unusedFiles, invalidFiles)
*/
open fun check(): MediaCheckResult = check(null)
private fun check(local: Array<File>?): MediaCheckResult {
val mdir = File(dir())
// gather all media references in NFC form
val allRefs: MutableSet<String> = HashSet()
col.db.query("select id, mid, flds from notes").use { cur ->
while (cur.moveToNext()) {
val nid = cur.getLong(0)
val mid = cur.getLong(1)
val flds = cur.getString(2)
var noteRefs = filesInStr(mid, flds)
// check the refs are in NFC
@KotlinCleanup("simplify with first {}")
for (f in noteRefs) {
// if they're not, we'll need to fix them first
if (f != Utils.nfcNormalized(f)) {
_normalizeNoteRefs(nid)
noteRefs = filesInStr(mid, flds)
break
}
}
allRefs.addAll(noteRefs)
}
}
// loop through media directory
val unused: MutableList<String> = ArrayList()
val invalid: List<String> = ArrayList()
val files: Array<File>
files = local ?: mdir.listFiles()!!
var renamedFiles = false
for (file in files) {
@Suppress("NAME_SHADOWING")
var file = file
if (local == null) {
if (file.isDirectory) {
// ignore directories
continue
}
}
if (file.name.startsWith("_")) {
// leading _ says to ignore file
continue
}
val nfcFile = File(dir(), Utils.nfcNormalized(file.name))
// we enforce NFC fs encoding
if (local == null) {
if (file.name != nfcFile.name) {
// delete if we already have the NFC form, otherwise rename
renamedFiles = if (nfcFile.exists()) {
file.delete()
true
} else {
file.renameTo(nfcFile)
true
}
file = nfcFile
}
}
// compare
if (!allRefs.contains(nfcFile.name)) {
unused.add(file.name)
} else {
allRefs.remove(nfcFile.name)
}
}
// if we renamed any files to nfc format, we must rerun the check
// to make sure the renamed files are not marked as unused
if (renamedFiles) {
return check(local)
}
@KotlinCleanup(".filter { }")
val noHave: MutableList<String> = ArrayList()
for (x in allRefs) {
if (!x.startsWith("_")) {
noHave.add(x)
}
}
// make sure the media DB is valid
try {
findChanges()
} catch (ignored: SQLException) {
Timber.w(ignored)
_deleteDB()
}
return MediaCheckResult(noHave, unused, invalid)
}
private fun _normalizeNoteRefs(nid: Long) {
val note = col.getNote(nid)
val flds = note.fields
@KotlinCleanup("improve")
for (c in flds.indices) {
val fld = flds[c]
val nfc = Utils.nfcNormalized(fld)
if (nfc != fld) {
note.setField(c, nfc)
}
}
note.flush()
}
/**
* Copying on import
* ***********************************************************
*/
open fun have(fname: String): Boolean = File(dir(), fname).exists()
/**
* Illegal characters and paths
* ***********************************************************
*/
fun stripIllegal(str: String): String = fIllegalCharReg.matcher(str).replaceAll("")
fun hasIllegal(str: String): Boolean = fIllegalCharReg.matcher(str).find()
@KotlinCleanup("fix reassignment")
fun cleanFilename(fname: String): String {
@Suppress("NAME_SHADOWING")
var fname = fname
fname = stripIllegal(fname)
fname = _cleanWin32Filename(fname)
fname = _cleanLongFilename(fname)
if ("" == fname) {
fname = "renamed"
}
return fname
}
/** This method only change things on windows. So it's the
* identity here. */
private fun _cleanWin32Filename(fname: String): String = fname
@KotlinCleanup("Fix reassignment")
private fun _cleanLongFilename(fname: String): String {
/* a fairly safe limit that should work on typical windows
paths and on eCryptfs partitions, even with a duplicate
suffix appended */
@Suppress("NAME_SHADOWING")
var fname = fname
var nameMax = 136
val pathMax = 1024 // 240 for windows
// cap nameMax based on absolute path
val dirLen =
fname.length // ideally, name should be normalized. Without access to nio.Paths library, it's hard to do it really correctly. This is still a better approximation than nothing.
val remaining = pathMax - dirLen
nameMax = min(remaining, nameMax)
Assert.that(
nameMax > 0,
"The media directory is maximally long. There is no more length available for file name."
)
if (fname.length > nameMax) {
val lastSlash = fname.indexOf("/")
val lastDot = fname.indexOf(".")
if (lastDot == -1 || lastDot < lastSlash) {
// no dot, or before last slash
fname = fname.substring(0, nameMax)
} else {
val ext = fname.substring(lastDot + 1)
var head = fname.substring(0, lastDot)
val headMax = nameMax - ext.length
head = head.substring(0, headMax)
fname = head + ext
Assert.that(
fname.length <= nameMax,
"The length of the file is greater than the maximal name value."
)
}
}
return fname
}
/*
Tracking changes
***********************************************************
*/
/**
* Scan the media directory if it's changed, and note any changes.
*/
fun findChanges() {
findChanges(false)
}
/**
* @param force Unconditionally scan the media directory for changes (i.e., ignore differences in recorded and current
* directory mod times). Use this when rebuilding the media database.
*/
open fun findChanges(force: Boolean) {
if (force || _changed() != null) {
_logChanges()
}
}
fun haveDirty(): Boolean = db!!.queryScalar("select 1 from media where dirty=1 limit 1") > 0
/**
* Returns the number of seconds from epoch since the last modification to the file in path. Important: this method
* does not automatically append the root media directory to the path; the FULL path of the file must be specified.
*
* @param path The path to the file we are checking. path can be a file or a directory.
* @return The number of seconds (rounded down).
*/
private fun _mtime(path: String): Long = File(path).lastModified() / 1000
private fun _checksum(path: String): String = Utils.fileChecksum(path)
/**
* Return dir mtime if it has changed since the last findChanges()
* Doesn't track edits, but user can add or remove a file to update
*
* @return The modification time of the media directory if it has changed since the last call of findChanges(). If
* it hasn't, it returns null.
*/
fun _changed(): Long? {
val mod = db!!.queryLongScalar("select dirMod from meta")
val mtime = _mtime(dir())
return if (mod != 0L && mod == mtime) {
null
} else mtime
}
@KotlinCleanup("destructure directly val (added, removed) = _changes()")
private fun _logChanges() {
val result = _changes()
val added = result.first
val removed = result.second
val media = ArrayList<Array<Any?>>(added.size + removed.size)
for (f in added) {
val path = File(dir(), f).absolutePath
val mt = _mtime(path)
media.add(arrayOf(f, _checksum(path), mt, 1))
}
for (f in removed) {
media.add(arrayOf(f, null, 0, 1))
}
// update media db
db!!.apply {
executeMany("insert or replace into media values (?,?,?,?)", media)
execute("update meta set dirMod = ?", _mtime(dir()))
commit()
}
}
private fun _changes(): Pair<List<String>, List<String>> {
val cache: MutableMap<String, Array<Any>> = HashMapInit(
db!!.queryScalar("SELECT count() FROM media WHERE csum IS NOT NULL")
)
try {
db!!.query("select fname, csum, mtime from media where csum is not null").use { cur ->
while (cur.moveToNext()) {
val name = cur.getString(0)
val csum = cur.getString(1)
val mod = cur.getLong(2)
cache[name] = arrayOf(csum, mod, false)
}
}
} catch (e: SQLException) {
throw RuntimeException(e)
}
val added: MutableList<String> = ArrayList()
val removed: MutableList<String> = ArrayList()
// loop through on-disk files
for (f in File(dir()).listFiles()!!) {
// ignore directories and thumbs.db
if (f.isDirectory) {
continue
}
val fname = f.name
if ("thumbs.db".equals(fname, ignoreCase = true)) {
continue
}
// and files with invalid chars
if (hasIllegal(fname)) {
continue
}
// empty files are invalid; clean them up and continue
val sz = f.length()
if (sz == 0L) {
f.delete()
continue
}
if (sz > 100 * 1024 * 1024) {
col.log("ignoring file over 100MB", f)
continue
}
// check encoding
val normf = Utils.nfcNormalized(fname)
if (fname != normf) {
// wrong filename encoding which will cause sync errors
val nf = File(dir(), normf)
if (nf.exists()) {
f.delete()
} else {
f.renameTo(nf)
}
}
// newly added?
if (!cache.containsKey(fname)) {
added.add(fname)
} else {
// modified since last time?
if (_mtime(f.absolutePath) != cache[fname]!![1] as Long) {
// and has different checksum?
if (_checksum(f.absolutePath) != cache[fname]!![0]) {
added.add(fname)
}
}
// mark as used
cache[fname]!![2] = true
}
}
// look for any entries in the cache that no longer exist on disk
for ((key, value) in cache) {
if (!(value[2] as Boolean)) {
removed.add(key)
}
}
return Pair(added, removed)
}
/**
* Syncing related
* ***********************************************************
*/
fun lastUsn(): Int = db!!.queryScalar("select lastUsn from meta")
fun setLastUsn(usn: Int) {
db!!.execute("update meta set lastUsn = ?", usn)
db!!.commit()
}
fun syncInfo(fname: String?): Pair<String?, Int> {
db!!.query("select csum, dirty from media where fname=?", fname!!).use { cur ->
return if (cur.moveToNext()) {
val csum = cur.getString(0)
val dirty = cur.getInt(1)
Pair(csum, dirty)
} else {
Pair(null, 0)
}
}
}
fun markClean(fnames: List<String?>) {
for (fname in fnames) {
db!!.execute("update media set dirty=0 where fname=?", fname!!)
}
}
fun syncDelete(fname: String) {
val f = File(dir(), fname)
if (f.exists()) {
f.delete()
}
db!!.execute("delete from media where fname=?", fname)
}
fun mediacount(): Int = db!!.queryScalar("select count() from media where csum is not null")
fun dirtyCount(): Int = db!!.queryScalar("select count() from media where dirty=1")
open fun forceResync() {
db!!.apply {
execute("delete from media")
execute("update meta set lastUsn=0,dirMod=0")
execute("vacuum")
execute("analyze")
commit()
}
}
/*
* Media syncing: zips
* ***********************************************************
*/
/**
* Unlike python, our temp zip file will be on disk instead of in memory. This avoids storing
* potentially large files in memory which is not feasible with Android's limited heap space.
*
*
* Notes:
*
*
* - The maximum size of the changes zip is decided by the constant SYNC_ZIP_SIZE. If a media file exceeds this
* limit, only that file (in full) will be zipped to be sent to the server.
*
*
* - This method will be repeatedly called from MediaSyncer until there are no more files (marked "dirty" in the DB)
* to send.
*
*
* - Since AnkiDroid avoids scanning the media directory on every sync, it is possible for a file to be marked as a
* new addition but actually have been deleted (e.g., with a file manager). In this case we skip over the file
* and mark it as removed in the database. (This behaviour differs from the desktop client).
*
*
*/
fun mediaChangesZip(): Pair<File, List<String>> {
val f = File(col.path.replaceFirst("collection\\.anki2$".toRegex(), "tmpSyncToServer.zip"))
val fnames: MutableList<String> = ArrayList()
try {
ZipOutputStream(BufferedOutputStream(FileOutputStream(f))).use { z ->
db!!.query(
"select fname, csum from media where dirty=1 limit " + Consts.SYNC_MAX_FILES
).use { cur ->
z.setMethod(ZipOutputStream.DEFLATED)
// meta is a list of (fname, zipName), where zipName of null is a deleted file
// NOTE: In python, meta is a list of tuples that then gets serialized into json and added
// to the zip as a string. In our version, we use JSON objects from the start to avoid the
// serialization step. Instead of a list of tuples, we use JSONArrays of JSONArrays.
val meta = JSONArray()
var sz = 0
val buffer = ByteArray(2048)
var c = 0
while (cur.moveToNext()) {
val fname = cur.getString(0)
val csum = cur.getString(1)
fnames.add(fname)
val normName = Utils.nfcNormalized(fname)
if (!TextUtils.isEmpty(csum)) {
try {
col.log("+media zip $fname")
val file = File(dir(), fname)
val bis = BufferedInputStream(FileInputStream(file), 2048)
z.putNextEntry(ZipEntry(Integer.toString(c)))
@KotlinCleanup("improve")
var count: Int
while (bis.read(buffer, 0, 2048).also { count = it } != -1) {
z.write(buffer, 0, count)
}
z.closeEntry()
bis.close()
meta.put(JSONArray().put(normName).put(Integer.toString(c)))
sz += file.length().toInt()
} catch (e: FileNotFoundException) {
Timber.w(e)
// A file has been marked as added but no longer exists in the media directory.
// Skip over it and mark it as removed in the db.
removeFile(fname)
}
} else {
col.log("-media zip $fname")
meta.put(JSONArray().put(normName).put(""))
}
if (sz >= Consts.SYNC_MAX_BYTES) {
break
}
c++
}
z.putNextEntry(ZipEntry("_meta"))
z.write(Utils.jsonToString(meta).toByteArray())
z.closeEntry()
// Don't leave lingering temp files if the VM terminates.
f.deleteOnExit()
return Pair(f, fnames)
}
}
} catch (e: IOException) {
Timber.e(e, "Failed to create media changes zip: ")
throw RuntimeException(e)
}
}
/**
* Extract zip data; return the number of files extracted. Unlike the python version, this method consumes a
* ZipFile stored on disk instead of a String buffer. Holding the entire downloaded data in memory is not feasible
* since some devices can have very limited heap space.
*
* This method closes the file before it returns.
*/
@Throws(IOException::class)
fun addFilesFromZip(z: ZipFile): Int {
return try {
// get meta info first
val meta =
JSONObject(Utils.convertStreamToString(z.getInputStream(z.getEntry("_meta"))))
// then loop through all files
var cnt = 0
val zipEntries = Collections.list(z.entries())
val media: MutableList<Array<Any>> = ArrayList(zipEntries.size)
for (i in zipEntries) {
val fileName = i.name
if ("_meta" == fileName) {
// ignore previously-retrieved meta
continue
}
var name = meta.getString(fileName)
// normalize name for platform
name = Utils.nfcNormalized(name)
// save file
val destPath = dir() + File.separator + name
z.getInputStream(i)
.use { zipInputStream -> Utils.writeToFile(zipInputStream, destPath) }
val csum = Utils.fileChecksum(destPath)
// update db
media.add(arrayOf(name, csum, _mtime(destPath), 0))
cnt += 1
}
if (!media.isEmpty()) {
db!!.executeMany("insert or replace into media values (?,?,?,?)", media)
}
cnt
} finally {
z.close()
}
}
/*
* ***********************************************************
* The methods below are not in LibAnki.
* ***********************************************************
*/
/**
* Add an entry into the media database for file named fname, or update it
* if it already exists.
*/
open fun markFileAdd(fname: String) {
Timber.d("Marking media file addition in media db: %s", fname)
val path = File(dir(), fname).absolutePath
db!!.execute(
"insert or replace into media values (?,?,?,?)",
fname, _checksum(path), _mtime(path), 1
)
}
/**
* Remove a file from the media directory if it exists and mark it as removed in the media database.
*/
open fun removeFile(fname: String) {
val f = File(dir(), fname)
if (f.exists()) {
f.delete()
}
Timber.d("Marking media file removal in media db: %s", fname)
db!!.execute(
"insert or replace into media values (?,?,?,?)",
fname, null, 0, 1
)
}
/**
* @return True if the media db has not been populated yet.
*/
fun needScan(): Boolean {
val mod = db!!.queryLongScalar("select dirMod from meta")
return mod == 0L
}
@Throws(IOException::class)
open fun rebuildIfInvalid() {
try {
_changed()
return
} catch (e: Exception) {
if (!ExceptionUtil.containsMessage(e, "no such table: meta")) {
throw e
}
CrashReportService.sendExceptionReport(e, "media::rebuildIfInvalid")
// TODO: We don't know the root cause of the missing meta table
Timber.w(e, "Error accessing media database. Rebuilding")
// continue below
}
// Delete and recreate the file
db!!.database.close()
val path = db!!.path
Timber.i("Deleted %s", path)
File(path).delete()
db = DB.withAndroidFramework(col.context, path)
_initDB()
}
companion object {
// Upstream illegal chars defined on disallowed_char()
// in https://github.com/ankitects/anki/blob/main/rslib/src/media/files.rs
private val fIllegalCharReg = Pattern.compile("[\\[\\]><:\"/?*^\\\\|\\x00\\r\\n]")
private val fRemotePattern = Pattern.compile("(https?|ftp)://")
/*
* A note about the regular expressions below: the python code uses named groups for the image and sound patterns.
* Our version of Java doesn't support named groups, so we must use indexes instead. In the expressions below, the
* group names (e.g., ?P<fname>) have been stripped and a comment placed above indicating the index of the group
* name in the original. Refer to these indexes whenever the python code makes use of a named group.
*/
/**
* Group 1 = Contents of [sound:] tag
* Group 2 = "fname"
*/
// Regexes defined on https://github.com/ankitects/anki/blob/b403f20cae8fcdd7c3ff4c8d21766998e8efaba0/pylib/anki/media.py#L34-L45
private val fSoundRegexps = Pattern.compile("(?i)(\\[sound:([^]]+)])")
// src element quoted case
/**
* Group 1 = Contents of `<img>|<audio>` tag
* Group 2 = "str"
* Group 3 = "fname"
* Group 4 = Backreference to "str" (i.e., same type of quote character) */
private val fImgAudioRegExpQ =
Pattern.compile("(?i)(<(?:img|audio)\\b[^>]* src=([\"'])([^>]+?)(\\2)[^>]*>)")
private val fObjectRegExpQ =
Pattern.compile("(?i)(<object\\b[^>]* data=([\"'])([^>]+?)(\\2)[^>]*>)")
// unquoted case
/**
* Group 1 = Contents of `<img>|<audio>` tag
* Group 2 = "fname"
*/
private val fImgAudioRegExpU =
Pattern.compile("(?i)(<(?:img|audio)\\b[^>]* src=(?!['\"])([^ >]+)[^>]*?>)")
private val fObjectRegExpU =
Pattern.compile("(?i)(<object\\b[^>]* data=(?!['\"])([^ >]+)[^>]*?>)")
val REGEXPS = listOf(
fSoundRegexps,
fImgAudioRegExpQ,
fImgAudioRegExpU,
fObjectRegExpQ,
fObjectRegExpU
)
fun getCollectionMediaPath(collectionPath: String): String {
return collectionPath.replaceFirst("\\.anki2$".toRegex(), ".media")
}
/**
* Percent-escape UTF-8 characters in local image filenames.
* @param string The string to search for image references and escape the filenames.
* @return The string with the filenames of any local images percent-escaped as UTF-8.
*/
@KotlinCleanup("fix 'string' as var")
fun escapeImages(string: String, unescape: Boolean = false): String {
@Suppress("NAME_SHADOWING")
var string = string
for (p in listOf(fImgAudioRegExpQ, fImgAudioRegExpU)) {
val m = p.matcher(string)
// NOTE: python uses the named group 'fname'. Java doesn't have named groups, so we have to determine
// the index based on which pattern we are using
val fnameIdx = if (p == fImgAudioRegExpU) 2 else 3
while (m.find()) {
val tag = m.group(0)!!
val fname = m.group(fnameIdx)!!
if (fRemotePattern.matcher(fname).find()) {
// don't do any escaping if remote image
} else {
string = if (unescape) {
string.replace(tag, tag.replace(fname, Uri.decode(fname)))
} else {
string.replace(tag, tag.replace(fname, Uri.encode(fname, "/")))
}
}
}
}
return string
}
/**
* Used by other classes to determine the index of a regular expression group named "fname"
* (Anki2Importer needs this). This is needed because we didn't implement the "transformNames"
* function and have delegated its job to the caller of this class.
*/
fun indexOfFname(p: Pattern): Int {
return if (p == fSoundRegexps) 2 else if (p == fImgAudioRegExpU) 2 else 3
}
}
init {
if (server) {
mDir = null
} else {
// media directory
mDir = getCollectionMediaPath(col.path)
val fd = File(mDir!!)
if (!fd.exists()) {
if (!fd.mkdir()) {
Timber.e("Cannot create media directory: %s", mDir)
}
}
}
}
}
data class MediaCheckResult(val noHave: List<String>, val unused: List<String>, val invalid: List<String>)
| AnkiDroid/src/main/java/com/ichi2/libanki/Media.kt | 846104334 |
/*
* Copyright (c) 2017. Toshi Inc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.toshi.view.activity
import android.app.Activity
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.toshi.R
import com.toshi.crypto.util.TypeConverter
import com.toshi.exception.CurrencyException
import com.toshi.extensions.setActivityResultAndFinish
import com.toshi.extensions.toast
import com.toshi.util.CurrencyUtil
import com.toshi.util.EthUtil
import com.toshi.util.LocaleUtil
import com.toshi.util.OnSingleClickListener
import com.toshi.util.PaymentType
import com.toshi.util.sharedPrefs.AppPrefs
import com.toshi.view.adapter.AmountInputAdapter
import com.toshi.viewModel.AmountViewModel
import kotlinx.android.synthetic.main.activity_amount.amountInputView
import kotlinx.android.synthetic.main.activity_amount.btnContinue
import kotlinx.android.synthetic.main.activity_amount.closeButton
import kotlinx.android.synthetic.main.activity_amount.ethValue
import kotlinx.android.synthetic.main.activity_amount.localCurrencyCode
import kotlinx.android.synthetic.main.activity_amount.localCurrencySymbol
import kotlinx.android.synthetic.main.activity_amount.localValueView
import kotlinx.android.synthetic.main.activity_amount.networkStatusView
import kotlinx.android.synthetic.main.activity_amount.toolbarTitle
import java.math.BigDecimal
class AmountActivity : AppCompatActivity() {
companion object {
const val VIEW_TYPE = "type"
const val INTENT_EXTRA__ETH_AMOUNT = "eth_amount"
}
private lateinit var viewModel: AmountViewModel
private val separator by lazy { LocaleUtil.getDecimalFormatSymbols().monetaryDecimalSeparator }
private val zero by lazy { LocaleUtil.getDecimalFormatSymbols().zeroDigit }
private var encodedEthAmount: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_amount)
init()
}
private fun init() {
initViewModel()
initToolbar()
initClickListeners()
initNetworkView()
updateEthAmount()
setCurrency()
initObservers()
}
private fun initViewModel() {
viewModel = ViewModelProviders.of(this).get(AmountViewModel::class.java)
}
private fun initToolbar() {
val viewType = getViewTypeFromIntent()
val title = if (viewType == PaymentType.TYPE_SEND) getString(R.string.send) else getString(R.string.request)
toolbarTitle.text = title
}
private fun getViewTypeFromIntent() = intent.getIntExtra(AmountActivity.VIEW_TYPE, PaymentType.TYPE_SEND)
private fun initClickListeners() {
closeButton.setOnClickListener { finish() }
btnContinue.setOnClickListener(continueClickListener)
amountInputView.setOnAmountClickedListener(amountClickedListener)
}
private val continueClickListener = object : OnSingleClickListener() {
override fun onSingleClick(v: View?) { setActivityResultAndFinish() }
}
private fun setActivityResultAndFinish() {
encodedEthAmount?.let {
setActivityResultAndFinish(
Activity.RESULT_OK,
{ putExtra(INTENT_EXTRA__ETH_AMOUNT, encodedEthAmount) }
)
}
}
private val amountClickedListener = object : AmountInputAdapter.OnKeyboardItemClicked {
override fun onValueClicked(value: Char) { handleValueClicked(value) }
override fun onBackSpaceClicked() { handleBackspaceClicked() }
}
private fun handleValueClicked(value: Char) {
if (value == this.separator) handleSeparatorClicked() else updateValue(value)
}
private fun handleBackspaceClicked() {
val currentLocalValue = localValueView.text.toString()
val endIndex = Math.max(0, currentLocalValue.length - 1)
val newLocalValue = currentLocalValue.substring(0, endIndex)
val localValue = if (newLocalValue == zero.toString()) "" else newLocalValue
localValueView.text = localValue
updateEthAmount()
}
private fun initNetworkView() {
networkStatusView.setNetworkVisibility(viewModel.getNetworks())
}
private fun getLocalValueAsBigDecimal(): BigDecimal {
val currentLocalValue = localValueView.text.toString()
if (currentLocalValue.isEmpty() || currentLocalValue == this.separator.toString()) {
return BigDecimal.ZERO
}
val parts = currentLocalValue.split(separator.toString())
val integerPart = if (parts.isEmpty()) currentLocalValue else parts[0]
val fractionalPart = if (parts.size < 2) "0" else parts[1]
val fullValue = integerPart + "." + fractionalPart
val trimmedValue = if (fullValue.endsWith(".0")) fullValue.substring(0, fullValue.length - 2) else fullValue
return BigDecimal(trimmedValue)
}
private fun handleSeparatorClicked() {
val currentLocalValue = localValueView.text.toString()
// Only allow a single decimal separator
if (currentLocalValue.indexOf(separator) >= 0) return
updateValue(separator)
}
private fun updateValue(value: Char) {
appendValueInUi(value)
updateEthAmount()
}
private fun appendValueInUi(value: Char) {
val currentLocalValue = localValueView.text.toString()
val isCurrentLocalValueEmpty = currentLocalValue.isEmpty() && value == zero
if (currentLocalValue.length >= 10 || isCurrentLocalValueEmpty) return
if (currentLocalValue.isEmpty() && value == separator) {
val localValue = String.format("%s%s", zero.toString(), separator.toString())
localValueView.text = localValue
return
}
val newLocalValue = currentLocalValue + value
localValueView.text = newLocalValue
}
private fun updateEthAmount() {
val localValue = getLocalValueAsBigDecimal()
viewModel.getEthAmount(localValue)
}
private fun setCurrency() {
try {
val currency = AppPrefs.getCurrency()
val currencyCode = CurrencyUtil.getCode(currency)
val currencySymbol = CurrencyUtil.getSymbol(currency)
localCurrencySymbol.text = currencySymbol
localCurrencyCode.text = currencyCode
} catch (e: CurrencyException) {
toast(R.string.unsupported_currency_message)
}
}
private fun initObservers() {
viewModel.ethAmount.observe(this, Observer {
ethAmount -> ethAmount
?.let { handleEth(it) }
?: toast(R.string.local_currency_to_eth_error)
})
}
private fun handleEth(ethAmount: BigDecimal) {
ethValue.text = EthUtil.ethAmountToUserVisibleString(ethAmount)
btnContinue.isEnabled = EthUtil.isLargeEnoughForSending(ethAmount)
val weiAmount = EthUtil.ethToWei(ethAmount)
encodedEthAmount = TypeConverter.toJsonHex(weiAmount)
}
} | app/src/main/java/com/toshi/view/activity/AmountActivity.kt | 485831223 |
/*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.http
import org.hamcrest.Matchers.notNullValue
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyZeroInteractions
import tech.sirwellington.alchemy.http.AlchemyRequestSteps.OnFailure
import tech.sirwellington.alchemy.http.AlchemyRequestSteps.OnSuccess
import tech.sirwellington.alchemy.http.AlchemyRequestSteps.Step5
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner
/**
*
* @author SirWellington
*/
@RunWith(AlchemyTestRunner::class)
class Step5ImplTest
{
@Mock
private lateinit var stateMachine: AlchemyHttpStateMachine
@Mock
private lateinit var request: HttpRequest
private lateinit var expectedClass: Class<TestPojo>
@Mock
private lateinit var onSuccess: OnSuccess<TestPojo>
@Mock
private lateinit var onFailure: OnFailure
private lateinit var instance: Step5<*>
@Before
fun setUp()
{
expectedClass = TestPojo::class.java
instance = Step5Impl(stateMachine, request, expectedClass, onSuccess)
verifyZeroInteractions(stateMachine, request, onSuccess)
}
@Test
fun testOnFailure()
{
instance.onFailure(onFailure)
verify(stateMachine).jumpToStep6(request, expectedClass, onSuccess, onFailure)
}
@Test
fun testToString()
{
val toString = instance.toString()
assertThat(toString, notNullValue())
assertFalse(toString.isEmpty())
}
}
| src/test/java/tech/sirwellington/alchemy/http/Step5ImplTest.kt | 672489020 |
package com.boardgamegeek.provider
import android.content.ContentValues
import android.content.Context
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
import android.net.Uri
import android.provider.BaseColumns
import com.boardgamegeek.provider.BggContract.*
import com.boardgamegeek.provider.BggContract.Companion.PATH_GAMES
import com.boardgamegeek.provider.BggContract.Companion.PATH_POLLS
import com.boardgamegeek.provider.BggContract.Companion.PATH_POLL_RESULTS
import com.boardgamegeek.provider.BggContract.GamePollResults.Columns.POLL_ID
import com.boardgamegeek.provider.BggContract.GamePolls
import com.boardgamegeek.provider.BggDatabase.Tables
import timber.log.Timber
class GamesIdPollsNameResultsProvider : BaseProvider() {
override fun getType(uri: Uri) = GamePollResults.CONTENT_TYPE
override val path = "$PATH_GAMES/#/$PATH_POLLS/*/$PATH_POLL_RESULTS"
override val defaultSortOrder = GamePollResults.DEFAULT_SORT
override fun buildSimpleSelection(uri: Uri): SelectionBuilder {
val gameId = Games.getGameId(uri)
val pollName = Games.getPollName(uri)
return SelectionBuilder()
.table(Tables.GAME_POLL_RESULTS)
.mapToTable(BaseColumns._ID, Tables.GAME_POLL_RESULTS)
.where(
"$POLL_ID = (SELECT ${Tables.GAME_POLLS}.${BaseColumns._ID} FROM ${Tables.GAME_POLLS} WHERE ${GamePolls.Columns.GAME_ID}=? AND ${GamePolls.Columns.POLL_NAME}=?)",
gameId.toString(),
pollName
)
}
override fun buildExpandedSelection(uri: Uri): SelectionBuilder {
val gameId = Games.getGameId(uri)
val pollName = Games.getPollName(uri)
return SelectionBuilder().table(Tables.POLLS_JOIN_POLL_RESULTS)
.mapToTable(BaseColumns._ID, Tables.GAME_POLL_RESULTS)
.whereEquals(GamePolls.Columns.GAME_ID, gameId)
.whereEquals(GamePolls.Columns.POLL_NAME, pollName)
}
override fun insert(context: Context, db: SQLiteDatabase, uri: Uri, values: ContentValues): Uri? {
val gameId = Games.getGameId(uri)
val pollName = Games.getPollName(uri)
val builder = GamesIdPollsNameProvider().buildSimpleSelection(Games.buildPollsUri(gameId, pollName))
val pollId = queryInt(db, builder, BaseColumns._ID)
values.put(POLL_ID, pollId)
var key = values.getAsString(GamePollResults.Columns.POLL_RESULTS_PLAYERS)
if (key.isNullOrEmpty()) key = "X"
values.put(GamePollResults.Columns.POLL_RESULTS_KEY, key)
try {
val rowId = db.insertOrThrow(Tables.GAME_POLL_RESULTS, null, values)
if (rowId != -1L) {
return Games.buildPollResultsUri(gameId, pollName, values.getAsString(GamePollResults.Columns.POLL_RESULTS_PLAYERS))
}
} catch (e: SQLException) {
Timber.e(e, "Problem inserting poll %2\$s for game %1\$s", gameId, pollName)
notifyException(context, e)
}
return null
}
}
| app/src/main/java/com/boardgamegeek/provider/GamesIdPollsNameResultsProvider.kt | 4218505792 |
package basic.io
import java.io.RandomAccessFile
import java.nio.channels.FileChannel
fun main(args: Array<String>) {
val size = 0x800_000L
// 创建 8.4 MB 大小的temp.txt
val fileChannel = RandomAccessFile("temp.txt", "rw").channel
val mappedBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, size)
for (i in 0 until size) {
mappedBuffer.put(i.toByte())
}
println("done writing")
val index = 10
mappedBuffer.get(index) //类似于RandomAccessFile()中的seek(10), 并read()出结果
fileChannel.close()
} | AdvancedJ/src/main/kotlin/basic/io/MemoryMappedFileDemo.kt | 3602180304 |
package com.hendraanggrian.openpss.schema
import com.hendraanggrian.openpss.nosql.Document
import com.hendraanggrian.openpss.nosql.Schema
import com.hendraanggrian.openpss.nosql.StringId
import kotlinx.nosql.dateTime
import kotlinx.nosql.string
import org.joda.time.DateTime
object Logs : Schema<Log>("logs", Log::class) {
val dateTime = dateTime("date_time")
val message = string("message")
val login = string("login")
}
data class Log(
val dateTime: DateTime,
val message: String,
val login: String
) : Document<Logs> {
companion object {
fun new(
message: String,
login: String
): Log =
Log(DateTime.now(), message, login)
}
override lateinit var id: StringId<Logs>
}
| openpss/src/com/hendraanggrian/openpss/schema/Log.kt | 3310227156 |
@file:Suppress("unused")
package org.illegaller.ratabb.hishoot2i.di
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.internal.modules.ApplicationContextModule
import dagger.hilt.components.SingletonComponent
import org.illegaller.ratabb.hishoot2i.data.pref.BackgroundToolPref
import org.illegaller.ratabb.hishoot2i.data.pref.BadgeToolPref
import org.illegaller.ratabb.hishoot2i.data.pref.ScreenToolPref
import org.illegaller.ratabb.hishoot2i.data.pref.SettingPref
import org.illegaller.ratabb.hishoot2i.data.pref.TemplatePref
import org.illegaller.ratabb.hishoot2i.data.pref.TemplateToolPref
import org.illegaller.ratabb.hishoot2i.data.pref.impl.BackgroundToolPrefImpl
import org.illegaller.ratabb.hishoot2i.data.pref.impl.BadgeToolPrefImpl
import org.illegaller.ratabb.hishoot2i.data.pref.impl.ScreenToolPrefImpl
import org.illegaller.ratabb.hishoot2i.data.pref.impl.SettingPrefImpl
import org.illegaller.ratabb.hishoot2i.data.pref.impl.TemplatePrefImpl
import org.illegaller.ratabb.hishoot2i.data.pref.impl.TemplateToolPrefImpl
import javax.inject.Singleton
@Module(includes = [ApplicationContextModule::class])
@InstallIn(SingletonComponent::class)
interface PrefModule {
@Binds
@Singleton
fun bindBackgroundToolPref(impl: BackgroundToolPrefImpl): BackgroundToolPref
@Binds
@Singleton
fun bindBadgeToolPref(impl: BadgeToolPrefImpl): BadgeToolPref
@Binds
@Singleton
fun bindScreenToolPref(impl: ScreenToolPrefImpl): ScreenToolPref
@Binds
@Singleton
fun bindSettingPref(impl: SettingPrefImpl): SettingPref
@Binds
@Singleton
fun bindTemplatePref(impl: TemplatePrefImpl): TemplatePref
@Binds
@Singleton
fun bindTemplateToolPref(impl: TemplateToolPrefImpl): TemplateToolPref
}
| app/src/main/java/org/illegaller/ratabb/hishoot2i/di/PrefModule.kt | 3508467452 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.