repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
getsentry/raven-java | sentry/src/test/java/io/sentry/protocol/SentryRuntimeTest.kt | 1 | 1215 | package io.sentry.protocol
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNotSame
class SentryRuntimeTest {
@Test
fun `copying Sentry runtime wont have the same references`() {
val runtime = SentryRuntime()
val unknown = mapOf(Pair("unknown", "unknown"))
runtime.acceptUnknownProperties(unknown)
val clone = SentryRuntime(runtime)
assertNotNull(clone)
assertNotSame(runtime, clone)
assertNotSame(runtime.unknown, clone.unknown)
}
@Test
fun `copying Sentry runtime system will have the same values`() {
val runtime = SentryRuntime()
runtime.name = "name"
runtime.version = "version"
runtime.rawDescription = "raw description"
val unknown = mapOf(Pair("unknown", "unknown"))
runtime.acceptUnknownProperties(unknown)
val clone = SentryRuntime(runtime)
assertEquals("name", clone.name)
assertEquals("version", clone.version)
assertEquals("raw description", clone.rawDescription)
assertNotNull(clone.unknown) {
assertEquals("unknown", it["unknown"])
}
}
}
| bsd-3-clause |
koma-im/koma | src/main/kotlin/koma/gui/view/window/chatroom/messaging/reading/display/room_event/m_message/common/image.kt | 1 | 4280 | package koma.gui.view.window.chatroom.messaging.reading.display.room_event.m_message.common
import javafx.event.EventHandler
import javafx.scene.Scene
import javafx.scene.control.Alert
import javafx.scene.control.MenuItem
import javafx.scene.image.Image
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import javafx.scene.input.MouseButton
import javafx.stage.Stage
import koma.Server
import koma.gui.dialog.file.save.downloadFileAs
import koma.gui.view.window.chatroom.messaging.reading.display.ViewNode
import koma.network.media.MHUrl
import link.continuum.desktop.gui.JFX
import link.continuum.desktop.gui.StackPane
import link.continuum.desktop.gui.add
import link.continuum.desktop.gui.component.FitImageRegion
import link.continuum.desktop.gui.component.MxcImageView
import link.continuum.desktop.util.gui.alert
import mu.KotlinLogging
import java.util.concurrent.atomic.AtomicBoolean
private val logger = KotlinLogging.logger {}
class ImageElement(
private val imageSize: Double = 200.0
) : ViewNode {
override val node = StackPane()
override val menuItems: List<MenuItem>
private var imageView = MxcImageView().apply {
fitHeight = imageSize
fitWidth = imageSize
}
private var url: MHUrl? = null
private var server: Server? = null
fun update(mxc: MHUrl, server: Server) {
imageView.setMxc(mxc, server)
this.url = mxc
this.server = server
}
init {
node.add(imageView.root)
node.setOnMouseClicked { event ->
if (event.button == MouseButton.PRIMARY) {
BiggerViews.show(url.toString(), imageView.image, url, server)
}
}
menuItems = menuItems()
}
fun cancelScope() {
imageView.cancelScope()
}
private fun menuItems(): List<MenuItem> {
val tm = MenuItem("Save Image")
tm.setOnAction {
val u = url?: run {
alert(
Alert.AlertType.ERROR,
"Can't download",
"url is null"
)
return@setOnAction
}
val s = server ?: run {
alert(
Alert.AlertType.ERROR,
"Can't download",
"http client is null"
)
return@setOnAction
}
downloadFileAs(s.mxcToHttp(u), title = "Save Image As", httpClient = s.okHttpClient)
}
return listOf(tm)
}
}
object BiggerViews {
private val views = mutableListOf<View>()
fun show(title: String, image: Image?, url: MHUrl?, server: Server?) {
val view = if (views.isEmpty()) {
logger.info { "creating img viewer window" }
View()
} else views.removeAt(views.size - 1)
view.show(title, image)
if (url != null && server != null) {
view.imageView.setMxc(url, server)
} else {
logger.debug { "url=$url, server=$server"}
}
}
private class View {
val root = StackPane()
private val scene = Scene(root)
private val stage = Stage().apply {
isResizable = true
}
val imageView = FitImageRegion(cover = false)
private val closed = AtomicBoolean(false)
init {
stage.scene = scene
stage.initOwner(JFX.primaryStage)
root.add(imageView)
stage.addEventFilter(KeyEvent.KEY_RELEASED) {
if (it.code != KeyCode.ESCAPE) return@addEventFilter
it.consume()
stage.close()
}
stage.onHidden = EventHandler{ close() }
}
private fun close() {
imageView.image = null
if (closed.getAndSet(true)) {
logger.debug { "image viewer $this already closed" }
return
}
if (views.size < 3) views.add(this)
}
fun show(title: String, image: Image?) {
closed.set(false)
logger.debug { "viewing image $image" }
imageView.image = image
this.stage.title = title
stage.show()
}
}
}
| gpl-3.0 |
Bambooin/trime | app/src/main/java/com/osfans/trime/util/ShortcutUtils.kt | 1 | 5963 | package com.osfans.trime.util
import android.app.SearchManager
import android.content.ClipboardManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.icu.text.DateFormat
import android.icu.util.Calendar
import android.icu.util.ULocale
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.SparseArray
import android.view.KeyEvent
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.IntentUtils
import com.osfans.trime.core.Rime
import com.osfans.trime.data.AppPrefs
import com.osfans.trime.ime.core.Trime
import com.osfans.trime.settings.LogActivity
import timber.log.Timber
import java.text.FieldPosition
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* Implementation to open/call specified application/function
*/
object ShortcutUtils {
fun call(context: Context, command: String, option: String): CharSequence? {
when (command) {
"broadcast" -> context.sendBroadcast(Intent(option))
"clipboard" -> return pasteFromClipboard(context)
"date" -> return getDate(option)
"run" -> startIntent(option)
"share_text" -> Trime.getService().shareText()
"liquid_keyboard" -> Trime.getService().selectLiquidKeyboard(option)
else -> startIntent(command, option)
}
return null
}
private fun startIntent(arg: String) {
val intent = when {
arg.indexOf(':') >= 0 -> {
Intent.parseUri(arg, Intent.URI_INTENT_SCHEME)
}
arg.indexOf('/') >= 0 -> {
Intent(Intent.ACTION_MAIN).apply {
addCategory(Intent.CATEGORY_LAUNCHER)
component = ComponentName.unflattenFromString(arg)
}
}
else -> IntentUtils.getLaunchAppIntent(arg)
}
intent.flags = (
Intent.FLAG_ACTIVITY_NEW_TASK
or Intent.FLAG_ACTIVITY_NO_HISTORY
)
ActivityUtils.startActivity(intent)
}
private fun startIntent(action: String, arg: String) {
val act = "android.intent.action.${action.uppercase()}"
var intent = Intent(act)
when (act) {
// Search or open link
// Note that web_search cannot directly open link
Intent.ACTION_WEB_SEARCH, Intent.ACTION_SEARCH -> {
if (arg.startsWith("http")) {
startIntent(arg)
ActivityUtils.startLauncherActivity()
return
} else {
intent.putExtra(SearchManager.QUERY, arg)
}
}
// Share text
Intent.ACTION_SEND -> intent = IntentUtils.getShareTextIntent(arg)
// Stage the data
else -> {
if (arg.isNotEmpty()) Intent(act).data = Uri.parse(arg) else Intent(act)
}
}
intent.flags = (Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY)
ActivityUtils.startActivity(intent)
}
private fun getDate(string: String): CharSequence {
var option = ""
var locale = ""
if (string.contains("@")) {
val opt = string.split(" ".toRegex(), 2)
if (opt.size == 2 && opt[0].contains("@")) {
locale = opt[0]
option = opt[1]
} else {
locale = opt[0]
}
}
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !TextUtils.isEmpty(locale)) {
val ul = ULocale(locale)
val cc = Calendar.getInstance(ul)
val df = if (option.isEmpty()) {
DateFormat.getDateInstance(DateFormat.LONG, ul)
} else {
android.icu.text.SimpleDateFormat(option, ul.toLocale())
}
df.format(cc, StringBuffer(256), FieldPosition(0)).toString()
} else {
SimpleDateFormat(string, Locale.getDefault()).format(Date()) // Time
}
}
fun pasteFromClipboard(context: Context): CharSequence? {
val systemClipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val systemPrimaryClip = systemClipboardManager.getPrimaryClip()
val clipItem = systemPrimaryClip?.getItemAt(0)
return clipItem?.coerceToText(context)
}
fun syncInBackground(context: Context) {
val prefs = AppPrefs.defaultInstance()
prefs.conf.lastBackgroundSync = Date().time
prefs.conf.lastSyncStatus = Rime.syncUserData(context)
}
fun openCategory(keyCode: Int): Boolean {
val category = applicationLaunchKeyCategories[keyCode]
return if (category != null) {
Timber.d("\t<TrimeInput>\topenCategory()\tkeycode=%d, app=%s", keyCode, category)
val intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY
ActivityUtils.startActivity(intent)
true
} else false
}
private val applicationLaunchKeyCategories = SparseArray<String>().apply {
append(KeyEvent.KEYCODE_EXPLORER, "android.intent.category.APP_BROWSER")
append(KeyEvent.KEYCODE_ENVELOPE, "android.intent.category.APP_EMAIL")
append(KeyEvent.KEYCODE_CONTACTS, "android.intent.category.APP_CONTACTS")
append(KeyEvent.KEYCODE_CALENDAR, "android.intent.category.APP_CALENDAR")
append(KeyEvent.KEYCODE_MUSIC, "android.intent.category.APP_MUSIC")
append(KeyEvent.KEYCODE_CALCULATOR, "android.intent.category.APP_CALCULATOR")
}
fun launchLogActivity(context: Context) {
context.startActivity(
Intent(context, LogActivity::class.java)
)
}
}
| gpl-3.0 |
seventhroot/elysium | bukkit/rpk-chat-lib-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/event/prefix/RPKBukkitPrefixUpdateEvent.kt | 1 | 1300 | /*
* Copyright 2019 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.chat.bukkit.event.prefix
import com.rpkit.chat.bukkit.prefix.RPKPrefix
import com.rpkit.core.bukkit.event.RPKBukkitEvent
import org.bukkit.event.Cancellable
import org.bukkit.event.HandlerList
class RPKBukkitPrefixUpdateEvent(
override val prefix: RPKPrefix
): RPKBukkitEvent(), RPKPrefixUpdateEvent, Cancellable {
companion object {
@JvmStatic val handlerList = HandlerList()
}
private var cancel: Boolean = false
override fun isCancelled(): Boolean {
return cancel
}
override fun setCancelled(cancel: Boolean) {
this.cancel = cancel
}
override fun getHandlers(): HandlerList {
return handlerList
}
} | apache-2.0 |
seventhroot/elysium | bukkit/rpk-auction-lib-bukkit/src/main/kotlin/com/rpkit/auctions/bukkit/event/bid/RPKBidDeleteEvent.kt | 1 | 190 | package com.rpkit.auctions.bukkit.event.bid
import com.rpkit.auctions.bukkit.bid.RPKBid
import com.rpkit.core.event.RPKEvent
interface RPKBidDeleteEvent: RPKEvent {
val bid: RPKBid
} | apache-2.0 |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/db/entity/NotePosition.kt | 1 | 936 | package com.orgzly.android.db.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
/**
* Note's position in the book.
*/
data class NotePosition(
@ColumnInfo(name = "book_id")
val bookId: Long,
/** Nested set model's left and right values */
val lft: Long = 0,
val rgt: Long = 0,
/** Level (depth) of a note */
val level: Int = 0,
/** ID of the parent note */
@ColumnInfo(name = "parent_id")
val parentId: Long = 0,
/** ID of the folded note which hides this one */
@ColumnInfo(name = "folded_under_id")
val foldedUnderId: Long = 0,
/** Is the note folded (collapsed) or unfolded (expanded) */
@ColumnInfo(name = "is_folded")
val isFolded: Boolean = false,
/** Number of descendants */
@ColumnInfo(name = "descendants_count")
val descendantsCount: Int = 0
) | gpl-3.0 |
hazuki0x0/YuzuBrowser | app/src/main/java/jp/hazuki/yuzubrowser/provider/ReadItLaterProviderBridge.kt | 1 | 1102 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.provider
import android.net.Uri
import jp.hazuki.yuzubrowser.ui.provider.IReadItLaterProvider
class ReadItLaterProviderBridge : IReadItLaterProvider {
override val editUri: Uri
get() = ReadItLaterProvider.EDIT_URI
override fun getReadUri(time: Long) = ReadItLaterProvider.getReadUri(time)
override fun getEditUri(time: Long) = ReadItLaterProvider.getEditUri(time)
override fun convertToEdit(uri: Uri) = ReadItLaterProvider.convertToEdit(uri)
} | apache-2.0 |
YouriAckx/AdventOfCode | 2017/src/day13/part2/part02-naive.kt | 1 | 1946 | package day13.part2
import java.io.File
/*
This solution works with the sample, but fails on the actual input because of the caching.
java.lang.OutOfMemoryError: GC overhead limit exceeded
Without caching, it is even slower to progress and it won't complete in a timely manner.
*/
data class Layer(val range: Int, val scanPosition: Int, private val direction: Int) {
fun roam(): Layer {
val newPosition = scanPosition + direction
return when {
newPosition < 0 -> this.copy(scanPosition = 1, direction = +1)
newPosition == range -> this.copy(scanPosition = range - 2, direction = -1)
else -> this.copy(scanPosition = newPosition)
}
}
companion object {
fun roamAll(layers: Map<Int, Layer>): Map<Int, Layer> {
val relayers = layers.toMutableMap()
relayers.forEach { n, l -> relayers[n] = l.roam() }
return relayers
}
}
}
class PacketWalker(val layers: Map<Int, Layer>) {
var waitedStates = mutableMapOf<Int, Map<Int, Layer>>()
private fun walk(delay: Int): Boolean {
println(delay)
var relayers = if (delay > 0) Layer.roamAll(waitedStates[delay - 1]!!) else layers
waitedStates[delay] = HashMap(relayers)//relayers.toMap()
return (0..layers.keys.max()!!).any { packet ->
val hit = relayers[packet]?.scanPosition == 0
relayers = Layer.roamAll(relayers)
hit
}
}
fun waitTimeBeforeCrossing() = generateSequence(0) { it + 1 }.dropWhile { walk(it) }.first()
}
fun main(args: Array<String>) {
val layers = File("src/day13/input.txt").readLines()
.map { it.split(": ").map { it.toInt() } }
.associateBy({ it[0] }, { Layer(it[1], 0, +1) })
.toMutableMap() // k=layer number; v=f/w layer
val packetWalker = PacketWalker(layers)
println(packetWalker.waitTimeBeforeCrossing())
}
| gpl-3.0 |
douglasjunior/AndroidBluetoothLibrary | SampleKotlin/src/main/java/com/github/douglasjunior/bluetoothsamplekotlin/SampleApplication.kt | 1 | 3197 | /*
* MIT License
*
* Copyright (c) 2015 Douglas Nassif Roma Junior
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.douglasjunior.bluetoothsamplekotlin
import android.app.Application
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import com.github.douglasjunior.bluetoothclassiclibrary.BluetoothClassicService
import com.github.douglasjunior.bluetoothclassiclibrary.BluetoothConfiguration
import com.github.douglasjunior.bluetoothclassiclibrary.BluetoothService
import java.util.UUID
/**
* Created by douglas on 29/05/17.
*/
class SampleApplication : Application() {
override fun onCreate() {
super.onCreate()
val config = BluetoothConfiguration()
config.bluetoothServiceClass = BluetoothClassicService::class.java // BluetoothClassicService.class or BluetoothLeService.class
config.context = applicationContext
config.bufferSize = 1024
config.characterDelimiter = '\n'
config.deviceName = "Bluetooth Sample"
config.callListenersInMainThread = true
//config.uuid = null; // When using BluetoothLeService.class set null to show all devices on scan.
config.uuid = UUID_DEVICE // For Classic
config.uuidService = UUID_SERVICE // For BLE
config.uuidCharacteristic = UUID_CHARACTERISTIC // For BLE
config.transport = BluetoothDevice.TRANSPORT_LE // Only for dual-mode devices
// For BLE
config.connectionPriority = BluetoothGatt.CONNECTION_PRIORITY_HIGH // Automatically request connection priority just after connection is through.
//or request connection priority manually, mService.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
BluetoothService.init(config)
}
companion object {
/*
* Change for the UUID that you want.
*/
private val UUID_DEVICE = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb")
private val UUID_SERVICE = UUID.fromString("e7810a71-73ae-499d-8c15-faa9aef0c3f2")
private val UUID_CHARACTERISTIC = UUID.fromString("bef8d6c9-9c21-4c9e-b632-bd58c1009f9f")
}
}
| mit |
Litote/kmongo | kmongo-coroutine-core/src/main/kotlin/org/litote/kmongo/coroutine/CoroutineChangeStreamPublisher.kt | 1 | 4729 | /*
* Copyright (C) 2016/2022 Litote
*
* 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.litote.kmongo.coroutine
import com.mongodb.client.model.Collation
import com.mongodb.client.model.changestream.ChangeStreamDocument
import com.mongodb.client.model.changestream.FullDocument
import com.mongodb.reactivestreams.client.ChangeStreamPublisher
import kotlinx.coroutines.reactive.awaitFirstOrNull
import org.bson.BsonDocument
import org.bson.BsonTimestamp
import java.util.concurrent.TimeUnit
/**
* Gets coroutine version of [ChangeStreamPublisher].
*/
val <T: Any> ChangeStreamPublisher<T>.coroutine: CoroutineChangeStreamPublisher<T>
get() = CoroutineChangeStreamPublisher(
this
)
/**
* Coroutine wrapper around [ChangeStreamPublisher].
*/
class CoroutineChangeStreamPublisher<TResult: Any>(override val publisher: ChangeStreamPublisher<TResult>) :
CoroutinePublisher<ChangeStreamDocument<TResult>>(publisher) {
/**
* Sets the fullDocument value.
*
* @param fullDocument the fullDocument
* @return this
*/
fun fullDocument(fullDocument: FullDocument): CoroutineChangeStreamPublisher<TResult> =
publisher.fullDocument(fullDocument).coroutine
/**
* Sets the logical starting point for the new change stream.
*
* @param resumeToken the resume token
* @return this
*/
fun resumeAfter(resumeToken: BsonDocument): CoroutineChangeStreamPublisher<TResult> =
publisher.resumeAfter(resumeToken).coroutine
/**
* The change stream will only provide changes that occurred after the specified timestamp.
*
*
* Any command run against the server will return an operation time that can be used here.
*
* The default value is an operation time obtained from the server before the change stream was created.
*
* @param startAtOperationTime the start at operation time
* @since 1.9
* @return this
* @mongodb.server.release 4.0
* @mongodb.driver.manual reference/method/db.runCommand/
*/
fun startAtOperationTime(startAtOperationTime: BsonTimestamp): CoroutineChangeStreamPublisher<TResult> =
publisher.startAtOperationTime(startAtOperationTime).coroutine
/**
* Sets the maximum await execution time on the server for this operation.
*
* @param maxAwaitTime the max await time. A zero value will be ignored, and indicates that the driver should respect the server's
* default value
* @param timeUnit the time unit, which may not be null
* @return this
*/
fun maxAwaitTime(maxAwaitTime: Long, timeUnit: TimeUnit): CoroutineChangeStreamPublisher<TResult> =
publisher.maxAwaitTime(maxAwaitTime, timeUnit).coroutine
/**
* Sets the collation options
*
*
* A null value represents the server default.
* @param collation the collation options to use
* @return this
*/
fun collation(collation: Collation): CoroutineChangeStreamPublisher<TResult> =
publisher.collation(collation).coroutine
/**
* Returns a list containing the results of the change stream based on the document class provided.
*
* @param <TDocument> the result type
* @return the new Mongo Iterable
*/
suspend inline fun <reified TDocument> withDocumentClass(): List<TDocument> =
publisher.withDocumentClass(TDocument::class.java).toList()
/**
* Sets the number of documents to return per batch.
*
*
* Overrides the [org.reactivestreams.Subscription.request] value for setting the batch size, allowing for fine grained
* control over the underlying cursor.
*
* @param batchSize the batch size
* @return this
* @since 1.8
* @mongodb.driver.manual reference/method/cursor.batchSize/#cursor.batchSize Batch Size
*/
fun batchSize(batchSize: Int): CoroutineChangeStreamPublisher<TResult> =
publisher.batchSize(batchSize).coroutine
/**
* Helper to return a publisher limited to the first result.
*
* @return a single item.
* @since 1.8
*/
suspend fun first(): ChangeStreamDocument<TResult>? = publisher.first().awaitFirstOrNull()
}
| apache-2.0 |
BlueBoxWare/LibGDXPlugin | src/test/testdata/inspections/unsafeIterators/OrderedMap.kt | 1 | 746 | package main
import com.badlogic.gdx.utils.ObjectMap
import com.badlogic.gdx.utils.OrderedMap
@Suppress("UNUSED_VARIABLE", "UNCHECKED_CAST", "USELESS_CAST")
class OrderedMapT {
var map = OrderedMap<String, Any>()
var map2 = OrderedMap<String, OrderedMap<String, Any>>()
fun test() {
map2.put("abc", map)
for (e in <warning>map2</warning>) {
for (e1 in <warning>e.value</warning>) {
}
}
}
var i1: Iterator<Any> = <warning>map.keys()</warning>
var i2: Iterator<Any> = <warning>map.values()</warning>
var i3: Iterator<Any> = <warning>map.iterator()</warning>
var i4: Iterator<Any> = <warning>map.entries()</warning>
var o: Any = <warning><warning>map2.values()</warning>.next().values()</warning>
}
| apache-2.0 |
fuzhouch/qbranch | compiler/src/main/kotlin/net/dummydigit/qbranch/compiler/Translator.kt | 1 | 808 | // Licensed under the MIT license. See LICENSE file in the project root
// for full license information.
package net.dummydigit.qbranch.compiler
import net.dummydigit.qbranch.compiler.symbols.*
internal interface Translator {
fun getGeneratedFileExt() : String
fun generateHeader() : String
fun generate(symbol : BuiltinTypeDef) : String
fun generate(symbol : BuiltinContainerDef) : String
fun generate(symbol : BuiltinKvpContainerDef) : String
fun generate(symbol: GenericTypeParamDef) : String
fun generate(symbol : AttributeDef) : String
fun generate(symbol : EnumDef) : String
fun generate(symbol : ImportDef) : String
fun generate(symbol : NamespaceDef) : String
fun generate(symbol : StructDef) : String
fun generate(symbol: StructFieldDef) : String
} | mit |
Petrulak/kotlin-mvp-clean-architecture | data/src/main/java/com/petrulak/cleankotlin/data/repository/WeatherRepositoryImpl.kt | 1 | 1799 | package com.petrulak.cleankotlin.data.repository
import com.petrulak.cleankotlin.data.mapper.base.Mapper
import com.petrulak.cleankotlin.data.source.LocalSource
import com.petrulak.cleankotlin.data.source.RemoteSource
import com.petrulak.cleankotlin.data.source.local.model.WeatherEntity
import com.petrulak.cleankotlin.data.source.remote.model.WeatherDto
import com.petrulak.cleankotlin.domain.model.Weather
import com.petrulak.cleankotlin.domain.repository.WeatherRepository
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Single
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class WeatherRepositoryImpl
@Inject
constructor(
private val remoteSource: RemoteSource,
private val localSource: LocalSource,
private val weatherDtoMapper: Mapper<Weather, WeatherDto>,
private val weatherEntityMapper: Mapper<Weather, WeatherEntity>
) : WeatherRepository {
override fun getWeatherForCityRemotely(city: String): Single<Weather> {
return remoteSource
.getWeatherForCity(city)
.map { weatherDtoMapper.map(it).copy(name = "London,uk", visibility = Random().nextInt(80 - 65) + 65) }
.doOnSuccess { localSource.save(it) }
}
override fun getWeatherForCityLocally(name: String): Flowable<Weather> {
return localSource
.getWeatherForCity(name)
.map { weatherEntityMapper.map(it) }
}
override fun save(weather: Weather): Completable {
return localSource.save(weather)
}
override fun getWeatherForCity(city: String): Flowable<Weather> {
val local = getWeatherForCityLocally(city)
val remote = getWeatherForCityRemotely(city).toFlowable()
return Flowable.merge(local, remote)
}
}
| mit |
erubit-open/platform | erubit.platform/src/main/java/a/erubit/platform/UserPresentBroadcastReceiver.kt | 1 | 780 | package a.erubit.platform
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
class UserPresentBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
/*
* Sent when the user is present after
* device wakes up (e.g when the keyguard is gone)
*/
if (Intent.ACTION_USER_PRESENT == intent.action) {
showFloatingView(context)
}
}
private fun showFloatingView(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
context.startForegroundService(Intent(context.applicationContext, InteractionService::class.java))
else
context.startService(Intent(context.applicationContext, InteractionService::class.java))
}
}
| gpl-3.0 |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/enums/Category.kt | 2 | 349 | package me.proxer.library.enums
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Enum holding the available categories.
*
* @author Ruben Gees
*/
@JsonClass(generateAdapter = false)
enum class Category {
@Json(name = "anime")
ANIME,
@Json(name = "manga")
MANGA,
@Json(name = "novel")
NOVEL
}
| gpl-3.0 |
josegonzalez/kotterknife | src/main/kotlin/butterknife/ButterKnife.kt | 1 | 4918 | package butterknife
import android.app.Activity
import android.app.Dialog
import android.app.Fragment
import android.support.v4.app.Fragment as SupportFragment
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.View
import kotlin.properties.ReadOnlyProperty
public fun <V : View> View.bindView(id: Int)
: ReadOnlyProperty<View, V> = required(id, ::findViewById)
public fun <V : View> Activity.bindView(id: Int)
: ReadOnlyProperty<Activity, V> = required(id, ::findViewById)
public fun <V : View> Dialog.bindView(id: Int)
: ReadOnlyProperty<Dialog, V> = required(id, ::findViewById)
public fun <V : View> Fragment.bindView(id: Int)
: ReadOnlyProperty<Fragment, V> = required(id, ::findViewById)
public fun <V : View> SupportFragment.bindView(id: Int)
: ReadOnlyProperty<SupportFragment, V> = required(id, ::findViewById)
public fun <V : View> ViewHolder.bindView(id: Int)
: ReadOnlyProperty<ViewHolder, V> = required(id, ::findViewById)
public fun <V : View> View.bindOptionalView(id: Int)
: ReadOnlyProperty<View, V?> = optional(id, ::findViewById)
public fun <V : View> Activity.bindOptionalView(id: Int)
: ReadOnlyProperty<Activity, V?> = optional(id, ::findViewById)
public fun <V : View> Dialog.bindOptionalView(id: Int)
: ReadOnlyProperty<Dialog, V?> = optional(id, ::findViewById)
public fun <V : View> Fragment.bindOptionalView(id: Int)
: ReadOnlyProperty<Fragment, V?> = optional(id, ::findViewById)
public fun <V : View> SupportFragment.bindOptionalView(id: Int)
: ReadOnlyProperty<SupportFragment, V?> = optional(id, ::findViewById)
public fun <V : View> ViewHolder.bindOptionalView(id: Int)
: ReadOnlyProperty<ViewHolder, V?> = optional(id, ::findViewById)
public fun <V : View> View.bindViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = required(ids, ::findViewById)
public fun <V : View> Activity.bindViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = required(ids, ::findViewById)
public fun <V : View> Dialog.bindViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = required(ids, ::findViewById)
public fun <V : View> Fragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<Fragment, List<V>> = required(ids, ::findViewById)
public fun <V : View> SupportFragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<SupportFragment, List<V>> = required(ids, ::findViewById)
public fun <V : View> ViewHolder.bindViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = required(ids, ::findViewById)
public fun <V : View> View.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = optional(ids, ::findViewById)
public fun <V : View> Activity.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = optional(ids, ::findViewById)
public fun <V : View> Dialog.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = optional(ids, ::findViewById)
public fun <V : View> Fragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Fragment, List<V>> = optional(ids, ::findViewById)
public fun <V : View> SupportFragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<SupportFragment, List<V>> = optional(ids, ::findViewById)
public fun <V : View> ViewHolder.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = optional(ids, ::findViewById)
private fun Fragment.findViewById(id: Int): View? = getView().findViewById(id)
private fun SupportFragment.findViewById(id: Int): View? = getView().findViewById(id)
private fun ViewHolder.findViewById(id: Int): View? = itemView.findViewById(id)
private fun viewNotFound(id:Int, desc: PropertyMetadata) =
throw IllegalStateException("View ID $id for '${desc.name}' not found.")
suppress("UNCHECKED_CAST")
private fun required<T, V : View>(id: Int, finder : T.(Int) -> View?)
= Lazy { t : T, desc -> t.finder(id) as V? ?: viewNotFound(id, desc) }
suppress("UNCHECKED_CAST")
private fun optional<T, V : View>(id: Int, finder : T.(Int) -> View?)
= Lazy { t : T, desc -> t.finder(id) as V? }
suppress("UNCHECKED_CAST")
private fun required<T, V : View>(ids: IntArray, finder : T.(Int) -> View?)
= Lazy { t : T, desc -> ids.map { t.finder(it) as V? ?: viewNotFound(it, desc) } }
suppress("UNCHECKED_CAST")
private fun optional<T, V : View>(ids: IntArray, finder : T.(Int) -> View?)
= Lazy { t : T, desc -> ids.map { t.finder(it) as V? }.filterNotNull() }
// Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it
private class Lazy<T, V>(private val initializer : (T, PropertyMetadata) -> V) : ReadOnlyProperty<T, V> {
private object EMPTY
private var value: Any? = EMPTY
override fun get(thisRef: T, desc: PropertyMetadata): V {
if (value == EMPTY) {
value = initializer(thisRef, desc)
}
@suppress("UNCHECKED_CAST")
return value as V
}
}
| apache-2.0 |
Esri/arcgis-runtime-samples-android | kotlin/set-initial-map-area/src/main/java/com/esri/arcgisruntime/sample/setinitialmaparea/MainActivity.kt | 1 | 2626 | /* Copyright 2020 Esri
*
* 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.esri.arcgisruntime.sample.setinitialmaparea
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.geometry.Envelope
import com.esri.arcgisruntime.geometry.SpatialReference
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.setinitialmaparea.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is required to access basemaps and other
// location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
// create a map with a topographic basemap
val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
// create an envelope around Shafer Basin
val initialExtent =
Envelope(
-12211308.778729, 4645116.003309, -12208257.879667, 4650542.535773,
SpatialReference.create(102100)
)
// create a viewpoint from the envelope
val viewpoint = Viewpoint(initialExtent)
// set the map to be displayed in the map view
mapView.map = map
// set the map's initial viewpoint
mapView.setViewpoint(viewpoint)
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 |
facebook/fresco | vito/nativecode/src/main/java/com/facebook/fresco/vito/nativecode/NativeCircularBitmapRounding.kt | 2 | 1186 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.nativecode
import com.facebook.common.internal.Supplier
import com.facebook.fresco.vito.core.impl.ImagePipelineUtilsImpl.CircularBitmapRounding
import com.facebook.imagepipeline.common.ImageDecodeOptions
class NativeCircularBitmapRounding(private val useFastNativeRounding: Supplier<Boolean>) :
CircularBitmapRounding {
private val circularImageDecodeOptions: ImageDecodeOptions by lazy {
ImageDecodeOptions.newBuilder()
.setBitmapTransformation(CircularBitmapTransformation(false, useFastNativeRounding.get()))
.build()
}
private val circularImageDecodeOptionsAntiAliased: ImageDecodeOptions by lazy {
ImageDecodeOptions.newBuilder()
.setBitmapTransformation(CircularBitmapTransformation(true, useFastNativeRounding.get()))
.build()
}
override fun getDecodeOptions(antiAliased: Boolean): ImageDecodeOptions =
if (antiAliased) circularImageDecodeOptionsAntiAliased else circularImageDecodeOptions
}
| mit |
mniami/android.kotlin.benchmark | app/src/main/java/guideme/volunteers/ui/activities/main/fragments/EmptyFragmentChanger.kt | 2 | 996 | package guideme.volunteers.ui.activities.main.fragments
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import guideme.volunteers.domain.Human
import guideme.volunteers.domain.Project
import guideme.volunteers.domain.Volunteer
import guideme.volunteers.helpers.dataservices.errors.ErrorMessage
class EmptyFragmentChanger(override var paused: Boolean = false,
override var supportFragmentManager: FragmentManager? = null) : FragmentChanger {
override fun showError(errorMessage: ErrorMessage) {
}
override fun changeFragment(fragment: Fragment, name: String) {
}
override fun openSettings() {
}
override fun openAuthentication() {
}
override fun showVolunteerList() {
}
override fun openHome() {
}
override fun showProject(project: Project) {
}
override fun showVolunteer(volunteer: Volunteer) {
}
override fun openEditUserDetails(human: Human) {
}
} | apache-2.0 |
gradle/gradle | subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/support/WalkReproduciblyTest.kt | 4 | 1952 | /*
* 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.support
import org.gradle.kotlin.dsl.fixtures.FolderBasedTest
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
class WalkReproduciblyTest : FolderBasedTest() {
@Test
fun `walks directory tree top-down yielding sorted files`() {
withFolders {
"root" {
withFile("root-f2")
"b" {
withFile("b-f1")
}
"c" {
"c1" {
"c11" {
withFile("c11-f1")
}
}
}
"a" {
"a2" {
withFile("a2-f2")
withFile("a2-f1")
}
"a1" {}
}
withFile("root-f1")
}
}
assertThat(
folder("root").walkReproducibly().map { it.name }.toList(),
equalTo(
listOf(
"root",
"root-f1", "root-f2", "a", "b", "c",
"a1", "a2", "b-f1", "c1",
"a2-f1", "a2-f2", "c11",
"c11-f1"
)
)
)
}
}
| apache-2.0 |
marlonlom/timeago | ta_library/src/test/java/com/github/marlonlom/utilities/timeago/usages/YearsAgoTest.kt | 1 | 4905 | /*
* Copyright (c) 2016, marlonlom
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.marlonlom.utilities.timeago.usages
import com.github.marlonlom.utilities.timeago.DataBuilder.getExpectedMessage
import com.github.marlonlom.utilities.timeago.DataBuilder.newLocalBundle
import com.github.marlonlom.utilities.timeago.DataBuilder.newMessagesResource
import com.github.marlonlom.utilities.timeago.DataBuilder.randomLanguageRef
import com.github.marlonlom.utilities.timeago.DataBuilder.useTimeAgo
import com.github.marlonlom.utilities.timeago.TimeAgo.Periods.*
import com.github.marlonlom.utilities.timeago.TimeAgoMessages
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.util.*
import java.util.Calendar.MONTH
import java.util.Calendar.YEAR
import java.util.Calendar.getInstance as getCalendarInstance
/**
* Unit tests class for TimeAgo years usage.
*
* @author marlonlom
* @version 4.1.0
* @since 2.1.0
*/
@RunWith(JUnit4::class)
class YearsAgoTest {
/**
* Random language code for getting messages and making timeago work.
*/
private val languageRef: String = randomLanguageRef
/**
* The time ago messages.
*/
private lateinit var timeAgoMessages: TimeAgoMessages
/**
* The Local bundle.
*/
private var localBundle: ResourceBundle? = null
/**
* Setup messages resource.
*/
@Before
fun setupMessagesResource() {
println("<${javaClass.simpleName}> Selected language for testing: $languageRef.")
timeAgoMessages = newMessagesResource(languageRef)
localBundle = newLocalBundle(languageRef)
}
/**
* Should show past date time with almost two years.
*/
@Test
fun shouldShowPastDateTimeWithAlmostTwoYears() {
val calendar = getCalendarInstance().apply {
add(MONTH, -10)
add(YEAR, -1)
}
val results = useTimeAgo(calendar.timeInMillis, timeAgoMessages)
val expected = getExpectedMessage(localBundle!!, ALMOST_TWO_YEARS_PAST.propertyKey)
assertEquals(expected, results)
}
/**
* Should show future date time with almost two years.
*/
@Test
fun shouldShowFutureDateTimeWithAlmostTwoYears() {
val calendar = getCalendarInstance().apply {
add(MONTH, 10)
add(YEAR, 1)
}
val results = useTimeAgo(calendar.timeInMillis, timeAgoMessages)
val expected = getExpectedMessage(localBundle!!, ALMOST_TWO_YEARS_FUTURE.propertyKey)
assertEquals(expected, results)
}
/**
* Should show past date time over one year.
*/
@Test
fun shouldShowPastDateTimeOverOneYear() {
val calendar = getCalendarInstance().apply {
add(MONTH, -4)
add(YEAR, -1)
}
val results = useTimeAgo(calendar.timeInMillis, timeAgoMessages)
val expected = getExpectedMessage(localBundle!!, OVER_A_YEAR_PAST.propertyKey)
assertEquals(expected, results)
}
/**
* Should show past date time with almost one year.
*/
@Test
fun shouldShowPastDateTimeWithAlmostOneYear() {
val calendar = getCalendarInstance().apply { add(MONTH, -12) }
val results = useTimeAgo(calendar.timeInMillis, timeAgoMessages)
val expected = getExpectedMessage(localBundle!!, ABOUT_A_YEAR_PAST.propertyKey)
assertEquals(expected, results)
}
/**
* Should show future date time over one year.
*/
@Test
fun shouldShowFutureDateTimeOverOneYear() {
val calendar = getCalendarInstance().apply {
add(MONTH, 4)
add(YEAR, 1)
}
val results = useTimeAgo(calendar.timeInMillis, timeAgoMessages)
val expected = getExpectedMessage(localBundle!!, OVER_A_YEAR_FUTURE.propertyKey)
assertEquals(expected, results)
}
/**
* Should show future date time with almost one year.
*/
@Test
fun shouldShowFutureDateTimeWithAlmostOneYear() {
val calendar = getCalendarInstance().apply { add(MONTH, 12) }
val results = useTimeAgo(calendar.timeInMillis, timeAgoMessages)
val expected = getExpectedMessage(localBundle!!, ABOUT_A_YEAR_FUTURE.propertyKey)
assertEquals(expected, results)
}
}
| apache-2.0 |
AlekseyZhelo/LBM | LWJGL_APP/src/main/java/com/alekseyzhelo/lbm/gui/lwjgl/render/util/RenderUtil.kt | 1 | 1296 | package com.alekseyzhelo.lbm.gui.lwjgl.render.util
private fun binarySearch(a: FloatArray, key: Float): Int {
var low = 0
var high = a.size - 1
while (low <= high) {
val mid = (low + high).ushr(1)
val midVal = a[mid]
if (midVal < key)
low = mid + 1 // Neither val is NaN, thisVal is smaller
else if (midVal > key)
high = mid - 1 // Neither val is NaN, thisVal is larger
else {
val midBits = java.lang.Float.floatToIntBits(midVal)
val keyBits = java.lang.Float.floatToIntBits(key)
if (midBits == keyBits)
// Values are equal
return if (mid > 0) mid - 1 else mid // Key found
else if (midBits < keyBits)
// (-0.0, 0.0) or (!NaN, NaN)
low = mid + 1
else
// (0.0, -0.0) or (NaN, !NaN)
high = mid - 1
}
}
return low - 1 // key not found.
}
private val x = floatArrayOf(0.0f, 0.15f, 0.4f, 0.5f, 0.65f, 0.8f, 1.0f)
private val r = floatArrayOf(0.0f, 0.0f, 0.0f, 0.56470588f, 1.0f, 1.0f, 0.54509804f)
private val g = floatArrayOf(0.0f, 0.0f, 1.0f, 0.93333333f, 1.0f, 0.0f, 0.0f)
private val b = floatArrayOf(0.54509804f, 1.0f, 1.0f, 0.56470588f, 0.0f, 0.0f, 0.0f) | apache-2.0 |
AlmasB/FXGL | fxgl-entity/src/test/kotlin/com/almasb/fxgl/physics/box2d/common/Mat22Test.kt | 1 | 825 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.physics.box2d.common
import com.almasb.fxgl.core.math.Vec2
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.*
import org.hamcrest.MatcherAssert
import org.hamcrest.MatcherAssert.*
import org.junit.jupiter.api.Test
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class Mat22Test {
@Test
fun `Matrix mul vector`() {
val mat = Mat22()
mat.ex.set(2f, 3f)
mat.ey.set(4f, 7f)
val v = Vec2(1f, 2f)
// [ 2 4 ] x [ 1 ] = [ 10 ]
// [ 3 7 ] [ 2 ] [ 17 ]
val out = Vec2()
Mat22.mulToOutUnsafe(mat, v, out)
assertThat(out, `is`(Vec2(10f, 17f)))
}
} | mit |
FutureioLab/FastPeak | app/src/main/java/com/binlly/fastpeak/service/remoteconfig/RemoteConfigService.kt | 1 | 416 | package com.binlly.fastpeak.service.remoteconfig
import com.binlly.fastpeak.config.AppConfigModel
/**
* Created by binlly on 17/2/20.
*/
interface RemoteConfigService {
val config: AppConfigModel?
val mockRouter: Map<String, Int>
fun saveConfig(configModel: AppConfigModel)
fun pullMockConfig(listener: () -> Unit)
fun getRouter(): Map<String, Int>
fun isMock(key: String): Boolean
}
| mit |
RP-Kit/RPKit | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/command/mute/MuteCommand.kt | 1 | 2993 | /*
* Copyright 2021 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.command.mute
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelName
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelService
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
/**
* Mute command.
* Mutes a chat channel.
*/
class MuteCommand(private val plugin: RPKChatBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
if (args.isEmpty()) {
sender.sendMessage(plugin.messages["mute-usage"])
return true
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-service"])
return true
}
val chatChannelService = Services[RPKChatChannelService::class.java]
if (chatChannelService == null) {
sender.sendMessage(plugin.messages["no-chat-channel-service"])
return true
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
return true
}
val chatChannel = chatChannelService.getChatChannel(RPKChatChannelName(args[0]))
if (chatChannel == null) {
sender.sendMessage(plugin.messages["mute-invalid-chatchannel"])
return true
}
if (!sender.hasPermission("rpkit.chat.command.mute.${chatChannel.name.value}")) {
sender.sendMessage(plugin.messages["no-permission-mute", mapOf(
"channel" to chatChannel.name.value
)])
return true
}
chatChannel.removeListener(minecraftProfile)
sender.sendMessage(plugin.messages["mute-valid", mapOf(
"channel" to chatChannel.name.value
)])
return true
}
}
| apache-2.0 |
myfreeweb/freepass | android/app/src/main/java/technology/unrelenting/freepass/NumberLimitsInputFilter.kt | 1 | 477 | package technology.unrelenting.freepass
import android.text.InputFilter
import android.text.Spanned
class NumberLimitsInputFilter(val min: Long, val max: Long) : InputFilter {
override fun filter(src: CharSequence?, start: Int, end: Int, dst: Spanned?, dstart: Int, dend: Int): CharSequence? {
try {
val num = java.lang.Long.parseLong(dst.toString() + src.toString())
if (num >= min && num <= max) return null
} catch (e: NumberFormatException) {}
return ""
}
} | unlicense |
google/summit-ast | src/main/javatests/com/google/summit/translation/CompilationUnitTest.kt | 1 | 2294 | /*
* 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.summit.translation
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import com.google.summit.ast.declaration.EnumDeclaration
import com.google.summit.ast.declaration.TriggerDeclaration
import com.google.summit.testing.TranslateHelpers
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class CompilationUnitTest {
@Test
fun enum_translation_hasClassDeclaration() {
val cu = TranslateHelpers.parseAndTranslate("enum Test { }")
assertThat(cu.typeDeclaration).isInstanceOf(EnumDeclaration::class.java)
}
@Test
fun parent_reverses_getChildren() {
val cu = TranslateHelpers.parseAndTranslate("class Test { }")
val classDecl = cu.typeDeclaration
assertThat(cu.getChildren()).containsExactly(classDecl)
assertThat(classDecl.parent).isEqualTo(cu)
assertWithMessage("CompilationUnits are the root of the AST and should have no parent")
.that(cu.parent)
.isNull()
}
@Test
fun trigger_translatesTo_expectedTree() {
val cu =
TranslateHelpers.parseAndTranslate(
"trigger MyTrigger on MyObject(before update, after delete) { }"
)
val triggerDecl = cu.typeDeclaration as TriggerDeclaration
assertThat(cu.getChildren()).containsExactly(triggerDecl)
assertThat(triggerDecl.id.asCodeString()).isEqualTo("MyTrigger")
assertThat(triggerDecl.target.asCodeString()).isEqualTo("MyObject")
assertThat(triggerDecl.cases)
.containsExactly(
TriggerDeclaration.TriggerCase.TRIGGER_BEFORE_UPDATE,
TriggerDeclaration.TriggerCase.TRIGGER_AFTER_DELETE
)
}
}
| apache-2.0 |
MichaelRocks/lightsaber | processor/src/main/java/io/michaelrocks/lightsaber/processor/commons/CloseableExtensions.kt | 1 | 835 | /*
* Copyright 2018 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.commons
import java.io.Closeable
import java.io.IOException
fun Closeable.closeQuietly() {
try {
close()
} catch (exception: IOException) {
// Ignore the exception.
}
}
| apache-2.0 |
wakingrufus/mastodon-jfx | src/main/kotlin/com/github/wakingrufus/mastodon/client/BuildTimelinesClient.kt | 1 | 239 | package com.github.wakingrufus.mastodon.client
import com.sys1yagi.mastodon4j.MastodonClient
import com.sys1yagi.mastodon4j.api.method.Timelines
fun buildTimelinesClient(client: MastodonClient) : Timelines{
return Timelines(client)
} | mit |
appnexus/mobile-sdk-android | tests/AppNexusSDKTestApp/app/src/androidTest/java/appnexus/com/appnexussdktestapp/placement/native/NativeOnePxTest.kt | 1 | 6295 | /*
* Copyright 2019 APPNEXUS INC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package appnexus.com.appnexussdktestapp.placement.native
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.test.espresso.Espresso
import androidx.test.espresso.IdlingPolicies
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import appnexus.com.appnexussdktestapp.NativeActivity
import appnexus.com.appnexussdktestapp.R
import appnexus.com.appnexussdktestapp.util.Utility.Companion.checkVisibilityDetectorMap
import com.appnexus.opensdk.SDKSettings
import com.appnexus.opensdk.XandrAd
import com.microsoft.appcenter.espresso.Factory
import kotlinx.android.synthetic.main.layout_native.*
import org.hamcrest.Matchers.not
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class NativeOnePxTest {
@get:Rule
var reportHelper = Factory.getReportHelper()
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(NativeActivity::class.java, false, false)
lateinit var nativeActivity: NativeActivity
@Before
fun setup() {
XandrAd.reset()
XandrAd.init(123, null, false, null)
IdlingPolicies.setMasterPolicyTimeout(1, TimeUnit.MINUTES)
IdlingPolicies.setIdlingResourceTimeout(1, TimeUnit.MINUTES)
var intent = Intent()
mActivityTestRule.launchActivity(intent)
nativeActivity = mActivityTestRule.activity
IdlingRegistry.getInstance().register(nativeActivity.idlingResource)
}
@After
fun destroy() {
XandrAd.init(10094, null, false) { }
Thread.sleep(2000)
IdlingRegistry.getInstance().unregister(nativeActivity.idlingResource)
reportHelper.label("Stopping App")
}
/*
* Sanity Test for the Native Ad
* */
@Test
fun nativeAdLoadTestOnePx() {
XandrAd.init(10094, null, false) { }
Thread.sleep(2000)
nativeActivity.shouldDisplay = false
nativeActivity.triggerAdLoad("17058950")
Espresso.onView(ViewMatchers.withId(R.id.title))
.check(ViewAssertions.matches(not(ViewMatchers.isDisplayed())))
checkVisibilityDetectorMap(1, nativeActivity)
setVisibility(View.VISIBLE)
Espresso.onView(ViewMatchers.withId(R.id.title))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Espresso.onView(ViewMatchers.withId(R.id.description))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Thread.sleep(5000)
Espresso.onView(ViewMatchers.withId(R.id.icon))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Espresso.onView(ViewMatchers.withId(R.id.image))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
checkVisibilityDetectorMap(0, nativeActivity)
}
/*
* Sanity Test for the Native Ad
* */
@Test
fun nativeAdLoadBGTest() {
XandrAd.init(10094, null, false) { }
Thread.sleep(2000)
nativeActivity.shouldDisplay = false
nativeActivity.triggerAdLoad("17058950",bgTask = true)
Espresso.onView(ViewMatchers.withId(R.id.title))
.check(ViewAssertions.matches(not(ViewMatchers.isDisplayed())))
checkVisibilityDetectorMap(1, nativeActivity)
setVisibility(View.VISIBLE)
Espresso.onView(ViewMatchers.withId(R.id.title))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Espresso.onView(ViewMatchers.withId(R.id.description))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Thread.sleep(5000)
Espresso.onView(ViewMatchers.withId(R.id.icon))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Espresso.onView(ViewMatchers.withId(R.id.image))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
checkVisibilityDetectorMap(0, nativeActivity)
}
/*
* Sanity Test for the Native Ad
* */
@Test
fun nativeAdLoadBGExecutorTest() {
XandrAd.init(10094, null, false) { }
Thread.sleep(2000)
nativeActivity.shouldDisplay = false
nativeActivity.triggerAdLoad("17058950", bgTask = true, useExecutor = true)
Espresso.onView(ViewMatchers.withId(R.id.title))
.check(ViewAssertions.matches(not(ViewMatchers.isDisplayed())))
checkVisibilityDetectorMap(1, nativeActivity)
setVisibility(View.VISIBLE)
Espresso.onView(ViewMatchers.withId(R.id.title))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Espresso.onView(ViewMatchers.withId(R.id.description))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Thread.sleep(5000)
Espresso.onView(ViewMatchers.withId(R.id.icon))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Espresso.onView(ViewMatchers.withId(R.id.image))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
checkVisibilityDetectorMap(0, nativeActivity)
}
private fun setVisibility(visibility: Int) {
Handler(Looper.getMainLooper()).post({
nativeActivity.main_native.visibility = visibility
})
}
}
| apache-2.0 |
ansman/kotshi | tests/src/main/kotlin/se/ansman/kotshi/ClassWithManyProperties.kt | 1 | 1949 | package se.ansman.kotshi
@JsonSerializable
data class ClassWithManyProperties(
val v1: String = "v1",
val v2: String = "v2",
val v3: String = "v3",
val v4: String = "v4",
val v5: String = "v5",
val v6: String = "v6",
val v7: String = "v7",
val v8: String = "v8",
val v9: String = "v9",
val v10: String = "v10",
val v11: String = "v11",
val v12: String = "v12",
val v13: String = "v13",
val v14: String = "v14",
val v15: String = "v15",
val v16: String = "v16",
val v17: String = "v17",
val v18: String = "v18",
val v19: String = "v19",
val v20: String = "v20",
val v21: String = "v21",
val v22: String = "v22",
val v23: String = "v23",
val v24: String = "v24",
val v25: String = "v25",
val v26: String = "v26",
val v27: String = "v27",
val v28: String = "v28",
val v29: String = "v29",
val v30: String = "v30",
val v31: String = "v31",
val v32: String = "v32",
val v33: String = "v33",
val v34: String = "v34",
val v35: String = "v35",
val v36: String = "v36",
val v37: String = "v37",
val v38: String = "v38",
val v39: String = "v39",
val v40: String = "v40",
val v41: String = "v41",
val v42: String = "v42",
val v43: String = "v43",
val v44: String = "v44",
val v45: String = "v45",
val v46: String = "v46",
val v47: String = "v47",
val v48: String = "v48",
val v49: String = "v49",
val v50: String = "v50",
val v51: String = "v51",
val v52: String = "v52",
val v53: String = "v53",
val v54: String = "v54",
val v55: String = "v55",
val v56: String = "v56",
val v57: String = "v57",
val v58: String = "v58",
val v59: String = "v59",
val v60: String = "v60",
val v61: String = "v61",
val v62: String = "v62",
val v63: String = "v63",
val v64: String = "v64",
val v65: String = "v65",
)
| apache-2.0 |
vindkaldr/replicator | libreplicator/src/main/kotlin/org/libreplicator/module/replicator/CryptoModule.kt | 2 | 1575 | /*
* Copyright (C) 2016 Mihรกly Szabรณ
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.libreplicator.module.replicator
import dagger.Module
import dagger.Provides
import org.libreplicator.component.replicator.ReplicatorScope
import org.libreplicator.crypto.DefaultCipher
import org.libreplicator.crypto.api.Cipher
import org.libreplicator.module.replicator.setting.ReplicatorCryptoSettings
@Module
class CryptoModule(private val cryptoSettings: ReplicatorCryptoSettings) {
@Provides @ReplicatorScope
fun provideCipher(): Cipher {
if (cryptoSettings.isEncryptionEnabled && cryptoSettings.sharedSecret.isNotBlank()) {
return DefaultCipher(cryptoSettings.sharedSecret)
}
return object : Cipher {
override fun encrypt(content: String): String = content
override fun decrypt(encryptedContent: String): String = encryptedContent
}
}
}
| gpl-3.0 |
jiangkang/KTools | app/src/main/java/com/jiangkang/ktools/initializer/ImageLibInitializer.kt | 1 | 365 | package com.jiangkang.ktools.initializer
import android.content.Context
import androidx.startup.Initializer
class ImageLibInitializer : Initializer<Any>{
override fun create(context: Context): Any {
TODO("Not yet implemented")
}
override fun dependencies(): MutableList<Class<out Initializer<*>>> {
TODO("Not yet implemented")
}
} | mit |
thomasvolk/alkali | src/test/kotlin/net/t53k/alkali/tree/ActorTreeTest.kt | 1 | 3750 | /*
* Copyright 2017 Thomas Volk
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package net.t53k.alkali.tree
import net.t53k.alkali.Actor
import net.t53k.alkali.ActorReference
import net.t53k.alkali.test.actorTest
import org.junit.Assert
import org.junit.Test
data class Init(val maxLevel: Long, val leafes: Int) {
fun totalCount() = (0..maxLevel).map { Math.pow(leafes.toDouble(), it.toDouble()) }.sum().toInt()
}
data class Start(val path: String, val level: Long, val maxLevel: Long, val leafes: Int) {
fun maxLevelReached() = level >= maxLevel
fun leaf(leafNumber: Int) = Start("$path-$leafNumber", level + 1, maxLevel, leafes)
}
data class Created(val name: String)
data class TreeCreated(val leafeCount: Long)
data class Question(val message: String)
data class Answer(val question: Question, val message: String)
class Tree : Actor() {
private lateinit var root: ActorReference
private var count: Long = 0
private lateinit var start: Init
private lateinit var starter: ActorReference
override fun receive(message: Any) {
when(message) {
is Init -> {
root = actor("Test-R", Node::class)
root send Start("R", 0, message.maxLevel, message.leafes)
start = message
starter = sender()
}
is Created -> {
count++
if(count >= start.totalCount()) {
starter send TreeCreated(count)
}
}
is Question -> root send message
is Answer -> starter send message
}
}
}
class Node : Actor() {
private lateinit var parent: ActorReference
private val children = mutableListOf<ActorReference>()
override fun receive(message: Any) {
when(message) {
is Start -> {
parent = sender()
if(!message.maxLevelReached()) {
for(i in 0..(message.leafes - 1)) {
val leafMsg = message.leaf(i)
val n = actor("Test-${leafMsg.path}", Node::class)
n send leafMsg
children += n
}
}
sender() send Created(self().name)
}
is Created -> parent send message
is Question -> {
children.forEach { it send message }
self() send Answer(message, "Answer to: ${message.message}")
}
is Answer -> parent send message
}
}
}
class ActorTreeTest {
@Test
fun tree() {
actorTest {
val tree = testSystem().actor("tree", Tree::class)
tree send Init(3, 2)
onMessage { msg ->
when(msg) {
is TreeCreated -> Assert.assertEquals(15, msg.leafeCount)
else -> Assert.fail("wrong message: $msg")
}
}
}
}
}
| apache-2.0 |
andrei-heidelbacher/algostorm | algostorm-systems/src/main/kotlin/com/andreihh/algostorm/systems/graphics2d/GraphicsSystem.kt | 1 | 1319 | /*
* Copyright (c) 2017 Andrei Heidelbacher <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.andreihh.algostorm.systems.graphics2d
import com.andreihh.algostorm.systems.EventSystem
abstract class GraphicsSystem : EventSystem() {
companion object {
const val TILE_WIDTH: String = "TILE_WIDTH"
const val TILE_HEIGHT: String = "TILE_HEIGHT"
const val TILE_SET_COLLECTION: String = "TILE_SET_COLLECTION"
const val CAMERA: String = "CAMERA"
const val GRAPHICS_DRIVER: String = "GRAPHICS_DRIVER"
}
protected val tileWidth: Int by context(TILE_WIDTH)
protected val tileHeight: Int by context(TILE_HEIGHT)
protected val tileSetCollection: TileSetCollection
by context(TILE_SET_COLLECTION)
}
| apache-2.0 |
Shynixn/PetBlocks | petblocks-bukkit-plugin/petblocks-bukkit-nms-109R2/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_9_R2/CraftPetArmorstand.kt | 1 | 2824 | package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_9_R2
import com.github.shynixn.petblocks.api.business.proxy.ArmorstandPetProxy
import com.github.shynixn.petblocks.api.business.proxy.EntityPetProxy
import net.minecraft.server.v1_9_R2.EnumItemSlot
import org.bukkit.craftbukkit.v1_9_R2.CraftServer
import org.bukkit.craftbukkit.v1_9_R2.entity.CraftArmorStand
import org.bukkit.craftbukkit.v1_9_R2.inventory.CraftItemStack
import org.bukkit.inventory.ItemStack
/**
* Created by Shynixn 2019.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2019 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 CraftPetArmorstand(server: CraftServer, nmsPet: NMSPetArmorstand) : CraftArmorStand(server, nmsPet),
ArmorstandPetProxy {
/**
* Sets the helmet item stack securely if
* blocked by the NMS call.
*/
override fun <I> setHelmetItemStack(item: I) {
require(item is ItemStack?)
(handle as NMSPetArmorstand).setSecureSlot(EnumItemSlot.HEAD, CraftItemStack.asNMSCopy(item))
}
/**
* Sets the boots item stack securely if
* blocked by the NMS call.
*/
override fun <I> setBootsItemStack(item: I) {
require(item is ItemStack?)
(handle as NMSPetArmorstand).setSecureSlot(EnumItemSlot.FEET, CraftItemStack.asNMSCopy(item))
}
/**
* Removes this entity.
*/
override fun deleteFromWorld() {
super.remove()
}
/**
* Ignore all other plugins trying to remove this entity. This is the entity of PetBlocks,
* no one else is allowed to modify this!
*/
override fun remove() {
}
/**
* Custom type.
*/
override fun toString(): String {
return "PetBlocks{ArmorstandEntity}"
}
} | apache-2.0 |
world-federation-of-advertisers/common-jvm | src/main/kotlin/org/wfanet/measurement/common/crypto/InvalidSignatureException.kt | 1 | 879 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.common.crypto
/**
* Indicates that there is a problem matching data to a signature. Either the signature is invalid
* for the data or can't be found at all.
*/
class InvalidSignatureException(message: String) : Exception(message)
| apache-2.0 |
mozilla-mobile/focus-android | app/src/test/java/org/mozilla/focus/searchwidget/ExternalIntentNavigationTest.kt | 1 | 8771 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.searchwidget
import android.app.Activity
import android.content.Context
import android.os.Bundle
import mozilla.components.browser.state.selector.allTabs
import mozilla.components.browser.state.selector.findCustomTabOrSelectedTab
import mozilla.components.browser.state.selector.privateTabs
import mozilla.components.browser.state.state.SessionState
import mozilla.components.feature.search.widget.BaseVoiceSearchActivity
import mozilla.components.support.test.libstate.ext.waitUntilIdle
import mozilla.components.support.test.robolectric.testContext
import mozilla.telemetry.glean.testing.GleanTestRule
import org.junit.Assert.assertNotNull
import org.junit.Rule
import org.junit.Test
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.runner.RunWith
import org.mozilla.focus.GleanMetrics.SearchWidget
import org.mozilla.focus.activity.IntentReceiverActivity
import org.mozilla.focus.ext.components
import org.mozilla.focus.ext.settings
import org.mozilla.focus.perf.Performance
import org.mozilla.focus.state.AppAction
import org.mozilla.focus.state.Screen
import org.mozilla.focus.utils.SearchUtils
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
@RunWith(RobolectricTestRunner::class)
internal class ExternalIntentNavigationTest {
@get:Rule
val gleanTestRule = GleanTestRule(testContext)
private val activity: Activity = Robolectric.buildActivity(Activity::class.java).setup().get()
private val appStore = activity.components.appStore
@Test
fun `GIVEN the onboarding should be shown and the app is not used in performance tests WHEN the app is opened THEN show the onboarding`() {
activity.settings.isFirstRun = true
ExternalIntentNavigation.handleAppOpened(null, activity)
appStore.waitUntilIdle()
assertEquals(Screen.FirstRun, appStore.state.screen)
}
@Test
@Config(shadows = [ShadowPerformance::class])
fun `GIVEN the onboarding should be shown and the app is used in a performance test WHEN the app is opened THEN show the homescreen`() {
// The AppStore is initialized before the test runs. By default isFirstRun is true. Simulate it being false.
appStore.dispatch(AppAction.ShowHomeScreen)
appStore.waitUntilIdle()
activity.settings.isFirstRun = true
ExternalIntentNavigation.handleAppOpened(null, activity)
appStore.waitUntilIdle()
assertEquals(Screen.Home, appStore.state.screen)
}
@Test
@Config(shadows = [ShadowPerformance::class])
fun `GIVEN the onboarding should not be shown and in a performance test WHEN the app is opened THEN show the home screen`() {
// The AppStore is initialized before the test runs. By default isFirstRun is true. Simulate it being false.
appStore.dispatch(AppAction.ShowHomeScreen)
appStore.waitUntilIdle()
activity.settings.isFirstRun = false
ExternalIntentNavigation.handleAppOpened(null, activity)
appStore.waitUntilIdle()
assertEquals(Screen.Home, appStore.state.screen)
}
@Test
fun `GIVEN the onboarding should not be shown and not in a performance test WHEN the app is opened THEN show the home screen`() {
// The AppStore is initialized before the test runs. By default isFirstRun is true. Simulate it being false.
appStore.dispatch(AppAction.ShowHomeScreen)
appStore.waitUntilIdle()
activity.settings.isFirstRun = false
ExternalIntentNavigation.handleAppOpened(null, activity)
appStore.waitUntilIdle()
assertEquals(Screen.Home, appStore.state.screen)
}
@Test
fun `GIVEN a tab is already open WHEN trying to navigate to the current tab THEN navigate to it and return true`() {
activity.components.tabsUseCases.addTab(url = "https://mozilla.com")
activity.components.store.waitUntilIdle()
val result = ExternalIntentNavigation.handleBrowserTabAlreadyOpen(activity)
activity.components.appStore.waitUntilIdle()
assertTrue(result)
val selectedTabId = activity.components.store.state.selectedTabId!!
assertEquals(Screen.Browser(selectedTabId, false), activity.components.appStore.state.screen)
}
@Test
fun `GIVEN no tabs are currently open WHEN trying to navigate to the current tab THEN navigate home and return false`() {
// The AppStore is initialized before the test runs. By default isFirstRun is true. Simulate it being false.
appStore.dispatch(AppAction.ShowHomeScreen)
appStore.waitUntilIdle()
val result = ExternalIntentNavigation.handleBrowserTabAlreadyOpen(activity)
activity.components.appStore.waitUntilIdle()
assertFalse(result)
assertEquals(Screen.Home, activity.components.appStore.state.screen)
}
@Test
fun `GIVEN a text search from the search widget WHEN handling widget interactions THEN record telemetry, show the home screen and return true`() {
val bundle = Bundle().apply {
putBoolean(IntentReceiverActivity.SEARCH_WIDGET_EXTRA, true)
}
val result = ExternalIntentNavigation.handleWidgetTextSearch(bundle, activity)
appStore.waitUntilIdle()
assertTrue(result)
assertNotNull(SearchWidget.newTabButton.testGetValue())
assertEquals(Screen.Home, appStore.state.screen)
}
@Test
fun `GIVEN no text search from the search widget WHEN handling widget interactions THEN don't record telemetry, show the home screen and false true`() {
// The AppStore is initialized before the test runs. By default isFirstRun is true. Simulate it being false.
appStore.dispatch(AppAction.ShowHomeScreen)
appStore.waitUntilIdle()
val bundle = Bundle()
val result = ExternalIntentNavigation.handleWidgetTextSearch(bundle, activity)
appStore.waitUntilIdle()
assertFalse(result)
assertNull(SearchWidget.newTabButton.testGetValue())
assertEquals(Screen.Home, appStore.state.screen)
}
@Test
fun `GIVEN a voice search WHEN handling widget interactions THEN create and open a new tab and return true`() {
val browserStore = activity.components.store
val searchArgument = "test"
val bundle = Bundle().apply {
putString(BaseVoiceSearchActivity.SPEECH_PROCESSING, searchArgument)
}
val result = ExternalIntentNavigation.handleWidgetVoiceSearch(bundle, activity)
assertTrue(result)
browserStore.waitUntilIdle()
assertEquals(1, browserStore.state.allTabs.size)
assertEquals(1, browserStore.state.privateTabs.size)
val voiceSearchTab = browserStore.state.privateTabs[0]
assertEquals(voiceSearchTab, browserStore.state.findCustomTabOrSelectedTab())
assertEquals(SearchUtils.createSearchUrl(activity, searchArgument), voiceSearchTab.content.url)
assertEquals(SessionState.Source.External.ActionSend(null), voiceSearchTab.source)
assertEquals(searchArgument, voiceSearchTab.content.searchTerms)
appStore.waitUntilIdle()
assertEquals(Screen.Browser(voiceSearchTab.id, false), appStore.state.screen)
}
@Test
fun `GIVEN no voice search WHEN handling widget interactions THEN don't open a new tab and return false`() {
// The AppStore is initialized before the test runs. By default isFirstRun is true. Simulate it being false.
appStore.dispatch(AppAction.ShowHomeScreen)
appStore.waitUntilIdle()
val browserStore = activity.components.store
val bundle = Bundle()
val result = ExternalIntentNavigation.handleWidgetVoiceSearch(bundle, activity)
assertFalse(result)
browserStore.waitUntilIdle()
assertEquals(0, browserStore.state.allTabs.size)
appStore.waitUntilIdle()
assertEquals(Screen.Home, appStore.state.screen)
}
}
/**
* Shadow of [Performance] that will have [processIntentIfPerformanceTest] always return `true`.
*/
@Implements(Performance::class)
class ShadowPerformance {
@Implementation
@Suppress("Unused_Parameter")
fun processIntentIfPerformanceTest(bundle: Bundle?, context: Context) = true
}
| mpl-2.0 |
mplatvoet/kovenant | projects/core/src/main/kotlin/queue-jvm.kt | 1 | 3602 | /*
* Copyright (c) 2015 Mark Platvoet<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* THE SOFTWARE.
*/
package nl.komponents.kovenant
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicInteger
class NonBlockingWorkQueue<V : Any>() : BlockingSupportWorkQueue<V>() {
private val queue = ConcurrentLinkedQueue<V>()
override fun tryPoll(): V? = queue.poll()
override fun tryOffer(elem: V): Boolean = queue.offer(elem)
override fun size(): Int = queue.size
override fun isEmpty(): Boolean = queue.isEmpty()
override fun isNotEmpty(): Boolean = !isEmpty()
override fun remove(elem: Any?): Boolean = queue.remove(elem)
}
abstract class BlockingSupportWorkQueue<V : Any>() : WorkQueue<V> {
private val waitingThreads = AtomicInteger(0)
//yes I could also use a ReentrantLock with a Condition but
//introduces quite a lot of overhead and the semantics
//are just the same
private val mutex = Object()
abstract fun tryPoll(): V?
abstract fun tryOffer(elem: V): Boolean
override fun offer(elem: V): Boolean {
val added = tryOffer(elem)
if (added && waitingThreads.get() > 0) {
synchronized(mutex) {
//maybe there aren't any threads waiting or
//there isn't anything in the queue anymore
//just notify, we've got this far
mutex.notifyAll()
}
}
return added
}
override fun poll(block: Boolean, timeoutMs: Long): V? {
if (!block) return tryPoll()
val elem = tryPoll()
if (elem != null) return elem
waitingThreads.incrementAndGet()
try {
return if (timeoutMs > -1L) {
blockingPoll(timeoutMs)
} else {
blockingPoll()
}
} finally {
waitingThreads.decrementAndGet()
}
}
private fun blockingPoll(): V? {
synchronized(mutex) {
while (true) {
val retry = tryPoll()
if (retry != null) return retry
mutex.wait()
}
}
throw KovenantException("unreachable")
}
private fun blockingPoll(timeoutMs: Long): V? {
val deadline = System.currentTimeMillis() + timeoutMs
synchronized(mutex) {
while (true) {
val retry = tryPoll()
if (retry != null || System.currentTimeMillis() >= deadline) return retry
mutex.wait(timeoutMs)
}
}
throw KovenantException("unreachable")
}
}
| mit |
chat-sdk/chat-sdk-android | chat-sdk-vendor/src/main/java/smartadapter/viewevent/viewmodel/ViewEventApplicationViewModel.kt | 1 | 1457 | package smartadapter.viewevent.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import smartadapter.viewevent.listener.OnViewEventListener
import smartadapter.viewevent.model.ViewEvent
/**
* Basic android view model that wraps an [OnViewEventListener].
*/
open class ViewEventApplicationViewModel<VE : ViewEvent, T : OnViewEventListener<VE>>(
application: Application,
val viewEventListener: T
) : AndroidViewModel(application) {
init {
viewEventListener.eventListener = {
eventObserver.postValue(it)
}
}
private val eventObserver by lazy(mode = LazyThreadSafetyMode.PUBLICATION) {
MutableLiveData<VE>()
}
fun observe(
lifecycle: LifecycleOwner,
observer: Observer<VE>
): T {
eventObserver.observe(lifecycle, observer)
return viewEventListener
}
fun observe(
lifecycle: LifecycleOwner,
listener: (VE) -> Unit
): T {
eventObserver.observe(lifecycle, Observer {
listener.invoke(it)
})
return viewEventListener
}
fun removeListener(observer: Observer<ViewEvent>) =
eventObserver.removeObserver(observer)
fun removeObservers(lifecycleOwner: LifecycleOwner) =
eventObserver.removeObservers(lifecycleOwner)
} | apache-2.0 |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/cargo/runconfig/command/CargoExecutableRunConfigurationProducer.kt | 2 | 3067 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.runconfig.command
import com.intellij.execution.Location
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.RunConfigurationProducer
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.cargo.runconfig.mergeWithDefault
import org.rust.cargo.toolchain.CargoCommandLine
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.ext.cargoWorkspace
import org.rust.lang.core.psi.ext.ancestorStrict
import org.rust.openapiext.toPsiFile
class CargoExecutableRunConfigurationProducer : RunConfigurationProducer<CargoCommandConfiguration>(CargoCommandConfigurationType()) {
override fun isConfigurationFromContext(
configuration: CargoCommandConfiguration,
context: ConfigurationContext
): Boolean {
val location = context.location ?: return false
val target = findBinaryTarget(location) ?: return false
return configuration.canBeFrom(target.cargoCommandLine)
}
override fun setupConfigurationFromContext(
configuration: CargoCommandConfiguration,
context: ConfigurationContext,
sourceElement: Ref<PsiElement>
): Boolean {
val location = context.location ?: return false
val target = findBinaryTarget(location) ?: return false
val fn = location.psiElement.ancestorStrict<RsFunction>()
val source = if (fn != null && isMainFunction(fn)) fn else context.psiLocation?.containingFile
sourceElement.set(source)
configuration.name = target.configurationName
val cmd = target.cargoCommandLine.mergeWithDefault(configuration)
configuration.setFromCmd(cmd)
return true
}
private class ExecutableTarget(target: CargoWorkspace.Target) {
val configurationName: String = "Run ${target.name}"
val cargoCommandLine = CargoCommandLine.forTarget(target, "run")
}
companion object {
fun isMainFunction(fn: RsFunction): Boolean {
val ws = fn.cargoWorkspace ?: return false
return fn.name == "main" && findBinaryTarget(ws, fn.containingFile.virtualFile) != null
}
private fun findBinaryTarget(location: Location<*>): ExecutableTarget? {
val file = location.virtualFile ?: return null
val rsFile = file.toPsiFile(location.project) as? RsFile ?: return null
val ws = rsFile.cargoWorkspace ?: return null
return findBinaryTarget(ws, file)
}
private fun findBinaryTarget(ws: CargoWorkspace, file: VirtualFile): ExecutableTarget? {
val target = ws.findTargetByCrateRoot(file) ?: return null
if (!target.isBin && !target.isExample) return null
return ExecutableTarget(target)
}
}
}
| mit |
ProgramLeague/EmailEverything | src/main/kotlin/ray/eldath/ew/util/EmailAddressConfig.kt | 1 | 539 | package ray.eldath.ew.util
import org.simplejavamail.mailer.config.TransportStrategy
class EmailHost(val sender: Sender, val receiver: Receiver) {
class Sender(val host: String, val port: Int, val protocol: EmailHostProtocol, val transportStrategy: TransportStrategy)
class Receiver(val host: String, val port: Int, val protocol: EmailHostProtocol, val ssl: Boolean)
}
enum class EmailHostProtocol {
SMTP, IMAP, POP3;
}
class EmailAddressConfig(val name: String, val address: String, val password: String, val emailHost: EmailHost) | gpl-3.0 |
google/horologist | media-sample-benchmark/src/main/java/com/google/android/horologist/mediasample/benchmark/BaselineProfile.kt | 1 | 1906 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.mediasample.benchmark
import androidx.benchmark.macro.ExperimentalBaselineProfilesApi
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.android.horologist.media.benchmark.BaseMediaBaselineProfile
import com.google.android.horologist.media.benchmark.MediaApp
import org.junit.runner.RunWith
// This test generates a baseline profile rules file that can be added to the app to configure
// the classes and methods that are pre-compiled at installation time, rather than JIT'd at runtime.
// 1) Run this test on a device
// 2) Copy the generated file to your workspace - command is output as part of the test:
// `adb pull "/sdcard/Android/media/com.example.android.wearable.composeadvanced.benchmark/"
// "additional_test_output/BaselineProfile_profile-baseline-prof-2022-03-25-16-58-49.txt"
// .`
// 3) Add the rules as androidMain/baseline-prof.txt
// Note that Compose libraries have profile rules already so the main benefit is to add any
// rules that are specific to classes and methods in your own app and library code.
@ExperimentalBaselineProfilesApi
@RunWith(AndroidJUnit4::class)
class BaselineProfile : BaseMediaBaselineProfile() {
override val mediaApp: MediaApp = TestMedia.MediaSampleApp
}
| apache-2.0 |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/ui/preferences/components/AppItem.kt | 1 | 3205 | /*
* Copyright 2021, Lawnchair
*
* 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 app.lawnchair.ui.preferences.components
import android.graphics.Bitmap
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import app.lawnchair.util.App
import com.google.accompanist.placeholder.PlaceholderHighlight
import com.google.accompanist.placeholder.material.fade
import com.google.accompanist.placeholder.material.placeholder
@Composable
fun AppItem(
app: App,
onClick: (app: App) -> Unit,
widget: (@Composable () -> Unit)? = null,
) {
AppItem(
label = app.label,
icon = app.icon,
onClick = { onClick(app) },
widget = widget,
)
}
@Composable
fun AppItem(
label: String,
icon: Bitmap,
onClick: () -> Unit,
widget: (@Composable () -> Unit)? = null,
) {
AppItemLayout(
modifier = Modifier
.clickable(onClick = onClick),
widget = widget,
icon = {
Image(
bitmap = icon.asImageBitmap(),
contentDescription = null,
modifier = Modifier.size(30.dp),
)
},
title = { Text(text = label) }
)
}
@Composable
fun AppItemPlaceholder(
widget: (@Composable () -> Unit)? = null,
) {
AppItemLayout(
widget = widget,
icon = {
Spacer(
modifier = Modifier
.size(30.dp)
.placeholder(
visible = true,
highlight = PlaceholderHighlight.fade(),
)
)
}
) {
Spacer(
modifier = Modifier
.width(120.dp)
.height(24.dp)
.placeholder(
visible = true,
highlight = PlaceholderHighlight.fade(),
)
)
}
}
@Composable
private fun AppItemLayout(
modifier: Modifier = Modifier,
widget: (@Composable () -> Unit)? = null,
icon: @Composable () -> Unit,
title: @Composable () -> Unit,
) {
PreferenceTemplate(
title = title,
modifier = modifier,
startWidget = {
widget?.let {
it()
Spacer(modifier = Modifier.requiredWidth(16.dp))
}
icon()
},
verticalPadding = 12.dp
)
}
| gpl-3.0 |
JavaEden/OrchidCore | OrchidCore/src/main/kotlin/com/eden/orchid/impl/commands/DeployCommand.kt | 1 | 937 | package com.eden.orchid.impl.commands
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.BooleanDefault
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.tasks.OrchidCommand
import com.google.inject.Provider
import javax.inject.Inject
@Description("Publish the Orchid build results.")
class DeployCommand
@Inject
constructor(
private val contextProvider: Provider<OrchidContext>
) : OrchidCommand(100, "deploy") {
@Option
@BooleanDefault(true)
@Description("Whether to run a dry deploy, validating all options but not actually deploying anything.")
var dry: Boolean = true
override fun parameters(): Array<String> {
return arrayOf("dry")
}
@Throws(Exception::class)
override fun run(commandName: String) {
contextProvider.get().deploy(dry)
}
}
| mit |
Shynixn/BlockBall | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/entity/ArenaMetaEntity.kt | 1 | 7464 | @file:Suppress("UNCHECKED_CAST")
package com.github.shynixn.blockball.core.logic.persistence.entity
import com.github.shynixn.blockball.api.business.annotation.YamlSerialize
import com.github.shynixn.blockball.api.business.enumeration.BallActionType
import com.github.shynixn.blockball.api.business.enumeration.ParticleType
import com.github.shynixn.blockball.api.business.enumeration.PlaceHolder
import com.github.shynixn.blockball.api.persistence.entity.ArenaMeta
import com.github.shynixn.blockball.api.persistence.entity.HologramMeta
/**
* 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 ArenaMetaEntity : ArenaMeta {
/** Meta data for spectating setting. */
@YamlSerialize(orderNumber = 12, value = "spectator-meta")
override val spectatorMeta: SpectatorMetaEntity = SpectatorMetaEntity()
/** Meta data of the customizing Properties. */
@YamlSerialize(orderNumber = 13, value = "customizing-meta")
override val customizingMeta: CustomizationMetaEntity = CustomizationMetaEntity()
/** Meta data for rewards */
@YamlSerialize(orderNumber = 10, value = "reward-meta")
override val rewardMeta: RewardEntity = RewardEntity()
/** Meta data of all holograms. */
override val hologramMetas: ArrayList<HologramMeta>
get() = this.internalHologramMetas as ArrayList<HologramMeta>
/** Meta data of a generic lobby. */
@YamlSerialize(orderNumber = 1, value = "meta")
override val lobbyMeta: LobbyMetaEntity = LobbyMetaEntity()
/** Meta data of the hub lobby. */
@YamlSerialize(orderNumber = 2, value = "hubgame-meta")
override var hubLobbyMeta: HubLobbyMetaEntity = HubLobbyMetaEntity()
/** Meta data of the minigame lobby. */
@YamlSerialize(orderNumber = 3, value = "minigame-meta")
override val minigameMeta: MinigameLobbyMetaEntity = MinigameLobbyMetaEntity()
/** Meta data of the bungeecord lobby. */
@YamlSerialize(orderNumber = 4, value = "bungeecord-meta")
override val bungeeCordMeta: BungeeCordLobbyMetaEntity = BungeeCordLobbyMetaEntity()
/** Meta data of the doubleJump. */
@YamlSerialize(orderNumber = 8, value = "double-jump")
override val doubleJumpMeta: DoubleJumpMetaEntity = DoubleJumpMetaEntity()
/** Meta data of the bossbar. */
@YamlSerialize(orderNumber = 7, value = "bossbar")
override val bossBarMeta: BossBarMetaEntity = BossBarMetaEntity()
/** Meta data of the scoreboard. */
@YamlSerialize(orderNumber = 6, value = "scoreboard")
override val scoreboardMeta: ScoreboardEntity = ScoreboardEntity()
/** Meta data of proection. */
@YamlSerialize(orderNumber = 5, value = "protection")
override val protectionMeta: ArenaProtectionMetaEntity = ArenaProtectionMetaEntity()
/** Meta data of the ball. */
@YamlSerialize(orderNumber = 4, value = "ball")
override val ballMeta: BallMetaEntity = BallMetaEntity("http://textures.minecraft.net/texture/8e4a70b7bbcd7a8c322d522520491a27ea6b83d60ecf961d2b4efbbf9f605d")
/** Meta data of the blueTeam. */
@YamlSerialize(orderNumber = 3, value = "team-blue")
override val blueTeamMeta: TeamMetaEntity = TeamMetaEntity("Team Blue", "&9", PlaceHolder.BLUE_COLOR.placeHolder + PlaceHolder.BLUE_GOALS.placeHolder + " : " + PlaceHolder.RED_COLOR.placeHolder + PlaceHolder.RED_GOALS.placeHolder, PlaceHolder.BLUE_COLOR.placeHolder + PlaceHolder.LASTHITBALL.placeHolder + " scored for " + PlaceHolder.TEAM_BLUE.placeHolder, PlaceHolder.BLUE_COLOR.placeHolder + PlaceHolder.TEAM_BLUE.placeHolder, PlaceHolder.BLUE_COLOR.placeHolder + PlaceHolder.TEAM_BLUE.placeHolder + "&a has won the match", PlaceHolder.BLUE_COLOR.placeHolder + PlaceHolder.TEAM_BLUE.placeHolder, "&eMatch ended in a draw.")
/** Meta data of the redTeam. */
@YamlSerialize(orderNumber = 2, value = "team-red")
override val redTeamMeta: TeamMetaEntity = TeamMetaEntity("Team Red", "&c", PlaceHolder.RED_COLOR.placeHolder + PlaceHolder.RED_GOALS.placeHolder + " : " + PlaceHolder.BLUE_COLOR.placeHolder + PlaceHolder.BLUE_GOALS.placeHolder, PlaceHolder.RED_COLOR.placeHolder + PlaceHolder.LASTHITBALL.placeHolder + " scored for " + PlaceHolder.TEAM_RED.placeHolder, PlaceHolder.RED_COLOR.placeHolder + PlaceHolder.TEAM_RED.placeHolder, PlaceHolder.RED_COLOR.placeHolder + PlaceHolder.TEAM_RED.placeHolder + "&a has won the match", PlaceHolder.RED_COLOR.placeHolder + PlaceHolder.TEAM_RED.placeHolder, "&eMatch ended in a draw.")
@YamlSerialize(orderNumber = 9, value = "holograms")
private val internalHologramMetas: ArrayList<HologramMetaEntity> = ArrayList()
init {
val partMetaSpawn = ParticleEntity()
partMetaSpawn.typeName = ParticleType.EXPLOSION_NORMAL.name
partMetaSpawn.amount = 10
partMetaSpawn.speed = 0.1
partMetaSpawn.offset.x = 2.0
partMetaSpawn.offset.y = 2.0
partMetaSpawn.offset.z = 2.0
ballMeta.particleEffects[BallActionType.ONSPAWN] = partMetaSpawn
val partMetaInteraction = ParticleEntity()
partMetaInteraction.typeName = ParticleType.CRIT.name
partMetaInteraction.amount = 5
partMetaInteraction.speed = 0.1
partMetaInteraction.offset.x = 2.0
partMetaInteraction.offset.y = 2.0
partMetaInteraction.offset.z = 2.0
ballMeta.particleEffects[BallActionType.ONINTERACTION] = partMetaInteraction
val partMetaKick = ParticleEntity()
partMetaKick.typeName = ParticleType.EXPLOSION_LARGE.name
partMetaKick.amount = 5
partMetaKick.speed = 0.1
partMetaKick.offset.x = 0.2
partMetaKick.offset.y = 0.2
partMetaKick.offset.z = 0.2
ballMeta.particleEffects[BallActionType.ONKICK] = partMetaKick
val partMetaShoot = ParticleEntity()
partMetaShoot.typeName = ParticleType.EXPLOSION_NORMAL.name
partMetaShoot.amount = 5
partMetaShoot.speed = 0.1
partMetaShoot.offset.x = 0.1
partMetaShoot.offset.y = 0.1
partMetaShoot.offset.z = 0.1
ballMeta.particleEffects[BallActionType.ONPASS] = partMetaShoot
val soundMetaKick = SoundEntity()
soundMetaKick.name = "ZOMBIE_WOOD"
soundMetaKick.volume = 10.0
soundMetaKick.pitch = 1.5
ballMeta.soundEffects[BallActionType.ONKICK] = soundMetaKick
}
} | apache-2.0 |
HerbLuo/shop-api | src/main/java/cn/cloudself/service/impl/OrderServiceImpl.kt | 1 | 9882 | package cn.cloudself.service.impl
import cn.cloudself.components.annotation.ParamChecker
import cn.cloudself.dao.*
import cn.cloudself.exception.http.RequestBadException
import cn.cloudself.exception.http.ServerException
import cn.cloudself.model.*
import cn.cloudself.service.IOrderService
import org.apache.log4j.Logger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.util.Assert
/**
* @author HerbLuo
* @version 1.0.0.d
*/
@Service
@Transactional
open class OrderServiceImpl @Autowired
constructor(
private val orderDao: IOrderDao,
private val itemDao: IItemDao,
private val addressDao: IAddressDao,
private val itemSellingInfoDao: IItemSellingInfoDao,
private val deliverDao: IDeliverDao,
private val orderAShopDao: IOrderAShopDao,
private val messageDao: IMessageDao,
private val logger: Logger,
private val itemCommentDao: IItemCommentDao
) : IOrderService {
/**
* ๅๅพๅๅฒ่ฎขๅ
*
* @param userId ็จๆทid
* @param page .
* @param aPageSize .
* @return .
*/
@ParamChecker(
greaterThan0 = intArrayOf(0, 2),
greaterOrEqual0 = intArrayOf(1)
)
@Throws(Exception::class)
override fun getOrdersByUser(
userId: Int, page: Int, aPageSize: Int
): Page<OrderEntity> {
return orderDao.findByUserIdAndEnabledTrue(
userId,
PageRequest(page, aPageSize, Sort(Sort.Direction.DESC, "createTime"))
)
}
/**
* ๅๅปบ่ฎขๅ
*
* @param userId .
* @param orderAShops ่ฎขๅ๏ผๅไธบๅฏนไธชๅบ้บ๏ผ
* @return ่ฎขๅid
*/
@ParamChecker(greaterThan0 = intArrayOf(0), notEmpty = intArrayOf(1))
@Throws(Exception::class)
override fun createOrder(userId: Int, orderAShops: List<OrderAShopEntity>): Int? {
// 1. ่ฟๆปคorderAShop๏ผๅฐid ๅ่ดง็ถๆ ๆถ่ดง็ถๆ ๆฏๅฆ่ฏ่ฎบ ๆๆฃ ่ฎพไธบ้ป่ฎคๅผ
// 2. ๆฃๆฅๅๅไธๅๅฎถๆฏๅฆๅฏนๅบ
// 3. ๆฃๆฅๆถ่ดงๅฐๅๆฏๅฆไธบ็จๆทๅไธ็ๆถ่ดงๅฐๅ๏ผ้ฒๆญขๅฐๅไฟกๆฏๆณ้ฒ๏ผ
// 4. ่ฟๆปคorderAnItem ็idๅผ ไฟ่ฏ่ดญไนฐ็ๅๅๆฐ้๏ผquantity๏ผๅคงไบ0
// 5. ๅๅๅบๅญๆฃๆฅ
for (orderAShop in orderAShops) {
/*
* 1 request param to json bean
*/
orderAShop.id = 0
orderAShop.areDeliver = null
orderAShop.areReceive = null
orderAShop.areEvaluate = null
orderAShop.discount = null
orderAShop.userId = userId
/*
* 2
*/
// non-null check
val orderAnItems = orderAShop.orderAnItems
?: throw RequestBadException("items ไธ่ฝไธบ็ฉบ")
val shopid = orderAShop.shop?.id ?: throw RequestBadException("shop ไธ่ฝไธบ็ฉบ")
// ้่ฆๆฃๆฅ็item id
val itemIds = orderAnItems
.map { it.item ?: throw RequestBadException("items ไธ่ฝไธบ็ฉบ")}
.map { it.id }
// ๆฐๆฎๅบไธญๅๅบๆฅ็Itemๅฏน่ฑก
itemDao.findAll(itemIds)
.filter { it.shop?.id != shopid }
.forEach { throw RequestBadException("ๅๅไฟกๆฏไธๅบ้บๆๅฎไธไธ่ด") }
/*
* 3
*/
val address = addressDao.findOne(orderAShop.address?.id
?: throw RequestBadException("addressไธ่ฝๆช็ฉบ")
)
address.userId != userId &&
throw RequestBadException("ๅฐๅไฟกๆฏไธ็ฌฆ่ฆๆฑ")
for (orderAnItem in orderAnItems) {
orderAnItem.item == null &&
throw RequestBadException("ๅๅไฟกๆฏไธ่ฝไธบ็ฉบ")
/*
* 4
*/
orderAnItem.id = 0
orderAnItem.quantity <= 0 &&
throw RequestBadException("่ดญไนฐ็ๅๅๆฐ้ไธ่ฝๅฐไบ0")
/*
* 5
*/
if (!kucunChecker(orderAnItem.item!!.id, orderAnItem.quantity)) {
throw RequestBadException("ๅบๅญไธ่ถณ")
}
}
}
var order = OrderEntity()
order.userId = userId
order.orderAShops = orderAShops
order = orderDao.save(order)
return order.id
}
/**
* ๆฃๆฅๅบๅญ้ข็ๆนๆณ
*
* @return .
*/
private fun kucunChecker(itemId: Int?, quantity: Int?): Boolean {
Assert.notNull(itemId)
Assert.notNull(quantity)
val itemSellingInfo = itemSellingInfoDao.findOne(itemId)
return itemSellingInfo != null &&
itemSellingInfo.inOrdering + quantity!! <= itemSellingInfo.quantity
}
/**
* ็ๆ่ฎขๅ็ๆฏไปไฟกๆฏ
* ่ฎก็ฎ่ฎขๅไปทๆ ผ
*
* @param orderId .
* @param userId .
* @return .
*/
@ParamChecker(0, 1)
@Throws(Exception::class)
override fun pay(orderId: Int, userId: Int): PayEntity {
val order = orderDao.findOne(orderId)
if (order.areFinished!!) {
throw RequestBadException("่ฎขๅๅทฒๅฎๆ")
}
if (order.arePaied!!) {
throw RequestBadException("่ฎขๅๅทฒๆฏไป")
}
if (order.userId != userId) {
throw RequestBadException("็จๆทไฟกๆฏไธ็ฌฆ")
}
val orderAShops = order.orderAShops
Assert.notEmpty(orderAShops, "ๅๅปบไบ้่ฏฏ็่ฎขๅ๏ผ")
/*
* ่ฎก็ฎ่ฎขๅไปทๆ ผ
*/
var discount = 0.0 //ๅๅฎถ็ป็ๆๆฃ
var totalCost = 0.0 //ๅๅไปทๆ ผๅ่ฎก
for (orderAShop in orderAShops!!) {
/*
* ่ฎก็ฎๆๆฃ
*/
val t = orderAShop.discount
discount += t ?: 0.0
val orderAnItems = orderAShop.orderAnItems!!
/*
* ็ดฏๅ ๅๅไปทๆ ผ
*/
for ((_, quantity, item) in orderAnItems) {
Assert.notNull(quantity, "ๅๅๆฐ้ไธบ็ฉบ๏ผ")
if (quantity <= 0) {
throw ServerException("ๅๅๆฐ้ๅฐไบ0๏ผ")
}
logger.debug(item)
Assert.notNull(item, "ๅๅไฟกๆฏไธบ็ฉบ๏ผ")
val itemPrice = item!!.price
if (itemPrice <= 0) {
throw ServerException("ๅๅไปทๆ ผๅฐไบ0๏ผ")
}
totalCost += itemPrice * quantity
}
}
/*
* ๆ็ปไปทๆ ผ
*/
var pay = totalCost - discount
if (pay > 200000) {
throw RequestBadException("่ฎขๅไปทๆ ผไธ่ฝๅคงไบ10ไธๅ
")
}
pay = (pay * 100).toInt() / 100.0
if (pay <= 0) {
throw ServerException("่ฎขๅไปทๆ ผไธ่ฝๅฐไบ0.01ๅ
")
}
val payEntity = newPay
payEntity.price = pay
return payEntity
}
private val newPay: PayEntity
get() {
val payEntity = PayEntity()
payEntity.thirdPayUrl = "https://pay.cloudself.cn/"
return payEntity
}
/**
* ๅ่ดง
*
* @param sellerId ๅบไธปid
* @param orderAShopId ๅไธชๅบ้บ็่ฎขๅ
* @param delivers ๅฟซ้ๅฏน่ฑก
*/
@ParamChecker(greaterThan0 = intArrayOf(0, 1), notEmpty = intArrayOf(2))
@Throws(Exception::class)
override fun deliver(
sellerId: Int, orderAShopId: Int, delivers: List<DeliverEntity>
): Iterable<DeliverEntity> {
// ๅไธชๅบ้บ๏ผๅไธช่ฎขๅไธๅ
่ฎธไธไผ ๅคงไบ10ไธช่ฟๅๅท
if (delivers.size > 10) {
throw RequestBadException("ๅไธช่ฎขๅไธๅ
่ฎธไธไผ ๅคงไบ10ไธช็ฉๆต่ฟๅๅท")
} else if (delivers.size > 5) {
logger.warn("่ฟๅๅท่ฟๅค")
}
// ๆฃๆต่ฏฅ่ฎขๅๆฏๅฆๅฑไบ ่ฏฅๅบไธป
val ordershop = orderAShopDao.findOne(orderAShopId)
?: throw RequestBadException("่ฎขๅไธๅญๅจ")
if (ordershop.shop!!.sellerId != sellerId) {
throw RequestBadException("ๅบ้บไฟกๆฏไธ็ฌฆ")
}
// ๆฃๆต่ฎขๅๆฏๅฆๅทฒๅ่ดง
if (ordershop.areDeliver!!) {
throw RequestBadException("่ฏฅ่ฎขๅๅทฒๅ่ดง")
}
// ๆดๆนๆๆ็idไฟกๆฏ
for (deliver in delivers) {
deliver.orderAShopId = orderAShopId
}
val newdelivers = deliverDao.save(delivers)
// ๅฐ่ฎขๅ็ถๆ่ฎพ็ฝฎไธบๅทฒๅ่ดง
ordershop.areDeliver = true
orderAShopDao.save(ordershop)
// ้็ฅ็จๆทๅทฒๅ่ดง
messageDao.save(MessageEntity("ๆจ็่ฎขๅๅทฒๅ่ดง", "ๅ่ดงไฟกๆฏ", ordershop.userId!!))
return newdelivers
}
/**
* ๆถ่ดง
*
* @param userId ไธๅ็จๆทid
* @param orderAShopId ่ฎขๅid๏ผๅบ้บ๏ผ
* @return ๆฏๅฆๆง่กๆๅ
*/
override fun receiveOne(userId: Int?, orderAShopId: Int?): Boolean? {
return null
}
/**
* ่ฏ่ฎบ
*
* @param itemComments ่ฏ่ฎบ
*/
override fun comment(
itemComments: Iterable<ItemCommentEntity>, userId: Int
): Iterable<ItemCommentEntity> {
for (itemComment in itemComments) {
itemComment.createTime = null
itemComment.id = 0
itemComment.userId = userId
}
return itemCommentDao.save(itemComments)
}
} | mit |
MyDogTom/detekt | detekt-rules/src/test/resources/cases/LoopWithTooManyJumpStatements.kt | 1 | 537 | package cases
@Suppress("unused", "ConstantConditionIf")
class LoopWithTooManyJumpStatements {
fun tooManyJumps() { // reports 3
val i = 0
for (j in 1..2) {
if (i > 1) {
break
} else {
continue
}
}
while (i < 2) {
if (i > 1) break else continue
}
do {
if (i > 1) break else continue
} while (i < 2)
}
fun onlyOneJump() {
for (i in 1..2) {
if (i > 1) break
}
}
fun jumpsInNestedLoops() {
for (i in 1..2) {
if (i > 1) break
while (i > 1) {
if (i > 1) continue
}
}
}
}
| apache-2.0 |
john9x/jdbi | kotlin/src/main/kotlin/org/jdbi/v3/core/kotlin/Extensions.kt | 2 | 4162 | /*
* 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.jdbi.v3.core.kotlin
import org.jdbi.v3.core.Jdbi
import org.jdbi.v3.core.extension.ExtensionCallback
import org.jdbi.v3.core.extension.ExtensionConsumer
import org.jdbi.v3.core.kotlin.internal.KotlinPropertyArguments
import org.jdbi.v3.core.qualifier.Qualifier
import org.jdbi.v3.core.result.ResultBearing
import org.jdbi.v3.core.result.ResultIterable
import org.jdbi.v3.core.statement.SqlStatement
import org.jdbi.v3.meta.Beta
import kotlin.reflect.KAnnotatedElement
import kotlin.reflect.KClass
import kotlin.reflect.full.findAnnotation
private val metadataFqName = "kotlin.Metadata"
fun Class<*>.isKotlinClass(): Boolean {
return this.annotations.singleOrNull { it.annotationClass.java.name == metadataFqName } != null
}
inline fun <reified T : Any> ResultBearing.mapTo(): ResultIterable<T> {
return this.mapTo(T::class.java)
}
inline fun <O : Any> ResultIterable<O>.useSequence(block: (Sequence<O>) -> Unit) {
this.iterator().use {
block(it.asSequence())
}
}
@Beta
fun <This : SqlStatement<This>> SqlStatement<This>.bindKotlin(name: String, obj: Any): This {
return this.bindNamedArgumentFinder(KotlinPropertyArguments(obj, name))
}
@Beta
fun <This : SqlStatement<This>> SqlStatement<This>.bindKotlin(obj: Any): This {
return this.bindNamedArgumentFinder(KotlinPropertyArguments(obj))
}
/**
* A convenience method which opens an extension of the given type, yields it to a callback, and returns the result
* of the callback. A handle is opened if needed by the extension, and closed before returning to the caller.
*
* @param extensionType the type of extension.
* @param callback a callback which will receive the extension.
* @param <R> the return type
* @param <E> the extension type
* @param <X> the exception type optionally thrown by the callback
* @return the value returned by the callback.
* @throws org.jdbi.v3.core.extension.NoSuchExtensionException if no [org.jdbi.v3.core.extension.ExtensionFactory]
* is registered which supports the given extension type.
* @throws X if thrown by the callback.
*/
fun <E : Any, R, X : Exception> Jdbi.withExtension(extensionType: KClass<E>, callback: ExtensionCallback<R, E, X>): R {
return withExtension(extensionType.java, callback)
}
/**
* A convenience method which opens an extension of the given type, and yields it to a callback. A handle is opened
* if needed by the extention, and closed before returning to the caller.
*
* @param extensionType the type of extension
* @param callback a callback which will receive the extension
* @param <E> the extension type
* @param <X> the exception type optionally thrown by the callback
* @throws org.jdbi.v3.core.extension.NoSuchExtensionException if no [org.jdbi.v3.core.extension.ExtensionFactory]
* is registered which supports the given extension type.
* @throws X if thrown by the callback.
*/
fun <E : Any, X : Exception> Jdbi.useExtension(extensionType: KClass<E>, callback: ExtensionConsumer<E, X>) {
useExtension(extensionType.java, callback)
}
/**
* Returns the set of qualifying annotations on the given Kotlin elements.
* @param elements the annotated element. Null elements are ignored.
* @return the set of qualifying annotations on the given elements.
*/
fun getQualifiers(vararg elements: KAnnotatedElement?): Set<Annotation> {
return elements.filterNotNull()
.flatMap { element -> element.annotations }
.filter { anno -> anno.annotationClass.findAnnotation<Qualifier>() != null }
.toSet()
}
| apache-2.0 |
jpmoreto/play-with-robots | android/app/src/main/java/jpm/android/ui/common/ZoomAndMoveView.kt | 1 | 3553 | package jpm.android.ui.common
import android.content.Context
import android.util.AttributeSet
import android.view.ScaleGestureDetector
import android.view.View
import android.view.MotionEvent.INVALID_POINTER_ID
import android.view.MotionEvent
/**
* Created by jm on 18/02/17.
*
*/
abstract class ZoomAndMoveView: View {
protected var mPosX = 0f
protected var mPosY = 0f
private var mLastTouchX = 0f
private var mLastTouchY = 0f
// The โactive pointerโ is the one currently moving our object.
private var mActivePointerId = INVALID_POINTER_ID
private var mScaleDetector: ScaleGestureDetector? = null
protected var mScaleFactor = 1f
private inner class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
mScaleFactor *= detector.scaleFactor
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f))
invalidate()
return true
}
}
private fun init() {
mScaleDetector = ScaleGestureDetector(context, ScaleListener())
}
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
override fun onTouchEvent(ev: MotionEvent): Boolean {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector!!.onTouchEvent(ev)
val action = ev.action
when (action and MotionEvent.ACTION_MASK) {
MotionEvent.ACTION_DOWN -> {
mLastTouchX = ev.x
mLastTouchY = ev.y
mActivePointerId = ev.getPointerId(0)
}
MotionEvent.ACTION_MOVE -> {
val pointerIndex = ev.findPointerIndex(mActivePointerId)
val x = ev.getX(pointerIndex)
val y = ev.getY(pointerIndex)
// Only move if the ScaleGestureDetector isn't processing a gesture.
if (!mScaleDetector!!.isInProgress) {
val dx = x - mLastTouchX
val dy = y - mLastTouchY
mPosX += dx
mPosY += dy
invalidate()
}
mLastTouchX = x
mLastTouchY = y
}
MotionEvent.ACTION_UP -> {
mActivePointerId = INVALID_POINTER_ID
}
MotionEvent.ACTION_CANCEL -> {
mActivePointerId = INVALID_POINTER_ID
}
MotionEvent.ACTION_POINTER_UP -> {
val pointerIndex = ev.action and MotionEvent.ACTION_POINTER_INDEX_MASK shr MotionEvent.ACTION_POINTER_INDEX_SHIFT
val pointerId = ev.getPointerId(pointerIndex)
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
val newPointerIndex = if (pointerIndex == 0) 1 else 0
mLastTouchX = ev.getX(newPointerIndex)
mLastTouchY = ev.getY(newPointerIndex)
mActivePointerId = ev.getPointerId(newPointerIndex)
}
}
}
return true
}
} | mit |
http4k/http4k | http4k-multipart/src/test/kotlin/org/http4k/lens/MultipartFormTest.kt | 1 | 5520 | package org.http4k.lens
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.throws
import org.http4k.core.Body
import org.http4k.core.ContentType
import org.http4k.core.ContentType.Companion
import org.http4k.core.ContentType.Companion.MultipartFormWithBoundary
import org.http4k.core.ContentType.Companion.MultipartMixedWithBoundary
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.with
import org.http4k.lens.Validator.Feedback
import org.http4k.lens.Validator.Strict
import org.http4k.testing.ApprovalTest
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith(ApprovalTest::class)
class MultipartFormTest {
private val emptyRequest = Request(GET, "")
private val stringRequiredField = MultipartFormField.string().required("hello")
private val intRequiredField = MultipartFormField.string().int().required("another")
private val fieldWithHeaders = MultipartFormField.required("fieldWithHeaders")
private val requiredFile = MultipartFormFile.required("file")
private val message = javaClass.getResourceAsStream("fullMessage.txt").reader().use { it.readText() }
private fun validFile() = MultipartFormFile("hello.txt", ContentType.TEXT_HTML, "bits".byteInputStream())
private val DEFAULT_BOUNDARY = "hello"
@Test
fun `multipart form serialized into request`() {
val populatedRequest = emptyRequest.with(
multipartFormLens(Strict, ::MultipartMixedWithBoundary) of MultipartForm().with(
stringRequiredField of "world",
intRequiredField of 123,
requiredFile of validFile(),
fieldWithHeaders of MultipartFormField("someValue",
listOf("MyHeader" to "myHeaderValue")
)
)
)
assertThat(populatedRequest.toMessage().replace("\r\n", "\n"), equalTo(message))
}
@Test
fun `multipart form blows up if not correct content type`() {
val request = emptyRequest.with(
multipartFormLens(Strict) of MultipartForm().with(
stringRequiredField of "world",
intRequiredField of 123,
requiredFile of validFile()
)).replaceHeader("Content-Type", "unknown; boundary=hello")
assertThat({
multipartFormLens(Strict)(request)
}, throws(lensFailureWith<Any?>(Unsupported(Header.CONTENT_TYPE.meta), overallType = Failure.Type.Unsupported)))
}
@Test
fun `multipart form extracts ok form values`() {
val request = emptyRequest.with(
multipartFormLens(Strict) of MultipartForm().with(
stringRequiredField of "world",
intRequiredField of 123,
requiredFile of validFile()
)
)
val expected = MultipartForm(
mapOf("hello" to listOf(MultipartFormField("world")),
"another" to listOf(MultipartFormField("123"))),
mapOf("file" to listOf(validFile())))
assertThat(multipartFormLens(Strict)(request), equalTo(expected))
}
@Test
fun `feedback multipart form extracts ok form values and errors`() {
val request = emptyRequest.with(
multipartFormLens(Feedback) of MultipartForm().with(
intRequiredField of 123,
requiredFile of validFile()
)
)
val requiredString = MultipartFormField.string().required("hello")
assertThat(multipartFormLens(Feedback)(request), equalTo(MultipartForm(
mapOf("another" to listOf(MultipartFormField("123"))),
mapOf("file" to listOf(validFile())),
listOf(Missing(requiredString.meta)))))
}
@Test
fun `strict multipart form blows up with invalid form values`() {
val intStringField = MultipartFormField.string().required("another")
val request = emptyRequest.with(
Body.multipartForm(
Strict,
stringRequiredField,
intStringField,
requiredFile,
defaultBoundary = DEFAULT_BOUNDARY,
contentTypeFn = ::MultipartFormWithBoundary
).toLens() of
MultipartForm().with(
stringRequiredField of "hello",
intStringField of "world",
requiredFile of validFile()
)
)
assertThat(
{ multipartFormLens(Strict)(request) },
throws(lensFailureWith<Any?>(Invalid(intRequiredField.meta), overallType = Failure.Type.Invalid))
)
}
@Test
fun `can set multiple values on a form`() {
val stringField = MultipartFormField.string().required("hello")
val intField = MultipartFormField.string().int().required("another")
val populated = MultipartForm()
.with(stringField of "world",
intField of 123)
assertThat(stringField(populated), equalTo("world"))
assertThat(intField(populated), equalTo(123))
}
private fun multipartFormLens(validator: Validator,
contentTypeFn: (String) -> ContentType = Companion::MultipartFormWithBoundary
) = Body.multipartForm(validator, stringRequiredField, intRequiredField, requiredFile, defaultBoundary = DEFAULT_BOUNDARY, contentTypeFn = contentTypeFn).toLens()
}
| apache-2.0 |
appcube/SunshineReloaded | mobile/src/main/kotlin/info/appcube/sunshine/main/MainProtocol.kt | 1 | 363 | package info.appcube.sunshine.main
import info.appcube.sunshine.api.WeatherForecastResponse
/**
* Created by artjom on 25.06.16.
*/
interface MainProtocol {
interface MainView {
fun showData(data: WeatherForecastResponse?)
fun showError()
fun showLoadingProgress()
}
interface MainListener {
fun loadData()
}
} | apache-2.0 |
greenspand/totemz | app/src/main/java/ro/cluj/totemz/screens/user/UserView.kt | 1 | 146 | package ro.cluj.totemz.screens.user
import ro.cluj.totemz.MvpBase
/**
* Created by sorin on 11.03.17.
*/
interface UserView : MvpBase.View {
} | apache-2.0 |
google/kiosk-app-reference-implementation | app/src/androidTest/java/com/ape/apps/sample/baypilot/ExampleInstrumentedTest.kt | 1 | 1270 | /*
* 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.ape.apps.sample.baypilot
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.ape.apps.sample.baypilot", appContext.packageName)
}
} | apache-2.0 |
kotlin-es/kotlin-JFrame-standalone | 12-start-async-spinner-button-application/src/main/kotlin/components/statusBar/StatusBarImpl.kt | 2 | 1381 | package components.progressBar
import utils.ThreadMain
import java.awt.Dimension
import java.util.concurrent.CompletableFuture
import javax.swing.BoxLayout
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.SwingConstants
import javax.swing.border.BevelBorder
/**
* Created by vicboma on 05/12/16.
*/
class StatusBarImpl internal constructor(private val _width : Int) : JPanel() , StatusBar {
private var statusLabel = JLabel();
companion object {
fun create(_width: Int): StatusBar {
return StatusBarImpl(_width)
}
}
init{
border = BevelBorder(BevelBorder.LOWERED);
preferredSize = Dimension(_width, 19);
layout = BoxLayout(this, BoxLayout.X_AXIS);
statusLabel.horizontalAlignment = SwingConstants.LEFT;
this.add(statusLabel);
}
override fun asyncUI() = asyncSpel(StatusBar.TEXT,1000L,50L)
private fun asyncSpel(str: String, delay: Long, sequence:Long) {
ThreadMain.asyncUI {
CompletableFuture.runAsync {
Thread.sleep(delay)
statusLabel.text = ""
for (i in 0..str.length - 1) {
Thread.sleep(sequence)
statusLabel.text += str[i].toString()
}
}.thenAcceptAsync {
asyncUI()
}
}
}
}
| mit |
Nandi/http | src/main/kotlin/com/headlessideas/http/util/UtilityFunction.kt | 1 | 613 | package com.headlessideas.http.util
import com.headlessideas.http.Header
import java.nio.file.Files
import java.nio.file.Path
val Path.contentTypeHeader: Header
get() = getContentType(this)
private fun getContentType(path: Path) = when (path.extension) {
"html", "htm" -> html
"css" -> css
"csv" -> csv
"png" -> png
"jpg", "jpeg" -> jpeg
"gif" -> gif
"js" -> js
"json" -> json
"svg" -> svg
else -> plain
}
fun Path.exists(): Boolean = Files.exists(this)
fun Path.readable(): Boolean = Files.isReadable(this)
val Path.extension: String
get() = toFile().extension | mit |
czyzby/gdx-setup | src/main/kotlin/com/github/czyzby/setup/prefs/gradleTasksPreference.kt | 2 | 508 | package com.github.czyzby.setup.prefs
import com.github.czyzby.autumn.mvc.stereotype.preference.Property
import com.github.czyzby.kiwi.util.common.Strings
/**
* These tasks will be run after the project generation.
* @author MJ
*/
@Property("GradleTasks")
class GradleTasksPreference : AbstractStringPreference() {
override fun serialize(preference: String): String = preference.split(Regex(Strings.WHITESPACE_SPLITTER_REGEX))
.filter { it.isNotBlank() }.joinToString(separator = " ")
}
| unlicense |
googlecodelabs/android-paging | advanced/start/app/src/main/java/com/example/android/codelabs/paging/ui/ReposAdapter.kt | 1 | 1686 | /*
* 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.android.codelabs.paging.ui
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import com.example.android.codelabs.paging.model.Repo
/**
* Adapter for the list of repositories.
*/
class ReposAdapter : ListAdapter<Repo, RepoViewHolder>(REPO_COMPARATOR) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RepoViewHolder {
return RepoViewHolder.create(parent)
}
override fun onBindViewHolder(holder: RepoViewHolder, position: Int) {
val repoItem = getItem(position)
if (repoItem != null) {
holder.bind(repoItem)
}
}
companion object {
private val REPO_COMPARATOR = object : DiffUtil.ItemCallback<Repo>() {
override fun areItemsTheSame(oldItem: Repo, newItem: Repo): Boolean =
oldItem.fullName == newItem.fullName
override fun areContentsTheSame(oldItem: Repo, newItem: Repo): Boolean =
oldItem == newItem
}
}
}
| apache-2.0 |
craigjbass/pratura | src/test/kotlin/uk/co/craigbass/pratura/unit/usecase/catalogue/ViewAllProductsSpec.kt | 1 | 1477 | package uk.co.craigbass.pratura.unit.usecase.catalogue
import com.madetech.clean.usecase.execute
import org.amshove.kluent.shouldEqual
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.*
import uk.co.craigbass.pratura.domain.*
import uk.co.craigbass.pratura.unit.testdouble.*
import uk.co.craigbass.pratura.usecase.catalogue.ViewAllProducts
import java.math.BigDecimal.ONE
class ViewAllProductsSpec : Spek({
var products: List<Product> = listOf()
val currency = Currency("GBP", "GB", "en")
val productRetriever = memoized { StubProductRetriever(products) }
val useCase = memoized {
ViewAllProducts(productRetriever(),
StubCurrencyRetriever(currency))
}
given("one product is available") {
beforeEachTest {
products = listOf(
Product(
sku = "sku:90",
price = ONE,
name = "Bottle of Water"
)
)
}
val presentableProducts = memoized { useCase().execute() }
val firstPresentableProduct = memoized { presentableProducts().first() }
it("should return one product") {
presentableProducts().count().shouldEqual(1)
}
it("should have the correct sku") {
firstPresentableProduct().sku.shouldEqual("sku:90")
}
it("should have the correct price") {
firstPresentableProduct().price.shouldEqual("ยฃ1.00")
}
it("should have the correct name") {
firstPresentableProduct().name.shouldEqual("Bottle of Water")
}
}
})
| bsd-3-clause |
tipsy/javalin | javalin-graphql/src/main/java/io/javalin/plugin/graphql/graphql/MutationGraphql.kt | 1 | 69 | package io.javalin.plugin.graphql.graphql
interface MutationGraphql
| apache-2.0 |
timbotetsu/kotlin-koans | src/ii_collections/_23_CompoundTasks.kt | 2 | 818 | package ii_collections
fun Shop.getCustomersWhoOrderedProduct(product: Product): Set<Customer> {
// Return the set of customers who ordered the specified product
return this.customers.filter { it.orderedProducts.contains(product) }.toSet()
}
fun Customer.getMostExpensiveDeliveredProduct(): Product? {
// Return the most expensive product among all delivered products
// (use the Order.isDelivered flag)
return this.orders.filter { it.isDelivered }.flatMap { it.products }.maxBy { it.price }
}
fun Shop.getNumberOfTimesProductWasOrdered(product: Product): Int {
// Return the number of times the given product was ordered.
// Note: a customer may order the same product for several times.
return this.customers.flatMap { it.orders }.flatMap { it.products }.count { it == product }
}
| mit |
ankidroid/Anki-Android | AnkiDroid/src/test/java/com/ichi2/anki/services/NoteServiceTest.kt | 1 | 12528 | /*
Copyright (c) 2021 Kael Madar <[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.services
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ichi2.anki.RobolectricTest
import com.ichi2.anki.multimediacard.IMultimediaEditableNote
import com.ichi2.anki.multimediacard.fields.ImageField
import com.ichi2.anki.multimediacard.fields.MediaClipField
import com.ichi2.anki.servicelayer.NoteService
import com.ichi2.libanki.Collection
import com.ichi2.libanki.Consts
import com.ichi2.libanki.Model
import com.ichi2.libanki.Note
import com.ichi2.testutils.createTransientFile
import com.ichi2.utils.KotlinCleanup
import org.hamcrest.CoreMatchers.*
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.io.FileMatchers.*
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import java.io.File
import java.io.FileWriter
import java.io.IOException
@KotlinCleanup("have Model constructor accent @Language('JSON')")
@RunWith(AndroidJUnit4::class)
class NoteServiceTest : RobolectricTest() {
@KotlinCleanup("lateinit")
var testCol: Collection? = null
@Before
fun before() {
testCol = col
}
// temporary directory to test importMediaToDirectory function
@get:Rule
var directory = TemporaryFolder()
@get:Rule
var directory2 = TemporaryFolder()
// tests if the text fields of the notes are the same after calling updateJsonNoteFromMultimediaNote
@Test
fun updateJsonNoteTest() {
val testModel = testCol!!.models.byName("Basic")
val multiMediaNote: IMultimediaEditableNote? = NoteService.createEmptyNote(testModel!!)
multiMediaNote!!.getField(0)!!.text = "foo"
multiMediaNote.getField(1)!!.text = "bar"
val basicNote = Note(testCol!!, testModel).apply {
setField(0, "this should be changed to foo")
setField(1, "this should be changed to bar")
}
NoteService.updateJsonNoteFromMultimediaNote(multiMediaNote, basicNote)
assertEquals(basicNote.fields[0], multiMediaNote.getField(0)!!.text)
assertEquals(basicNote.fields[1], multiMediaNote.getField(1)!!.text)
}
// tests if updateJsonNoteFromMultimediaNote throws a RuntimeException if the ID's of the notes don't match
@Test
fun updateJsonNoteRuntimeErrorTest() {
// model with ID 42
var testModel = Model("{\"flds\": [{\"name\": \"foo bar\", \"ord\": \"1\"}], \"id\": \"42\"}")
val multiMediaNoteWithID42: IMultimediaEditableNote? = NoteService.createEmptyNote(testModel)
// model with ID 45
testModel = Model("{\"flds\": [{\"name\": \"foo bar\", \"ord\": \"1\"}], \"id\": \"45\"}")
val noteWithID45 = Note(testCol!!, testModel)
val expectedException: Throwable = assertThrows(RuntimeException::class.java) { NoteService.updateJsonNoteFromMultimediaNote(multiMediaNoteWithID42, noteWithID45) }
assertEquals(expectedException.message, "Source and Destination Note ID do not match.")
}
@Test
@Throws(IOException::class)
fun importAudioClipToDirectoryTest() {
val fileAudio = directory.newFile("testaudio.wav")
// writes a line in the file so the file's length isn't 0
FileWriter(fileAudio).use { fileWriter -> fileWriter.write("line1") }
val audioField = MediaClipField()
audioField.audioPath = fileAudio.absolutePath
NoteService.importMediaToDirectory(testCol!!, audioField)
val outFile = File(testCol!!.media.dir(), fileAudio.name)
assertThat("path should be equal to new file made in NoteService.importMediaToDirectory", outFile, aFileWithAbsolutePath(equalTo(audioField.audioPath)))
}
// Similar test like above, but with an ImageField instead of a MediaClipField
@Test
@Throws(IOException::class)
fun importImageToDirectoryTest() {
val fileImage = directory.newFile("test_image.png")
// writes a line in the file so the file's length isn't 0
FileWriter(fileImage).use { fileWriter -> fileWriter.write("line1") }
val imgField = ImageField()
imgField.extraImagePathRef = fileImage.absolutePath
NoteService.importMediaToDirectory(testCol!!, imgField)
val outFile = File(testCol!!.media.dir(), fileImage.name)
assertThat("path should be equal to new file made in NoteService.importMediaToDirectory", outFile, aFileWithAbsolutePath(equalTo(imgField.extraImagePathRef)))
}
/**
* Tests if after importing:
*
* * New file keeps its name
* * File with same name, but different content, has its name changed
* * File with same name and content don't have its name changed
*
* @throws IOException if new created files already exist on temp directory
*/
@Test
@Throws(IOException::class)
fun importAudioWithSameNameTest() {
val f1 = directory.newFile("audio.mp3")
val f2 = directory2.newFile("audio.mp3")
// writes a line in the file so the file's length isn't 0
FileWriter(f1).use { fileWriter -> fileWriter.write("1") }
// do the same to the second file, but with different data
FileWriter(f2).use { fileWriter -> fileWriter.write("2") }
val fld1 = MediaClipField()
fld1.audioPath = f1.absolutePath
val fld2 = MediaClipField()
fld2.audioPath = f2.absolutePath
// third field to test if name is kept after reimporting the same file
val fld3 = MediaClipField()
fld3.audioPath = f1.absolutePath
NoteService.importMediaToDirectory(testCol!!, fld1)
val o1 = File(testCol!!.media.dir(), f1.name)
NoteService.importMediaToDirectory(testCol!!, fld2)
val o2 = File(testCol!!.media.dir(), f2.name)
NoteService.importMediaToDirectory(testCol!!, fld3)
// creating a third outfile isn't necessary because it should be equal to the first one
assertThat("path should be equal to new file made in NoteService.importMediaToDirectory", o1, aFileWithAbsolutePath(equalTo(fld1.audioPath)))
assertThat("path should be different to new file made in NoteService.importMediaToDirectory", o2, aFileWithAbsolutePath(not(fld2.audioPath)))
assertThat("path should be equal to new file made in NoteService.importMediaToDirectory", o1, aFileWithAbsolutePath(equalTo(fld3.audioPath)))
}
// Similar test like above, but with an ImageField instead of a MediaClipField
@Test
@Throws(IOException::class)
fun importImageWithSameNameTest() {
val f1 = directory.newFile("img.png")
val f2 = directory2.newFile("img.png")
// write a line in the file so the file's length isn't 0
FileWriter(f1).use { fileWriter -> fileWriter.write("1") }
// do the same to the second file, but with different data
FileWriter(f2).use { fileWriter -> fileWriter.write("2") }
val fld1 = ImageField()
fld1.extraImagePathRef = f1.absolutePath
val fld2 = ImageField()
fld2.extraImagePathRef = f2.absolutePath
// third field to test if name is kept after reimporting the same file
val fld3 = ImageField()
fld3.extraImagePathRef = f1.absolutePath
NoteService.importMediaToDirectory(testCol!!, fld1)
val o1 = File(testCol!!.media.dir(), f1.name)
NoteService.importMediaToDirectory(testCol!!, fld2)
val o2 = File(testCol!!.media.dir(), f2.name)
NoteService.importMediaToDirectory(testCol!!, fld3)
// creating a third outfile isn't necessary because it should be equal to the first one
assertThat("path should be equal to new file made in NoteService.importMediaToDirectory", o1, aFileWithAbsolutePath(equalTo(fld1.extraImagePathRef)))
assertThat("path should be different to new file made in NoteService.importMediaToDirectory", o2, aFileWithAbsolutePath(not(fld2.extraImagePathRef)))
assertThat("path should be equal to new file made in NoteService.importMediaToDirectory", o1, aFileWithAbsolutePath(equalTo(fld3.extraImagePathRef)))
}
/**
* Sometimes media files cannot be imported directly to the media directory,
* so they are copied to cache then imported and deleted.
* This tests if cached media are properly deleted after import.
*/
@Test
fun tempAudioIsDeletedAfterImport() {
val file = createTransientFile("foo")
val field = MediaClipField().apply {
audioPath = file.absolutePath
hasTemporaryMedia = true
}
NoteService.importMediaToDirectory(testCol!!, field)
assertThat("Audio temporary file should have been deleted after importing", file, not(anExistingFile()))
}
// Similar test like above, but with an ImageField instead of a MediaClipField
@Test
fun tempImageIsDeletedAfterImport() {
val file = createTransientFile("foo")
val field = ImageField().apply {
extraImagePathRef = file.absolutePath
hasTemporaryMedia = true
}
NoteService.importMediaToDirectory(testCol!!, field)
assertThat("Image temporary file should have been deleted after importing", file, not(anExistingFile()))
}
@Test
fun testAvgEase() {
// basic case: no cards are new
val note = addNoteUsingModelName("Cloze", "{{c1::Hello}}{{c2::World}}{{c3::foo}}{{c4::bar}}", "extra")
// factor for cards: 3000, 1500, 1000, 750
for ((i, card) in note.cards().withIndex()) {
card.apply {
type = Consts.CARD_TYPE_REV
factor = 3000 / (i + 1)
flush()
}
}
// avg ease = (3000/10 + 1500/10 + 100/10 + 750/10) / 4 = [156.25] = 156
assertEquals(156, NoteService.avgEase(note))
// test case: one card is new
note.cards()[2].apply {
type = Consts.CARD_TYPE_NEW
flush()
}
// avg ease = (3000/10 + 1500/10 + 750/10) / 3 = [175] = 175
assertEquals(175, NoteService.avgEase(note))
// test case: all cards are new
for (card in note.cards()) {
card.type = Consts.CARD_TYPE_NEW
card.flush()
}
// no cards are rev, so avg ease cannot be calculated
assertEquals(null, NoteService.avgEase(note))
}
@Test
fun testAvgInterval() {
// basic case: all cards are relearning or review
val note = addNoteUsingModelName("Cloze", "{{c1::Hello}}{{c2::World}}{{c3::foo}}{{c4::bar}}", "extra")
val reviewOrRelearningList = listOf(Consts.CARD_TYPE_REV, Consts.CARD_TYPE_RELEARNING)
val newOrLearningList = listOf(Consts.CARD_TYPE_NEW, Consts.CARD_TYPE_LRN)
// interval for cards: 3000, 1500, 1000, 750
for ((i, card) in note.cards().withIndex()) {
card.apply {
type = reviewOrRelearningList.shuffled().first()
ivl = 3000 / (i + 1)
flush()
}
}
// avg interval = (3000 + 1500 + 1000 + 750) / 4 = [1562.5] = 1562
assertEquals(1562, NoteService.avgInterval(note))
// case: one card is new or learning
note.cards()[2].apply {
type = newOrLearningList.shuffled().first()
flush()
}
// avg interval = (3000 + 1500 + 750) / 3 = [1750] = 1750
assertEquals(1750, NoteService.avgInterval(note))
// case: all cards are new or learning
for (card in note.cards()) {
card.type = newOrLearningList.shuffled().first()
card.flush()
}
// no cards are rev or relearning, so avg interval cannot be calculated
assertEquals(null, NoteService.avgInterval(note))
}
}
| gpl-3.0 |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/multimediacard/fields/AudioField.kt | 1 | 2957 | /****************************************************************************************
* Copyright (c) 2013 Bibek Shrestha <[email protected]> *
* Copyright (c) 2013 Zaur Molotnikov <[email protected]> *
* Copyright (c) 2013 Nicolas Raoul <[email protected]> *
* Copyright (c) 2013 Flavio Lerda <[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.multimediacard.fields
import com.ichi2.libanki.Collection
import com.ichi2.utils.KotlinCleanup
import java.io.File
import java.util.regex.Pattern
/**
* Implementation of Audio field types
*/
abstract class AudioField : FieldBase(), IField {
private var mAudioPath: String? = null
override var imagePath: String? = null
override var audioPath: String?
get() = mAudioPath
set(value) {
mAudioPath = value
setThisModified()
}
override var text: String? = null
override var hasTemporaryMedia: Boolean = false
@KotlinCleanup("get() can be simplified with a scope function")
override val formattedValue: String
get() {
if (audioPath == null) {
return ""
}
val file = File(audioPath!!)
return if (file.exists()) "[sound:${file.name}]" else ""
}
override fun setFormattedString(col: Collection, value: String) {
val p = Pattern.compile(PATH_REGEX)
val m = p.matcher(value)
var res = ""
if (m.find()) {
res = m.group(1)!!
}
val mediaDir = col.media.dir() + "/"
audioPath = mediaDir + res
}
companion object {
protected const val PATH_REGEX = "\\[sound:(.*)]"
}
}
| gpl-3.0 |
ankidroid/Anki-Android | AnkiDroid/src/test/java/com/ichi2/anki/InitialActivityWithConflictTest.kt | 1 | 2602 | /*
* 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 androidx.test.ext.junit.runners.AndroidJUnit4
import com.ichi2.anki.InitialActivity.StartupFailure
import com.ichi2.anki.InitialActivity.getStartupFailureType
import com.ichi2.testutils.BackendEmulatingOpenConflict
import com.ichi2.testutils.BackupManagerTestUtilities
import com.ichi2.testutils.grantWritePermissions
import com.ichi2.testutils.revokeWritePermissions
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.shadows.ShadowEnvironment
@RunWith(AndroidJUnit4::class)
class InitialActivityWithConflictTest : RobolectricTest() {
@Before
override fun setUp() {
super.setUp()
BackendEmulatingOpenConflict.enable()
}
@After
override fun tearDown() {
super.tearDown()
BackendEmulatingOpenConflict.disable()
}
@Test
fun testInitialActivityResult() {
try {
setupForDatabaseConflict()
val f = getStartupFailureType(targetContext)
assertThat("A conflict should be returned", f, equalTo(StartupFailure.DATABASE_LOCKED))
} finally {
setupForDefault()
}
}
companion object {
fun setupForDatabaseConflict() {
grantWritePermissions()
ShadowEnvironment.setExternalStorageState("mounted")
}
fun setupForValid(context: Context) {
grantWritePermissions()
ShadowEnvironment.setExternalStorageState("mounted")
BackupManagerTestUtilities.setupSpaceForBackup(context)
}
fun setupForDefault() {
revokeWritePermissions()
ShadowEnvironment.setExternalStorageState("removed")
}
}
}
| gpl-3.0 |
apoi/quickbeer-android | app/src/main/java/quickbeer/android/feature/beerdetails/BeerReviewsViewHolder.kt | 2 | 2839 | /**
* This file is part of QuickBeer.
* Copyright (C) 2017 Antti Poikela <[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 quickbeer.android.feature.beerdetails
import android.view.View
import androidx.annotation.StringRes
import java.lang.String.valueOf
import quickbeer.android.R
import quickbeer.android.databinding.ReviewListItemBinding
import quickbeer.android.domain.review.Review
import quickbeer.android.ui.adapter.base.ListViewHolder
import quickbeer.android.ui.adapter.review.ReviewListModel
/**
* View holder for reviews in list
*/
class BeerReviewsViewHolder(
private val binding: ReviewListItemBinding
) : ListViewHolder<ReviewListModel>(binding.root) {
override fun bind(item: ReviewListModel) {
val metadata = item.review.userName +
(item.review.country?.let { ", $it" } ?: "") +
"\n" + item.review.timeEntered
binding.user.text = metadata
binding.score.text = String.format("%.1f", item.review.totalScore)
binding.description.text = item.review.comments
if (item.review.appearance != null) {
setDetails(item.review)
binding.detailsRow.visibility = View.VISIBLE
} else {
binding.detailsRow.visibility = View.GONE
}
}
private fun setDetails(review: Review) {
binding.appearance.text = valueOf(review.appearance)
binding.aroma.text = valueOf(review.aroma)
binding.flavor.text = valueOf(review.flavor)
binding.mouthfeel.text = valueOf(review.mouthfeel)
binding.overall.text = valueOf(review.overall)
binding.appearanceColumn.setOnClickListener { showToast(R.string.review_appearance_hint) }
binding.aromaColumn.setOnClickListener { showToast(R.string.review_aroma_hint) }
binding.flavorColumn.setOnClickListener { showToast(R.string.review_flavor_hint) }
binding.mouthfeelColumn.setOnClickListener { showToast(R.string.review_mouthfeel_hint) }
binding.overallColumn.setOnClickListener { showToast(R.string.review_overall_hint) }
}
private fun showToast(@StringRes resource: Int) {
// toastProvider.showCancelableToast(resource, Toast.LENGTH_LONG)
}
}
| gpl-3.0 |
matkoniecz/StreetComplete | app/src/test/java/de/westnordost/streetcomplete/quests/TestMapDataWithGeometry.kt | 1 | 1145 | package de.westnordost.streetcomplete.quests
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry
import de.westnordost.streetcomplete.data.osm.mapdata.MutableMapData
import de.westnordost.streetcomplete.testutils.bbox
import de.westnordost.streetcomplete.data.osm.geometry.ElementGeometry
import de.westnordost.streetcomplete.data.osm.geometry.ElementPointGeometry
import de.westnordost.streetcomplete.data.osm.mapdata.Element
class TestMapDataWithGeometry(elements: Iterable<Element>) : MutableMapData(), MapDataWithGeometry {
init {
addAll(elements)
boundingBox = bbox()
}
val nodeGeometriesById: MutableMap<Long, ElementPointGeometry?> = mutableMapOf()
val wayGeometriesById: MutableMap<Long, ElementGeometry?> = mutableMapOf()
val relationGeometriesById: MutableMap<Long, ElementGeometry?> = mutableMapOf()
override fun getNodeGeometry(id: Long): ElementPointGeometry? = nodeGeometriesById[id]
override fun getWayGeometry(id: Long): ElementGeometry? = wayGeometriesById[id]
override fun getRelationGeometry(id: Long): ElementGeometry? = relationGeometriesById[id]
}
| gpl-3.0 |
SpryServers/sprycloud-android | src/main/java/com/nextcloud/client/core/ClockImpl.kt | 2 | 1194 | /*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.core
import java.util.Date
import java.util.TimeZone
class ClockImpl : Clock {
override val currentTime: Long
get() {
return System.currentTimeMillis()
}
override val currentDate: Date
get() {
return Date(currentTime)
}
override val tz: TimeZone
get() = TimeZone.getDefault()
}
| gpl-2.0 |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/edithistory/EditHistoryFragment.kt | 1 | 4090 | package de.westnordost.streetcomplete.edithistory
import android.os.Bundle
import android.view.View
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import de.westnordost.streetcomplete.Injector
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.edithistory.Edit
import de.westnordost.streetcomplete.data.edithistory.EditHistorySource
import de.westnordost.streetcomplete.data.edithistory.EditKey
import de.westnordost.streetcomplete.databinding.FragmentEditHistoryListBinding
import de.westnordost.streetcomplete.ktx.viewBinding
import de.westnordost.streetcomplete.ktx.viewLifecycleScope
import de.westnordost.streetcomplete.view.insets_animation.respectSystemInsets
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
/** Shows a list of the edit history */
class EditHistoryFragment : Fragment(R.layout.fragment_edit_history_list) {
@Inject internal lateinit var editHistorySource: EditHistorySource
interface Listener {
/** Called when an edit has been selected and the undo-button appeared */
fun onSelectedEdit(edit: Edit)
/** Called when the edit that was selected has been removed */
fun onDeletedSelectedEdit()
/** Called when the edit history is empty now */
fun onEditHistoryIsEmpty()
}
private val listener: Listener? get() = parentFragment as? Listener ?: activity as? Listener
private val binding by viewBinding(FragmentEditHistoryListBinding::bind)
private val adapter = EditHistoryAdapter(this::onSelected, this::onSelectionDeleted, this::onUndo)
private val editHistoryListener = object : EditHistorySource.Listener {
override fun onAdded(edit: Edit) { viewLifecycleScope.launch { adapter.onAdded(edit) } }
override fun onSynced(edit: Edit) { viewLifecycleScope.launch { adapter.onSynced(edit) } }
override fun onDeleted(edits: List<Edit>) {
viewLifecycleScope.launch {
adapter.onDeleted(edits)
if (editHistorySource.getCount() == 0) {
listener?.onEditHistoryIsEmpty()
}
}
}
override fun onInvalidated() {
viewLifecycleScope.launch {
val edits = withContext(Dispatchers.IO) { editHistorySource.getAll() }
adapter.setEdits(edits)
if (edits.isEmpty()) {
listener?.onEditHistoryIsEmpty()
}
}
}
}
init {
Injector.applicationComponent.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
editHistorySource.addListener(editHistoryListener)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val initialPaddingBottom = binding.editHistoryList.paddingBottom
binding.editHistoryList.respectSystemInsets {
updatePadding(left = it.left, top = it.top, bottom = it.bottom + initialPaddingBottom)
}
viewLifecycleScope.launch {
val edits = withContext(Dispatchers.IO) { editHistorySource.getAll() }
adapter.setEdits(edits)
val first = edits.firstOrNull { it.isUndoable }
if (first != null) {
adapter.select(first)
}
binding.editHistoryList.adapter = adapter
}
}
override fun onDestroy() {
super.onDestroy()
editHistorySource.removeListener(editHistoryListener)
}
fun select(editKey: EditKey) {
val edit = editHistorySource.get(editKey) ?: return
adapter.select(edit)
}
private fun onSelected(edit: Edit) {
listener?.onSelectedEdit(edit)
}
private fun onSelectionDeleted() {
listener?.onDeletedSelectedEdit()
}
private fun onUndo(edit: Edit) {
UndoDialog(requireContext(), edit).show()
}
}
| gpl-3.0 |
JetBrains/anko | anko/library/robolectricTests/src/test/java/ClassParserTest.kt | 2 | 3884 | @file:Suppress("UNUSED_PARAMETER", "EqualsOrHashCode")
package com.example.android_test
import android.text.SpannedString
import org.jetbrains.anko.db.ClassParserConstructor
import org.jetbrains.anko.db.classParser
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(constants = BuildConfig::class)
class ClassParserTest {
@Test
fun test() {
with (classParser<Class1>()) {
arrayOf<Any?>("A", Long.MAX_VALUE, Double.MIN_VALUE).also {
assertEquals(Class1("A", Long.MAX_VALUE, Double.MIN_VALUE), parseRow(it))
assertThrows { parseRow(emptyArray()) }
assertThrows { parseRow(arrayOf<Any?>(1)) }
}
}
with (classParser<Class1>()) {
arrayOf<Any?>('A', 5, -1.0).also {
val cl = Class1("A", 5, -1.0)
assertEquals(cl, parseRow(it))
assertThrows { parseRow(arrayOf("A", 5.0, -1.0)) }
assertEquals(cl, parseRow(arrayOf('A', 5, -1.0f)))
}
}
with (classParser<Class2>()) {
arrayOf<Any?>('c', 4, (-2).toShort(), -10.0F).also {
val cl = Class2('c', 4, (-2).toShort(), -10.0F)
assertEquals(cl, parseRow(it))
assertEquals(cl, parseRow(arrayOf("c", 4L, -2, -10.0)))
assertEquals(cl, parseRow(arrayOf("c", 4L, -2L, -10.0)))
assertThrows { parseRow(arrayOf("cc", 4L, -2, -10.0)) }
assertThrows { parseRow(arrayOf('c', 4.0, -2, -10.0)) }
}
}
assertThrows { classParser<Class3>() }
with (classParser<Class4>()) {
arrayOf<Any?>("ABC", "BCD", null).also {
assertEquals(Class4("ABC", "BCD", null), parseRow(it))
parseRow(arrayOf(SpannedString("ABC"), "BCD", 'c'))
}
}
assertThrows { classParser<Class5>() }
assertThrows { classParser<Class6>() }
assertThrows { classParser<Class7>() }
assertThrows { classParser<Class8>() }
assertThrows { classParser<Class9>() }
classParser<Class10>()
assertThrows { classParser<Class11>() }
with (classParser<Class12>()) {
arrayOf<Any?>(0).also {
val clTrue = Class12(true)
val clFalse = Class12(false)
assertEquals(clFalse, parseRow(it))
assertEquals(clFalse, parseRow(arrayOf(0L)))
assertEquals(clTrue, parseRow(arrayOf(1)))
assertEquals(clTrue, parseRow(arrayOf(1L)))
}
}
}
data class Class1(val s: String, val l: Long, val d: Double?)
data class Class2(val c: Char, val i: Int?, val s: Short, val f: Float)
class Class3
data class Class4(val a: CharSequence, val b: String, val c: Char?)
data class Class5 private constructor(val s: String)
data class Class6 protected constructor(val s: String)
data class Class7(val a: String, val b: Throwable)
class Class8(vararg val a: String) {
override fun equals(other: Any?) = a.contentEquals((other as Array<*>))
}
class Class9 {
constructor(a: Int)
constructor(a: Long)
}
class Class10 {
@ClassParserConstructor constructor(a: Int)
constructor(a: Long)
}
class Class11 {
@ClassParserConstructor constructor(a: Int)
@ClassParserConstructor constructor(a: Long)
}
private fun assertThrows(f: () -> Unit) {
try {
f()
} catch (e: Exception) {
return
}
throw AssertionError("Exception was not thrown")
}
data class Class12(val b: Boolean)
}
| apache-2.0 |
songzhw/Hello-kotlin | AdvancedJ/src/main/kotlin/basic/io/RandomAccessFileDemo.kt | 1 | 742 | package basic.io
import java.io.RandomAccessFile
fun readFile() {
val stream = RandomAccessFile("build.gradle", "rw")
println("first position = ${stream.filePointer}")
//ๅจๆๆซ่ฟฝๅไธไธชๆณจ้
val comment = "\n// added by RandomAccessFile demo"
stream.seek(stream.length())
stream.write(comment.toByteArray()) //javaไธญๆฏ็จ"write(comment.getBytes())"
// ่ฆๅผๅง่ฏปๅๆไปถ, ๅฐฑๅพๅ็งปๆฏๆ้ๅฐๆๅผๅงๆฅ
stream.seek(0)
val buff = ByteArray(1024)
var readedCount = stream.read(buff)
while (readedCount > 0) {
println(String(buff, 0, readedCount))
readedCount = stream.read(buff)
}
stream.close()
}
fun main(args: Array<String>) {
readFile()
} | apache-2.0 |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/sorter/AverageWeightSorter.kt | 1 | 983 | package com.boardgamegeek.sorter
import android.content.Context
import androidx.annotation.StringRes
import com.boardgamegeek.R
import com.boardgamegeek.entities.CollectionItemEntity
import java.text.DecimalFormat
abstract class AverageWeightSorter(context: Context) : CollectionSorter(context) {
private val defaultValue = context.getString(R.string.text_unknown)
@StringRes
override val descriptionResId = R.string.collection_sort_average_weight
override fun getHeaderText(item: CollectionItemEntity): String {
val averageWeight = item.averageWeight
return if (averageWeight == 0.0) defaultValue else DecimalFormat("#.0").format(averageWeight)
}
override fun getDisplayInfo(item: CollectionItemEntity): String {
val averageWeight = item.averageWeight
val info = if (averageWeight == 0.0) defaultValue else DecimalFormat("0.000").format(averageWeight)
return "${context.getString(R.string.weight)} $info"
}
}
| gpl-3.0 |
devulex/eventorage | backend/src/com/devulex/eventorage/config/ElasticsearchConfig.kt | 1 | 1543 | package com.devulex.eventorage.config
import org.elasticsearch.client.transport.TransportClient
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.common.transport.InetSocketTransportAddress
import org.elasticsearch.transport.client.PreBuiltTransportClient
import org.jetbrains.ktor.config.ApplicationConfig
import java.net.InetAddress
import java.net.UnknownHostException
@Throws(UnknownHostException::class)
fun connectElasticsearch(applicationConfig: ApplicationConfig): TransportClient {
val clusterName = applicationConfig.property("elasticsearch.cluster.name")
val settings = Settings.builder()
.put("cluster.name", clusterName.getString())
.put("client.transport.sniff", true)
.build()
val client = PreBuiltTransportClient(settings)
val clusterNodes = applicationConfig.property("elasticsearch.cluster.nodes").getList()
if (clusterNodes.isEmpty()) {
throw NoSuchElementException("List nodes Elasticsearch is empty.")
}
for (node in clusterNodes) {
val nodeSplit = node.split(":")
if (nodeSplit.size != 2) {
throw IllegalArgumentException("Node address should have delimiter \":\" between host and port values.")
}
val host = nodeSplit.first()
val port = nodeSplit.last().toInt()
client.addTransportAddress(InetSocketTransportAddress(InetAddress.getByName(host), port))
}
return client
}
fun disconnectElasticsearch(client: TransportClient) {
client.close();
}
| mit |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/registry/type/data/NotePitchRegistry.kt | 1 | 1707 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.registry.type.data
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.key.minecraftKey
import org.lanternpowered.server.catalog.DefaultCatalogType
import org.lanternpowered.server.registry.internalCatalogTypeRegistry
import org.spongepowered.api.data.type.NotePitch
val NotePitchRegistry = internalCatalogTypeRegistry<NotePitch> {
val sortedNotePitches = arrayOf(
"F_SHARP0",
"G0",
"G_SHARP0",
"A1",
"A_SHARP1",
"B1",
"C1",
"C_SHARP1",
"D1",
"D_SHARP1",
"E1",
"F1",
"F_SHARP1",
"G1",
"G_SHARP1",
"A2",
"A_SHARP2",
"B2",
"C2",
"C_SHARP2",
"D2",
"D_SHARP2",
"E2",
"F2",
"F_SHARP2"
)
val entries = sortedNotePitches.mapIndexed { index, name ->
register(index, LanternNotePitch(minecraftKey(name.toLowerCase())))
}
entries.forEachIndexed { index, notePitch -> notePitch.next = entries[(index + 1) % entries.size] }
}
private class LanternNotePitch(key: NamespacedKey) : DefaultCatalogType(key), NotePitch {
lateinit var next: NotePitch
override fun cycleNext(): NotePitch = this.next
}
| mit |
Kotlin/kotlinx.serialization | formats/cbor/jvmTest/src/kotlinx/serialization/cbor/CborWriterSpecTest.kt | 1 | 2126 | /*
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.cbor
import io.kotlintest.matchers.*
import io.kotlintest.properties.*
import io.kotlintest.specs.*
import kotlinx.serialization.*
import kotlinx.serialization.cbor.internal.*
class CborWriterSpecTest : WordSpec() {
init {
fun withEncoder(block: CborEncoder.() -> Unit): String {
val result = ByteArrayOutput()
CborEncoder(result).block()
return HexConverter.printHexBinary(result.toByteArray()).lowercase()
}
// Examples from https://tools.ietf.org/html/rfc7049#appendix-A
"CBOR Encoder" should {
"encode integers" {
val tabl = table(
headers("input", "output"),
row(0, "00"),
row(10, "0a"),
row(25, "1819"),
row(1000, "1903e8"),
row(-1, "20"),
row(-1000, "3903e7")
)
forAll(tabl) { input, output ->
withEncoder { encodeNumber(input.toLong()) } shouldBe output
}
}
"encode doubles" {
val tabl = table(
headers("input", "output"),
row(1.0e+300, "fb7e37e43c8800759c"),
row(-4.1, "fbc010666666666666")
)
forAll(tabl) { input, output ->
withEncoder { encodeDouble(input) } shouldBe output
}
}
"encode strings" {
val tabl = table(
headers("input", "output"),
row("IETF", "6449455446"),
row("\"\\", "62225c"),
row("\ud800\udd51", "64f0908591")
)
forAll(tabl) { input, output ->
withEncoder { encodeString(input) } shouldBe output
}
}
}
}
}
| apache-2.0 |
cescoffier/vertx-configuration-service | vertx-configuration/src/main/kotlin/io/vertx/kotlin/ext/configuration/ConfigurationChange.kt | 1 | 515 | package io.vertx.kotlin.ext.configuration
import io.vertx.ext.configuration.ConfigurationChange
fun ConfigurationChange(
newConfiguration: io.vertx.core.json.JsonObject? = null,
previousConfiguration: io.vertx.core.json.JsonObject? = null): ConfigurationChange = io.vertx.ext.configuration.ConfigurationChange().apply {
if (newConfiguration != null) {
this.newConfiguration = newConfiguration
}
if (previousConfiguration != null) {
this.previousConfiguration = previousConfiguration
}
}
| apache-2.0 |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/inspections/SafeDeleteFix.kt | 1 | 1837 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.hannahsten.texifyidea.inspections
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.refactoring.safeDelete.SafeDeleteHandler
/**
* Source: com.intellij.codeInsight.daemon.impl.quickfix.SafeDeleteFix
*/
open class SafeDeleteFix(element: PsiElement) : LocalQuickFixAndIntentionActionOnPsiElement(element) {
override fun getText(): String {
val startElement = startElement
return "Safe delete " + startElement.text
}
override fun getFamilyName(): String {
return "Safe delete"
}
override fun invoke(
project: Project,
file: PsiFile,
editor: Editor?,
startElement: PsiElement,
endElement: PsiElement
) {
if (!FileModificationService.getInstance().prepareFileForWrite(file)) return
val elements = arrayOf(startElement)
SafeDeleteHandler.invoke(project, elements, true)
}
override fun startInWriteAction(): Boolean {
return false
}
} | mit |
jamieadkins95/Roach | domain/src/main/java/com/jamieadkins/gwent/domain/deck/AddCardToDeckUseCase.kt | 1 | 2121 | package com.jamieadkins.gwent.domain.deck
import com.jamieadkins.gwent.domain.SchedulerProvider
import com.jamieadkins.gwent.domain.card.model.GwentCardColour
import com.jamieadkins.gwent.domain.card.repository.CardRepository
import com.jamieadkins.gwent.domain.deck.DeckConstants.BRONZE_MAX
import com.jamieadkins.gwent.domain.deck.DeckConstants.GOLD_MAX
import com.jamieadkins.gwent.domain.deck.repository.DeckRepository
import io.reactivex.Single
import io.reactivex.functions.BiFunction
import javax.inject.Inject
class AddCardToDeckUseCase @Inject constructor(
private val cardRepository: CardRepository,
private val deckRepository: DeckRepository,
private val schedulerProvider: SchedulerProvider
) {
fun addCard(deckId: String, cardId: String): Single<AddCardToDeckResult> {
val countInDeck = deckRepository.getDeckOnce(deckId).map { it.cardCounts[cardId] ?: 0 }
val cardTier = cardRepository.getCard(cardId).firstOrError().map { it.colour }
return Single.zip(countInDeck, cardTier, BiFunction { inDeck: Int, tier: GwentCardColour -> Pair(inDeck, tier) })
.flatMap {
val count = it.first
val newCount = count + 1
when (it.second) {
GwentCardColour.BRONZE -> {
if (count < BRONZE_MAX) updateCardCount(deckId, cardId, newCount) else Single.just(AddCardToDeckResult.MaximumReached)
}
GwentCardColour.GOLD -> {
if (count < GOLD_MAX) updateCardCount(deckId, cardId, newCount) else Single.just(AddCardToDeckResult.MaximumReached)
}
GwentCardColour.LEADER -> Single.just(AddCardToDeckResult.CantAddLeaders)
}
}
.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.ui())
}
private fun updateCardCount(deckId: String, cardId: String, count: Int): Single<AddCardToDeckResult> {
return deckRepository.updateCardCount(deckId, cardId, count).toSingleDefault(AddCardToDeckResult.Success)
}
} | apache-2.0 |
i7c/cfm | server/mbservice/src/main/kotlin/org/rliz/mbs/release/data/Medium.kt | 1 | 333 | package org.rliz.mbs.release.data
import java.util.Date
class Medium {
val id: Long? = null
// format | integer
// edits_pending | integer
val release: Release? = null
val position: Int? = null
val name: String? = null
val lastUpdated: Date? = null
val trackCount: Int? = null
}
| gpl-3.0 |
GDG-Nantes/devfest-android | app/src/main/kotlin/com/gdgnantes/devfest/android/provider/ScheduleSeed.kt | 1 | 2858 | package com.gdgnantes.devfest.android.provider
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import com.gdgnantes.devfest.android.R
import com.gdgnantes.devfest.android.http.JsonConverters
import com.gdgnantes.devfest.android.json.fromJson
import com.gdgnantes.devfest.android.model.Schedule
import com.gdgnantes.devfest.android.model.toContentValues
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.Reader
internal class ScheduleSeed(val context: Context) {
companion object {
private const val TAG = "ScheduleSeed"
private const val DEBUG_LOG_PERFORMANCE = true
}
fun seed(database: SQLiteDatabase) {
var now: Long = 0
if (DEBUG_LOG_PERFORMANCE) {
now = System.currentTimeMillis()
}
val schedule = parse()
if (DEBUG_LOG_PERFORMANCE) {
Log.i(TAG, "Parsing took: ${System.currentTimeMillis() - now}ms")
now = System.currentTimeMillis()
}
insert(database, schedule)
if (DEBUG_LOG_PERFORMANCE) {
Log.i(TAG, "Insertion took: ${System.currentTimeMillis() - now}ms")
}
}
private fun insert(database: SQLiteDatabase, schedule: Schedule) {
insertRooms(database, schedule)
insertSpeakers(database, schedule)
insertSessions(database, schedule)
}
private fun insertRooms(database: SQLiteDatabase, schedule: Schedule) {
schedule.rooms.forEach {
database.insert(ScheduleDatabase.Tables.ROOMS, null, it.toContentValues())
}
}
private fun insertSpeakers(database: SQLiteDatabase, schedule: Schedule) {
schedule.speakers.forEach {
database.insert(ScheduleDatabase.Tables.SPEAKERS, null, it.toContentValues())
}
}
private fun insertSessions(database: SQLiteDatabase, schedule: Schedule) {
schedule.sessions.forEach { session ->
database.insert(ScheduleDatabase.Tables.SESSIONS, null, session.toContentValues())
session.speakersIds?.forEach { speakerId ->
val values = ContentValues().apply {
put(ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SESSION_ID, session.id)
put(ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SPEAKER_ID, speakerId)
}
database.insert(ScheduleDatabase.Tables.SESSIONS_SPEAKERS, null, values)
}
}
}
private fun parse(): Schedule {
var reader: Reader? = null
try {
reader = BufferedReader(InputStreamReader(context.resources.openRawResource(R.raw.seed)))
return JsonConverters.main.fromJson(reader)
} finally {
reader?.close()
}
}
}
| apache-2.0 |
c4software/Android-Password-Store | app/src/main/java/com/zeapo/pwdstore/autofill/AutofillRecyclerAdapter.kt | 1 | 6543 | /*
* Copyright ยฉ 2014-2019 The Android Password Store Authors. All Rights Reserved.
* SPDX-License-Identifier: GPL-2.0
*/
package com.zeapo.pwdstore.autofill
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SortedList
import androidx.recyclerview.widget.SortedListAdapterCallback
import com.zeapo.pwdstore.R
import com.zeapo.pwdstore.utils.splitLines
import java.util.ArrayList
import java.util.Locale
internal class AutofillRecyclerAdapter(
allApps: List<AppInfo>,
private val activity: AutofillPreferenceActivity
) : RecyclerView.Adapter<AutofillRecyclerAdapter.ViewHolder>() {
private val apps: SortedList<AppInfo>
private val allApps: ArrayList<AppInfo> // for filtering, maintain a list of all
private var browserIcon: Drawable? = null
init {
val callback = object : SortedListAdapterCallback<AppInfo>(this) {
// don't take into account secondary text. This is good enough
// for the limited add/remove usage for websites
override fun compare(o1: AppInfo, o2: AppInfo): Int {
return o1.appName.toLowerCase(Locale.ROOT).compareTo(o2.appName.toLowerCase(Locale.ROOT))
}
override fun areContentsTheSame(oldItem: AppInfo, newItem: AppInfo): Boolean {
return oldItem.appName == newItem.appName
}
override fun areItemsTheSame(item1: AppInfo, item2: AppInfo): Boolean {
return item1.appName == item2.appName
}
}
apps = SortedList(AppInfo::class.java, callback)
apps.addAll(allApps)
this.allApps = ArrayList(allApps)
try {
browserIcon = activity.packageManager.getApplicationIcon("com.android.browser")
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context)
.inflate(R.layout.autofill_row_layout, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val app = apps.get(position)
holder.packageName = app.packageName
holder.appName = app.appName
holder.isWeb = app.isWeb
holder.icon.setImageDrawable(app.icon)
holder.name.text = app.appName
holder.secondary.visibility = View.VISIBLE
val prefs: SharedPreferences
prefs = if (app.appName != app.packageName) {
activity.applicationContext.getSharedPreferences("autofill", Context.MODE_PRIVATE)
} else {
activity.applicationContext.getSharedPreferences("autofill_web", Context.MODE_PRIVATE)
}
when (val preference = prefs.getString(holder.packageName, "")) {
"" -> {
holder.secondary.visibility = View.GONE
holder.view.setBackgroundResource(0)
}
"/first" -> holder.secondary.setText(R.string.autofill_apps_first)
"/never" -> holder.secondary.setText(R.string.autofill_apps_never)
else -> {
holder.secondary.setText(R.string.autofill_apps_match)
holder.secondary.append(" " + preference!!.splitLines()[0])
if (preference.trim { it <= ' ' }.splitLines().size - 1 > 0) {
holder.secondary.append(" and " +
(preference.trim { it <= ' ' }.splitLines().size - 1) + " more")
}
}
}
}
override fun getItemCount(): Int {
return apps.size()
}
fun getPosition(appName: String): Int {
return apps.indexOf(AppInfo(null, appName, false, null))
}
// for websites, URL = packageName == appName
fun addWebsite(packageName: String) {
apps.add(AppInfo(packageName, packageName, true, browserIcon))
allApps.add(AppInfo(packageName, packageName, true, browserIcon))
}
fun removeWebsite(packageName: String) {
apps.remove(AppInfo(null, packageName, false, null))
allApps.remove(AppInfo(null, packageName, false, null)) // compare with equals
}
fun updateWebsite(oldPackageName: String, packageName: String) {
apps.updateItemAt(getPosition(oldPackageName), AppInfo(packageName, packageName, true, browserIcon))
allApps.remove(AppInfo(null, oldPackageName, false, null)) // compare with equals
allApps.add(AppInfo(null, packageName, false, null))
}
fun filter(s: String) {
if (s.isEmpty()) {
apps.addAll(allApps)
return
}
apps.beginBatchedUpdates()
for (app in allApps) {
if (app.appName.toLowerCase(Locale.ROOT).contains(s.toLowerCase(Locale.ROOT))) {
apps.add(app)
} else {
apps.remove(app)
}
}
apps.endBatchedUpdates()
}
internal class AppInfo(var packageName: String?, var appName: String, var isWeb: Boolean, var icon: Drawable?) {
override fun equals(other: Any?): Boolean {
return other is AppInfo && this.appName == other.appName
}
override fun hashCode(): Int {
var result = packageName?.hashCode() ?: 0
result = 31 * result + appName.hashCode()
result = 31 * result + isWeb.hashCode()
result = 31 * result + (icon?.hashCode() ?: 0)
return result
}
}
internal inner class ViewHolder(var view: View) : RecyclerView.ViewHolder(view), View.OnClickListener {
var name: AppCompatTextView = view.findViewById(R.id.app_name)
var icon: AppCompatImageView = view.findViewById(R.id.app_icon)
var secondary: AppCompatTextView = view.findViewById(R.id.secondary_text)
var packageName: String? = null
var appName: String? = null
var isWeb: Boolean = false
init {
view.setOnClickListener(this)
}
override fun onClick(v: View) {
activity.showDialog(packageName, appName, isWeb)
}
}
}
| gpl-3.0 |
alphafoobar/intellij-community | platform/configuration-store-impl/src/StateStorageManagerImpl.kt | 4 | 15767 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorage.SaveSession
import com.intellij.openapi.components.StateStorageChooserEx.Resolution
import com.intellij.openapi.components.impl.stores.StateStorageManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.PathUtilRt
import com.intellij.util.ReflectionUtil
import com.intellij.util.SmartList
import com.intellij.util.ThreeState
import com.intellij.util.containers.ContainerUtil
import gnu.trove.THashMap
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import java.io.File
import java.io.IOException
import java.util.LinkedHashMap
import java.util.concurrent.locks.ReentrantLock
import java.util.regex.Pattern
import kotlin.concurrent.withLock
import kotlin.reflect.jvm.java
/**
* If componentManager not specified, storage will not add file tracker (see VirtualFileTracker)
* <p/>
* <b>Note:</b> this class is used in upsource, please notify upsource team in case you change its API.
*/
open class StateStorageManagerImpl(private val rootTagName: String,
private val pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null,
val componentManager: ComponentManager? = null,
private val virtualFileTracker: StorageVirtualFileTracker? = StateStorageManagerImpl.createDefaultVirtualTracker(componentManager) ) : StateStorageManager {
private val macros: MutableList<Macro> = ContainerUtil.createLockFreeCopyOnWriteList()
private val storageLock = ReentrantLock()
private val storages = THashMap<String, StateStorage>()
public var streamProvider: StreamProvider? = null
// access under storageLock
private var isUseVfsListener = if (componentManager == null) ThreeState.NO else ThreeState.UNSURE // unsure because depends on stream provider state
protected open val isUseXmlProlog: Boolean
get() = true
companion object {
private val MACRO_PATTERN = Pattern.compile("(\\$[^\\$]*\\$)")
fun createDefaultVirtualTracker(componentManager: ComponentManager?) = when (componentManager) {
null -> {
null
}
is Application -> {
StorageVirtualFileTracker(componentManager.getMessageBus())
}
else -> {
val tracker = (ApplicationManager.getApplication().stateStore.getStateStorageManager() as StateStorageManagerImpl).virtualFileTracker
if (tracker != null) {
Disposer.register(componentManager, Disposable {
tracker.remove { it.storageManager.componentManager == componentManager }
})
}
tracker
}
}
}
override final fun getMacroSubstitutor() = pathMacroSubstitutor
private data class Macro(val key: String, var value: String)
TestOnly fun getVirtualFileTracker() = virtualFileTracker
/**
* @param expansion System-independent.
*/
fun addMacro(key: String, expansion: String) {
assert(!key.isEmpty())
val value: String
if (expansion.contains("\\")) {
val message = "Macro $key set to system-dependent expansion $expansion"
if (ApplicationManager.getApplication().isUnitTestMode()) {
throw IllegalArgumentException(message)
}
else {
LOG.warn(message)
value = FileUtilRt.toSystemIndependentName(expansion)
}
}
else {
value = expansion
}
// you must not add duplicated macro, but our ModuleImpl.setModuleFilePath does it (it will be fixed later)
for (macro in macros) {
if (key.equals(macro.key)) {
macro.value = value
return
}
}
macros.add(Macro(key, value))
}
// system-independent paths
open fun pathRenamed(oldPath: String, newPath: String, event: VFileEvent?) {
for (macro in macros) {
if (oldPath.equals(macro.value)) {
macro.value = newPath
}
}
}
override final fun getStateStorage(storageSpec: Storage) = getOrCreateStorage(storageSpec.file, storageSpec.roamingType, storageSpec.storageClass.java as Class<out StateStorage>, storageSpec.stateSplitter.java)
override final fun getStateStorage(fileSpec: String, roamingType: RoamingType) = getOrCreateStorage(fileSpec, roamingType)
protected open fun normalizeFileSpec(fileSpec: String): String {
val path = FileUtilRt.toSystemIndependentName(fileSpec)
// fileSpec for directory based storage could be erroneously specified as "name/"
return if (path.endsWith('/')) path.substring(0, path.length() - 1) else path
}
/**
* @param fileSpec Must be normalized (see normalizeFileSpec})
* @return System-independent path
*/
open fun fileSpecToPath(fileSpec: String): String = expandMacros(fileSpec)
fun getOrCreateStorage(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT, storageClass: Class<out StateStorage> = javaClass<StateStorage>(), @SuppressWarnings("deprecation") stateSplitter: Class<out StateSplitter> = javaClass<StateSplitterEx>()): StateStorage {
val collapsedPath = normalizeFileSpec(fileSpec)
val key = if (storageClass == javaClass<StateStorage>()) collapsedPath else storageClass.getName()
storageLock.withLock {
var storage = storages.get(key)
if (storage == null) {
storage = createStateStorage(storageClass, collapsedPath, roamingType, stateSplitter)
storages.put(key, storage)
}
return storage
}
}
fun getCachedFileStorages(changed: Collection<String>, deleted: Collection<String>) = storageLock.withLock { Pair(getCachedFileStorages(changed), getCachedFileStorages(deleted)) }
fun getCachedFileStorages(fileSpecs: Collection<String>): Collection<StateStorage> {
if (fileSpecs.isEmpty()) {
return emptyList()
}
storageLock.withLock {
var result: MutableList<FileBasedStorage>? = null
for (fileSpec in fileSpecs) {
val storage = storages.get(normalizeFileSpec(fileSpec))
if (storage is FileBasedStorage) {
if (result == null) {
result = SmartList<FileBasedStorage>()
}
result.add(storage)
}
}
return result ?: emptyList()
}
}
// overridden in upsource
protected open fun createStateStorage(storageClass: Class<out StateStorage>, fileSpec: String, roamingType: RoamingType, @SuppressWarnings("deprecation") stateSplitter: Class<out StateSplitter>): StateStorage {
if (storageClass != javaClass<StateStorage>()) {
val constructor = storageClass.getConstructors()[0]!!
constructor.setAccessible(true)
return constructor.newInstance(componentManager!!, this) as StateStorage
}
if (isUseVfsListener == ThreeState.UNSURE) {
isUseVfsListener = ThreeState.fromBoolean(streamProvider == null || !streamProvider!!.enabled)
}
val filePath = fileSpecToPath(fileSpec)
if (stateSplitter != javaClass<StateSplitter>() && stateSplitter != javaClass<StateSplitterEx>()) {
val storage = MyDirectoryStorage(this, File(filePath), ReflectionUtil.newInstance(stateSplitter))
virtualFileTracker?.put(filePath, storage)
return storage
}
if (!ApplicationManager.getApplication().isHeadlessEnvironment() && PathUtilRt.getFileName(filePath).lastIndexOf('.') < 0) {
throw IllegalArgumentException("Extension is missing for storage file: $filePath")
}
val effectiveRoamingType = if (roamingType == RoamingType.DEFAULT && fileSpec == StoragePathMacros.WORKSPACE_FILE) RoamingType.DISABLED else roamingType
val storage = MyFileStorage(this, File(filePath), fileSpec, rootTagName, effectiveRoamingType, getMacroSubstitutor(fileSpec), streamProvider)
if (isUseVfsListener == ThreeState.YES) {
virtualFileTracker?.put(filePath, storage)
}
return storage
}
private class MyDirectoryStorage(override val storageManager: StateStorageManagerImpl, file: File, splitter: StateSplitter) : DirectoryBasedStorage(storageManager.pathMacroSubstitutor, file, splitter), StorageVirtualFileTracker.TrackedStorage
private class MyFileStorage(override val storageManager: StateStorageManagerImpl,
file: File,
fileSpec: String,
rootElementName: String,
roamingType: RoamingType,
pathMacroManager: TrackingPathMacroSubstitutor? = null,
provider: StreamProvider? = null) : FileBasedStorage(file, fileSpec, rootElementName, pathMacroManager, roamingType, provider), StorageVirtualFileTracker.TrackedStorage {
override val isUseXmlProlog: Boolean
get() = storageManager.isUseXmlProlog
override fun beforeElementSaved(element: Element) {
storageManager.beforeElementSaved(element)
super<FileBasedStorage>.beforeElementSaved(element)
}
override fun beforeElementLoaded(element: Element) {
storageManager.beforeElementLoaded(element)
super<FileBasedStorage>.beforeElementLoaded(element)
}
override fun dataLoadedFromProvider(element: Element?) {
storageManager.dataLoadedFromProvider(this, element)
}
}
protected open fun beforeElementSaved(element: Element) {
}
protected open fun beforeElementLoaded(element: Element) {
}
protected open fun dataLoadedFromProvider(storage: FileBasedStorage, element: Element?) {
}
override final fun rename(path: String, newName: String) {
storageLock.withLock {
val storage = getOrCreateStorage(collapseMacros(path), RoamingType.DEFAULT) as FileBasedStorage
val file = storage.getVirtualFile()
try {
if (file != null) {
file.rename(storage, newName)
}
else if (storage.file.getName() != newName) {
// old file didn't exist or renaming failed
val expandedPath = expandMacros(path)
val parentPath = PathUtilRt.getParentPath(expandedPath)
storage.setFile(null, File(parentPath, newName))
pathRenamed(expandedPath, "$parentPath/$newName", null)
}
}
catch (e: IOException) {
LOG.debug(e)
}
}
}
fun clearStorages() {
storageLock.withLock {
try {
if (virtualFileTracker != null) {
storages.forEachEntry({ collapsedPath, storage ->
virtualFileTracker.remove(fileSpecToPath(collapsedPath))
true
})
}
}
finally {
storages.clear()
}
}
}
protected open fun getMacroSubstitutor(fileSpec: String): TrackingPathMacroSubstitutor? = pathMacroSubstitutor
override final fun expandMacros(path: String): String {
// replacement can contains $ (php tests), so, this check must be performed before expand
val matcher = MACRO_PATTERN.matcher(path)
matcherLoop@
while (matcher.find()) {
val m = matcher.group(1)
for (macro in macros) {
if (macro.key == m) {
continue@matcherLoop
}
}
throw IllegalArgumentException("Unknown macro: $m in storage file spec: $path")
}
var expanded = path
for ((key, value) in macros) {
expanded = StringUtil.replace(expanded, key, value)
}
return expanded
}
fun expandMacro(macro: String): String {
for ((key, value) in macros) {
if (key == macro) {
return value
}
}
throw IllegalArgumentException("Unknown macro $macro")
}
override final fun collapseMacros(path: String): String {
var result = path
for ((key, value) in macros) {
result = StringUtil.replace(result, value, key)
}
return result
}
override fun startExternalization() = StateStorageManagerExternalizationSession(this)
class StateStorageManagerExternalizationSession(protected val storageManager: StateStorageManagerImpl) : StateStorageManager.ExternalizationSession {
private val mySessions = LinkedHashMap<StateStorage, StateStorage.ExternalizationSession>()
override fun setState(storageSpecs: Array<Storage>, component: Any, componentName: String, state: Any) {
val stateStorageChooser = component as? StateStorageChooserEx
for (storageSpec in storageSpecs) {
val resolution = if (stateStorageChooser == null) Resolution.DO else stateStorageChooser.getResolution(storageSpec, StateStorageOperation.WRITE)
if (resolution == Resolution.SKIP) {
continue
}
getExternalizationSession(storageManager.getStateStorage(storageSpec))?.setState(component, componentName, if (storageSpec.deprecated || resolution === Resolution.CLEAR) Element("empty") else state)
}
}
override fun setStateInOldStorage(component: Any, componentName: String, state: Any) {
val stateStorage = storageManager.getOldStorage(component, componentName, StateStorageOperation.WRITE)
if (stateStorage != null) {
getExternalizationSession(stateStorage)?.setState(component, componentName, state)
}
}
protected fun getExternalizationSession(stateStorage: StateStorage): StateStorage.ExternalizationSession? {
var session: StateStorage.ExternalizationSession? = mySessions.get(stateStorage)
if (session == null) {
session = stateStorage.startExternalization()
if (session != null) {
mySessions.put(stateStorage, session)
}
}
return session
}
override fun createSaveSessions(): List<SaveSession> {
if (mySessions.isEmpty()) {
return emptyList()
}
var saveSessions: MutableList<SaveSession>? = null
val externalizationSessions = mySessions.values()
for (session in externalizationSessions) {
val saveSession = session.createSaveSession()
if (saveSession != null) {
if (saveSessions == null) {
if (externalizationSessions.size() == 1) {
return listOf(saveSession)
}
saveSessions = SmartList<SaveSession>()
}
saveSessions.add(saveSession)
}
}
return ContainerUtil.notNullize(saveSessions)
}
}
override fun getOldStorage(component: Any, componentName: String, operation: StateStorageOperation): StateStorage? {
val oldStorageSpec = getOldStorageSpec(component, componentName, operation) ?: return null
@suppress("DEPRECATED_SYMBOL_WITH_MESSAGE")
return getStateStorage(oldStorageSpec, if (component is com.intellij.openapi.util.RoamingTypeDisabled) RoamingType.DISABLED else RoamingType.DEFAULT)
}
protected open fun getOldStorageSpec(component: Any, componentName: String, operation: StateStorageOperation): String? = null
}
fun String.startsWithMacro(macro: String): Boolean {
val i = macro.length()
return length() > i && charAt(i) == '/' && startsWith(macro)
} | apache-2.0 |
arturbosch/detekt | detekt-gradle-plugin/src/test/kotlin/io/gitlab/arturbosch/detekt/DetektReportMergeSpec.kt | 1 | 8336 | package io.gitlab.arturbosch.detekt
import io.gitlab.arturbosch.detekt.testkit.DslGradleRunner
import io.gitlab.arturbosch.detekt.testkit.DslTestBuilder
import io.gitlab.arturbosch.detekt.testkit.ProjectLayout
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
internal class DetektReportMergeSpec : Spek({
describe("Sarif merge is configured correctly for multi module project") {
val groovy by memoized { DslTestBuilder.groovy() }
val groovyBuildFileContent by memoized {
"""
|${groovy.gradlePlugins}
|
|allprojects {
| ${groovy.gradleRepositories}
|}
|
|task sarifReportMerge(type: io.gitlab.arturbosch.detekt.report.ReportMergeTask) {
| output = project.layout.buildDirectory.file("reports/detekt/merge.sarif")
|}
|
|subprojects {
| ${groovy.gradleSubprojectsApplyPlugins}
|
| detekt {
| reports.sarif.enabled = true
| }
|
| plugins.withType(io.gitlab.arturbosch.detekt.DetektPlugin) {
| tasks.withType(io.gitlab.arturbosch.detekt.Detekt) { detektTask ->
| sarifReportMerge.configure { mergeTask ->
| mergeTask.mustRunAfter(detektTask)
| mergeTask.input.from(detektTask.sarifReportFile)
| }
| }
| }
|}
|""".trimMargin()
}
val kotlin by memoized { DslTestBuilder.kotlin() }
val kotlinBuildFileContent by memoized {
"""
|${kotlin.gradlePlugins}
|
|allprojects {
| ${kotlin.gradleRepositories}
|}
|
|val sarifReportMerge by tasks.registering(io.gitlab.arturbosch.detekt.report.ReportMergeTask::class) {
| output.set(project.layout.buildDirectory.file("reports/detekt/merge.sarif"))
|}
|
|subprojects {
| ${kotlin.gradleSubprojectsApplyPlugins}
|
| detekt {
| reports.sarif.enabled = true
| }
|
| plugins.withType(io.gitlab.arturbosch.detekt.DetektPlugin::class) {
| tasks.withType(io.gitlab.arturbosch.detekt.Detekt::class) detekt@{
| sarifReportMerge.configure {
| this.mustRunAfter(this@detekt)
| input.from([email protected])
| }
| }
| }
|}
|""".trimMargin()
}
it("using Groovy and Kotlin") {
listOf(
groovy to groovyBuildFileContent,
kotlin to kotlinBuildFileContent
).forEach { (builder, mainBuildFileContent) ->
val projectLayout = ProjectLayout(numberOfSourceFilesInRootPerSourceDir = 0).apply {
addSubmodule(
name = "child1",
numberOfSourceFilesPerSourceDir = 2,
numberOfCodeSmells = 2
)
addSubmodule(
name = "child2",
numberOfSourceFilesPerSourceDir = 4,
numberOfCodeSmells = 4
)
}
val gradleRunner = DslGradleRunner(projectLayout, builder.gradleBuildName, mainBuildFileContent)
gradleRunner.setupProject()
gradleRunner.runTasksAndExpectFailure("detekt", "sarifReportMerge", "--continue") { _ ->
assertThat(projectFile("build/reports/detekt/detekt.sarif")).doesNotExist()
assertThat(projectFile("build/reports/detekt/merge.sarif")).exists()
assertThat(projectFile("build/reports/detekt/merge.sarif").readText())
.contains("\"ruleId\": \"detekt.style.MagicNumber\"")
projectLayout.submodules.forEach {
assertThat(projectFile("${it.name}/build/reports/detekt/detekt.sarif")).exists()
}
}
}
}
}
describe("XML merge is configured correctly for multi module project") {
val groovy by memoized { DslTestBuilder.groovy() }
val groovyBuildFileContent by memoized {
"""
|${groovy.gradlePlugins}
|
|allprojects {
| ${groovy.gradleRepositories}
|}
|
|task xmlReportMerge(type: io.gitlab.arturbosch.detekt.report.ReportMergeTask) {
| output = project.layout.buildDirectory.file("reports/detekt/merge.xml")
|}
|
|subprojects {
| ${groovy.gradleSubprojectsApplyPlugins}
|
| detekt {
| reports.xml.enabled = true
| }
|
| plugins.withType(io.gitlab.arturbosch.detekt.DetektPlugin) {
| tasks.withType(io.gitlab.arturbosch.detekt.Detekt) { detektTask ->
| xmlReportMerge.configure { mergeTask ->
| mergeTask.mustRunAfter(detektTask)
| mergeTask.input.from(detektTask.xmlReportFile)
| }
| }
| }
|}
|""".trimMargin()
}
val kotlin by memoized { DslTestBuilder.kotlin() }
val kotlinBuildFileContent by memoized {
"""
|${kotlin.gradlePlugins}
|
|allprojects {
| ${kotlin.gradleRepositories}
|}
|
|val xmlReportMerge by tasks.registering(io.gitlab.arturbosch.detekt.report.ReportMergeTask::class) {
| output.set(project.layout.buildDirectory.file("reports/detekt/merge.xml"))
|}
|
|subprojects {
| ${kotlin.gradleSubprojectsApplyPlugins}
|
| detekt {
| reports.xml.enabled = true
| }
|
| plugins.withType(io.gitlab.arturbosch.detekt.DetektPlugin::class) {
| tasks.withType(io.gitlab.arturbosch.detekt.Detekt::class) detekt@{
| xmlReportMerge.configure {
| this.mustRunAfter(this@detekt)
| input.from([email protected])
| }
| }
| }
|}
|""".trimMargin()
}
it("using Groovy and Kotlin") {
listOf(
groovy to groovyBuildFileContent,
kotlin to kotlinBuildFileContent
).forEach { (builder, mainBuildFileContent) ->
val projectLayout = ProjectLayout(numberOfSourceFilesInRootPerSourceDir = 0).apply {
addSubmodule(
name = "child1",
numberOfSourceFilesPerSourceDir = 2,
numberOfCodeSmells = 2
)
addSubmodule(
name = "child2",
numberOfSourceFilesPerSourceDir = 4,
numberOfCodeSmells = 4
)
}
val gradleRunner = DslGradleRunner(projectLayout, builder.gradleBuildName, mainBuildFileContent)
gradleRunner.setupProject()
gradleRunner.runTasksAndExpectFailure("detekt", "xmlReportMerge", "--continue") { _ ->
assertThat(projectFile("build/reports/detekt/detekt.xml")).doesNotExist()
assertThat(projectFile("build/reports/detekt/merge.xml")).exists()
assertThat(projectFile("build/reports/detekt/merge.xml").readText())
.contains("<error column=\"30\" line=\"4\"")
projectLayout.submodules.forEach {
assertThat(projectFile("${it.name}/build/reports/detekt/detekt.xml")).exists()
}
}
}
}
}
})
| apache-2.0 |
calintat/Units | app/src/main/java/com/calintat/units/ui/ListItem.kt | 1 | 1851 | package com.calintat.units.ui
import android.text.TextUtils
import android.util.TypedValue
import android.view.Gravity
import android.view.ViewGroup
import android.widget.LinearLayout
import com.calintat.units.R
import org.jetbrains.anko.*
class ListItem() : AnkoComponent<ViewGroup> {
override fun createView(ui: AnkoContext<ViewGroup>) = with(ui) {
linearLayout {
lparams(width = matchParent, height = wrapContent)
backgroundResource = attr(R.attr.selectableItemBackground)
gravity = Gravity.CENTER_VERTICAL
minimumHeight = dip(72)
orientation = LinearLayout.HORIZONTAL
textView {
id = R.id.list_item_num
ellipsize = TextUtils.TruncateAt.MARQUEE
marqueeRepeatLimit = -1 // repeat indefinitely
maxLines = 1
padding = dip(16)
textAppearance = R.style.TextAppearance_AppCompat_Subhead
}.lparams(width = 0, height = wrapContent, weight = 1f)
verticalLayout {
gravity = Gravity.END
padding = dip(16)
textView {
id = R.id.list_item_str
maxLines = 1
textAppearance = R.style.TextAppearance_AppCompat_Body2
}.lparams(width = wrapContent, height = wrapContent)
textView {
id = R.id.list_item_sym
maxLines = 1
textAppearance = R.style.TextAppearance_AppCompat_Body1
}.lparams(width = wrapContent, height = wrapContent)
}
}
}
internal fun AnkoContext<*>.attr(value: Int): Int {
return TypedValue().let { ctx.theme.resolveAttribute(value, it, true); it.resourceId }
}
} | apache-2.0 |
vitaorganizer/vitaorganizer | src/com/soywiz/vitaorganizer/StatusUpdater.kt | 3 | 185 | package com.soywiz.vitaorganizer
interface StatusUpdater {
fun updateStatus(status: String)
}
//fun StatusUpdater.updateStatus(status: Text) = updateStatus(status.toString())
| gpl-3.0 |
arturbosch/detekt | detekt-rules-naming/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/naming/ClassNaming.kt | 1 | 1776 | package io.gitlab.arturbosch.detekt.rules.naming
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.api.config
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import io.gitlab.arturbosch.detekt.api.internal.Configuration
import io.gitlab.arturbosch.detekt.rules.identifierName
import org.jetbrains.kotlin.psi.KtClassOrObject
/**
* Reports class or object names that do not follow the specified naming convention.
*/
@ActiveByDefault(since = "1.0.0")
class ClassNaming(config: Config = Config.empty) : Rule(config) {
override val defaultRuleIdAliases: Set<String> = setOf("ClassName")
override val issue = Issue(
javaClass.simpleName,
Severity.Style,
"A class or object's name should fit the naming pattern defined in the projects configuration.",
debt = Debt.FIVE_MINS
)
@Configuration("naming pattern")
private val classPattern: Regex by config("[A-Z][a-zA-Z0-9]*") { it.toRegex() }
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
if (!classOrObject.identifierName().removeSurrounding("`").matches(classPattern)) {
report(
CodeSmell(
issue,
Entity.atName(classOrObject),
message = "Class and Object names should match the pattern: $classPattern"
)
)
}
}
companion object {
const val CLASS_PATTERN = "classPattern"
}
}
| apache-2.0 |
arturbosch/detekt | detekt-metrics/src/test/kotlin/io/github/detekt/metrics/processors/SLOCVisitorSpec.kt | 1 | 586 | package io.github.detekt.metrics.processors
import io.github.detekt.test.utils.compileContentForTest
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class SLOCVisitorSpec : Spek({
describe("SLOC Visitor") {
it("defaultClass") {
val file = compileContentForTest(default)
val loc = with(file) {
accept(SLOCVisitor())
getUserData(sourceLinesKey)
}
assertThat(loc).isEqualTo(3)
}
}
})
| apache-2.0 |
ExMCL/ExMCL | ExMCL API/src/main/kotlin/com/n9mtq4/exmcl/api/tabs/events/TabEvents.kt | 1 | 2075 | /*
* MIT License
*
* Copyright (c) 2016 Will (n9Mtq4) Bresnahan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.n9mtq4.exmcl.api.tabs.events
import com.n9mtq4.logwindow.BaseConsole
import com.n9mtq4.logwindow.events.DefaultGenericEvent
import java.awt.Component
/**
* Created by will on 2/27/16 at 3:09 PM.
*
* @author Will "n9Mtq4" Bresnahan
*/
class CreateTabEvent(val title: String, val component: Component, baseConsole: BaseConsole) : DefaultGenericEvent(baseConsole) {
override fun toString() = "${this.javaClass.name}{title=$title, component=$component}"
}
class LowLevelCreateTabEvent(val title: String, val component: Component, baseConsole: BaseConsole) : DefaultGenericEvent(baseConsole) {
override fun toString() = "${this.javaClass.name}{title=$title, component=$component}"
}
class SafeForLowLevelTabCreationEvent(initiatingBaseConsole: BaseConsole) : DefaultGenericEvent(initiatingBaseConsole)
class SafeForTabCreationEvent(initiatingBaseConsole: BaseConsole) : DefaultGenericEvent(initiatingBaseConsole)
| mit |
Light-Team/ModPE-IDE-Source | editorkit/src/main/kotlin/com/brackeys/ui/editorkit/listener/OnUndoRedoChangedListener.kt | 1 | 726 | /*
* Copyright 2021 Brackeys IDE 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.brackeys.ui.editorkit.listener
fun interface OnUndoRedoChangedListener {
fun onUndoRedoChanged()
} | apache-2.0 |
robertwb/incubator-beam | learning/katas/kotlin/Common Transforms/Aggregation/Mean/src/org/apache/beam/learning/katas/commontransforms/aggregation/mean/Task.kt | 9 | 1633 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.beam.learning.katas.commontransforms.aggregation.mean
import org.apache.beam.learning.katas.util.Log
import org.apache.beam.sdk.Pipeline
import org.apache.beam.sdk.options.PipelineOptionsFactory
import org.apache.beam.sdk.transforms.Create
import org.apache.beam.sdk.transforms.Mean
import org.apache.beam.sdk.values.PCollection
object Task {
@JvmStatic
fun main(args: Array<String>) {
val options = PipelineOptionsFactory.fromArgs(*args).create()
val pipeline = Pipeline.create(options)
val numbers = pipeline.apply(Create.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
val output = applyTransform(numbers)
output.apply(Log.ofElements())
pipeline.run()
}
@JvmStatic
fun applyTransform(input: PCollection<Int>): PCollection<Double> {
return input.apply(Mean.globally())
}
} | apache-2.0 |
sungmin-park/Klask | src/test/kotlin/com/klask/response.kt | 1 | 1977 | package com.klask.response
import com.khtml.elements.Div
import com.khtml.elements.Html
import com.klask.Klask
import com.klask.RedirectResponse
import com.klask.router.Route
import com.klask.shorthands.redirect
import org.junit.Assert
import org.junit.Test
object app : Klask() {
Route("/")
fun index(): String {
return "index"
}
Route("/unit")
fun unit() {
}
Route("/html")
fun html(): Html {
return Html {
body {
h1(text_ = "html")
}
}
}
Route("/korean.html")
fun koreanHtml(): Div {
return Div(text_ = "ํ๊ธ")
}
Route("/korean.text")
fun koreanText(): String {
return "ํ๊ธ"
}
Route("/redirect")
fun redirect(): RedirectResponse {
return redirect("/redirect/stand-on")
}
}
class ResponseTest {
Test
fun testStringResponse() {
Assert.assertEquals("index", app.client.get("/").data)
}
Test
fun testUnitResponse() {
Assert.assertEquals("", app.client.get("/unit").data)
}
Test
fun testHtml() {
val response = app.client.get("/html")
Assert.assertEquals("<!DOCTYPE html><html><body><h1>html</h1></body></html>", response.data)
Assert.assertEquals("text/html", response.contentType)
}
Test
fun testKorean() {
Assert.assertEquals("<div>ํ๊ธ</div>", app.client.get("/korean.html").data)
Assert.assertEquals("ํ๊ธ", app.client.get("/korean.text").data)
app.run(onBackground = true)
Assert.assertEquals("<div>ํ๊ธ</div>", app.server.get("/korean.html"))
Assert.assertEquals("ํ๊ธ", app.server.get("/korean.text"))
app.stop()
}
Test
fun testRedirect() {
app.client.get("/redirect").let {
Assert.assertEquals(302, it.statusCode)
Assert.assertEquals("/redirect/stand-on", (it as RedirectResponse).location)
}
}
}
| mit |
michaelgallacher/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.kt | 5 | 938 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.psi.scope.PsiScopeProcessor
import org.jetbrains.plugins.groovy.lang.resolve.processors.DynamicMembersHint
fun shouldProcessDynamicMethods(processor: PsiScopeProcessor): Boolean {
return processor.getHint(DynamicMembersHint.KEY)?.shouldProcessMethods() ?: false
} | apache-2.0 |
jraska/github-client | app/src/androidTest/java/com/jraska/github/client/settings/SettingsTest.kt | 1 | 949 | package com.jraska.github.client.settings
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.doesNotExist
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withSubstring
import com.jraska.github.client.DeepLinkLaunchTest
import com.jraska.github.client.navigation.Urls
import org.junit.Test
class SettingsTest {
@Test
fun whenConsoleClickedThenConsoleOpens() {
DeepLinkLaunchTest.launchDeepLink(Urls.settings().toString())
onView(withId(R.id.console_item_container)).perform(click())
onView(withSubstring(Urls.console().toString())).check(matches(isDisplayed()))
onView(withId(R.id.console_item_container)).check(doesNotExist())
}
}
| apache-2.0 |
nemerosa/ontrack | ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/webhooks/DefaultWebhookPayloadRenderer.kt | 1 | 345 | package net.nemerosa.ontrack.extension.notifications.webhooks
import net.nemerosa.ontrack.json.asJson
import org.springframework.stereotype.Component
@Component
class DefaultWebhookPayloadRenderer : WebhookPayloadRenderer {
override fun render(payload: WebhookPayload<*>): String {
return payload.asJson().toPrettyString()
}
} | mit |
nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/SearchResult.kt | 1 | 923 | package net.nemerosa.ontrack.model.structure
import com.fasterxml.jackson.annotation.JsonIgnore
import java.net.URI
/**
* Result for a research
*/
class SearchResult
@JvmOverloads
constructor(
/**
* Short title
*/
val title: String,
/**
* Description linked to the item being found
*/
val description: String,
/**
* API access point
*/
val uri: URI,
/**
* Web access point
*/
val page: URI,
/**
* Score for the search
*/
val accuracy: Double,
/**
* Type of result
*/
val type: SearchResultType,
/**
* Meta-data which can be used internally
*/
@get:JsonIgnore
val data: Map<String, *>? = null
) {
companion object {
const val SEARCH_RESULT_ITEM = "item"
}
}
| mit |
nemerosa/ontrack | ontrack-extension-auto-versioning/src/main/java/net/nemerosa/ontrack/extension/av/config/AutoVersioningTargetConfig.kt | 1 | 808 | package net.nemerosa.ontrack.extension.av.config
/**
* Description of an auto versioning configuration
*
* @property targetRegex Regex to use in the target file to identify the line to replace
* with the new version. The first matching group must be the version.
* @property targetProperty Optional replacement for the regex, using only a property name
* @property targetPropertyRegex Optional regex to use on the [property][targetProperty] value
* @property targetPropertyType When [targetProperty] is defined, defines the type of property (defaults to Java properties file, but could be NPM, etc.)
*/
interface AutoVersioningTargetConfig {
val targetRegex: String?
val targetProperty: String?
val targetPropertyRegex: String?
val targetPropertyType: String?
} | mit |
nemerosa/ontrack | ontrack-extension-jenkins/src/main/java/net/nemerosa/ontrack/extension/jenkins/autoversioning/JenkinsPostProcessingConfigCredentialsExtensions.kt | 1 | 222 | package net.nemerosa.ontrack.extension.jenkins.autoversioning
/**
* Rendering as a Jenkins parameter
*/
fun List<JenkinsPostProcessingConfigCredentials>.renderParameter(): String = joinToString("|") { it.renderLine() }
| mit |
nemerosa/ontrack | ontrack-extension-auto-versioning/src/main/java/net/nemerosa/ontrack/extension/av/event/AutoVersioningEventServiceImpl.kt | 1 | 3958 | package net.nemerosa.ontrack.extension.av.event
import net.nemerosa.ontrack.common.getOrNull
import net.nemerosa.ontrack.extension.av.dispatcher.AutoVersioningOrder
import net.nemerosa.ontrack.extension.av.event.AutoVersioningEvents.AUTO_VERSIONING_ERROR
import net.nemerosa.ontrack.extension.av.event.AutoVersioningEvents.AUTO_VERSIONING_PR_MERGE_TIMEOUT_ERROR
import net.nemerosa.ontrack.extension.av.event.AutoVersioningEvents.AUTO_VERSIONING_SUCCESS
import net.nemerosa.ontrack.extension.scm.service.SCMPullRequest
import net.nemerosa.ontrack.model.events.*
import net.nemerosa.ontrack.model.exceptions.ProjectNotFoundException
import net.nemerosa.ontrack.model.structure.StructureService
import net.nemerosa.ontrack.model.support.StartupService
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
class AutoVersioningEventServiceImpl(
private val structureService: StructureService,
private val eventFactory: EventFactory,
private val eventPostService: EventPostService,
) : AutoVersioningEventService, StartupService {
/**
* We do need a separate transaction to send events in case of error
* because the current transaction WILL be cancelled
*/
@Transactional(propagation = Propagation.REQUIRES_NEW)
override fun sendError(order: AutoVersioningOrder, message: String, error: Exception) {
eventPostService.post(
error(order, message, error)
)
}
override fun sendPRMergeTimeoutError(order: AutoVersioningOrder, pr: SCMPullRequest) {
eventPostService.post(
prMergeTimeoutError(order, pr)
)
}
override fun sendSuccess(order: AutoVersioningOrder, message: String, pr: SCMPullRequest) {
eventPostService.post(
success(order, message, pr)
)
}
override fun getName(): String = "Registration of auto versioning events"
override fun startupOrder(): Int = StartupService.JOB_REGISTRATION
override fun start() {
eventFactory.register(AUTO_VERSIONING_SUCCESS)
eventFactory.register(AUTO_VERSIONING_ERROR)
eventFactory.register(AUTO_VERSIONING_PR_MERGE_TIMEOUT_ERROR)
}
internal fun success(
order: AutoVersioningOrder,
message: String,
pr: SCMPullRequest,
): Event =
Event.of(AUTO_VERSIONING_SUCCESS)
.withBranch(order.branch)
.withExtraProject(sourceProject(order))
.with("version", order.targetVersion)
.with("message", close(message))
.with("pr-name", pr.name)
.with("pr-link", pr.link)
.build()
internal fun error(
order: AutoVersioningOrder,
message: String,
error: Exception,
): Event =
Event.of(AUTO_VERSIONING_ERROR)
.withBranch(order.branch)
.withExtraProject(sourceProject(order))
.with("version", order.targetVersion)
.with("message", close(message))
.with("error", close(error.message ?: error::class.java.name))
.build()
internal fun prMergeTimeoutError(
order: AutoVersioningOrder,
pr: SCMPullRequest,
): Event =
Event.of(AUTO_VERSIONING_PR_MERGE_TIMEOUT_ERROR)
.withBranch(order.branch)
.withExtraProject(sourceProject(order))
.with("version", order.targetVersion)
.with("pr-name", pr.name)
.with("pr-link", pr.link)
.build()
private fun sourceProject(order: AutoVersioningOrder) =
structureService.findProjectByName(order.sourceProject)
.getOrNull()
?: throw ProjectNotFoundException(order.sourceProject)
private fun close(message: String) = if (message.endsWith(".")) {
message
} else {
"$message."
}
} | mit |
nemerosa/ontrack | ontrack-extension-github/src/test/java/net/nemerosa/ontrack/extension/github/GitHubConnectionsIT.kt | 1 | 3710 | package net.nemerosa.ontrack.extension.github
import net.nemerosa.ontrack.extension.git.model.gitRepository
import net.nemerosa.ontrack.extension.git.service.GitService
import net.nemerosa.ontrack.extension.github.client.OntrackGitHubClientFactory
import net.nemerosa.ontrack.extension.github.model.GitHubEngineConfiguration
import net.nemerosa.ontrack.extension.github.property.GitHubProjectConfigurationProperty
import net.nemerosa.ontrack.extension.github.property.GitHubProjectConfigurationPropertyType
import net.nemerosa.ontrack.git.GitRepositoryClientFactory
import net.nemerosa.ontrack.test.TestUtils.uid
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlin.test.fail
/**
* Testings all connection modes
*/
@TestOnGitHub
class GitHubConnectionsIT : AbstractGitHubTestSupport() {
@Autowired
private lateinit var clientFactory: OntrackGitHubClientFactory
@Autowired
private lateinit var gitRepositoryClientFactory: GitRepositoryClientFactory
@Autowired
private lateinit var gitService: GitService
@Test
fun `Username and token access`() {
runTest(
GitHubEngineConfiguration(
name = uid("GH"),
url = null,
user = githubTestEnv.user,
oauth2Token = githubTestEnv.token,
)
)
}
@Test
fun `Token only access`() {
runTest(
GitHubEngineConfiguration(
name = uid("GH"),
url = null,
oauth2Token = githubTestEnv.token,
)
)
}
@Test
fun `App access`() {
runTest(
GitHubEngineConfiguration(
name = uid("GH"),
url = null,
appId = githubTestEnv.appId,
appPrivateKey = githubTestEnv.appPrivateKey,
appInstallationAccountName = githubTestEnv.appInstallationAccountName,
)
)
}
private fun runTest(
configuration: GitHubEngineConfiguration,
) {
// Creates & saves the GitHub configuration
asAdmin {
gitConfigurationService.newConfiguration(configuration)
}
// Testing the API
val client = clientFactory.create(configuration)
val issue = client.getIssue(githubTestEnv.fullRepository, githubTestEnv.issue)
assertNotNull(issue, "Issue ${githubTestEnv.fullRepository}#${githubTestEnv.issue} has been found")
// Testing the local sync
project {
setProperty(
this, GitHubProjectConfigurationPropertyType::class.java, GitHubProjectConfigurationProperty(
configuration = configuration,
repository = githubTestEnv.fullRepository,
indexationInterval = 0,
issueServiceConfigurationIdentifier = null,
)
)
val gitConfiguration = gitService.getProjectConfiguration(this) ?: fail("No Git project configuration")
val gitRepositoryClient = gitRepositoryClientFactory.getClient(gitConfiguration.gitRepository)
gitRepositoryClient.sync { println(it) }
gitRepositoryClient.test()
assertTrue(gitRepositoryClient.isReady, "Repository is ready to be used")
// Getting the readme to make sure
val readme = gitRepositoryClient.download(githubTestEnv.branch, githubTestEnv.readme)
assertNotNull(readme) {
assertTrue(it.isNotBlank(), "The readme could be downloaded")
}
}
}
} | mit |
goodwinnk/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/eventLog/FeatureUsageFileEventLogger.kt | 2 | 2589 | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.internal.statistic.eventLog
import com.intellij.openapi.Disposable
import com.intellij.util.ConcurrencyUtil
import java.io.File
import java.util.*
open class FeatureUsageFileEventLogger(private val sessionId: String,
private val build: String,
private val bucket: String,
private val recorderVersion: String,
private val writer: FeatureUsageEventWriter) : FeatureUsageEventLogger, Disposable {
protected val myLogExecutor = ConcurrencyUtil.newSingleThreadExecutor(javaClass.simpleName)
private var lastEvent: LogEvent? = null
private var lastEventTime: Long = 0
private var lastEventCreatedTime: Long = 0
override fun log(recorderId: String, action: String, isState: Boolean) {
log(recorderId, action, Collections.emptyMap(), isState)
}
override fun log(recorderId: String, action: String, data: Map<String, Any>, isState: Boolean) {
val eventTime = System.currentTimeMillis()
myLogExecutor.execute(Runnable {
val creationTime = System.currentTimeMillis()
val event = newLogEvent(sessionId, build, bucket, eventTime, recorderId, recorderVersion, action, isState)
for (datum in data) {
event.event.addData(datum.key, datum.value)
}
log(writer, event, creationTime)
})
}
private fun log(writer: FeatureUsageEventWriter, event: LogEvent, createdTime: Long) {
if (lastEvent != null && event.time - lastEventTime <= 10000 && lastEvent!!.shouldMerge(event)) {
lastEventTime = event.time
lastEvent!!.event.increment()
}
else {
logLastEvent(writer)
lastEvent = event
lastEventTime = event.time
lastEventCreatedTime = createdTime
}
}
private fun logLastEvent(writer: FeatureUsageEventWriter) {
lastEvent?.let {
if (it.event.isEventGroup()) {
it.event.addData("last", lastEventTime)
}
it.event.addData("created", lastEventCreatedTime)
writer.log(LogEventSerializer.toString(it))
}
lastEvent = null
}
override fun getLogFiles(): List<File> {
return writer.getFiles()
}
override fun dispose() {
dispose(writer)
}
private fun dispose(writer: FeatureUsageEventWriter) {
myLogExecutor.execute(Runnable {
logLastEvent(writer)
})
myLogExecutor.shutdown()
}
} | apache-2.0 |
edvin/tornadofx-samples | spring-example/src/test/kotlin/no/tornadofx/fxsample/springexample/TestSpringExampleView.kt | 1 | 402 | package no.tornadofx.fxsample.springexample
import no.tornado.fxsample.TestBase
import kotlin.test.Test
import org.testfx.assertions.api.Assertions.assertThat
class TestSpringExampleView: TestBase() {
override fun initView() {
showView<SpringExampleView, SpringExampleApp>()
}
@Test
fun testView() {
assertThat(lookup(HelloBean.data).queryLabeled()).isVisible
}
} | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.