content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.lasthopesoftware.bluewater.client.stored.service.receivers.GivenSyncHasStarted
import android.content.Intent
import com.lasthopesoftware.bluewater.client.stored.sync.StoredFileSynchronization
import com.lasthopesoftware.bluewater.client.stored.sync.notifications.PostSyncNotification
import com.lasthopesoftware.bluewater.client.stored.sync.receivers.SyncStartedReceiver
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions
import org.junit.BeforeClass
import org.junit.Test
import java.util.*
class WhenReceivingTheEvent {
companion object {
private val notifications: MutableCollection<String?> = ArrayList()
@JvmStatic
@BeforeClass
fun context() {
val syncNotification = mockk<PostSyncNotification>()
with(syncNotification) {
every { notify(any()) } answers {
notifications.add(firstArg())
}
}
val receiver = SyncStartedReceiver(syncNotification)
receiver.onReceive(
mockk(),
Intent(StoredFileSynchronization.onSyncStartEvent)
)
}
}
@Test
fun thenNotificationsBegin() {
Assertions.assertThat(notifications).containsExactly(null as String?)
}
}
| projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/service/receivers/GivenSyncHasStarted/WhenReceivingTheEvent.kt | 3561899086 |
package org.softlang.megal.plugins
import org.softlang.megal.content.*
//import org.softlang.megal.content.by
//import org.softlang.megal.content.from
import java.io.InputStreamReader
import java.net.URI
/**
* Base interface for all configurable plugins.
*/
interface Plugin
/**
* Root navigation plugin, resolves root URI to content.
*/
interface BaseResolver : Plugin {
/**
* Initializes root navigation.
* @param uri The root URI
* @return Returns resolved content
*/
operator fun get(uri: URI): Content
/**
* Initializes root navigation.
* @param uri The root URI as a string
* @return Returns resolved content
*/
operator fun get(uri: String) = get(URI(uri))
}
/**
* Creates a simple root navigation plugin.
* @param method The implementation
* @return Returns a new root navigation plugin
*/
inline fun baseBy(crossinline method: (URI) -> Content) =
object : BaseResolver {
override fun get(uri: URI) = method(uri)
}
/**
* Nested navigation plugin, resolves navigating URI in a given context.
*/
interface NestedResolver : Plugin {
/**
* Navigates to the [uri] in a given [context].
* @param uri The nested URI
* @param context The context to resolve in
* @return Returns the next resolved content
*/
operator fun get(uri: URI, context: Content): Content
/**
* Navigates to the [uri] in a given [context].
* @param uri The nested URI as a string
* @param context The context to resolve in
* @return Returns the next resolved content
*/
operator fun get(uri: String, context: Content) = get(URI(uri), context)
}
/**
* Creates a simple nested navigation plugin.
* @param method The implementation
* @return Returns a new nested navigation plugin
*/
inline fun nestedBy(crossinline method: (URI, Content) -> Content) =
object : NestedResolver {
override fun get(uri: URI, context: Content) = method(uri, context)
}
/**
* Evaluation plugin, used for inference, verification et cetera.
*/
interface EvalPlugin : Plugin {
/**
* Evaluates the given input as arbitrary content.
* @param content The content to handle
* @return Returns result content
*/
fun eval(content: Content): Content
}
/**
* Creates a simple evaluation plugin.
* @param method The implementation
* @return Returns a new evaluation plugin
*/
inline fun evalBy(crossinline method: (Content) -> Content) =
object : EvalPlugin {
override fun eval(content: Content) = method(content)
} | src/main/kotlin/org/softlang/megal/plugins/Plugin.kt | 3151203876 |
package meng.keddit.features.news.adapter
import android.support.v4.util.SparseArrayCompat
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import meng.keddit.commons.RedditNewsItem
import meng.keddit.commons.adapter.*
/**
* Created by meng on 2017/7/31.
*/
class NewsAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var items: ArrayList<ViewType>
private var delegateAdapters = SparseArrayCompat<ViewTypeDelegateAdapter>()
private var loadingItem = object : ViewType {
override fun getViewType() = AdapterConstants.LOADING
}
init {
delegateAdapters.put(AdapterConstants.LOADING, LoadingDelegateAdapter())
delegateAdapters.put(AdapterConstants.NEWS, NewsDelegateAdapter())
items = ArrayList()
items.add(loadingItem)
}
override fun getItemCount(): Int {
return items.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return delegateAdapters.get(viewType).onCreateViewHolder(parent)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
delegateAdapters.get(getItemViewType(position)).onBindViewHolder(holder, this.items[position])
}
override fun getItemViewType(position: Int): Int {
return this.items[position].getViewType()
}
fun addNews(news: List<RedditNewsItem>) {
// first remove loading and notify
val initPosition = items.size - 1
items.removeAt(initPosition)
// insert news and the loading at the end of the list
items.addAll(news)
items.add(loadingItem)
notifyItemRangeChanged(initPosition, items.size + 1)
}
fun clearAndAddNews(news: List<RedditNewsItem>) {
items.clear()
notifyItemRangeRemoved(0, getLastPosition())
items.addAll(news)
items.add(loadingItem)
notifyItemRangeInserted(0, items.size)
}
fun getNews(): List<RedditNewsItem> {
return items.filter { it.getViewType() == AdapterConstants.NEWS }
.map { it as RedditNewsItem }
}
private fun getLastPosition() = if (items.lastIndex == -1) 0 else items.lastIndex
} | app/src/main/java/meng/keddit/features/news/adapter/NewsAdapter.kt | 3119791879 |
/*
* Copyright (c) 2021 The sky 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 com.sky.android.news.data.cache
import android.content.Context
import com.google.gson.Gson
import com.jakewharton.disklrucache.DiskLruCache
import com.sky.android.common.util.Alog
import com.sky.android.common.util.FileUtil
import com.sky.android.common.util.MD5Util
import com.sky.android.news.BuildConfig
import java.io.File
import java.io.IOException
/**
* Created by sky on 17-9-21.
*/
class CacheManager private constructor(private val mContext: Context): ICacheManager {
private var mDiskLruCache: DiskLruCache? = null
private var mGson: Gson = Gson()
companion object {
private val TAG = CacheManager::class.java.simpleName
private const val MAX_SIZE = 1024 * 1024 * 20
@Volatile
private var instance: ICacheManager? = null
fun getInstance(context: Context): ICacheManager {
if (instance == null) {
synchronized(CacheManager::class) {
if (instance == null) {
instance = CacheManager(context)
}
}
}
return instance!!
}
}
init {
initCacheManager()
}
private fun initCacheManager() {
val version = BuildConfig.VERSION_CODE
val cacheDir = File(mContext.cacheDir, "net_cache")
if (!cacheDir.exists()) FileUtil.createDir(cacheDir)
mDiskLruCache = try {
DiskLruCache.open(cacheDir, version, 1, MAX_SIZE.toLong())
} catch (e: IOException) {
Alog.e(TAG, "打开缓存目录异常", e)
null
}
}
@Synchronized
override fun <T> get(key: String, tClass: Class<T>): T? {
try {
// 获取缓存信息
val snapshot = get(key)
if (snapshot != null) {
// 返回相应的信息
return mGson.fromJson(snapshot.getString(0), tClass)
}
} catch (e: Exception) {
Alog.e(TAG, "获取信息失败", e)
}
return null
}
@Synchronized
override fun <T> put(key: String, value: T): Boolean {
var editor: DiskLruCache.Editor? = null
try {
// 获取编辑器
editor = edit(key)
if (editor != null) {
// 保存数据
editor.set(0, mGson.toJson(value))
editor.commit()
return true
}
} catch (e: Exception) {
abortQuietly(editor)
Alog.e(TAG, "保存分类信息出错!", e)
} finally {
flushQuietly()
}
return false
}
@Synchronized
override fun remove(key: String): Boolean {
if (!verifyCache()) return false
try {
// 删除数据
mDiskLruCache!!.remove(key)
return true
} catch (e: IOException) {
Alog.e(TAG, "移除数据失败", e)
}
return false
}
override fun clear() {
if (!verifyCache()) return
try {
// 删除数据
mDiskLruCache!!.delete()
initCacheManager()
} catch (e: IOException) {
Alog.e(TAG, "删除数据失败", e)
}
}
@Synchronized
override fun close() {
if (!verifyCache()) return
try {
mDiskLruCache!!.close()
} catch (e: IOException) {
Alog.e(TAG, "关闭缓存失败", e)
}
}
override fun buildKey(value: String): String = MD5Util.md5sum(value)
private fun verifyCache(): Boolean = mDiskLruCache != null
@Throws(IOException::class)
private operator fun get(key: String): DiskLruCache.Snapshot? =
if (verifyCache()) mDiskLruCache!!.get(key) else null
@Throws(IOException::class)
private fun edit(key: String): DiskLruCache.Editor? =
if (verifyCache()) mDiskLruCache!!.edit(key) else null
@Throws(IOException::class)
private fun abort(editor: DiskLruCache.Editor?) {
editor?.abort()
}
private fun abortQuietly(editor: DiskLruCache.Editor?) {
try {
abort(editor)
} catch (e: IOException) {
Alog.e(TAG, "abortQuietly", e)
}
}
@Throws(IOException::class)
private fun flush() {
if (verifyCache()) mDiskLruCache!!.flush()
}
private fun flushQuietly() {
try {
flush()
} catch (e: IOException) {
Alog.e(TAG, "flushQuietly", e)
}
}
} | app/src/main/java/com/sky/android/news/data/cache/CacheManager.kt | 608600739 |
/*
* 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 com.jetbrains.python
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.EditorTestUtil
import com.jetbrains.python.console.PyConsoleEnterHandler
import com.jetbrains.python.console.PythonConsoleView
import com.jetbrains.python.fixtures.PyTestCase
/**
* Created by Yuli Fiterman on 9/20/2016.
*/
class PyConsoleEnterHandlerTest : PyTestCase() {
lateinit private var myEditor: Editor
lateinit private var myEnterHandler: PyConsoleEnterHandler
override fun setUp() {
super.setUp()
resetEditor()
myEnterHandler = PyConsoleEnterHandler()
}
private fun resetEditor() {
myEditor = disposeOnTearDown(PythonConsoleView(myFixture.project, "Console", projectDescriptor?.sdk)).consoleEditor
}
fun push(text: String): Boolean {
text.forEach { EditorTestUtil.performTypingAction(myEditor, it) }
return myEnterHandler.handleEnterPressed(myEditor as EditorEx)
}
fun testTripleQuotes() {
assertFalse(push("'''abs"))
}
fun testSingleQuote() {
assertTrue(push("'a'"))
assertTrue(push("a = 'abc'"))
assertTrue(push("'abc"))
assertTrue(push("a = 'st"))
}
fun testSimpleSingleLine() {
assertTrue(push("a = 1"))
resetEditor()
assertFalse(push("for a in range(5):"))
resetEditor()
assertFalse(push("a = [1,\n2,"))
}
fun testInputComplete1() {
assertFalse(push("if 1:"))
assertFalse(push("\tx=1"))
assertTrue(push(""))
}
fun testInputComplete2() {
assertFalse(push("x = (2+\\"))
assertTrue(push("3)"))
}
fun testInputComplete3() {
push("if 1:")
assertFalse(push(" x = (2+"))
assertFalse(push(" y = 3"))
assertTrue(push(""))
}
fun testInputComplete4() {
push("try:")
push(" a = 5")
push("except:")
assertFalse(push(" raise"))
}
fun testLineContinuation() {
assertFalse(push("import os, \\"))
assertTrue(push("sys"))
}
fun testLineContinuation2() {
assertTrue(push("1 \\\n\n"))
}
fun testCellMagicHelp() {
assertTrue(push("%%cellm?"))
}
fun testCellMagic() {
assertFalse(push("%%cellm firstline"))
assertFalse(push(" line2"))
assertFalse(push(" line3"))
assertTrue(push(""))
}
fun testMultiLineIf() {
assertFalse(push("if True:"))
assertFalse(push(""))
assertFalse(push(""))
assertFalse(push(""))
assertFalse(push("\ta = 1"))
assertTrue(push(""))
}
fun testTryExcept() {
assertFalse(push("try:"))
assertFalse(push(""))
assertFalse(push(""))
assertFalse(push("\ta = 1"))
assertFalse(push(""))
assertFalse(push(""))
assertFalse(push("except:"))
assertFalse(push(""))
assertFalse(push(""))
assertFalse(push("\tprint('hi!')"))
assertTrue(push(""))
}
fun testBackSlash() {
assertFalse(push("if True and \\"))
assertFalse(push("\tTrue:"))
assertFalse(push("\ta = 1"))
assertTrue(push(""))
}
fun testMultipleBackSlash() {
assertFalse(push("if\\"))
assertFalse(push("\tTrue\\"))
assertFalse(push("\t:\\"))
assertFalse(push(""))
assertFalse(push("\ta = \\"))
assertFalse(push("\t1"))
assertTrue(push(""))
}
fun testDocstringDouble() {
assertFalse(push("a = \"\"\"test"))
assertFalse(push("second"))
assertTrue(push("third\"\"\""))
}
fun testDocstring() {
assertFalse(push("a = '''test"))
assertFalse(push("second"))
assertTrue(push("third'''"))
}
fun testFunction() {
assertFalse(push("def foo():"))
assertFalse(push(""))
assertFalse(push("\ta = 1"))
assertFalse(push("\treturn 'hi!'"))
assertTrue(push(""))
}
override fun tearDown() {
Disposer.dispose(testRootDisposable)
super.tearDown()
}
}
| python/testSrc/com/jetbrains/python/PyConsoleEnterHandlerTest.kt | 373822083 |
/*
* Copyright 2017 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.
*/
@file:kotlin.jvm.JvmName("BiMapsKt")
@file:kotlin.jvm.JvmMultifileClass
package com.uchuhimo.collections
/**
* Returns an empty read-only bimap of specified type.
*
* @return an empty read-only bimap
*/
fun <K, V> emptyBiMap(): BiMap<K, V> = @Suppress("UNCHECKED_CAST") (emptyBiMap as BiMap<K, V>)
/**
* Returns a new read-only bimap containing all key-value pairs from the given map.
*
* The returned bimap preserves the entry iteration order of the original map.
*
* @receiver the original map
* @return a new read-only bimap
*/
fun <K, V> Map<K, V>.toBiMap(): BiMap<K, V> =
if (isNotEmpty()) {
val inversePairs = entries.map { (key, value) -> value to key }.toMap()
BiMapImpl(this, inversePairs)
} else {
emptyBiMap()
}
/**
* Returns a new read-only bimap with the specified contents, given as a list of pairs
* where the first value is the key and the second is the value.
*
* If multiple pairs have the same key or the same value, the resulting bimap will contain
* the last of those pairs.
*
* Entries of the bimap are iterated in the order they were specified.
*
* @param pairs the specified contents for the returned bimap
* @return a new read-only bimap
*/
fun <K, V> biMapOf(vararg pairs: Pair<K, V>): BiMap<K, V> = pairs.toMap().toBiMap()
/**
* Returns a new read-only bimap, mapping only the specified key to the
* specified value.
*
* @param pair a pair of key and value for the returned bimap
* @return a new read-only bimap
*/
fun <K, V> biMapOf(pair: Pair<K, V>): BiMap<K, V> =
BiMapImpl(mapOf(pair), mapOf(pair.second to pair.first))
private class BiMapImpl<K, V> private constructor(delegate: Map<K, V>) :
BiMap<K, V>, Map<K, V> by delegate {
constructor(forward: Map<K, V>, backward: Map<V, K>) : this(forward) {
_inverse = BiMapImpl(backward, this)
}
private constructor(backward: Map<K, V>, forward: BiMap<V, K>) : this(backward) {
_inverse = forward
}
private lateinit var _inverse: BiMap<V, K>
override val inverse: BiMap<V, K> get() = _inverse
override val values: Set<V> get() = inverse.keys
override fun equals(other: Any?): Boolean = equals(this, other)
override fun hashCode(): Int = hashCodeOf(this)
}
internal fun equals(bimap: BiMap<*, *>, other: Any?): Boolean {
if (bimap === other) return true
if (other !is BiMap<*, *>) return false
if (other.size != bimap.size) return false
val i = bimap.entries.iterator()
while (i.hasNext()) {
val e = i.next()
val key = e.key
val value = e.value
if (value == null) {
if (other[key] != null || !other.containsKey(key))
return false
} else {
if (value != other[key])
return false
}
}
return true
}
internal fun hashCodeOf(map: Map<*, *>): Int {
return map.entries.fold(0) { acc, entry ->
acc + entry.hashCode()
}
}
private val emptyBiMap = BiMapImpl<Any?, Any?>(emptyMap(), emptyMap())
| src/main/kotlin/com/uchuhimo/collections/BiMaps.kt | 1560503337 |
package buffer
import core.JustDB
import storage.Block
/**
* Buffer Abort
* Created by liufengkai on 2017/4/30.
*/
class BufferAbortException : RuntimeException()
/**
* Buffer-Manager Impl
* Created by liufengkai on 2017/4/30.
*/
class BufferManagerImpl(justDB: JustDB, bufferNumber: Int) : BufferManager {
/**
* max-wait-time
*/
private val MAX_TIME: Long = 10000 // 10 seconds
private val bufferPoolManager = BufferPoolManagerImpl(justDB, bufferNumber)
/**
* sync - lock - object
*/
private val lock = java.lang.Object()
/**
* Buffer pin block
* @param block => block
*/
@Throws(BufferAbortException::class)
override
fun pin(block: Block): Buffer = synchronized(lock) {
try {
val timestamp = System.currentTimeMillis()
var buff = bufferPoolManager.pin(block)
while (buff == null && !waitingTooLong(timestamp)) {
lock.wait(MAX_TIME)
buff = bufferPoolManager.pin(block)
}
if (buff == null)
throw BufferAbortException()
return buff
} catch (e: InterruptedException) {
throw BufferAbortException()
}
}
/**
* Pin new fileName Block
* @param fileName
* @param pageFormatter
*/
@Throws(BufferAbortException::class)
override
fun pinNew(fileName: String, pageFormatter: PageFormatter): Buffer = synchronized(lock) {
try {
val timestamp = System.currentTimeMillis()
var buff = bufferPoolManager.pinNew(fileName, pageFormatter)
while (buff == null && !waitingTooLong(timestamp)) {
lock.wait(MAX_TIME)
// get new block
buff = bufferPoolManager.pinNew(fileName, pageFormatter)
}
if (buff == null)
throw BufferAbortException()
return buff
} catch (e: InterruptedException) {
throw BufferAbortException()
}
}
/**
* unpin buffer from block
* @param buffer this buffer
*/
override
fun unpin(buffer: Buffer) = synchronized(lock) {
bufferPoolManager.unpin(buffer)
// unpin all -> lock
if (!buffer.isPinned())
lock.notifyAll()
}
override
fun flushAll(transaction: Int) {
bufferPoolManager.flushAll(transaction)
}
override
fun available(): Int {
return bufferPoolManager.available()
}
private fun waitingTooLong(startTime: Long) = System.currentTimeMillis() - startTime > MAX_TIME
}
| src/buffer/BufferManagerImpl.kt | 349339571 |
/*
* 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.transformations.impl.synch
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil
class SynchronizedTransformationAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (element is GrAnnotation && element.qualifiedName == ANNO_FQN) {
val method = (element.owner as? GrModifierList)?.parent as? GrMethod ?: return
if (GrTraitUtil.isMethodAbstract(method)) {
holder.createErrorAnnotation(element, "@Synchronized not allowed on abstract method")
}
}
else if (element.node.elementType == GroovyTokenTypes.mIDENT) {
val field = element.parent as? GrField ?: return
val staticField = field.isStatic()
if (!staticField) {
val hasStaticMethods = getMethodsReferencingLock(field).any { it.isStatic() }
if (hasStaticMethods) {
holder.createErrorAnnotation(element, "Lock field '${field.name}' must be static")
}
}
else if (field.name == LOCK_NAME) {
val hasInstanceMethods = getMethodsReferencingLock(field).any { !it.isStatic() }
if (hasInstanceMethods) {
holder.createErrorAnnotation(element, "Lock field '$LOCK_NAME' must not be static")
}
}
}
else if (PATTERN.accepts(element)) {
element as GrLiteral
val reference = element.reference ?: return
val field = reference.resolve() as? GrField
if (field == null) {
val range = reference.rangeInElement.shiftRight(element.textRange.startOffset)
holder.createErrorAnnotation(range, "Lock field '${element.value}' not found")
}
}
}
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/impl/synch/SynchronizedTransformationAnnotator.kt | 452345993 |
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dessertclicker.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
) | app/src/main/java/com/example/dessertclicker/ui/theme/Shape.kt | 132003480 |
package com.bytewelder.kip8.ui
/**
* Implementation of a Panel that can render a ScreenBuffer.
*/
class Screen internal constructor(val screenBuffer: ScreenBuffer, val pixelSize: Int) : javax.swing.JPanel(), java.awt.event.ActionListener {
val timer: javax.swing.Timer
private val DELAY = 50
init {
timer = javax.swing.Timer(DELAY, this)
timer.start()
setSize(pixelSize * screenBuffer.columns, pixelSize * screenBuffer.rows)
}
override fun paintComponent(graphics: java.awt.Graphics) {
super.paintComponent(graphics)
val graphics2d = graphics as java.awt.Graphics2D
drawBackground(graphics2d)
drawPixels(graphics2d)
}
override fun actionPerformed(e: java.awt.event.ActionEvent) {
repaint()
}
private fun drawPoint(graphics: java.awt.Graphics2D, x: Int, y: Int) {
val fromX = pixelSize * x
val fromY = pixelSize * y
graphics.fillRect(fromX, fromY, pixelSize, pixelSize)
}
private fun drawBackground(graphics: java.awt.Graphics2D) {
graphics.paint = java.awt.Color.black
graphics.fillRect(0, 0, width, height)
}
private fun drawPixels(graphics: java.awt.Graphics2D) {
graphics.paint = java.awt.Color.green
screenBuffer.forEachPixel { x, y, isOn ->
if (isOn) {
drawPoint(graphics, x, y)
}
}
}
} | src/main/kotlin/com/bytewelder/kip8/ui/Screen.kt | 3559572894 |
package com.nextfaze.devfun.reference
import com.nextfaze.devfun.DeveloperAnnotation
/**
* Annotated elements will be recorded by DevFun for later retrieval via `devFun.developerReferences<DeveloperReference>()`.
*
* In general this is not used much beyond testing.
*
* Typically usage of this type is via your own custom annotations with [DeveloperAnnotation] à la [DeveloperLogger].
*
* @see DeveloperAnnotation
* @see Dagger2Component
* @see DeveloperLogger
*/
@Retention(AnnotationRetention.SOURCE)
@DeveloperAnnotation(developerReference = true)
annotation class DeveloperReference
/**
* Properties interface for @[DeveloperReference].
*
* TODO: This interface should be generated by DevFun at compile time, but as the annotations are in a separate module to the compiler
* that itself depends on the annotations module, it is non-trivial to run the DevFun processor upon it (module dependencies become cyclic).
*/
@Suppress("unused")
interface DeveloperReferenceProperties
| devfun-annotations/src/main/java/com/nextfaze/devfun/reference/DeveloperReference.kt | 734935206 |
package cc.aoeiuv020.panovel.migration
import cc.aoeiuv020.panovel.IView
import cc.aoeiuv020.panovel.util.VersionName
/**
* Created by AoEiuV020 on 2018.05.16-22:56:40.
*/
interface MigrationView : IView {
fun showDowngrade(from: VersionName, to: VersionName)
// 这个必调用,除非迁移抛异常,其他操作等迁移完了在这个方法内进行,
fun showMigrateComplete(from: VersionName, to: VersionName)
fun showUpgrading(from: VersionName, migration: Migration)
fun showMigrateError(from: VersionName, migration: Migration)
fun showError(message: String, e: Throwable)
} | app/src/main/java/cc/aoeiuv020/panovel/migration/MigrationView.kt | 4103430750 |
package com.didichuxing.doraemonkit.gps_mock.lbs.route
/**
* Created by kuloud on 4/11/16.
*/
object NaviSettings {
const val POLYLINE_Z_INDEX = 1
const val ROUTE_SHADOW_Z_INDEX = -1
const val ROUTE_NORMAL_Z_INDEX = 0
const val TEXT_Z_INDEX = 4
/**
* 位置信息获取的频率(长),单位为毫秒。
*/
const val LOCATION_UPDATE_TIME_LONG_IN_MILLIS = 3000
}
| Android/dokit-gps-mock/src/main/java/com/didichuxing/doraemonkit/gps_mock/lbs/route/NaviSettings.kt | 985746340 |
package io.gitlab.arturbosch.detekt.rules.bugs
import io.github.detekt.test.utils.resourceAsPath
import io.gitlab.arturbosch.detekt.test.lint
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class IteratorNotThrowingNoSuchElementExceptionSpec : Spek({
val subject by memoized { IteratorNotThrowingNoSuchElementException() }
describe("IteratorNotThrowingNoSuchElementException rule") {
it("reports invalid next() implementations") {
val path = resourceAsPath("IteratorImplPositive.kt")
assertThat(subject.lint(path)).hasSize(4)
}
it("does not report correct next() implemenations") {
val path = resourceAsPath("IteratorImplNegative.kt")
assertThat(subject.lint(path)).isEmpty()
}
}
})
| detekt-rules-errorprone/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/IteratorNotThrowingNoSuchElementExceptionSpec.kt | 1985526215 |
package com.github.pgutkowski.kgraphql.schema.execution
import com.github.pgutkowski.kgraphql.ExecutionException
import com.github.pgutkowski.kgraphql.RequestException
import com.github.pgutkowski.kgraphql.isLiteral
import com.github.pgutkowski.kgraphql.request.Variables
import com.github.pgutkowski.kgraphql.schema.DefaultSchema
import com.github.pgutkowski.kgraphql.schema.scalar.deserializeScalar
import com.github.pgutkowski.kgraphql.schema.structure2.InputValue
import com.github.pgutkowski.kgraphql.schema.structure2.Type
import kotlin.reflect.KType
import kotlin.reflect.jvm.jvmErasure
open class ArgumentTransformer(val schema : DefaultSchema) {
fun transformValue(type: Type, value: String, variables: Variables) : Any? {
val kType = type.toKType()
return when {
value.startsWith("$") -> {
variables.get (
kType.jvmErasure, kType, value, { subValue -> transformValue(type, subValue, variables) }
)
}
value == "null" && type.isNullable() -> null
value == "null" && type.isNotNullable() -> {
throw RequestException("argument '$value' is not valid value of type ${type.unwrapped().name}")
}
else -> {
return transformString(value, kType)
}
}
}
private fun transformString(value: String, kType: KType): Any {
val kClass = kType.jvmErasure
fun throwInvalidEnumValue(enumType : Type.Enum<*>){
throw RequestException(
"Invalid enum ${schema.model.enums[kClass]?.name} value. Expected one of ${enumType.values}"
)
}
schema.model.enums[kClass]?.let { enumType ->
if(value.isLiteral()) {
throw RequestException("String literal '$value' is invalid value for enum type ${enumType.name}")
}
return enumType.values.find { it.name == value }?.value ?: throwInvalidEnumValue(enumType)
} ?: schema.model.scalars[kClass]?.let { scalarType ->
return deserializeScalar(scalarType, value)
} ?: throw RequestException("Invalid argument value '$value' for type ${schema.model.inputTypes[kClass]?.name}")
}
fun transformCollectionElementValue(inputValue: InputValue<*>, value: String, variables: Variables): Any? {
assert(inputValue.type.isList())
val elementType = inputValue.type.unwrapList().ofType as Type?
?: throw ExecutionException("Unable to handle value of element of collection without type")
return transformValue(elementType, value, variables)
}
fun transformPropertyValue(parameter: InputValue<*>, value: String, variables: Variables): Any? {
return transformValue(parameter.type, value, variables)
}
} | src/main/kotlin/com/github/pgutkowski/kgraphql/schema/execution/ArgumentTransformer.kt | 517427885 |
/* 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.web
import android.content.Context
import mozilla.components.browser.session.Session
import mozilla.components.browser.session.SessionManager
import org.mozilla.focus.ext.components
class CleanupSessionObserver(
private val context: Context
) : SessionManager.Observer {
override fun onSessionRemoved(session: Session) {
if (context.components.sessionManager.sessions.isEmpty()) {
WebViewProvider.performCleanup(context)
}
}
override fun onAllSessionsRemoved() {
WebViewProvider.performCleanup(context)
}
}
| app/src/main/java/org/mozilla/focus/web/CleanupSessionObserver.kt | 1462647394 |
package com.fireflysource.net.http.common.v2.stream
import com.fireflysource.common.`object`.Assert
import com.fireflysource.common.concurrent.exceptionallyAccept
import com.fireflysource.common.sys.Result
import com.fireflysource.common.sys.Result.discard
import com.fireflysource.common.sys.SystemLogger
import com.fireflysource.net.http.common.exception.Http2StreamFrameProcessException
import com.fireflysource.net.http.common.model.HttpHeader
import com.fireflysource.net.http.common.model.MetaData
import com.fireflysource.net.http.common.v2.frame.*
import com.fireflysource.net.http.common.v2.frame.CloseState.*
import com.fireflysource.net.http.common.v2.frame.CloseState.Event.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.Closeable
import java.io.IOException
import java.time.Duration
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import java.util.function.Consumer
class AsyncHttp2Stream(
private val asyncHttp2Connection: AsyncHttp2Connection,
private val id: Int,
private val local: Boolean,
var listener: Stream.Listener = defaultStreamListener
) : Stream, Closeable {
companion object {
private val log = SystemLogger.create(AsyncHttp2Stream::class.java)
val defaultStreamListener = Stream.Listener.Adapter()
}
private val attributes: ConcurrentMap<String, Any> by lazy { ConcurrentHashMap() }
private val sendWindow = AtomicInteger()
private val recvWindow = AtomicInteger()
private val level = AtomicInteger()
private val closeState = AtomicReference(NOT_CLOSED)
private var localReset = false
private var remoteReset = false
private val createTime = System.currentTimeMillis()
private var lastActiveTime = createTime
private var idleTimeout: Long = 0
private var idleCheckJob: Job? = null
private var dataLength = Long.MIN_VALUE
val stashedDataFrames = LinkedList<DataFrameEntry>()
override fun getId(): Int = id
override fun getHttp2Connection(): Http2Connection = asyncHttp2Connection
override fun getIdleTimeout(): Long = idleTimeout
override fun setIdleTimeout(idleTimeout: Long) {
if (idleTimeout > 0) {
this.idleTimeout = idleTimeout
val job = idleCheckJob
idleCheckJob = if (job == null) {
launchIdleCheckJob()
} else {
job.cancel(CancellationException("Set the new idle timeout. id: $id"))
launchIdleCheckJob()
}
}
}
private fun noIdle() {
lastActiveTime = System.currentTimeMillis()
}
private fun launchIdleCheckJob() = asyncHttp2Connection.coroutineScope.launch {
while (true) {
val timeout = Duration.ofSeconds(idleTimeout).toMillis()
val delayTime = (timeout - getIdleTime()).coerceAtLeast(0)
log.debug { "Stream idle check delay: $delayTime" }
if (delayTime > 0) {
delay(delayTime)
}
val idle = getIdleTime()
if (idle >= timeout) {
notifyIdleTimeout()
break
}
}
}
private fun getIdleTime() = System.currentTimeMillis() - lastActiveTime
private fun notifyIdleTimeout() {
try {
val reset = listener.onIdleTimeout(this, TimeoutException("Stream idle timeout"))
if (reset) {
val frame = ResetFrame(id, ErrorCode.CANCEL_STREAM_ERROR.code)
reset(frame, discard())
}
} catch (e: Exception) {
log.error(e) { "failure while notifying listener" }
}
}
override fun getAttribute(key: String): Any? = attributes[key]
override fun setAttribute(key: String, value: Any) {
attributes[key] = value
}
override fun removeAttribute(key: String): Any? = attributes.remove(key)
fun process(frame: Frame, result: Consumer<Result<Void>>) {
when (frame.type) {
FrameType.HEADERS -> onHeaders(frame as HeadersFrame, result)
FrameType.DATA -> onData(frame as DataFrame, result)
FrameType.RST_STREAM -> onReset(frame as ResetFrame, result)
FrameType.PUSH_PROMISE -> {
// They are closed when receiving an end-stream DATA frame.
// Pushed streams implicitly locally closed.
// They are closed when receiving an end-stream DATA frame.
updateClose(true, AFTER_SEND)
result.accept(Result.SUCCESS)
}
FrameType.WINDOW_UPDATE -> result.accept(Result.SUCCESS)
FrameType.FAILURE -> notifyFailure(this, frame as FailureFrame, result)
else -> throw Http2StreamFrameProcessException("Process frame type error. ${frame.type}")
}
}
// header frame
override fun headers(frame: HeadersFrame, result: Consumer<Result<Void>>) {
try {
noIdle()
Assert.isTrue(frame.streamId == id, "The headers frame id must equal the stream id")
sendControlFrame(frame, result)
} catch (e: Exception) {
result.accept(Result.createFailedResult(e))
}
}
private fun onHeaders(frame: HeadersFrame, result: Consumer<Result<Void>>) {
noIdle()
val metaData: MetaData = frame.metaData
if (metaData.isRequest || metaData.isResponse) {
val fields = metaData.fields
var length: Long = -1
if (fields != null) {
length = fields.getLongField(HttpHeader.CONTENT_LENGTH.value)
}
dataLength = if (length >= 0) length else Long.MIN_VALUE
}
if (updateClose(frame.isEndStream, RECEIVED)) {
asyncHttp2Connection.removeStream(this)
}
result.accept(Result.SUCCESS)
}
// push promise frame
override fun push(frame: PushPromiseFrame, promise: Consumer<Result<Stream?>>, listener: Stream.Listener) {
noIdle()
asyncHttp2Connection.push(frame, promise, listener)
}
// data frame
override fun data(frame: DataFrame, result: Consumer<Result<Void>>) {
noIdle()
asyncHttp2Connection.sendDataFrame(this, frame)
.thenAccept { result.accept(Result.SUCCESS) }
.exceptionallyAccept { result.accept(Result.createFailedResult(it)) }
}
private fun onData(frame: DataFrame, result: Consumer<Result<Void>>) {
noIdle()
if (getRecvWindow() < 0) {
// It's a bad client, it does not deserve to be treated gently by just resetting the stream.
asyncHttp2Connection.close(ErrorCode.FLOW_CONTROL_ERROR.code, "stream_window_exceeded", discard())
result.accept(Result.createFailedResult(IOException("stream_window_exceeded")))
return
}
// SPEC: remotely closed streams must be replied with a reset.
if (isRemotelyClosed()) {
reset(ResetFrame(id, ErrorCode.STREAM_CLOSED_ERROR.code), discard())
result.accept(Result.createFailedResult(IOException("stream_closed")))
return
}
if (isReset) { // Just drop the frame.
result.accept(Result.createFailedResult(IOException("stream_reset")))
return
}
if (dataLength != Long.MIN_VALUE) {
dataLength -= frame.remaining()
if (frame.isEndStream && dataLength != 0L) {
reset(ResetFrame(id, ErrorCode.PROTOCOL_ERROR.code), discard())
result.accept(Result.createFailedResult(IOException("invalid_data_length")))
return
}
}
if (updateClose(frame.isEndStream, RECEIVED)) {
asyncHttp2Connection.removeStream(this)
}
notifyData(this, frame, result)
}
fun isRemotelyClosed(): Boolean {
val state = closeState.get()
return state === REMOTELY_CLOSED || state === CLOSING
}
private fun notifyData(stream: Stream, frame: DataFrame, result: Consumer<Result<Void>>) {
try {
listener.onData(stream, frame, result)
} catch (e: Throwable) {
log.error(e) { "Failure while notifying listener $listener" }
result.accept(Result.createFailedResult(e))
}
}
// window update
fun updateSendWindow(delta: Int): Int = sendWindow.getAndAdd(delta)
fun getSendWindow(): Int = sendWindow.get()
fun updateRecvWindow(delta: Int): Int = recvWindow.getAndAdd(delta)
fun getRecvWindow(): Int = recvWindow.get()
fun addAndGetLevel(delta: Int): Int = level.addAndGet(delta)
fun setLevel(level: Int) {
this.level.set(level)
}
// reset frame
override fun reset(frame: ResetFrame, result: Consumer<Result<Void>>) {
if (isReset) {
result.accept(Result.createFailedResult(IllegalStateException("The stream: $id is reset")))
return
}
localReset = true
sendControlFrame(frame, result)
}
override fun isReset(): Boolean {
return localReset || remoteReset
}
private fun onReset(frame: ResetFrame, result: Consumer<Result<Void>>) {
remoteReset = true
close()
asyncHttp2Connection.removeStream(this)
notifyReset(this, frame, result)
}
private fun notifyReset(stream: Stream, frame: ResetFrame, result: Consumer<Result<Void>>) {
try {
listener.onReset(stream, frame, result)
} catch (e: Exception) {
log.error(e) { "failure while notifying listener" }
}
}
private fun notifyFailure(stream: Stream, frame: FailureFrame, result: Consumer<Result<Void>>) {
try {
listener.onFailure(stream, frame.error, frame.reason, result)
} catch (e: Exception) {
log.error(e) { "failure while notifying listener" }
result.accept(Result.createFailedResult(e))
}
}
private fun sendControlFrame(frame: Frame, result: Consumer<Result<Void>>) {
asyncHttp2Connection.sendControlFrame(this, frame)
.thenAccept { result.accept(Result.SUCCESS) }
.exceptionallyAccept { result.accept(Result.createFailedResult(it)) }
}
// close frame
override fun close() {
val oldState = closeState.getAndSet(CLOSED)
if (oldState != CLOSED) {
idleCheckJob?.cancel(CancellationException("The stream closed. id: $id"))
val deltaClosing = if (oldState == CLOSING) -1 else 0
asyncHttp2Connection.updateStreamCount(local, -1, deltaClosing)
notifyClosed(this)
}
}
fun updateClose(update: Boolean, event: Event): Boolean {
log.debug { "Update close for $this update=$update event=$event" }
if (!update) {
return false
}
return when (event) {
RECEIVED -> updateCloseAfterReceived()
BEFORE_SEND -> updateCloseBeforeSend()
AFTER_SEND -> updateCloseAfterSend()
}
}
override fun isClosed(): Boolean {
return closeState.get() == CLOSED
}
private fun updateCloseAfterReceived(): Boolean {
while (true) {
when (val current = closeState.get()) {
NOT_CLOSED -> if (closeState.compareAndSet(current, REMOTELY_CLOSED)) {
return false
}
LOCALLY_CLOSING -> {
if (closeState.compareAndSet(current, CLOSING)) {
asyncHttp2Connection.updateStreamCount(local, 0, 1)
return false
}
}
LOCALLY_CLOSED -> {
close()
return true
}
else -> return false
}
}
}
private fun updateCloseBeforeSend(): Boolean {
while (true) {
when (val current = closeState.get()) {
NOT_CLOSED -> if (closeState.compareAndSet(current, LOCALLY_CLOSING)) {
return false
}
REMOTELY_CLOSED -> if (closeState.compareAndSet(current, CLOSING)) {
asyncHttp2Connection.updateStreamCount(local, 0, 1)
return false
}
else -> return false
}
}
}
private fun updateCloseAfterSend(): Boolean {
while (true) {
when (val current = closeState.get()) {
NOT_CLOSED, LOCALLY_CLOSING -> if (closeState.compareAndSet(current, LOCALLY_CLOSED)) {
return false
}
REMOTELY_CLOSED, CLOSING -> {
close()
return true
}
else -> return false
}
}
}
private fun notifyClosed(stream: Stream) {
try {
listener.onClosed(stream)
} catch (x: Throwable) {
log.info("Failure while notifying listener $listener", x)
}
}
fun notifyTerminal(stream: Stream) {
try {
listener.onTerminal(stream)
} catch (x: Throwable) {
log.info("Failure while notifying listener $listener", x)
}
}
override fun toString(): String {
return String.format(
"%s@%x#%d{sendWindow=%s,recvWindow=%s,local=%b,reset=%b/%b,%s,age=%d}",
"AsyncHttp2Stream",
hashCode(),
getId(),
sendWindow,
recvWindow,
local,
localReset,
remoteReset,
closeState,
(System.currentTimeMillis() - createTime)
)
}
} | firefly-net/src/main/kotlin/com/fireflysource/net/http/common/v2/stream/AsyncHttp2Stream.kt | 3750259228 |
/*
* Copyright (C) 2017 Olmo Gallegos Hernández.
*
* 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 es.voghdev.hellokotlin.domain
import kotlin.reflect.KProperty
class NotNullSingleValueVar<T> {
var value: T? = null
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value ?: throw IllegalStateException("${property.name} " +
"not initialized")
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = if (this.value == null) value
else throw IllegalStateException("{$property.name} already initialized")
}
} | app/src/main/java/es/voghdev/hellokotlin/domain/NotNullSingleValueVar.kt | 3589101300 |
package org.rust.cargo.runconfig
import com.intellij.execution.configurations.RunProfile
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.runners.DefaultProgramRunner
import org.rust.cargo.runconfig.command.CargoCommandConfiguration
class RsRunner : DefaultProgramRunner() {
override fun canRun(executorId: String, profile: RunProfile): Boolean =
executorId == DefaultRunExecutor.EXECUTOR_ID && profile is CargoCommandConfiguration
override fun getRunnerId(): String = "RustRunner"
}
| src/main/kotlin/org/rust/cargo/runconfig/RsRunner.kt | 1806513907 |
package org.rust.lang.core.completion
import org.intellij.lang.annotations.Language
class RsKeywordCompletionContributorTest : RsCompletionTestBase() {
fun testBreakInForLoop() = checkSingleCompletion("break", """
fn foo() {
for _ in 0..4 {
bre/*caret*/
}
}
""")
fun testBreakInLoop() = checkSingleCompletion("break", """
fn foo() {
loop {
br/*caret*/
}
}
""")
fun testBreakInWhileLoop() = checkSingleCompletion("break", """
fn foo() {
while true {
brea/*caret*/
}
}
""")
fun testBreakNotAppliedIfDoesntStartStmt() = checkNoCompletion("""
fn foo() {
while true {
let brea/*caret*/
}
}
""")
fun testBreakNotAppliedOutsideLoop() = checkNoCompletion("""
fn foo() {
bre/*caret*/
}
""")
fun testBreakNotAppliedWithinClosure() = checkNoCompletion("""
fn bar() {
loop {
let _ = || { bre/*caret*/ }
}
}
""")
fun testContinueInForLoop() = checkSingleCompletion("continue", """
fn foo() {
for _ in 0..4 {
cont/*caret*/
}
}
""")
fun testContinueInLoop() = checkSingleCompletion("continue", """
fn foo() {
loop {
cont/*caret*/
}
}
""")
fun testContinueInWhileLoop() = checkSingleCompletion("continue", """
fn foo() {
while true {
conti/*caret*/
}
}
""")
fun testConst() = checkSingleCompletion("const", """
con/*caret*/
""")
fun testPubConst() = checkSingleCompletion("const", """
pub con/*caret*/
""")
fun testEnum() = checkSingleCompletion("enum", """
enu/*caret*/
""")
fun testEnumAtTheFileVeryBeginning() = checkSingleCompletion("enum", "enu/*caret*/")
fun testPubEnum() = checkSingleCompletion("enum", """
pub enu/*caret*/
""")
fun testEnumWithinMod() = checkSingleCompletion("enum", """
mod foo {
en/*caret*/
}
""")
fun testEnumWithinFn() = checkSingleCompletion("enum", """
fn foo() {
en/*caret*/
}
""")
fun testEnumWithinFnNestedBlock() = checkSingleCompletion("enum", """
fn foo() {{
en/*caret*/
}}
""")
fun testEnumWithinFnAfterOtherStmt() = checkSingleCompletion("enum", """
fn foo() {
let _ = 10;
en/*caret*/
}
""")
fun testEnumNotAppliedIfDoesntStartStmtWithinFn() = checkNoCompletion("""
fn foo() {
let en/*caret*/
}
""")
fun testEnumNotAppliedWithinStruct() = checkNoCompletion("""
struct Foo {
en/*caret*/
}
""")
fun testEnumNotAppliedIfDoesntStartStmt() = checkNoCompletion("""
mod en/*caret*/
""")
fun testExtern() = checkSingleCompletion("extern", """
ext/*caret*/
""")
fun testPubExtern() = checkSingleCompletion("extern", """
pub ext/*caret*/
""")
fun testUnsafeExtern() = checkSingleCompletion("extern", """
unsafe ext/*caret*/
""")
fun testPubUnsafeExtern() = checkSingleCompletion("extern", """
pub unsafe ext/*caret*/
""")
fun testExternCrate() = checkSingleCompletion("crate", """
extern cr/*caret*/
""")
fun testCrateNotAppliedAtFileBeginning() = checkNoCompletion("crat/*caret*/")
fun testCrateNotAppliedWithoutPrefix() = checkNoCompletion("""
crat/*caret*/
""")
fun testFn() = checkContainsCompletion("fn", """
f/*caret*/
""")
fun testPubFn() = checkContainsCompletion("fn", """
pub f/*caret*/
""")
fun testExternFn() = checkSingleCompletion("fn", """
extern f/*caret*/
""")
fun testUnsafeFn() = checkSingleCompletion("fn", """
unsafe f/*caret*/
""")
fun testImpl() = checkSingleCompletion("impl", """
imp/*caret*/
""")
fun testUnsafeImpl() = checkSingleCompletion("impl", """
unsafe im/*caret*/
""")
fun testLetWithinFn() = checkSingleCompletion("let", """
fn main() {
let a = 12;
le/*caret*/
}
""")
fun testLetWithinAssocFn() = checkSingleCompletion("let", """
struct Foo;
impl Foo {
fn shutdown() { le/*caret*/ }
}
""")
fun testLetWithinMethod() = checkSingleCompletion("let", """
struct Foo;
impl Foo {
fn calc(&self) { le/*caret*/ }
}
""")
fun testLetNotAppliedWithinNestedMod() = checkNoCompletion("""
fn foo() {
mod bar {
le/*caret*/
}
}
""")
fun testMod() = checkSingleCompletion("mod", """
mo/*caret*/
""")
fun testPubMod() = checkSingleCompletion("mod", """
pub mo/*caret*/
""")
fun testMut() = checkSingleCompletion("mut", """
fn main() {
let m/*caret*/
}
""")
fun testReturnWithinFn() = checkSingleCompletion("return", """
fn main() {
re/*caret*/
}
""")
fun testReturnWithinAssocFn() = checkSingleCompletion("return", """
struct Foo;
impl Foo {
fn shutdown() { retu/*caret*/ }
}
""")
fun testReturnWithinMethod() = checkSingleCompletion("return", """
struct Foo;
impl Foo {
fn print(&self) { retu/*caret*/ }
}
""")
fun testReturnNotAppliedOnFileLevel() = checkNoCompletion("""
retu/*caret*/
""")
fun testReturnNotAppliedWithinParametersList() = checkNoCompletion("""
fn foo(retu/*caret*/) {}
""")
fun testReturnNotAppliedBeforeBlock() = checkNoCompletion("""
fn foo() retu/*caret*/ {}
""")
fun testReturnNotAppliedIfDoesntStartStatement() = checkNoCompletion("""
const retu/*caret*/
""")
fun testStatic() = checkSingleCompletion("static", """
sta/*caret*/
""")
fun testPubStatic() = checkSingleCompletion("static", """
pub stat/*caret*/
""")
fun testStruct() = checkSingleCompletion("struct", """
str/*caret*/
""")
fun testPubStruct() = checkSingleCompletion("struct", """
pub str/*caret*/
""")
fun testTrait() = checkSingleCompletion("trait", """
tra/*caret*/
""")
fun testPubTrait() = checkSingleCompletion("trait", """
pub tra/*caret*/
""")
fun testUnsafeTrait() = checkSingleCompletion("trait", """
unsafe tra/*caret*/
""")
fun testType() = checkSingleCompletion("type", """
typ/*caret*/
""")
fun testPubType() = checkSingleCompletion("type", """
pub typ/*caret*/
""")
fun testUnsafe() = checkSingleCompletion("unsafe", """
uns/*caret*/
""")
fun testPubUnsafe() = checkSingleCompletion("unsafe", """
pub unsa/*caret*/
""")
fun testUse() = checkSingleCompletion("use", """
us/*caret*/
""")
fun testPubUse() = checkSingleCompletion("use", """
pub us/*caret*/
""")
fun testUseSelf() = checkSingleCompletion("self::", """
use se/*caret*/
""")
fun testUseSuper() = checkSingleCompletion("super::", """
mod m { use su/*caret*/ }
""")
fun `test else`() = checkCompletion("else", """
fn main() {
if true { } /*caret*/
}
""", """
fn main() {
if true { } else { /*caret*/ }
}
""")
fun `test else if`() = checkCompletion("else if", """
fn main() {
if true { } /*caret*/
}
""", """
fn main() {
if true { } else if /*caret*/ { }
}
""")
fun `test return from unit function`() = checkCompletion("return",
"fn foo() { ret/*caret*/}",
"fn foo() { return;/*caret*/}"
)
fun `test return from explicit unit function`() = checkCompletion("return",
"fn foo() -> () { ret/*caret*/}",
"fn foo() -> () { return;/*caret*/}"
)
fun `test return from non-unit function`() = checkCompletion("return",
"fn foo() -> i32 { ret/*caret*/}",
"fn foo() -> i32 { return /*caret*/}"
)
private fun checkCompletion(
lookupString: String,
@Language("Rust") before: String,
@Language("Rust") after: String
) = checkByText(before, after) {
val items = myFixture.completeBasic()
?: return@checkByText // single completion was inserted
val lookupItem = items.find { it.lookupString == lookupString }
myFixture.lookup.currentItem = lookupItem
myFixture.type('\n')
}
}
| src/test/kotlin/org/rust/lang/core/completion/RsKeywordCompletionContributorTest.kt | 3983706316 |
package com.beust.kobalt.misc
import java.io.BufferedReader
import java.io.File
import java.io.InputStream
import java.io.InputStreamReader
import java.util.concurrent.TimeUnit
class RunCommandInfo {
lateinit var command: String
var args : List<String> = arrayListOf()
var directory : File = File("")
var env : Map<String, String> = hashMapOf()
/**
* Some commands fail but return 0, so the only way to find out if they failed is to look
* at the error stream. However, some commands succeed but output text on the error stream.
* This field is used to specify how errors are caught.
*/
var useErrorStreamAsErrorIndicator : Boolean = true
var useInputStreamAsErrorIndicator : Boolean = false
var ignoreExitValue : Boolean = false
var errorCallback: Function1<List<String>, Unit> = NewRunCommand.DEFAULT_ERROR
var successCallback: Function1<List<String>, Unit> = NewRunCommand.DEFAULT_SUCCESS
var isSuccess: (Boolean, List<String>, List<String>) -> Boolean = {
isSuccess: Boolean,
input: List<String>,
error: List<String> ->
var hasErrors = ! isSuccess
if (useErrorStreamAsErrorIndicator && ! hasErrors) {
hasErrors = hasErrors || error.size > 0
}
if (useInputStreamAsErrorIndicator && ! hasErrors) {
hasErrors = hasErrors || input.size > 0
}
! hasErrors
}
var containsErrors: ((List<String>) -> Boolean)? = null
}
fun runCommand(init: RunCommandInfo.() -> Unit) = NewRunCommand(RunCommandInfo().apply { init() }).invoke()
open class NewRunCommand(val info: RunCommandInfo) {
companion object {
val DEFAULT_SUCCESS = { output: List<String> -> }
// val DEFAULT_SUCCESS_VERBOSE = { output: List<String> -> kobaltLog(2, "Success:\n " + output.joinToString
// ("\n"))}
// val defaultSuccess = DEFAULT_SUCCESS
val DEFAULT_ERROR = { output: List<String> ->
kobaltError(output.joinToString("\n "))
}
}
// fun useErrorStreamAsErrorIndicator(f: Boolean) : RunCommand {
// useErrorStreamAsErrorIndicator = f
// return this
// }
fun invoke() : Int {
val allArgs = arrayListOf<String>()
allArgs.add(info.command)
allArgs.addAll(info.args)
val pb = ProcessBuilder(allArgs)
pb.directory(info.directory)
kobaltLog(2, "Running command in directory ${info.directory.absolutePath}" +
"\n " + allArgs.joinToString(" ").replace("\\", "/"))
pb.environment().let { pbEnv ->
info.env.forEach {
pbEnv.put(it.key, it.value)
}
}
val process = pb.start()
// Run the command and collect the return code and streams
val processFinished = process.waitFor(240, TimeUnit.SECONDS)
if (!processFinished)
kobaltError("process timed out!")
val processExitedOk = process.exitValue() == 0
if (!processExitedOk)
kobaltError("process returned non-zero code!")
val input =
if (process.inputStream.available() > 0) fromStream(process.inputStream)
else listOf()
val error =
if (process.errorStream.available() > 0) fromStream(process.errorStream)
else listOf()
kobaltLog(3, "info contains errors: " + (info.containsErrors != null))
// Check to see if the command succeeded
val isSuccess =
if (info.containsErrors != null) ! info.containsErrors!!(error)
else isSuccess(processFinished && if (info.ignoreExitValue) true else processExitedOk, input, error)
if (isSuccess) {
if (!info.useErrorStreamAsErrorIndicator) {
info.successCallback(error + input)
} else {
info.successCallback(input)
}
} else {
info.errorCallback(error + input)
}
return if (isSuccess) 0 else 1
}
/**
* Subclasses can override this method to do their own error handling, since commands can
* have various ways to signal errors.
*/
open protected fun isSuccess(isSuccess: Boolean, input: List<String>, error: List<String>) : Boolean {
var hasErrors: Boolean = ! isSuccess
if (info.useErrorStreamAsErrorIndicator && ! hasErrors) {
hasErrors = hasErrors || error.isNotEmpty()
}
if (info.useInputStreamAsErrorIndicator && ! hasErrors) {
hasErrors = hasErrors || input.isNotEmpty()
}
return ! hasErrors
}
/**
* Turn the given InputStream into a list of strings.
*/
private fun fromStream(ins: InputStream) : List<String> {
val result = arrayListOf<String>()
val br = BufferedReader(InputStreamReader(ins))
var line = br.readLine()
while (line != null) {
result.add(line)
line = br.readLine()
}
return result
}
}
| modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/NewRunCommand.kt | 556750980 |
package de.xikolo.viewmodels.section
import de.xikolo.models.LtiExercise
import de.xikolo.models.dao.ItemDao
import de.xikolo.viewmodels.section.base.ItemViewModel
class LtiExerciseViewModel(itemId: String) : ItemViewModel(itemId) {
val ltiExercise
get() = ItemDao.Unmanaged.findContent(itemId) as LtiExercise?
}
| app/src/main/java/de/xikolo/viewmodels/section/LtiExerciseViewModel.kt | 1850089132 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.inspection.injector
import com.demonwav.mcdev.util.Parameter
import com.demonwav.mcdev.util.isErasureEquivalentTo
import com.intellij.psi.PsiArrayType
import com.intellij.psi.PsiEllipsisType
import com.intellij.psi.PsiParameter
data class ParameterGroup(
val parameters: List<Parameter>?,
val required: Boolean = parameters != null,
val default: Boolean = required
) {
val size
get() = this.parameters?.size ?: 0
fun match(parameters: Array<PsiParameter>, currentPosition: Int): Boolean {
if (this.parameters == null) {
// Wildcard parameter groups always match
return true
}
// Check if remaining parameter count is enough
if (currentPosition + size > parameters.size) {
return false
}
var pos = currentPosition
// Check parameter types
for ((_, expectedType) in this.parameters) {
val type = parameters[pos++].type
if (!type.isErasureEquivalentTo(expectedType)) {
// Allow using array instead of varargs
if (expectedType !is PsiEllipsisType || type !is PsiArrayType || type != expectedType.toArrayType()) {
return false
}
}
}
return true
}
}
| src/main/kotlin/platform/mixin/inspection/injector/ParameterGroup.kt | 1577353747 |
package com.github.andrewoma.flux
public abstract class Store {
private val changeListeners: MutableMap<Any, () -> Unit> = hashMapOf()
fun <PAYLOAD> register(dispatcher: Dispatcher, actionDef: ActionDef<PAYLOAD>, callback: DispatchCallbackBody.(PAYLOAD) -> Unit): RegisteredActionHandler {
return dispatcher.register(this, actionDef, callback)
}
fun unRegister(dispatcher: Dispatcher, token: RegisteredActionHandler) {
dispatcher.unRegister(token)
}
public fun addChangeListener(self: Any, callback: () -> Unit) {
changeListeners.put(self, callback)
}
protected fun emitChange() {
changeListeners.values.forEach { it() }
}
fun removeListener(self: Any) {
changeListeners.remove(self)
}
}
public class ActionDef<PAYLOAD> {
public operator fun invoke(dispatcher: Dispatcher, payload: PAYLOAD) {
dispatcher.dispatch(this, payload)
}
}
private class ActionHandlers(val handlers: MutableList<RegisteredActionHandler> = arrayListOf()) {
}
public class RegisteredActionHandler internal constructor(val store: Store, val actionDef: ActionDef<*>, val callback: DispatchCallbackBody.(Any?) -> Unit) {
var pending = false
var handled = false
}
public class DispatchCallbackBody(val dispatcher: Dispatcher, val store: Store) {
fun waitFor(vararg registeredActionHandlers: Store) {
dispatcher.waitFor(registeredActionHandlers)
}
}
class Dispatcher {
private var pendingPayload: Any? = null
private var pendingActionDef: ActionDef<*>? = null
private val actionHandlersList: MutableMap<ActionDef<*>, ActionHandlers> = hashMapOf()
private var dispatching = false
fun <PAYLOAD> register(store: Store, action: ActionDef<PAYLOAD>, callback: DispatchCallbackBody.(PAYLOAD) -> Unit): RegisteredActionHandler {
val actionHandlers = actionHandlersList.getOrPut(action, { ActionHandlers() })
val registeredActionHandler = RegisteredActionHandler(store, action, callback as (DispatchCallbackBody.(Any?) -> Unit) )
actionHandlers.handlers.add(registeredActionHandler)
return registeredActionHandler
}
fun unRegister(registeredActionHandler: RegisteredActionHandler) {
actionHandlersList[registeredActionHandler.actionDef]?.handlers?.remove(registeredActionHandler)
}
fun waitFor(stores: Array<out Store>) {
require(dispatching) { "Dispatcher.waitFor(...): Must be invoked while dispatching." }
val handlersForCurrentAction = actionHandlersList[pendingActionDef]?.handlers.orEmpty()
val (pendingHandlers, nonPendingHandlers) = handlersForCurrentAction.filter { stores.contains(it.store) }.partition { it.pending || it.handled }
val unhandledHandlers = pendingHandlers.firstOrNull { !it.handled }
require(unhandledHandlers == null) { "Dispatcher.waitFor(...): Circular dependency detected while waiting for $unhandledHandlers." }
nonPendingHandlers.forEach {
require(actionHandlersList[it.actionDef]?.handlers?.contains(it) ?: false) { "Dispatcher.waitFor(...): $it does not map to a registered callback." }
invokeCallback(it)
}
}
fun <PAYLOAD> dispatch(action: ActionDef<PAYLOAD>, payload: PAYLOAD) {
require(!dispatching) { "Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch." }
this.startDispatching(action, payload);
try {
actionHandlersList[action]?.handlers?.forEach {
if (!it.pending) {
invokeCallback(it)
}
}
} finally {
this.stopDispatching();
}
}
private fun invokeCallback(it: RegisteredActionHandler) {
it.pending = true
val body = DispatchCallbackBody(this, it.store)
val callback = it.callback
body.callback(pendingPayload)
it.handled = true
}
private fun <PAYLOAD> startDispatching(action: ActionDef<PAYLOAD>, payload: PAYLOAD) {
actionHandlersList[action]?.handlers?.forEach {
it.pending = false
it.handled = false
}
pendingPayload = payload
pendingActionDef = action
dispatching = true
}
private fun stopDispatching() {
pendingActionDef = null
pendingPayload = null
dispatching = false
}
} | frontend/src/com/github/andrewoma/flux/flux.kt | 2825431588 |
/*
* Copyright (C) 2017-2022 Alexey Rochev <[email protected]>
*
* This file is part of Tremotesf.
*
* Tremotesf 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.
*
* Tremotesf 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.equeim.tremotesf.ui.serversettingsfragment
import android.os.Bundle
import android.view.View
import android.widget.ArrayAdapter
import androidx.annotation.LayoutRes
import androidx.annotation.StringRes
import com.google.android.material.snackbar.Snackbar
import org.equeim.libtremotesf.RpcConnectionState
import org.equeim.tremotesf.R
import org.equeim.tremotesf.databinding.ServerSettingsFragmentBinding
import org.equeim.tremotesf.rpc.GlobalRpc
import org.equeim.tremotesf.rpc.statusString
import org.equeim.tremotesf.torrentfile.rpc.Rpc
import org.equeim.tremotesf.ui.NavigationFragment
import org.equeim.tremotesf.ui.utils.*
class ServerSettingsFragment : NavigationFragment(
R.layout.server_settings_fragment,
R.string.server_settings
) {
private val binding by viewLifecycleObject(ServerSettingsFragmentBinding::bind)
private var connectSnackbar: Snackbar? by viewLifecycleObjectNullable()
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
binding.listView.apply {
adapter = ArrayAdapter(
requireContext(),
R.layout.server_settings_fragment_list_item,
resources.getStringArray(R.array.server_settings_items)
)
divider = null
setSelector(android.R.color.transparent)
setOnItemClickListener { _, _, position, _ ->
val directions = when (position) {
0 -> ServerSettingsFragmentDirections.toDownloadingFragment()
1 -> ServerSettingsFragmentDirections.toSeedingFragment()
2 -> ServerSettingsFragmentDirections.toQueueFragment()
3 -> ServerSettingsFragmentDirections.toSpeedFragment()
4 -> ServerSettingsFragmentDirections.toNetworkFragment()
else -> null
}
if (directions != null) {
navigate(directions)
}
}
}
GlobalRpc.status.launchAndCollectWhenStarted(viewLifecycleOwner, ::updateView)
}
private fun updateView(status: Rpc.Status) {
when (status.connectionState) {
RpcConnectionState.Disconnected -> {
connectSnackbar = binding.root.showSnackbar(
message = "",
length = Snackbar.LENGTH_INDEFINITE,
actionText = R.string.connect,
action = GlobalRpc.nativeInstance::connect
) {
if (connectSnackbar == it) {
connectSnackbar = null
}
}
binding.placeholder.text = status.statusString
hideKeyboard()
}
RpcConnectionState.Connecting -> {
binding.placeholder.text = getString(R.string.connecting)
connectSnackbar?.dismiss()
connectSnackbar = null
}
RpcConnectionState.Connected -> {
connectSnackbar?.dismiss()
connectSnackbar = null
}
}
with(binding) {
if (status.connectionState == RpcConnectionState.Connected) {
listView.visibility = View.VISIBLE
placeholderLayout.visibility = View.GONE
} else {
placeholderLayout.visibility = View.VISIBLE
listView.visibility = View.GONE
}
progressBar.visibility = if (status.connectionState == RpcConnectionState.Connecting) {
View.VISIBLE
} else {
View.GONE
}
}
}
open class BaseFragment(
@LayoutRes contentLayoutId: Int,
@StringRes titleRes: Int
) : NavigationFragment(contentLayoutId, titleRes) {
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
GlobalRpc.isConnected.launchAndCollectWhenStarted(viewLifecycleOwner) {
if (!it) {
navController.popBackStack()
}
}
}
}
}
| app/src/main/kotlin/org/equeim/tremotesf/ui/serversettingsfragment/ServerSettingsFragment.kt | 2272376497 |
package com.engineer.gif.revert.internal
/**
* @author rookie
* @since 07-06-2019
*/
internal data class ResFrame(var delay: Int, var path: String) : Comparable<String> {
override fun compareTo(other: String): Int {
return other.compareTo(path)
}
} | gif-revert/src/main/java/com/engineer/gif/revert/internal/ResFrame.kt | 2904815076 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.yuriel.kotmvp.bases
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import dev.yuriel.kotmvp.Dev
import dev.yuriel.mahjan.texture.TextureMgr
import dev.yuriel.kotmvp.views.GridLayerViews
/**
* Created by yuriel on 8/3/16.
*/
abstract class BaseScreen: Screen {
private val grid: GridLayerViews = GridLayerViews()
//private val batch = SpriteBatch()
private val font = BitmapFont()
protected val TAG: String = javaClass.simpleName
protected fun drawGrid() {
//batch.begin()
//font.draw(batch, TAG, 5 * Dev.UX, 5 * Dev.UY)
grid.draw()
//batch.end()
}
override fun dispose() {
for (l in preload()?: return) {
l.destroy()
}
}
abstract fun preload(): List<TextureMgr>?
} | app/src/main/java/dev/yuriel/kotmvp/bases/BaseScreen.kt | 2676428267 |
package engineer.carrot.warren.thump.curse.command
import engineer.carrot.warren.thump.api.ICommandHandler
import net.minecraft.command.ICommandSender
class CursePluginCommandHandler : ICommandHandler {
override fun getCommand() = "curse"
override fun getUsage() = "$command ???"
override fun processParameters(sender: ICommandSender, parameters: Array<String>) {
}
override fun addTabCompletionOptions(sender: ICommandSender, parameters: Array<String>): List<String> {
return listOf()
}
} | src/main/kotlin/engineer/carrot/warren/thump/curse/command/CursePluginCommandHandler.kt | 1146048437 |
package com.sessionm.smp_kotlin
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.TextView
class DeepLinkActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_deep_link)
val url = intent.getStringExtra("url")
val textView = findViewById<TextView>(R.id.deep_link_textview) as TextView
textView.text = url
}
}
| SMP_Kotlin/src/main/java/com/sessionm/smp_kotlin/DeepLinkActivity.kt | 2952352631 |
package ws.osiris.core
import org.testng.annotations.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
@Test
class MatchTest {
class Components : ComponentsProvider
private val req = Request(HttpMethod.GET, "notUsed", Params(), Params(), Params(), Params(), null)
private val comps = Components()
fun fixedRoute() {
val handler: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val route = LambdaRoute(HttpMethod.GET, "/foo", handler)
val node = RouteNode.create(route)
assertNull(node.match(HttpMethod.GET, "/"))
assertNull(node.match(HttpMethod.GET, "/bar"))
assertNull(node.match(HttpMethod.POST, "/foo"))
assertEquals("1", node.match(HttpMethod.GET, "/foo")!!.handler(comps, req).body)
}
fun fixedRouteMultipleMethods() {
val handler1: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val handler2: RequestHandler<Components> = { req -> req.responseBuilder().build("2") }
val route1 = LambdaRoute(HttpMethod.GET, "/foo", handler1)
val route2 = LambdaRoute(HttpMethod.POST, "/foo", handler2)
val node = RouteNode.create(route1, route2)
assertNull(node.match(HttpMethod.GET, "/"))
assertEquals("1", node.match(HttpMethod.GET, "/foo")!!.handler(comps, req).body)
assertEquals("2", node.match(HttpMethod.POST, "/foo")!!.handler(comps, req).body)
}
fun multipleFixedRoutes() {
val handler1: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val handler2: RequestHandler<Components> = { req -> req.responseBuilder().build("2") }
val route1 = LambdaRoute(HttpMethod.GET, "/foo", handler1)
val route2 = LambdaRoute(HttpMethod.POST, "/bar/baz", handler2)
val node = RouteNode.create(route1, route2)
assertNull(node.match(HttpMethod.GET, "/"))
assertNull(node.match(HttpMethod.GET, "/foo/baz"))
assertEquals("1", node.match(HttpMethod.GET, "/foo")!!.handler(comps, req).body)
assertEquals("2", node.match(HttpMethod.POST, "/bar/baz")!!.handler(comps, req).body)
}
fun variableRoute() {
val handler: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val route = LambdaRoute(HttpMethod.GET, "/{foo}", handler)
val node = RouteNode.create(route)
assertNull(node.match(HttpMethod.GET, "/"))
assertNull(node.match(HttpMethod.POST, "/bar"))
val match = node.match(HttpMethod.GET, "/bar")
val response = match!!.handler(comps, req)
assertEquals("1", response.body)
assertEquals(mapOf("foo" to "bar"), match.vars)
}
fun variableRouteMultipleMethods() {
val handler1: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val handler2: RequestHandler<Components> = { req -> req.responseBuilder().build("2") }
val route1 = LambdaRoute(HttpMethod.GET, "/{foo}", handler1)
val route2 = LambdaRoute(HttpMethod.POST, "/{foo}", handler2)
val node = RouteNode.create(route1, route2)
assertNull(node.match(HttpMethod.GET, "/"))
val match1 = node.match(HttpMethod.GET, "/bar")
val response1 = match1!!.handler(comps, req)
assertEquals("1", response1.body)
assertEquals(mapOf("foo" to "bar"), match1.vars)
val match2 = node.match(HttpMethod.POST, "/bar")
val response2 = match2!!.handler(comps, req)
assertEquals("2", response2.body)
assertEquals(mapOf("foo" to "bar"), match2.vars)
}
fun variableRouteMultipleVariables() {
val handler: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val route = LambdaRoute(HttpMethod.GET, "/{foo}/bar/{baz}", handler)
val node = RouteNode.create(route)
val match = node.match(HttpMethod.GET, "/abc/bar/def")
val response = match!!.handler(comps, req)
assertEquals(mapOf("foo" to "abc", "baz" to "def"), match.vars)
assertEquals("1", response.body)
}
fun multipleVariableRoutes() {
val handler1: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val handler2: RequestHandler<Components> = { req -> req.responseBuilder().build("2") }
val route1 = LambdaRoute(HttpMethod.GET, "/{foo}", handler1)
val route2 = LambdaRoute(HttpMethod.POST, "/{foo}/baz", handler2)
val node = RouteNode.create(route1, route2)
val match1 = node.match(HttpMethod.GET, "/bar")
val response1 = match1!!.handler(comps, req)
assertEquals("1", response1.body)
assertEquals(mapOf("foo" to "bar"), match1.vars)
val match2 = node.match(HttpMethod.POST, "/bar/baz")
val response2 = match2!!.handler(comps, req)
assertEquals("2", response2.body)
assertEquals(mapOf("foo" to "bar"), match2.vars)
assertNull(node.match(HttpMethod.POST, "/bar/qux"))
}
fun fixedTakesPriority() {
val handler1: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val handler2: RequestHandler<Components> = { req -> req.responseBuilder().build("2") }
val route1 = LambdaRoute(HttpMethod.GET, "/{foo}", handler1)
val route2 = LambdaRoute(HttpMethod.GET, "/foo", handler2)
val node = RouteNode.create(route1, route2)
assertEquals("2", node.match(HttpMethod.GET, "/foo")!!.handler(comps, req).body)
}
fun handlerAtRoot() {
val handler: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val route = LambdaRoute(HttpMethod.GET, "/", handler)
val node = RouteNode.create(route)
assertNull(node.match(HttpMethod.GET, "/foo"))
assertEquals("1", node.match(HttpMethod.GET, "/")!!.handler(comps, req).body)
}
}
| core/src/test/kotlin/ws/osiris/core/MatchTest.kt | 3999363421 |
package com.sapuseven.untis.models.untis
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import org.joda.time.LocalDate
import org.joda.time.format.ISODateTimeFormat
// TODO: Change all occurrences of startDate or endDate in string format to this type
@Serializable
class UntisDate(
val date: String
) {
@Serializer(forClass = UntisDate::class)
companion object : KSerializer<UntisDate> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("UntisDate", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, obj: UntisDate) {
encoder.encodeString(obj.date)
}
override fun deserialize(decoder: Decoder): UntisDate {
return UntisDate(decoder.decodeString())
}
fun fromLocalDate(localDate: LocalDate): UntisDate {
return UntisDate(localDate.toString(ISODateTimeFormat.date()))
}
}
override fun toString(): String {
return date
}
fun toLocalDate(): LocalDate {
return ISODateTimeFormat.date().parseLocalDate(date)
}
}
| app/src/main/java/com/sapuseven/untis/models/untis/UntisDate.kt | 2963914920 |
/*
* Quasar: lightweight threads and actors for the JVM.
* Copyright (c) 2015, Parallel Universe Software Co. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 3.0
* as published by the Free Software Foundation.
*/
package co.paralleluniverse.kotlin.actors
import co.paralleluniverse.actors.*
import co.paralleluniverse.actors.behaviors.BehaviorActor
import co.paralleluniverse.actors.behaviors.ProxyServerActor
import co.paralleluniverse.actors.behaviors.Supervisor
import co.paralleluniverse.actors.behaviors.Supervisor.*
import co.paralleluniverse.actors.behaviors.Supervisor.ChildMode
import co.paralleluniverse.actors.behaviors.Supervisor.ChildMode.*
import co.paralleluniverse.actors.behaviors.SupervisorActor
import co.paralleluniverse.actors.behaviors.SupervisorActor.*
import co.paralleluniverse.actors.behaviors.SupervisorActor.RestartStrategy.*
import co.paralleluniverse.fibers.Suspendable
import org.junit.Test
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit.*
import co.paralleluniverse.kotlin.Actor
import co.paralleluniverse.kotlin.Actor.Companion.Timeout
import co.paralleluniverse.kotlin.*
import java.text.SimpleDateFormat
import java.util.*
/**
* @author circlespainter
*/
// This example is meant to be a translation of the canonical
// Erlang [ping-pong example](http://www.erlang.org/doc/getting_started/conc_prog.html#id67347).
data class Msg(val txt: String, val from: ActorRef<Any?>)
val sdfDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
fun now(): String = "[${sdfDate.format(Date())}]"
class Ping(val n: Int) : Actor() {
@Suspendable override fun doRun() {
val pong: ActorRef<Any> = ActorRegistry.getActor("pong")
for(i in 1..n) {
val msg = Msg("ping$i", self())
println("${now()} Ping sending '$msg' to '$pong'")
pong.send(msg) // Fiber-blocking
println("${now()} Ping sent '$msg' to '$pong'")
println("${now()} Ping sending garbage 'aaa' to '$pong'")
pong.send("aaa") // Fiber-blocking
println("${now()} Ping sent garbage 'aaa' to '$pong'")
println("${now()} Ping receiving without timeout")
receive { // Fiber-blocking
println("${now()} Ping received '$it' (${it.javaClass})")
when (it) {
is String -> {
if (!it.startsWith("pong")) {
println("${now()} Ping discarding string '$it'")
null
}
}
else -> {
println("${now()} Ping discarding non-string '$it'")
null // Discard
}
}
}
}
println("${now()} Ping sending 'finished' to '$pong'")
pong.send("finished") // Fiber-blocking
println("${now()} Ping sent 'finished' to '$pong', exiting")
}
}
class Pong() : Actor() {
@Suspendable override fun doRun() {
var discardGarbage = false
while (true) {
println("${now()} Pong receiving with 1 sec timeout")
receive(1, SECONDS) { // Fiber-blocking
println("${now()} Pong received '$it' ('${it.javaClass}')")
when (it) {
is Msg -> {
if (it.txt.startsWith("ping")) {
val msg = "pong for ${it.txt}"
println("${now()} Pong sending '$msg' to '${it.from}'")
it.from.send(msg) // Fiber-blocking
println("${now()} Pong sent '$msg' to ${it.from}")
}
}
"finished" -> {
println("${now()} Pong received 'finished', exiting")
return // Non-local return, exit actor
}
is Timeout -> {
println("${now()} Pong timeout in 'receive', exiting")
return // Non-local return, exit actor
}
else -> {
if (discardGarbage) {
println("${now()} Pong discarding '$it'")
null
} else {
discardGarbage = true // Net times discard
println("${now()} Pong deferring '$it'")
defer()
}
}
}
}
}
}
}
public class KotlinPingPongActorTestWithDefer {
@Test public fun testActors() {
val pong = spawn(register("pong", Pong()))
val ping = spawn(Ping(3))
LocalActor.join(pong)
LocalActor.join(ping)
}
}
| quasar-kotlin/src/test/kotlin/co/paralleluniverse/kotlin/actors/PingPongWithDefer.kt | 498167419 |
package ch.schulealtendorf.psa.dto.user
data class UserRelation(
val password: String
)
| app/dto/src/main/kotlin/ch/schulealtendorf/psa/dto/user/UserRelation.kt | 3522115688 |
package com.anyaku.test.unit.crypt.combined
import com.anyaku.crypt.asymmetric.RSAKeyPair
import com.anyaku.crypt.combined.encrypt
import com.anyaku.crypt.combined.decrypt
import kotlin.test.assertEquals
import java.util.HashMap
import org.junit.Test as test
import com.anyaku.crypt.combined.encryptAny
import com.anyaku.crypt.combined.decryptAny
class combinedTest {
val keyPair = RSAKeyPair()
val message = "test test test"
val map = { (): Map<String, Any?> ->
val result = HashMap<String, Any?>()
result.put("test", "value")
result
}()
test fun testDataEncryption() {
val encrypted = encrypt(message.getBytes(), keyPair.publicKey)
assertEquals(256, encrypted.key.data.size)
assertEquals(32, encrypted.data.data.size)
}
test fun testDataDecryption() {
val encrypted = encrypt(message.getBytes(), keyPair.publicKey)
val decrypted = decrypt(encrypted, keyPair.privateKey)
assertEquals(message, String(decrypted))
}
test fun testMapEncryption() {
val encrypted = encryptAny(map, keyPair.publicKey)
assertEquals(256, encrypted.key.data.size)
assertEquals(48, encrypted.data.data.size)
}
[ suppress("UNCHECKED_CAST") ]
test fun testMapDecryption() {
val encrypted = encryptAny(map, keyPair.publicKey)
val decrypted = decryptAny(encrypted, keyPair.privateKey) as Map<String, Any?>
assertEquals(map.get("test"), decrypted.get("test"))
}
}
| src/test/kotlin/com/anyaku/test/unit/crypt/combined/combinedTest.kt | 826462456 |
package com.stripe.android.view
import android.content.Context
import android.content.res.ColorStateList
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import androidx.core.widget.ImageViewCompat
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.RecyclerView
import com.stripe.android.R
import com.stripe.android.databinding.AddPaymentMethodRowBinding
import com.stripe.android.databinding.GooglePayRowBinding
import com.stripe.android.databinding.MaskedCardRowBinding
import com.stripe.android.model.PaymentMethod
/**
* A [RecyclerView.Adapter] that holds a set of [MaskedCardView] items for a given set
* of [PaymentMethod] objects.
*/
internal class PaymentMethodsAdapter constructor(
intentArgs: PaymentMethodsActivityStarter.Args,
private val addableTypes: List<PaymentMethod.Type> = listOf(PaymentMethod.Type.Card),
initiallySelectedPaymentMethodId: String? = null,
private val shouldShowGooglePay: Boolean = false,
private val useGooglePay: Boolean = false,
private val canDeletePaymentMethods: Boolean = true
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
internal val paymentMethods = mutableListOf<PaymentMethod>()
internal var selectedPaymentMethodId: String? = initiallySelectedPaymentMethodId
internal val selectedPaymentMethod: PaymentMethod?
get() {
return selectedPaymentMethodId?.let { selectedPaymentMethodId ->
paymentMethods.firstOrNull { it.id == selectedPaymentMethodId }
}
}
internal var listener: Listener? = null
private val googlePayCount = 1.takeIf { shouldShowGooglePay } ?: 0
private val _addPaymentMethodArgs = MutableLiveData<AddPaymentMethodActivityStarter.Args>()
val addPaymentMethodArgs: LiveData<AddPaymentMethodActivityStarter.Args> = _addPaymentMethodArgs
internal val addCardArgs = AddPaymentMethodActivityStarter.Args.Builder()
.setBillingAddressFields(intentArgs.billingAddressFields)
.setShouldAttachToCustomer(true)
.setIsPaymentSessionActive(intentArgs.isPaymentSessionActive)
.setPaymentMethodType(PaymentMethod.Type.Card)
.setAddPaymentMethodFooter(intentArgs.addPaymentMethodFooterLayoutId)
.setPaymentConfiguration(intentArgs.paymentConfiguration)
.setWindowFlags(intentArgs.windowFlags)
.build()
internal val addFpxArgs = AddPaymentMethodActivityStarter.Args.Builder()
.setIsPaymentSessionActive(intentArgs.isPaymentSessionActive)
.setPaymentMethodType(PaymentMethod.Type.Fpx)
.setPaymentConfiguration(intentArgs.paymentConfiguration)
.build()
init {
setHasStableIds(true)
}
@JvmSynthetic
internal fun setPaymentMethods(paymentMethods: List<PaymentMethod>) {
this.paymentMethods.clear()
this.paymentMethods.addAll(paymentMethods)
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return paymentMethods.size + addableTypes.size + googlePayCount
}
override fun getItemViewType(position: Int): Int {
return when {
isGooglePayPosition(position) -> ViewType.GooglePay.ordinal
isPaymentMethodsPosition(position) -> {
val type = getPaymentMethodAtPosition(position).type
if (PaymentMethod.Type.Card == type) {
ViewType.Card.ordinal
} else {
super.getItemViewType(position)
}
}
else -> {
val paymentMethodType =
addableTypes[getAddableTypesPosition(position)]
return when (paymentMethodType) {
PaymentMethod.Type.Card -> ViewType.AddCard.ordinal
PaymentMethod.Type.Fpx -> ViewType.AddFpx.ordinal
else ->
throw IllegalArgumentException(
"Unsupported PaymentMethod type: ${paymentMethodType.code}"
)
}
}
}
}
private fun isGooglePayPosition(position: Int): Boolean {
return shouldShowGooglePay && position == 0
}
private fun isPaymentMethodsPosition(position: Int): Boolean {
val range = if (shouldShowGooglePay) {
1..paymentMethods.size
} else {
0 until paymentMethods.size
}
return position in range
}
override fun getItemId(position: Int): Long {
return when {
isGooglePayPosition(position) ->
GOOGLE_PAY_ITEM_ID
isPaymentMethodsPosition(position) ->
getPaymentMethodAtPosition(position).hashCode().toLong()
else ->
addableTypes[getAddableTypesPosition(position)].code.hashCode().toLong()
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is ViewHolder.PaymentMethodViewHolder -> {
val paymentMethod = getPaymentMethodAtPosition(position)
holder.setPaymentMethod(paymentMethod)
holder.setSelected(paymentMethod.id == selectedPaymentMethodId)
holder.itemView.setOnClickListener {
onPositionClicked(holder.bindingAdapterPosition)
}
}
is ViewHolder.GooglePayViewHolder -> {
holder.itemView.setOnClickListener {
selectedPaymentMethodId = null
listener?.onGooglePayClick()
}
holder.bind(useGooglePay)
}
is ViewHolder.AddCardPaymentMethodViewHolder -> {
holder.itemView.setOnClickListener {
_addPaymentMethodArgs.value = addCardArgs
}
}
is ViewHolder.AddFpxPaymentMethodViewHolder -> {
holder.itemView.setOnClickListener {
_addPaymentMethodArgs.value = addFpxArgs
}
}
}
}
@JvmSynthetic
internal fun onPositionClicked(position: Int) {
updateSelectedPaymentMethod(position)
listener?.onPaymentMethodClick(getPaymentMethodAtPosition(position))
}
private fun updateSelectedPaymentMethod(position: Int) {
val currentlySelectedPosition = paymentMethods.indexOfFirst {
it.id == selectedPaymentMethodId
}
if (currentlySelectedPosition != position) {
// selected a new Payment Method
notifyItemChanged(currentlySelectedPosition)
selectedPaymentMethodId = paymentMethods.getOrNull(position)?.id
}
// Notify the current position even if it's the currently selected position so that the
// ItemAnimator defined in PaymentMethodActivity is triggered.
notifyItemChanged(position)
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerView.ViewHolder {
return when (ViewType.values()[viewType]) {
ViewType.Card -> createPaymentMethodViewHolder(parent)
ViewType.AddCard -> createAddCardPaymentMethodViewHolder(parent)
ViewType.AddFpx -> createAddFpxPaymentMethodViewHolder(parent)
ViewType.GooglePay -> createGooglePayViewHolder(parent)
}
}
private fun createAddCardPaymentMethodViewHolder(
parent: ViewGroup
): ViewHolder.AddCardPaymentMethodViewHolder {
return ViewHolder.AddCardPaymentMethodViewHolder(parent.context, parent)
}
private fun createAddFpxPaymentMethodViewHolder(
parent: ViewGroup
): ViewHolder.AddFpxPaymentMethodViewHolder {
return ViewHolder.AddFpxPaymentMethodViewHolder(parent.context, parent)
}
private fun createPaymentMethodViewHolder(
parent: ViewGroup
): ViewHolder.PaymentMethodViewHolder {
val viewHolder = ViewHolder.PaymentMethodViewHolder(parent)
if (canDeletePaymentMethods) {
ViewCompat.addAccessibilityAction(
viewHolder.itemView,
parent.context.getString(R.string.delete_payment_method)
) { _, _ ->
listener?.onDeletePaymentMethodAction(
paymentMethod = getPaymentMethodAtPosition(viewHolder.bindingAdapterPosition)
)
true
}
}
return viewHolder
}
private fun createGooglePayViewHolder(
parent: ViewGroup
): ViewHolder.GooglePayViewHolder {
return ViewHolder.GooglePayViewHolder(parent.context, parent)
}
@JvmSynthetic
internal fun deletePaymentMethod(paymentMethod: PaymentMethod) {
getPosition(paymentMethod)?.let {
paymentMethods.remove(paymentMethod)
notifyItemRemoved(it)
}
}
@JvmSynthetic
internal fun resetPaymentMethod(paymentMethod: PaymentMethod) {
getPosition(paymentMethod)?.let {
notifyItemChanged(it)
}
}
/**
* Given an adapter position, translate to a `paymentMethods` element
*/
@JvmSynthetic
internal fun getPaymentMethodAtPosition(position: Int): PaymentMethod {
return paymentMethods[getPaymentMethodIndex(position)]
}
/**
* Given an adapter position, translate to a `paymentMethods` index
*/
private fun getPaymentMethodIndex(position: Int): Int {
return position - googlePayCount
}
/**
* Given a Payment Method, get its adapter position. For example, if the Google Pay button is
* being shown, the 2nd element in [paymentMethods] is actually the 3rd item in the adapter.
*/
internal fun getPosition(paymentMethod: PaymentMethod): Int? {
return paymentMethods.indexOf(paymentMethod).takeIf { it >= 0 }?.let {
it + googlePayCount
}
}
private fun getAddableTypesPosition(position: Int): Int {
return position - paymentMethods.size - googlePayCount
}
internal sealed class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal class AddCardPaymentMethodViewHolder(
viewBinding: AddPaymentMethodRowBinding
) : RecyclerView.ViewHolder(viewBinding.root) {
constructor(context: Context, parent: ViewGroup) : this(
AddPaymentMethodRowBinding.inflate(
LayoutInflater.from(context),
parent,
false
)
)
init {
itemView.id = R.id.stripe_payment_methods_add_card
itemView.contentDescription =
itemView.resources.getString(R.string.payment_method_add_new_card)
viewBinding.label.text =
itemView.resources.getString(R.string.payment_method_add_new_card)
}
}
internal class AddFpxPaymentMethodViewHolder(
viewBinding: AddPaymentMethodRowBinding
) : RecyclerView.ViewHolder(viewBinding.root) {
constructor(context: Context, parent: ViewGroup) : this(
AddPaymentMethodRowBinding.inflate(
LayoutInflater.from(context),
parent,
false
)
)
init {
itemView.id = R.id.stripe_payment_methods_add_fpx
itemView.contentDescription =
itemView.resources.getString(R.string.payment_method_add_new_fpx)
viewBinding.label.text =
itemView.resources.getString(R.string.payment_method_add_new_fpx)
}
}
internal class GooglePayViewHolder(
private val viewBinding: GooglePayRowBinding
) : RecyclerView.ViewHolder(viewBinding.root) {
constructor(context: Context, parent: ViewGroup) : this(
GooglePayRowBinding.inflate(
LayoutInflater.from(context),
parent,
false
)
)
private val themeConfig = ThemeConfig(itemView.context)
init {
ImageViewCompat.setImageTintList(
viewBinding.checkIcon,
ColorStateList.valueOf(themeConfig.getTintColor(true))
)
}
fun bind(isSelected: Boolean) {
viewBinding.label.setTextColor(
ColorStateList.valueOf(themeConfig.getTextColor(isSelected))
)
viewBinding.checkIcon.visibility = if (isSelected) {
View.VISIBLE
} else {
View.INVISIBLE
}
itemView.isSelected = isSelected
}
}
internal class PaymentMethodViewHolder constructor(
private val viewBinding: MaskedCardRowBinding
) : ViewHolder(viewBinding.root) {
constructor(parent: ViewGroup) : this(
MaskedCardRowBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
fun setPaymentMethod(paymentMethod: PaymentMethod) {
viewBinding.maskedCardItem.setPaymentMethod(paymentMethod)
}
fun setSelected(selected: Boolean) {
viewBinding.maskedCardItem.isSelected = selected
itemView.isSelected = selected
}
}
}
internal interface Listener {
fun onPaymentMethodClick(paymentMethod: PaymentMethod)
fun onGooglePayClick()
fun onDeletePaymentMethodAction(paymentMethod: PaymentMethod)
}
internal enum class ViewType {
Card,
AddCard,
AddFpx,
GooglePay
}
internal companion object {
internal val GOOGLE_PAY_ITEM_ID = "pm_google_pay".hashCode().toLong()
}
}
| payments-core/src/main/java/com/stripe/android/view/PaymentMethodsAdapter.kt | 1350431234 |
package reflection
import kotlin.reflect.KFunction2
import kotlin.reflect.full.memberProperties
var counter = 0
fun main(args: Array<String>) {
val person = Person("Alice", 29)
//返回一个KClass<Person>的实例
val kClass = person.javaClass.kotlin
println(kClass === Person::class) //true
println(kClass.simpleName) //Person
kClass.memberProperties.forEach {
println(it.name)
} //age, name
//反射调用foo函数
val kFunction = ::foo
kFunction.call(42)
kFunction.invoke(42)
kFunction(42) //不用显示的invoke就可以调用kFunction
/**
* KFunction2的类型称为合成的编译器生成类型,在kotlin.reflect中找不到他们的声明。
* 这意味着你可以使用任意数量参数的函数接口。
* 合成类型的方式减小了kotlin-reflect.jar的尺寸,同时避免了对函数类型参数数量的人为限制。
*
* KFunctionN每一个类型都继承了KFunction并加上一个额外的成员invoke,它拥有数量刚好的参数。
* 例如,KFunction2 声明了operator fun invoke (pl : P1, p2 : P2) : R,
* 其中P1和P2 代表着函数的参数类型,而R代表着函数的返回类型。
*
* 因此,如果你有这样一个具体类型的KFunction ,它的形参类型和返回类型是确定的,
* 那么应该优先使用这个具体类型的invoke 方法。
* call 方法是对所有类型都有效的通用手段,但是它不提供类型安全性。
*/
val kFunction2: KFunction2<Int, Int, Int> = ::sum
println(kFunction2.invoke(1, 2) + kFunction2(3, 4)) //10
/**
* 你也可以在一个KProperty实例上调用call方法,它会调用该属性的getter。
* 但是属性接口为你提供了一个更好的获取属性值的方式:get方法。
*
* 要访问get方法,你需要根据属性声明的方式来使用正确的属性接口。
* 顶层属性表示为KProperty0接口的实例,它有一个无参数的get方法:
*/
val kProperty = ::counter
kProperty.setter.call(21) //通过反射调用setter,把21作为实参传递
println(kProperty.call()) //通过“call”获取属性的值
println(kProperty.get()) //通过“get”获取属性的值
/**
* 一个成员属性由KProperty1的实例表示,它拥有一个单参数的get方法。
* 要访问该属性的值,必须提供你需要的值所属的那个对象实例。
*
* KProperty1是一个泛型类。变量memberProperty的类型是KProperty<Person, Int> ,
* 其中第一个类型参数表示接收者的类型,而第二个类型参数代表了属性的类型。
* 这样你只能对正确类型的接收者调用它的get方法。而memberProperty.get("Amanda")这样的调用不会通过编译。
* 还有一点值得注意,只能使用反射访问定义在最外层或者类中的属性,而不能访问函数的局部变量。
* 如果你定义了一个局部变量x并试图使用::x来获得它的引用,你会得到一个编译期的错误:
* "References to variables aren't supported yet" (现在还不支持对变量的引用〉。
*/
val person2 = Person("Amanda", 28)
val memberProperty = Person::age //在memberProperty变量中存储了一个指向属性的引用
println(memberProperty.get(person2)) //memberProperty.get(person)来获取属于具体person实例的这个属性的值。
}
fun sum(x: Int, y: Int) = x + y
fun foo(x: Int) = println(x)
class Person(val name: String, val age: Int) | src/main/kotlin/reflection/ReflectionTest.kt | 689777423 |
package com.stripe.android.test.e2e
import com.squareup.moshi.Json
import com.stripe.android.core.ApiVersion
sealed class Request {
data class CreatePaymentIntentParams(
@field:Json(name = "create_params") val createParams: CreateParams,
@field:Json(name = "account") val account: String? = null,
@field:Json(name = "version") val version: String = ApiVersion.API_VERSION_CODE
)
data class CreateSetupIntentParams(
@field:Json(name = "create_params") val createParams: CreateParams,
@field:Json(name = "account") val account: String? = null,
@field:Json(name = "version") val version: String = ApiVersion.API_VERSION_CODE
)
data class CreateParams(
@field:Json(name = "payment_method_types") val paymentMethodTypes: List<String>
)
}
| stripe-test-e2e/src/test/java/com/stripe/android/test/e2e/Request.kt | 1634359476 |
/*
* SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least.
* Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package de.sudoq.persistence
import de.sudoq.persistence.XmlTree
/**
* A class that can be (de-)serialised to/from XML.
*/
interface Xmlable {
/**
* Creates an XmlTree Objekt, which contains all persist-worthy attributes.
*
* @return [XmlTree] representation of the implementing class
*/
fun toXmlTree(): XmlTree?
/**
* Loads data from an xml representation into the implementing class
*
* @param xmlTreeRepresentation Representation of the implementing class.
* @throws IllegalArgumentException if the XML Representation has an unsupported structure.
*/
@Throws(IllegalArgumentException::class)
fun fillFromXml(xmlTreeRepresentation: XmlTree)
} | sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/persistence/Xmlable.kt | 1916329857 |
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.events
import com.tealcube.minecraft.bukkit.mythicdrops.api.events.MythicDropsCancellableEvent
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.CustomItem
import org.bukkit.event.HandlerList
import org.bukkit.inventory.ItemStack
class CustomItemGenerationEvent(var customItem: CustomItem, result: ItemStack) :
MythicDropsCancellableEvent() {
companion object {
@JvmStatic
val handlerList = HandlerList()
}
var isModified: Boolean = false
private set
var result: ItemStack = result
set(value) {
field = value
isModified = true
}
override fun getHandlers(): HandlerList = handlerList
}
| src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/events/CustomItemGenerationEvent.kt | 2171339761 |
package abi43_0_0.host.exp.exponent.modules.api.components.pagerview
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.recyclerview.widget.RecyclerView.Adapter
import java.util.*
class ViewPagerAdapter() : Adapter<ViewPagerViewHolder>() {
private val childrenViews: ArrayList<View> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewPagerViewHolder {
return ViewPagerViewHolder.create(parent)
}
override fun onBindViewHolder(holder: ViewPagerViewHolder, index: Int) {
val container: FrameLayout = holder.container
val child = getChildAt(index)
if (container.childCount > 0) {
container.removeAllViews()
}
if (child.parent != null) {
(child.parent as FrameLayout).removeView(child)
}
container.addView(child)
}
override fun getItemCount(): Int {
return childrenViews.size
}
fun addChild(child: View, index: Int) {
childrenViews.add(index, child)
notifyItemInserted(index)
}
fun getChildAt(index: Int): View {
return childrenViews[index]
}
fun removeChild(child: View) {
val index = childrenViews.indexOf(child)
removeChildAt(index)
}
fun removeAll() {
val removedChildrenCount = childrenViews.size
childrenViews.clear()
notifyItemRangeRemoved(0, removedChildrenCount)
}
fun removeChildAt(index: Int) {
childrenViews.removeAt(index)
notifyItemRemoved(index)
}
}
| android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/api/components/pagerview/ViewPagerAdapter.kt | 3107913804 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.RefreshQueue
import org.jetbrains.annotations.TestOnly
import org.rust.lang.core.crate.CratePersistentId
import org.rust.lang.core.macros.MacroExpansionFileSystem.FSItem
import org.rust.openapiext.findNearestExistingFile
class MacroExpansionVfsBatch(private val contentRoot: String) {
/**
* Should be used if file was just created and there is no corresponding [VirtualFile] yet.
* If we have [VirtualFile], then [VfsUtil.markDirty] should be used directly.
*/
private val pathsToMarkDirty: MutableSet<String> = hashSetOf()
var hasChanges: Boolean = false
private set
private val expansionFileSystem: MacroExpansionFileSystem = MacroExpansionFileSystem.getInstance()
class Path(val path: String) {
fun toVirtualFile(): VirtualFile? =
MacroExpansionFileSystem.getInstance().findFileByPath(path)
}
fun createFile(crate: CratePersistentId, expansionName: String, content: String, implicit: Boolean = false): Path {
val path = "${crate}/${expansionNameToPath(expansionName)}"
return createFile(path, content, implicit)
}
fun createFile(relativePath: String, content: String, implicit: Boolean = false): Path {
val path = "$contentRoot/$relativePath"
if (implicit) {
expansionFileSystem.createFileWithImplicitContent(path, content.toByteArray().size, mkdirs = true)
} else {
expansionFileSystem.createFileWithExplicitContent(path, content.toByteArray(), mkdirs = true)
}
val parent = path.substring(0, path.lastIndexOf('/'))
pathsToMarkDirty += parent
hasChanges = true
return Path(path)
}
fun deleteFile(file: FSItem) {
file.delete()
val virtualFile = expansionFileSystem.findFileByPath(file.absolutePath())
virtualFile?.let { markDirty(it) }
hasChanges = true
}
@TestOnly
fun deleteFile(file: VirtualFile) {
MacroExpansionFileSystem.getInstance().deleteFile(file.path)
markDirty(file)
hasChanges = true
}
@TestOnly
fun writeFile(file: VirtualFile, content: String) {
MacroExpansionFileSystem.getInstance().setFileContent(file.path, content.toByteArray())
markDirty(file)
hasChanges = true
}
fun applyToVfs(async: Boolean, callback: Runnable? = null) {
val root = expansionFileSystem.findFileByPath("/") ?: return
for (path in pathsToMarkDirty) {
markDirty(root.findNearestExistingFile(path).first)
}
RefreshQueue.getInstance().refresh(async, true, callback, root)
}
private fun markDirty(file: VirtualFile) {
VfsUtil.markDirty(false, false, file)
}
}
| src/main/kotlin/org/rust/lang/core/macros/MacroExpansionVfsBatch.kt | 2116784449 |
package com.twitter.meil_mitu.twitter4hk.aclog.api.tweets
import com.twitter.meil_mitu.twitter4hk.AbsOauth
import com.twitter.meil_mitu.twitter4hk.OauthType
import com.twitter.meil_mitu.twitter4hk.aclog.AbsAclogGet
import com.twitter.meil_mitu.twitter4hk.aclog.converter.IAclogStatusConverter
import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException
class Show<TAclogStatus>(
oauth: AbsOauth,
protected val json: IAclogStatusConverter<TAclogStatus>,
id: Long) : AbsAclogGet<TAclogStatus>(oauth) {
var authorization: Boolean = false
override val isAuthorization = authorization
var id: Long?by longParam("id")
override val url = "$host/api/tweets/show.json"
override val allowOauthType = OauthType.oauthEcho
init {
this.id = id
}
@Throws(Twitter4HKException::class)
override fun call(): TAclogStatus {
return json.toStatus(oauth.get(this))
}
}
| library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/aclog/api/tweets/Show.kt | 3665935309 |
package com.habitrpg.android.habitica.ui.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.user.User
import io.reactivex.rxjava3.disposables.CompositeDisposable
import javax.inject.Inject
abstract class BaseViewModel(initializeComponent: Boolean = true) : ViewModel() {
@Inject
lateinit var userRepository: UserRepository
@Inject
lateinit var userViewModel: MainUserViewModel
val user: LiveData<User?> by lazy {
userViewModel.user
}
init {
if (initializeComponent) {
HabiticaBaseApplication.userComponent?.let { inject(it) }
}
}
abstract fun inject(component: UserComponent)
override fun onCleared() {
userRepository.close()
disposable.clear()
super.onCleared()
}
internal val disposable = CompositeDisposable()
fun updateUser(path: String, value: Any) {
disposable.add(
userRepository.updateUser(path, value)
.subscribe({ }, RxErrorHandler.handleEmptyError())
)
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewmodels/BaseViewModel.kt | 3290089918 |
package org.tsdes.advanced.rest.exceptionhandling.dto
import io.swagger.annotations.ApiModelProperty
class DivisionDto(
@ApiModelProperty("The numerator in the division")
var x: Int? = null,
@ApiModelProperty("The denominator in the division. Must be non-zero.")
var y: Int? = null,
@ApiModelProperty("The result of dividing x by y")
var result: Int? = null
) | advanced/rest/exception-handling/src/main/kotlin/org/tsdes/advanced/rest/exceptionhandling/dto/DivisionDto.kt | 529502939 |
package com.quijotelui.electronico.comprobantes.nota.debito
import com.quijotelui.electronico.comprobantes.InformacionTributaria
import comprobantes.InformacionAdicional
import javax.xml.bind.annotation.XmlAttribute
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlRootElement
import javax.xml.bind.annotation.XmlType
@XmlRootElement
@XmlType(propOrder = arrayOf("infoTributaria", "infoNotaDebito", "motivos", "infoAdicional"))
class NotaDebito {
@XmlAttribute
private var id : String? = null
@XmlAttribute
private var version : String? = null
@XmlElement(name = "infoTributaria")
private var informacionTributaria = InformacionTributaria()
@XmlElement(name = "infoNotaDebito")
private var informacionNotaDebito = InformacionNotaDebito()
@XmlElement
private var motivos = Motivos()
@XmlElement(name = "infoAdicional")
private var informacionAdicional = InformacionAdicional()
fun setId(id : String) {
this.id = id
}
fun setVersion(version : String) {
this.version = version
}
fun setInformacionTributaria(informacionTributaria : InformacionTributaria) {
this.informacionTributaria = informacionTributaria
}
fun setInformacionNotaCredito(informacionFactura : InformacionNotaDebito) {
this.informacionNotaDebito = informacionFactura
}
fun setMotivos(motivos: Motivos) {
this.motivos = motivos
}
fun setInformacionAdicional(informacionAdicional: InformacionAdicional) {
this.informacionAdicional = informacionAdicional
}
} | src/main/kotlin/com/quijotelui/electronico/comprobantes/nota/debito/NotaDebito.kt | 2235276607 |
package nl.rsdt.japp.jotial.auth
import android.app.Activity
import android.content.Intent
import com.google.gson.annotations.SerializedName
import nl.rsdt.japp.R
import nl.rsdt.japp.application.Japp
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.application.activities.LoginActivity
import nl.rsdt.japp.jotial.net.apis.AuthApi
import org.acra.ktx.sendWithAcra
import retrofit2.Call
import retrofit2.Callback
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 13-7-2016
* Description...
*/
class Authentication : Callback<Authentication.KeyObject> {
private var callback: OnAuthenticationCompletedCallback? = null
private var username: String = ""
private var password: String = ""
fun executeAsync() {
val api = Japp.getApi(AuthApi::class.java)
api.login(LoginBody(username, password)).enqueue(this)
}
override fun onResponse(call: Call<KeyObject>, response: retrofit2.Response<KeyObject>) {
if (response.code() == 200) {
val key = response.body()?.key
/**
* Change the key in the release_preferences.
*/
val pEditor = JappPreferences.visiblePreferences.edit()
pEditor.putString(JappPreferences.ACCOUNT_KEY, key)
pEditor.apply()
callback?.onAuthenticationCompleted(AuthenticationResult(key, 200, Japp.getString(R.string.login_succes)))
} else {
val message: String = if (response.code() == 404) {
Japp.getString(R.string.wrong_data)
} else {
Japp.getString(R.string.error_on_login)
}
callback?.onAuthenticationCompleted(AuthenticationResult("", response.code(), message))
}
}
override fun onFailure(call: Call<KeyObject>, t: Throwable) {
t.sendWithAcra()
callback?.onAuthenticationCompleted(AuthenticationResult("", 0, Japp.getString(R.string.error_on_login)))
}
class AuthenticationResult(val key: String?, val code: Int, val message: String) {
val isSucceeded: Boolean
get() = key != null && !key.isEmpty()
}
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 2-9-2016
* Description...
*/
inner class LoginBody(private val gebruiker: String, private val ww: String)
inner class KeyObject {
@SerializedName("SLEUTEL")
public val key: String = ""
}
inner class ValidateObject {
@SerializedName("exists")
private val exists: Boolean = false
fun exists(): Boolean {
return exists
}
}
class Builder {
internal var buffer = Authentication()
fun setCallback(callback: OnAuthenticationCompletedCallback): Builder {
buffer.callback = callback
return this
}
fun setUsername(username: String): Builder {
buffer.username = username
return this
}
fun setPassword(password: String): Builder {
buffer.password = AeSimpleSHA1.trySHA1(password)
return this
}
fun create(): Authentication {
return buffer
}
}
interface OnAuthenticationCompletedCallback {
fun onAuthenticationCompleted(result: AuthenticationResult)
}
companion object {
val REQUEST_TAG = "Authentication"
/**
* TODO: don't use final here
*/
fun validate(activity: Activity) {
val api = Japp.getApi(AuthApi::class.java)
}
fun startLoginActivity(activity: Activity) {
val intent = Intent(activity, LoginActivity::class.java)
activity.startActivity(intent)
activity.finish()
}
}
}
| app/src/main/java/nl/rsdt/japp/jotial/auth/Authentication.kt | 1700811824 |
package taiwan.no1.app.ssfm.models.entities.lastfm
import com.google.gson.annotations.SerializedName
/**
* @author jieyi
* @since 10/16/17
*/
data class TopArtistEntity(var artists: Artists) {
data class Artists(@SerializedName("artist")
var artists: List<ArtistEntity.Artist>,
@SerializedName("@attr")
var attr: Attr?)
} | app/src/main/kotlin/taiwan/no1/app/ssfm/models/entities/lastfm/TopArtistEntity.kt | 2679990223 |
package de.droidcon.berlin2018.ui.sessiondetails
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler
import de.droidcon.berlin2018.model.Session
import de.droidcon.berlin2018.model.Speaker
import de.droidcon.berlin2018.ui.navigation.Navigator
import de.droidcon.berlin2018.ui.speakerdetail.SpeakerDetailsController
/**
*
*
* @author Hannes Dorfmann
*/
class SessionDetailsNavigator(private val controller: Controller) : Navigator {
override fun showHome() {
TODO(
"not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun showSessions() {
TODO(
"not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun showMySchedule() {
TODO(
"not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun showSpeakers() {
TODO(
"not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun showSpeakerDetails(speaker: Speaker) {
controller.router.pushController(
RouterTransaction.with(
SpeakerDetailsController(speaker.id())
)
.pushChangeHandler(HorizontalChangeHandler())
.popChangeHandler(HorizontalChangeHandler())
)
}
override fun showSessionDetails(session: Session) {
TODO(
"not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun showTweets() {
TODO(
"not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun showSearch() {
TODO(
"not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun popSelfFromBackstack() {
controller.router.popCurrentController()
}
override fun showLicences() {
TODO(
"not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun showSourceCode() {
TODO(
"not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
| app/src/main/java/de/droidcon/berlin2018/ui/sessiondetails/SessionDetailsNavigator.kt | 2051261495 |
fun some() {
listOf(1, 2).
<caret>map { it >= 2 }
} | kotlin-eclipse-ui-test/testData/format/autoIndent/continuationAfterDotCall.after.kt | 3026015757 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.openal.templates
import org.lwjgl.generator.*
import org.lwjgl.openal.*
val AL_EXT_MULAW = "EXTMulaw".nativeClassAL("EXT_MULAW") {
documentation = "Native bindings to the $extensionName extension."
IntConstant(
"Buffer formats.",
"FORMAT_MONO_MULAW_EXT"..0x10014,
"FORMAT_STEREO_MULAW_EXT"..0x10015
)
} | modules/templates/src/main/kotlin/org/lwjgl/openal/templates/AL_EXT_MULAW.kt | 3069242508 |
sinus | kotlin-eclipse-ui-test/testData/highlighting/basic/textWithTokenBetween.kt | 3883114132 |
package me.proxer.app.ui.view
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.View.MeasureSpec.AT_MOST
import android.view.View.MeasureSpec.UNSPECIFIED
import android.view.View.MeasureSpec.makeMeasureSpec
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.FrameLayout
import androidx.appcompat.widget.AppCompatButton
import androidx.core.content.withStyledAttributes
import com.google.android.flexbox.FlexboxLayout
import com.jakewharton.rxbinding3.view.clicks
import com.uber.autodispose.android.ViewScopeProvider
import com.uber.autodispose.autoDisposable
import io.reactivex.subjects.PublishSubject
import me.proxer.app.R
import me.proxer.app.util.extension.resolveColor
/**
* @author Ruben Gees
*/
class MaxLineFlexboxLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FlexboxLayout(context, attrs, defStyleAttr) {
val showAllEvents: PublishSubject<Unit> = PublishSubject.create()
var maxLines = Int.MAX_VALUE
private var currentWidth: Int = 0
private var currentLine: Int = 1
private var isShowAllButtonEnabled = false
init {
if (attrs != null) {
context.withStyledAttributes(attrs, R.styleable.MaxLineFlexboxLayout) {
maxLines = getInt(R.styleable.MaxLineFlexboxLayout_maxLines, Int.MAX_VALUE)
}
}
}
override fun removeAllViews() {
isShowAllButtonEnabled = false
currentWidth = 0
currentLine = 1
super.removeAllViews()
}
override fun addView(child: View) {
if (canAddView(child)) {
if (currentWidth + child.measuredWidth > width) {
currentWidth = child.measuredWidth
currentLine++
} else {
currentWidth += child.measuredWidth
}
super.addView(child)
}
}
fun canAddView(view: View): Boolean {
require(width != 0) { "Only call this method after this view has been laid out." }
if (view.measuredWidth == 0) {
view.measure(makeMeasureSpec(width, AT_MOST), makeMeasureSpec(0, UNSPECIFIED))
}
return currentWidth + view.measuredWidth <= width || currentLine + 1 <= maxLines
}
fun enableShowAllButton() {
if (isShowAllButtonEnabled) return
val container = FrameLayout(context)
val button = AppCompatButton(context, null, android.R.attr.borderlessButtonStyle)
button.text = context.getString(R.string.fragment_media_info_show_all)
button.layoutParams = FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT, Gravity.CENTER)
button.setTextColor(context.resolveColor(R.attr.colorSecondary))
button.clicks()
.doOnNext { maxLines = Int.MAX_VALUE }
.autoDisposable(ViewScopeProvider.from(this))
.subscribe(showAllEvents)
container.layoutParams = LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply {
isWrapBefore = true
}
container.addView(button)
super.addView(container)
}
}
| src/main/kotlin/me/proxer/app/ui/view/MaxLineFlexboxLayout.kt | 3987024983 |
package c6h2cl2.solidxp.item
import c6h2cl2.YukariLib.IToolWithType
import net.minecraft.item.ItemStack
/**
* @author C6H2Cl2
*/
interface ICraftResultEnchanted: IToolWithType {
fun getEnchanted(): ItemStack
} | src/main/java/c6h2cl2/solidxp/item/ICraftResultEnchanted.kt | 2066357147 |
package com.commonsense.android.kotlin.system.base.helpers
import org.junit.*
import org.junit.jupiter.api.Test
/**
*
*/
internal class ActivityResultWrapperTest {
@Ignore
@Test
fun onActivityResult() {
}
@Ignore
@Test
fun getCallback() {
}
@Ignore
@Test
fun getRequestCode() {
}
@Ignore
@Test
fun getRemoverFunction() {
}
} | system/src/test/kotlin/com/commonsense/android/kotlin/system/base/helpers/ActivityResultWrapperTest.kt | 3389898397 |
/*
* Copyright 2017 Adam Jordens
*
* 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.jordens.sleepybaby.user
import org.jordens.sleepybaby.FeedingConfigurationProperties
import org.jordens.sleepybaby.GenericResponse
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/api/users")
class UserController @Autowired constructor(val configurationProperties: FeedingConfigurationProperties) {
@GetMapping("/me")
fun me(): GenericResponse = GenericResponse.ok(Pair("me", UserDetails(configurationProperties.name)))
}
data class UserDetails(val name: String)
| jvm/sleepybaby-api/src/main/kotlin/org/jordens/sleepybaby/user/UserController.kt | 2819627395 |
package com.scienjus.smartqq.model
import com.google.gson.annotations.SerializedName
/**
* 讨论组.
* @author ScienJus
* *
* @author [Liang Ding](http://88250.b3log.org)
* *
* @date 2015/12/23.
*/
data class Discuss(
@SerializedName("did")
var discussId: Long = 0,
var name: String? = null
)
| src/main/kotlin/com/scienjus/smartqq/model/Discuss.kt | 1741237174 |
package cz.richter.david.astroants.parser
import cz.richter.david.astroants.indexedArrayListSpliterator
import cz.richter.david.astroants.model.InputMapSettings
import cz.richter.david.astroants.model.MapLocation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.*
import java.util.stream.Collectors
import java.util.stream.StreamSupport
/**
* Implementation of [InputMapParser] which uses sequential stream processing to parse all [MapLocation]s from [String]s
* Sequential stream usage unlike parallel does not need sorting after parsing [String]s
*/
@Component
class SequentialInputMapParser @Autowired constructor(private val mapLocationParser: MapLocationParser) : InputMapParser {
override fun parse(inputMapSettings: InputMapSettings): List<MapLocation> {
val gridSize = Math.sqrt(inputMapSettings.areas.size.toDouble()).toInt()
return StreamSupport.stream(indexedArrayListSpliterator(inputMapSettings.areas.withIndex(), inputMapSettings.areas.size), false)
.map { mapLocationParser.parse(it.index % gridSize, it.index / gridSize, it.value) }
.collect(Collectors.toList())
}
} | src/main/kotlin/cz/richter/david/astroants/parser/SequentialInputMapParser.kt | 2373167479 |
package ktx.style
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle
import com.badlogic.gdx.scenes.scene2d.utils.Drawable
import com.kotcrab.vis.ui.Sizes
import com.kotcrab.vis.ui.util.adapter.SimpleListAdapter.SimpleListAdapterStyle
import com.kotcrab.vis.ui.util.form.SimpleFormValidator.FormValidatorStyle
import com.kotcrab.vis.ui.widget.BusyBar.BusyBarStyle
import com.kotcrab.vis.ui.widget.LinkLabel.LinkLabelStyle
import com.kotcrab.vis.ui.widget.ListViewStyle
import com.kotcrab.vis.ui.widget.Menu.MenuStyle
import com.kotcrab.vis.ui.widget.MenuBar.MenuBarStyle
import com.kotcrab.vis.ui.widget.MenuItem.MenuItemStyle
import com.kotcrab.vis.ui.widget.MultiSplitPane.MultiSplitPaneStyle
import com.kotcrab.vis.ui.widget.PopupMenu.PopupMenuStyle
import com.kotcrab.vis.ui.widget.Separator.SeparatorStyle
import com.kotcrab.vis.ui.widget.Tooltip.TooltipStyle
import com.kotcrab.vis.ui.widget.VisCheckBox.VisCheckBoxStyle
import com.kotcrab.vis.ui.widget.VisImageButton.VisImageButtonStyle
import com.kotcrab.vis.ui.widget.VisImageTextButton.VisImageTextButtonStyle
import com.kotcrab.vis.ui.widget.VisSplitPane.VisSplitPaneStyle
import com.kotcrab.vis.ui.widget.VisTextButton.VisTextButtonStyle
import com.kotcrab.vis.ui.widget.VisTextField.VisTextFieldStyle
import com.kotcrab.vis.ui.widget.color.ColorPickerStyle
import com.kotcrab.vis.ui.widget.color.ColorPickerWidgetStyle
import com.kotcrab.vis.ui.widget.spinner.Spinner.SpinnerStyle
import com.kotcrab.vis.ui.widget.tabbedpane.TabbedPane.TabbedPaneStyle
import com.kotcrab.vis.ui.widget.toast.Toast.ToastStyle
import com.nhaarman.mockitokotlin2.mock
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Tests building utilities of VisUI widget styles.
*/
class VisStyleTest {
@Test
fun `should add Sizes`() {
val skin = skin {
sizes {
borderSize = 1f
}
}
val style = skin.get<Sizes>(defaultStyle)
assertEquals(1f, style.borderSize)
}
@Test
fun `should extend Sizes`() {
val skin = skin {
sizes("base") {
borderSize = 1f
}
sizes("new", extend = "base") {
buttonBarSpacing = 1f
}
}
val style = skin.get<Sizes>("new")
assertEquals(1f, style.borderSize)
assertEquals(1f, style.buttonBarSpacing)
}
@Test
fun `should add BusyBarStyle`() {
val skin = skin {
busyBar {
height = 1
}
}
val style = skin.get<BusyBarStyle>(defaultStyle)
assertEquals(1, style.height)
}
@Test
fun `should extend BusyBarStyle`() {
val skin = skin {
busyBar("base") {
height = 1
}
busyBar("new", extend = "base") {
segmentWidth = 1
}
}
val style = skin.get<BusyBarStyle>("new")
assertEquals(1, style.height)
assertEquals(1, style.segmentWidth)
}
@Test
fun `should add ColorPickerStyle`() {
val skin = skin {
colorPicker {
titleFontColor = Color.RED
}
}
val style = skin.get<ColorPickerStyle>(defaultStyle)
assertEquals(Color.RED, style.titleFontColor)
}
@Test
fun `should extend ColorPickerStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
colorPicker("base") {
pickerStyle = it.colorPickerWidget()
titleFontColor = Color.RED
}
colorPicker("new", extend = "base") {
stageBackground = drawable
}
}
val style = skin.get<ColorPickerStyle>("new")
assertEquals(Color.RED, style.titleFontColor)
assertEquals(drawable, style.stageBackground)
}
@Test
fun `should add ColorPickerWidgetStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
colorPickerWidget {
barSelector = drawable
}
}
val style = skin.get<ColorPickerWidgetStyle>(defaultStyle)
assertEquals(drawable, style.barSelector)
}
@Test
fun `should extend ColorPickerWidgetStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
colorPickerWidget("base") {
barSelector = drawable
}
colorPickerWidget("new", extend = "base") {
cross = drawable
}
}
val style = skin.get<ColorPickerWidgetStyle>("new")
assertEquals(drawable, style.barSelector)
assertEquals(drawable, style.cross)
}
@Test
fun `should add FormValidatorStyle`() {
val skin = skin {
formValidator {
colorTransitionDuration = 1f
}
}
val style = skin.get<FormValidatorStyle>(defaultStyle)
assertEquals(1f, style.colorTransitionDuration)
}
@Test
fun `should extend FormValidatorStyle`() {
val skin = skin {
formValidator("base") {
colorTransitionDuration = 1f
}
formValidator("new", extend = "base") {
errorLabelColor = Color.RED
}
}
val style = skin.get<FormValidatorStyle>("new")
assertEquals(1f, style.colorTransitionDuration)
assertEquals(Color.RED, style.errorLabelColor)
}
@Test
fun `should add LinkLabelStyle`() {
val skin = skin {
linkLabel {
fontColor = Color.RED
}
}
val style = skin.get<LinkLabelStyle>(defaultStyle)
assertEquals(Color.RED, style.fontColor)
}
@Test
fun `should extend LinkLabelStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
linkLabel("base") {
fontColor = Color.RED
}
linkLabel("new", extend = "base") {
background = drawable
}
}
val style = skin.get<LinkLabelStyle>("new")
assertEquals(Color.RED, style.fontColor)
assertEquals(drawable, style.background)
}
@Test
fun `should add ListViewStyle`() {
val scrollPane = mock<ScrollPaneStyle>()
val skin = skin {
listView {
scrollPaneStyle = scrollPane
}
}
val style = skin.get<ListViewStyle>(defaultStyle)
assertEquals(scrollPane, style.scrollPaneStyle)
}
@Test
fun `should extend ListViewStyle`() {
val scrollPane = ScrollPaneStyle()
val drawable = mock<Drawable>()
scrollPane.background = drawable
val skin = skin {
listView("base") {
scrollPaneStyle = scrollPane
}
listView("new", extend = "base") {
scrollPaneStyle.corner = drawable
}
}
val style = skin.get<ListViewStyle>("new")
// ScrollPaneStyle is copied, so nested properties are checked:
assertEquals(drawable, style.scrollPaneStyle.background)
assertEquals(drawable, style.scrollPaneStyle.corner)
}
@Test
fun `should add MenuStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
menu {
border = drawable
}
}
val style = skin.get<MenuStyle>(defaultStyle)
assertEquals(drawable, style.border)
}
@Test
fun `should extend MenuStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
menu("base") {
border = drawable
}
menu("new", extend = "base") {
background = drawable
}
}
val style = skin.get<MenuStyle>("new")
assertEquals(drawable, style.border)
assertEquals(drawable, style.background)
}
@Test
fun `should add MenuBarStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
menuBar {
background = drawable
}
}
val style = skin.get<MenuBarStyle>(defaultStyle)
assertEquals(drawable, style.background)
}
@Test
fun `should extend MenuBarStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
menuBar("base") {
background = drawable
}
menuBar("new", extend = "base")
}
val style = skin.get<MenuBarStyle>("new")
assertEquals(drawable, style.background)
}
@Test
fun `should add MenuItemStyle`() {
val skin = skin {
menuItem {
pressedOffsetX = 1f
}
}
val style = skin.get<MenuItemStyle>(defaultStyle)
assertEquals(1f, style.pressedOffsetX)
}
@Test
fun `should extend MenuItemStyle`() {
val skin = skin {
menuItem("base") {
pressedOffsetX = 1f
}
menuItem("new", extend = "base") {
pressedOffsetY = 1f
}
}
val style = skin.get<MenuItemStyle>("new")
assertEquals(1f, style.pressedOffsetX)
assertEquals(1f, style.pressedOffsetY)
}
@Test
fun `should add MultiSplitPaneStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
multiSplitPane {
handle = drawable
}
}
val style = skin.get<MultiSplitPaneStyle>(defaultStyle)
assertEquals(drawable, style.handle)
}
@Test
fun `should extend MultiSplitPaneStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
multiSplitPane("base") {
handle = drawable
}
multiSplitPane("new", extend = "base") {
handleOver = drawable
}
}
val style = skin.get<MultiSplitPaneStyle>("new")
assertEquals(drawable, style.handle)
assertEquals(drawable, style.handleOver)
}
@Test
fun `should add PopupMenuStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
popupMenu {
background = drawable
}
}
val style = skin.get<PopupMenuStyle>(defaultStyle)
assertEquals(drawable, style.background)
}
@Test
fun `should extend PopupMenuStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
popupMenu("base") {
background = drawable
}
popupMenu("new", extend = "base") {
border = drawable
}
}
val style = skin.get<PopupMenuStyle>("new")
assertEquals(drawable, style.background)
assertEquals(drawable, style.border)
}
@Test
fun `should add SeparatorStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
separator {
background = drawable
}
}
val style = skin.get<SeparatorStyle>(defaultStyle)
assertEquals(drawable, style.background)
}
@Test
fun `should extend SeparatorStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
separator("base") {
background = drawable
}
separator("new", extend = "base") {
thickness = 1
}
}
val style = skin.get<SeparatorStyle>("new")
assertEquals(drawable, style.background)
assertEquals(1, style.thickness)
}
@Test
fun `should add SimpleListAdapterStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
simpleListAdapter {
background = drawable
}
}
val style = skin.get<SimpleListAdapterStyle>(defaultStyle)
assertEquals(drawable, style.background)
}
@Test
fun `should extend SimpleListAdapterStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
simpleListAdapter("base") {
background = drawable
}
simpleListAdapter("new", extend = "base") {
selection = drawable
}
}
val style = skin.get<SimpleListAdapterStyle>("new")
assertEquals(drawable, style.background)
assertEquals(drawable, style.selection)
}
@Test
fun `should add SpinnerStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
spinner {
down = drawable
}
}
val style = skin.get<SpinnerStyle>(defaultStyle)
assertEquals(drawable, style.down)
}
@Test
fun `should extend SpinnerStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
spinner("base") {
down = drawable
}
spinner("new", extend = "base") {
up = drawable
}
}
val style = skin.get<SpinnerStyle>("new")
assertEquals(drawable, style.down)
assertEquals(drawable, style.up)
}
@Test
fun `should add TabbedPaneStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
tabbedPane {
background = drawable
}
}
val style = skin.get<TabbedPaneStyle>(defaultStyle)
assertEquals(drawable, style.background)
}
@Test
fun `should extend TabbedPaneStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
tabbedPane("base") {
background = drawable
}
tabbedPane("new", extend = "base") {
vertical = true
}
}
val style = skin.get<TabbedPaneStyle>("new")
assertEquals(drawable, style.background)
assertEquals(true, style.vertical)
}
@Test
fun `should add ToastStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
toast {
background = drawable
}
}
val style = skin.get<ToastStyle>(defaultStyle)
assertEquals(drawable, style.background)
}
@Test
fun `should extend ToastStyle`() {
val drawable = mock<Drawable>()
val buttonStyle = mock<VisImageButtonStyle>()
val skin = skin {
toast("base") {
background = drawable
}
toast("new", extend = "base") {
closeButtonStyle = buttonStyle
}
}
val style = skin.get<ToastStyle>("new")
assertEquals(drawable, style.background)
assertEquals(buttonStyle, style.closeButtonStyle)
}
@Test
fun `should add VisCheckBoxStyle`() {
val skin = skin {
visCheckBox {
pressedOffsetX = 1f
}
}
val style = skin.get<VisCheckBoxStyle>(defaultStyle)
assertEquals(1f, style.pressedOffsetX)
}
@Test
fun `should extend VisCheckBoxStyle`() {
val skin = skin {
visCheckBox("base") {
pressedOffsetX = 1f
}
visCheckBox("new", extend = "base") {
pressedOffsetY = 1f
}
}
val style = skin.get<VisCheckBoxStyle>("new")
assertEquals(1f, style.pressedOffsetX)
assertEquals(1f, style.pressedOffsetY)
}
@Test
fun `should add VisImageButtonStyle`() {
val skin = skin {
visImageButton {
pressedOffsetX = 1f
}
}
val style = skin.get<VisImageButtonStyle>(defaultStyle)
assertEquals(1f, style.pressedOffsetX)
}
@Test
fun `should extend VisImageButtonStyle`() {
val skin = skin {
visImageButton("base") {
pressedOffsetX = 1f
}
visImageButton("new", extend = "base") {
pressedOffsetY = 1f
}
}
val style = skin.get<VisImageButtonStyle>("new")
assertEquals(1f, style.pressedOffsetX)
assertEquals(1f, style.pressedOffsetY)
}
@Test
fun `should add VisImageTextButtonStyle`() {
val skin = skin {
visImageTextButton {
pressedOffsetX = 1f
}
}
val style = skin.get<VisImageTextButtonStyle>(defaultStyle)
assertEquals(1f, style.pressedOffsetX)
}
@Test
fun `should extend VisImageTextButtonStyle`() {
val skin = skin {
visImageTextButton("base") {
pressedOffsetX = 1f
}
visImageTextButton("new", extend = "base") {
pressedOffsetY = 1f
}
}
val style = skin.get<VisImageTextButtonStyle>("new")
assertEquals(1f, style.pressedOffsetX)
assertEquals(1f, style.pressedOffsetY)
}
@Test
fun `should add VisSplitPaneStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
visSplitPane {
handle = drawable
}
}
val style = skin.get<VisSplitPaneStyle>(defaultStyle)
assertEquals(drawable, style.handle)
}
@Test
fun `should extend VisSplitPaneStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
visSplitPane("base") {
handle = drawable
}
visSplitPane("new", extend = "base") {
handleOver = drawable
}
}
val style = skin.get<VisSplitPaneStyle>("new")
assertEquals(drawable, style.handle)
assertEquals(drawable, style.handleOver)
}
@Test
fun `should add VisTextButtonStyle`() {
val skin = skin {
visTextButton {
pressedOffsetX = 1f
}
}
val style = skin.get<VisTextButtonStyle>(defaultStyle)
assertEquals(1f, style.pressedOffsetX)
}
@Test
fun `should extend VisTextButtonStyle`() {
val skin = skin {
visTextButton("base") {
pressedOffsetX = 1f
}
visTextButton("new", extend = "base") {
pressedOffsetY = 1f
}
}
val style = skin.get<VisTextButtonStyle>("new")
assertEquals(1f, style.pressedOffsetX)
assertEquals(1f, style.pressedOffsetY)
}
@Test
fun `should add VisTextFieldStyle`() {
val skin = skin {
visTextField {
fontColor = Color.CYAN
}
}
val style = skin.get<VisTextFieldStyle>(defaultStyle)
assertEquals(Color.CYAN, style.fontColor)
}
@Test
fun `should extend VisTextFieldStyle`() {
val skin = skin {
visTextField("base") {
fontColor = Color.CYAN
}
visTextField("new", extend = "base") {
disabledFontColor = Color.BLACK
}
}
val style = skin.get<VisTextFieldStyle>("new")
assertEquals(Color.CYAN, style.fontColor)
assertEquals(Color.BLACK, style.disabledFontColor)
}
@Test
fun `should add VisTooltipStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
visTooltip {
background = drawable
}
}
val style = skin.get<TooltipStyle>(defaultStyle)
assertEquals(drawable, style.background)
}
@Test
fun `should extend VisTooltipStyle`() {
val drawable = mock<Drawable>()
val skin = skin {
visTooltip("base") {
background = drawable
}
visTooltip("new", extend = "base")
}
val style = skin.get<TooltipStyle>("new")
assertEquals(drawable, style.background)
}
}
| vis-style/src/test/kotlin/ktx/style/VisStyleTest.kt | 2569517412 |
package jp.yitt.filter
import android.graphics.Rect
import android.support.v7.widget.RecyclerView
import android.view.View
class TopBottomMarginItemDecoration(val topMarginPx: Int, val bottomMarginPx: Int) :
RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val itemCount = parent.adapter.itemCount
val position = parent.getChildAdapterPosition(view)
if (position == 0) {
outRect.top = topMarginPx
}
if (position == itemCount - 1) {
outRect.bottom = bottomMarginPx
}
}
}
| app/src/main/java/jp/yitt/filter/TopBottomMarginItemDecoration.kt | 512266731 |
package demo.kafka
import demo.kafka.generated.CityRain
import org.slf4j.LoggerFactory
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.stereotype.Component
@Component
class CityRainKafkaAdapter(private val cityRainKafkaTemplate: KafkaTemplate<String, CityRain>) {
private val log = LoggerFactory.getLogger(CityRainKafkaAdapter::class.java)
private val topic = "city_rain"
init {
log.info("init with kafkaTemplate=$cityRainKafkaTemplate")
}
fun updateCity(city: String, rain: CityRain) {
log.info("updateCity($city, $rain)")
cityRainKafkaTemplate.send(topic, city, rain)
}
}
| java_test_springboot_kafka/kafka_only/src/main/kotlin/demo/kafka/CityRainKafkaAdapter.kt | 532719738 |
package com.habitrpg.android.habitica.ui.views.navigation
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.BottomNavigationItemBinding
import com.habitrpg.common.habitica.extensions.getThemeColor
import com.habitrpg.common.habitica.extensions.isUsingNightModeResources
import com.habitrpg.common.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.extensions.setTintWith
class BottomNavigationItem @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
private var selectedIcon: Drawable? = null
private var icon: Drawable? = null
private val binding = BottomNavigationItemBinding.inflate(context.layoutInflater, this)
private var selectedVisibility = View.VISIBLE
private var deselectedVisibility = View.VISIBLE
var isActive = false
set(value) {
field = value
if (isActive) {
binding.selectedTitleView.visibility = selectedVisibility
binding.titleView.visibility = View.GONE
binding.iconView.setImageDrawable(selectedIcon)
if (context.isUsingNightModeResources()) {
binding.iconView.drawable.setTintWith(context.getThemeColor(R.attr.colorPrimaryDistinct), PorterDuff.Mode.SRC_ATOP)
} else {
binding.iconView.drawable.setTintWith(ContextCompat.getColor(context, R.color.white), PorterDuff.Mode.SRC_ATOP)
}
} else {
binding.selectedTitleView.visibility = View.GONE
binding.iconView.setImageDrawable(icon)
binding.titleView.visibility = deselectedVisibility
binding.iconView.drawable.setTintWith(context.getThemeColor(R.attr.textColorPrimaryDark), PorterDuff.Mode.SRC_ATOP)
}
}
var badgeCount: Int = 0
set(value) {
field = value
if (value == 0) {
binding.badge.visibility = View.INVISIBLE
} else {
binding.badge.visibility = View.VISIBLE
binding.badge.text = value.toString()
}
}
init {
val attributes = context.theme?.obtainStyledAttributes(
attrs,
R.styleable.BottomNavigationItem,
0, 0
)
if (attributes != null) {
icon = attributes.getDrawable(R.styleable.BottomNavigationItem_iconDrawable)
selectedIcon = attributes.getDrawable(R.styleable.BottomNavigationItem_selectedIconDrawable)
binding.iconView.setImageDrawable(icon)
binding.titleView.text = attributes.getString(R.styleable.BottomNavigationItem_title)
binding.selectedTitleView.text = attributes.getString(R.styleable.BottomNavigationItem_title)
}
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/navigation/BottomNavigationItem.kt | 4130551447 |
/*
* Copyright (C) 2020-2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpath.ast.plugin
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathPostfixExpr
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmLookupExpression
/**
* An XPath 3.0 and XQuery 3.0 `PostfixExpr` node in the XPath and XQuery AST
* that is associated with a `Lookup` node.
*/
interface PluginPostfixLookup : XPathPostfixExpr, XpmLookupExpression
| src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/plugin/PluginPostfixLookup.kt | 1136301965 |
package de.westnordost.streetcomplete.data.elementfilter.filters
import java.util.*
/** older 2002-11-11 / older today - 1 year */
class ElementOlderThan(dateFilter: DateFilter) : CompareElementAge(dateFilter) {
override fun compareTo(tagValue: Date) = tagValue < date
override val operator = "<"
} | app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/filters/ElementOlderThan.kt | 1468727156 |
/*
* MIT License
*
* Copyright (c) 2020. Nicholas Doglio
*
* 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.nicholasdoglio.eyebleach.util
import android.content.Context
import android.content.Intent
import android.net.Uri
fun Context.openWebPage(url: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
if (intent.resolveActivity(this.packageManager) != null) {
this.startActivity(intent)
}
}
fun Context.shareUrl(url: String) {
this.startActivity(
Intent.createChooser(
Intent(Intent.ACTION_SEND).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TASK
putExtra(Intent.EXTRA_TEXT, url)
type = "text/plain"
},
"Share your cute animals via: "
)
)
}
| app/src/main/java/com/nicholasdoglio/eyebleach/util/PresentationExtensions.kt | 3043280323 |
/* Copyright 2021 Braden Farmer
*
* 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.
*/
@file:OptIn(ExperimentalFoundationApi::class)
package com.farmerbb.notepad.ui.content
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.text.BasicText
import androidx.compose.material.Divider
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.farmerbb.notepad.R
import com.farmerbb.notepad.model.NoteMetadata
import com.farmerbb.notepad.ui.components.RtlTextWrapper
import com.farmerbb.notepad.ui.previews.NoteListPreview
import com.farmerbb.notepad.utils.safeGetOrDefault
import java.text.DateFormat
import java.util.Date
private val Date.noteListFormat: String get() = DateFormat
.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
.format(this)
@Composable
fun NoteListContent(
notes: List<NoteMetadata>,
selectedNotes: Map<Long, Boolean> = emptyMap(),
textStyle: TextStyle = TextStyle(),
dateStyle: TextStyle = TextStyle(),
showDate: Boolean = false,
rtlLayout: Boolean = false,
onNoteLongClick: (Long) -> Unit = {},
onNoteClick: (Long) -> Unit = {}
) {
when (notes.size) {
0 -> Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(id = R.string.no_notes_found),
color = colorResource(id = R.color.primary),
fontWeight = FontWeight.Thin,
fontSize = 30.sp
)
}
else -> LazyColumn {
itemsIndexed(notes) { _, note ->
val isSelected = selectedNotes.safeGetOrDefault(note.metadataId, false)
Column(modifier = Modifier
.then(
if (isSelected) {
Modifier.background(color = colorResource(id = R.color.praise_duarte))
} else Modifier
)
.combinedClickable(
onClick = { onNoteClick(note.metadataId) },
onLongClick = { onNoteLongClick(note.metadataId) }
)
) {
RtlTextWrapper(note.title, rtlLayout) {
BasicText(
text = note.title,
style = textStyle,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.fillMaxWidth()
.padding(
start = 16.dp,
end = 16.dp,
top = if (showDate) 8.dp else 12.dp,
bottom = if (showDate) 0.dp else 12.dp
)
)
}
if (showDate) {
BasicText(
text = note.date.noteListFormat,
style = dateStyle,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.align(Alignment.End)
.padding(
start = 16.dp,
end = 16.dp,
bottom = 8.dp
)
)
}
Divider()
}
}
}
}
}
@Preview
@Composable
fun NoteListContentPreview() = NoteListPreview() | app/src/main/java/com/farmerbb/notepad/ui/content/NoteListContent.kt | 118084631 |
package eu.kanade.tachiyomi.ui.library
import com.pushtorefresh.storio.sqlite.queries.RawQuery
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.tables.MangaTable
import exh.isLewdSource
import exh.metadata.sql.tables.SearchMetadataTable
import exh.search.SearchEngine
import exh.util.await
import exh.util.cancellable
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.toList
import timber.log.Timber
import uy.kohesive.injekt.injectLazy
/**
* Adapter storing a list of manga in a certain category.
*
* @param view the fragment containing this adapter.
*/
class LibraryCategoryAdapter(val view: LibraryCategoryView) :
FlexibleAdapter<LibraryItem>(null, view, true) {
// EXH -->
private val db: DatabaseHelper by injectLazy()
private val searchEngine = SearchEngine()
private var lastFilterJob: Job? = null
// Keep compatibility as searchText field was replaced when we upgraded FlexibleAdapter
var searchText
get() = getFilter(String::class.java) ?: ""
set(value) { setFilter(value) }
// EXH <--
/**
* The list of manga in this category.
*/
private var mangas: List<LibraryItem> = emptyList()
/**
* Sets a list of manga in the adapter.
*
* @param list the list to set.
*/
suspend fun setItems(cScope: CoroutineScope, list: List<LibraryItem>) {
// A copy of manga always unfiltered.
mangas = list.toList()
performFilter(cScope)
}
/**
* Returns the position in the adapter for the given manga.
*
* @param manga the manga to find.
*/
fun indexOf(manga: Manga): Int {
return currentItems.indexOfFirst { it.manga.id == manga.id }
}
// EXH -->
// Note that we cannot use FlexibleAdapter's built in filtering system as we cannot cancel it
// (well technically we can cancel it by invoking filterItems again but that doesn't work when
// we want to perform a no-op filter)
suspend fun performFilter(cScope: CoroutineScope) {
lastFilterJob?.cancel()
if(mangas.isNotEmpty() && searchText.isNotBlank()) {
val savedSearchText = searchText
val job = cScope.launch(Dispatchers.IO) {
val newManga = try {
// Prepare filter object
val parsedQuery = searchEngine.parseQuery(savedSearchText)
val sqlQuery = searchEngine.queryToSql(parsedQuery)
val queryResult = db.lowLevel().rawQuery(RawQuery.builder()
.query(sqlQuery.first)
.args(*sqlQuery.second.toTypedArray())
.build())
ensureActive() // Fail early when cancelled
val mangaWithMetaIdsQuery = db.getIdsOfFavoriteMangaWithMetadata().await()
val mangaWithMetaIds = LongArray(mangaWithMetaIdsQuery.count)
if(mangaWithMetaIds.isNotEmpty()) {
val mangaIdCol = mangaWithMetaIdsQuery.getColumnIndex(MangaTable.COL_ID)
mangaWithMetaIdsQuery.moveToFirst()
while (!mangaWithMetaIdsQuery.isAfterLast) {
ensureActive() // Fail early when cancelled
mangaWithMetaIds[mangaWithMetaIdsQuery.position] = mangaWithMetaIdsQuery.getLong(mangaIdCol)
mangaWithMetaIdsQuery.moveToNext()
}
}
ensureActive() // Fail early when cancelled
val convertedResult = LongArray(queryResult.count)
if(convertedResult.isNotEmpty()) {
val mangaIdCol = queryResult.getColumnIndex(SearchMetadataTable.COL_MANGA_ID)
queryResult.moveToFirst()
while (!queryResult.isAfterLast) {
ensureActive() // Fail early when cancelled
convertedResult[queryResult.position] = queryResult.getLong(mangaIdCol)
queryResult.moveToNext()
}
}
ensureActive() // Fail early when cancelled
// Flow the mangas to allow cancellation of this filter operation
mangas.asFlow().cancellable().filter { item ->
if(isLewdSource(item.manga.source)) {
val mangaId = item.manga.id ?: -1
if(convertedResult.binarySearch(mangaId) < 0) {
// Check if this manga even has metadata
if(mangaWithMetaIds.binarySearch(mangaId) < 0) {
// No meta? Filter using title
item.filter(savedSearchText)
} else false
} else true
} else {
item.filter(savedSearchText)
}
}.toList()
} catch (e: Exception) {
// Do not catch cancellations
if(e is CancellationException) throw e
Timber.w(e, "Could not filter mangas!")
mangas
}
withContext(Dispatchers.Main) {
updateDataSet(newManga)
}
}
lastFilterJob = job
job.join()
} else {
updateDataSet(mangas)
}
}
// EXH <--
}
| app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryAdapter.kt | 2818791376 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.xdebugger.XDebuggerBundle
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XValueChildrenList
import com.intellij.xdebugger.frame.XValueGroup
import org.jetbrains.concurrency.done
import org.jetbrains.concurrency.rejected
import org.jetbrains.concurrency.thenAsyncAccept
class ScopeVariablesGroup(val scope: Scope, parentContext: VariableContext, callFrame: CallFrame?) : XValueGroup(scope.createScopeNodeName()) {
private val context = createVariableContext(scope, parentContext, callFrame)
private val callFrame = if (scope.type == ScopeType.LOCAL) callFrame else null
override fun isAutoExpand() = scope.type == ScopeType.LOCAL || scope.type == ScopeType.CATCH
override fun getComment(): String? {
val className = scope.description
return if ("Object" == className) null else className
}
override fun computeChildren(node: XCompositeNode) {
val promise = processScopeVariables(scope, node, context, callFrame == null)
if (callFrame == null) {
return
}
promise
.done(node) {
context.memberFilter
.thenAsyncAccept(node) {
if (it.hasNameMappings()) {
it.sourceNameToRaw(RECEIVER_NAME)?.let {
return@thenAsyncAccept callFrame.evaluateContext.evaluate(it)
.done(node) {
VariableImpl(RECEIVER_NAME, it.value, null)
node.addChildren(XValueChildrenList.singleton(VariableView(
VariableImpl(RECEIVER_NAME, it.value, null), context)), true)
}
}
}
context.viewSupport.computeReceiverVariable(context, callFrame, node)
}
.rejected(node) {
context.viewSupport.computeReceiverVariable(context, callFrame, node)
}
}
}
}
fun createAndAddScopeList(node: XCompositeNode, scopes: List<Scope>, context: VariableContext, callFrame: CallFrame?) {
val list = XValueChildrenList(scopes.size)
for (scope in scopes) {
list.addTopGroup(ScopeVariablesGroup(scope, context, callFrame))
}
node.addChildren(list, true)
}
fun createVariableContext(scope: Scope, parentContext: VariableContext, callFrame: CallFrame?): VariableContext {
if (callFrame == null || scope.type == ScopeType.LIBRARY) {
// functions scopes - we can watch variables only from global scope
return ParentlessVariableContext(parentContext, scope, scope.type == ScopeType.GLOBAL)
}
else {
return VariableContextWrapper(parentContext, scope)
}
}
private class ParentlessVariableContext(parentContext: VariableContext, scope: Scope, private val watchableAsEvaluationExpression: Boolean) : VariableContextWrapper(parentContext, scope) {
override fun watchableAsEvaluationExpression() = watchableAsEvaluationExpression
}
private fun Scope.createScopeNodeName(): String {
when (type) {
ScopeType.GLOBAL -> return XDebuggerBundle.message("scope.global")
ScopeType.LOCAL -> return XDebuggerBundle.message("scope.local")
ScopeType.WITH -> return XDebuggerBundle.message("scope.with")
ScopeType.CLOSURE -> return XDebuggerBundle.message("scope.closure")
ScopeType.CATCH -> return XDebuggerBundle.message("scope.catch")
ScopeType.LIBRARY -> return XDebuggerBundle.message("scope.library")
ScopeType.INSTANCE -> return XDebuggerBundle.message("scope.instance")
ScopeType.CLASS -> return XDebuggerBundle.message("scope.class")
ScopeType.BLOCK -> return XDebuggerBundle.message("scope.block")
ScopeType.SCRIPT -> return XDebuggerBundle.message("scope.script")
ScopeType.UNKNOWN -> return XDebuggerBundle.message("scope.unknown")
else -> throw IllegalArgumentException(type.name)
}
} | platform/script-debugger/debugger-ui/src/ScopeVariablesGroup.kt | 2076277407 |
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message
import com.google.crypto.tink.subtle.Hex
import info.nightscout.androidaps.extensions.toHex
import org.junit.Assert.assertEquals
import org.junit.Test
class StringLengthPrefixEncodingTest {
private val p0Payload = Hex.decode("50,30,3d,00,01,a5".replace(",", "")) // from logs
private val p0Content = Hex.decode("a5")
@Test fun testFormatKeysP0() {
val payload = StringLengthPrefixEncoding.formatKeys(arrayOf("P0="), arrayOf(p0Content))
assertEquals(p0Payload.toHex(), payload.toHex())
}
@Test fun testParseKeysP0() {
val parsed = StringLengthPrefixEncoding.parseKeys(arrayOf("P0="), p0Payload)
assertEquals(parsed.size, 1)
assertEquals(parsed[0].toHex(), p0Content.toHex())
}
}
| omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/StringLengthPrefixEncodingTest.kt | 3925070428 |
package info.nightscout.androidaps.data
import android.content.Context
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.database.entities.Bolus
import info.nightscout.androidaps.database.entities.BolusCalculatorResult
import info.nightscout.androidaps.database.entities.TherapyEvent
import org.apache.commons.lang3.builder.EqualsBuilder
import org.junit.Assert
import org.junit.Test
import org.mockito.Mock
class DetailedBolusInfoTest : TestBase() {
@Mock lateinit var context: Context
@Test fun toStringShouldBeOverloaded() {
val detailedBolusInfo = DetailedBolusInfo()
Assert.assertEquals(true, detailedBolusInfo.toString().contains("insulin"))
}
@Test fun copyShouldCopyAllProperties() {
val d1 = DetailedBolusInfo()
d1.deliverAtTheLatest = 123
val d2 = d1.copy()
Assert.assertEquals(true, EqualsBuilder.reflectionEquals(d2, d1))
}
@Test
fun shouldAllowSerialization() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.bolusCalculatorResult = createBolusCalculatorResult()
detailedBolusInfo.context = context
detailedBolusInfo.eventType = DetailedBolusInfo.EventType.BOLUS_WIZARD
val serialized = detailedBolusInfo.toJsonString()
val deserialized = DetailedBolusInfo.fromJsonString(serialized)
Assert.assertEquals(1L, deserialized.bolusCalculatorResult?.timestamp)
Assert.assertEquals(DetailedBolusInfo.EventType.BOLUS_WIZARD, deserialized.eventType)
// Context should be excluded
Assert.assertNull(deserialized.context)
}
@Test
fun generateTherapyEventTest() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.timestamp = 1000
detailedBolusInfo.notes = "note"
detailedBolusInfo.mgdlGlucose = 180.0
detailedBolusInfo.glucoseType = DetailedBolusInfo.MeterType.FINGER
val therapyEvent = detailedBolusInfo.createTherapyEvent()
Assert.assertEquals(1000L, therapyEvent.timestamp)
Assert.assertEquals(TherapyEvent.Type.MEAL_BOLUS, therapyEvent.type)
Assert.assertEquals(TherapyEvent.GlucoseUnit.MGDL, therapyEvent.glucoseUnit)
Assert.assertEquals("note", therapyEvent.note)
Assert.assertEquals(180.0, therapyEvent.glucose)
Assert.assertEquals(TherapyEvent.MeterType.FINGER, therapyEvent.glucoseType)
}
@Test
fun generateBolus() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.timestamp = 1000
detailedBolusInfo.bolusType = DetailedBolusInfo.BolusType.SMB
detailedBolusInfo.insulin = 7.0
val bolus = detailedBolusInfo.createBolus()
Assert.assertEquals(1000L, bolus?.timestamp)
Assert.assertEquals(Bolus.Type.SMB, bolus?.type)
Assert.assertEquals(7.0, bolus?.amount)
}
@Test
fun generateCarbs() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.timestamp = 1000
detailedBolusInfo.carbs = 6.0
val carbs = detailedBolusInfo.createCarbs()
Assert.assertEquals(1000L, carbs?.timestamp)
Assert.assertEquals(6.0, carbs?.amount)
}
private fun createBolusCalculatorResult(): BolusCalculatorResult =
BolusCalculatorResult(
timestamp = 1,
targetBGLow = 5.0,
targetBGHigh = 5.0,
isf = 5.0,
ic = 5.0,
bolusIOB = 1.0,
wasBolusIOBUsed = true,
basalIOB = 1.0,
wasBasalIOBUsed = true,
glucoseValue = 10.0,
wasGlucoseUsed = true,
glucoseDifference = 1.0,
glucoseInsulin = 1.0,
glucoseTrend = 1.0,
wasTrendUsed = true,
trendInsulin = 1.0,
cob = 10.0,
wasCOBUsed = true,
cobInsulin = 1.0,
carbs = 5.0,
wereCarbsUsed = true,
carbsInsulin = 1.0,
otherCorrection = 1.0,
wasSuperbolusUsed = true,
superbolusInsulin = 1.0,
wasTempTargetUsed = true,
totalInsulin = 15.0,
percentageCorrection = 50,
profileName = "profile",
note = ""
)
} | core/src/test/java/info/nightscout/androidaps/data/DetailedBolusInfoTest.kt | 2707845373 |
/*
* 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 khttp.structures.authorization
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.util.Base64
import kotlin.test.assertEquals
class BasicAuthorizationSpec : Spek({
describe("a BasicAuthorization object") {
val username = "test"
val password = "hunter2"
val base64 = "Basic " + Base64.getEncoder().encode("$username:$password".toByteArray()).toString(Charsets.UTF_8)
val auth = BasicAuthorization(username, password)
context("checking the username") {
val authUsername = auth.user
it("should equal the original") {
assertEquals(username, authUsername)
}
}
context("checking the password") {
val authPassword = auth.password
it("should equal the original") {
assertEquals(password, authPassword)
}
}
context("checking the header") {
val (header, value) = auth.header
it("should have a first value of \"Authorization\"") {
assertEquals("Authorization", header)
}
it("should have a second value of the Base64 encoding") {
assertEquals(base64, value)
}
}
}
})
| src/test/kotlin/khttp/structures/authorization/BasicAuthorizationSpec.kt | 1014991771 |
package me.toptas.rssreader.model
/**
* Created by ftoptas on 24/07/18.
*/
data class Error(val code: Int = 0,
var message: String = "") {
companion object {
const val ERROR_GENERIC = -1
const val ERROR_NETWORK = -2
fun generic() = Error(code = ERROR_GENERIC)
fun network() = Error(code = ERROR_NETWORK)
}
} | app/src/main/java/me/toptas/rssreader/model/Error.kt | 1583919011 |
package io.redutan.nbasearc.monitoring.collector
import io.redutan.nbasearc.monitoring.collector.parser.ByteValue
import io.redutan.nbasearc.monitoring.collector.parser.EMPTY_BYTE_VALUE
import java.time.LocalDateTime
val UNKNOWN_STAT: Stat = Stat(LocalDateTime.MIN)
data class Stat(override val loggedAt: LocalDateTime,
val redis: Long,
val pg: Long,
val connection: Long,
val mem: ByteValue,
val ops: Long,
val hits: Long,
val misses: Long,
val keys: Long,
val expires: Long,
override val errorDescription: String = "")
: NbaseArcLog {
constructor(loggedAt: LocalDateTime, errorDescription: String = "")
: this(loggedAt, -1, -1, -1, EMPTY_BYTE_VALUE, -1, -1, -1, -1, -1, errorDescription)
override fun isUnknown(): Boolean {
return this == UNKNOWN_STAT
}
}
| src/main/kotlin/io/redutan/nbasearc/monitoring/collector/Stat.kt | 1456286472 |
package venus.riscv.insts.dsl.disasms
import venus.riscv.MachineCode
class RawDisassembler(private val disasm: (MachineCode) -> String) : InstructionDisassembler {
override fun invoke(mcode: MachineCode): String = disasm(mcode)
}
| src/main/kotlin/venus/riscv/insts/dsl/disasms/RawDisassembler.kt | 855864724 |
/*
* Copyright 2015 Realm 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 io.realm.examples.kotlin.model
import io.realm.RealmObject
import io.realm.RealmResults
import io.realm.annotations.LinkingObjects
open class Dog : RealmObject() {
var name: String? = null
@LinkingObjects("dog")
val owners: RealmResults<Person>? = null
}
| expert/realm-java/examples/kotlinExample/src/main/kotlin/io/realm/examples/kotlin/model/Dog.kt | 393221840 |
package com.task.data.remote
import com.task.data.Resource
import com.task.data.dto.recipes.Recipes
/**
* Created by AhmedEltaher
*/
internal interface RemoteDataSource {
suspend fun requestRecipes(): Resource<Recipes>
}
| app/src/main/java/com/task/data/remote/RemoteDataSource.kt | 4075504695 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.ui
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.NlsActions.ActionDescription
import com.intellij.openapi.util.NlsActions.ActionText
import javax.swing.Icon
import javax.swing.JButton
import javax.swing.JComponent
abstract class JButtonAction(text: @ActionText String?, @ActionDescription description: String? = null, icon: Icon? = null)
: DumbAwareAction(text, description, icon), CustomComponentAction {
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
val button = createButton()
button.addActionListener {
performAction(button, place, presentation)
}
button.text = presentation.getText(true)
return button
}
protected fun performAction(component: JComponent, place: String, presentation: Presentation) {
val dataContext = ActionToolbar.getDataContextFor(component)
val event = AnActionEvent.createFromInputEvent(null, place, presentation, dataContext)
if (ActionUtil.lastUpdateAndCheckDumb(this, event, true)) {
ActionUtil.performActionDumbAwareWithCallbacks(this, event)
}
}
protected open fun createButton(): JButton = JButton().configureForToolbar()
protected fun JButton.configureForToolbar(): JButton =
apply {
isFocusable = false
font = JBUI.Fonts.toolbarFont()
putClientProperty("ActionToolbar.smallVariant", true)
}
override fun updateCustomComponent(component: JComponent, presentation: Presentation) {
if (component is JButton) {
updateButtonFromPresentation(component, presentation)
}
}
protected open fun updateButtonFromPresentation(button: JButton, presentation: Presentation) {
button.isEnabled = presentation.isEnabled
button.isVisible = presentation.isVisible
button.text = presentation.getText(true)
button.icon = presentation.icon
button.mnemonic = presentation.mnemonic
button.displayedMnemonicIndex = presentation.displayedMnemonicIndex
button.toolTipText = presentation.description
}
} | platform/vcs-impl/src/com/intellij/util/ui/JButtonAction.kt | 1657019329 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.evaluate
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.evaluation.EvaluateException
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.containers.MultiMap
import org.jetbrains.annotations.TestOnly
import org.jetbrains.eval4j.Value
import org.jetbrains.kotlin.codegen.inline.SMAP
import org.jetbrains.kotlin.idea.debugger.BinaryCacheKey
import org.jetbrains.kotlin.idea.debugger.createWeakBytecodeDebugInfoStorage
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CompiledDataDescriptor
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtCodeFragment
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.types.KotlinType
import java.util.*
import java.util.concurrent.ConcurrentHashMap
class KotlinDebuggerCaches(project: Project) {
private val cachedCompiledData = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result<MultiMap<String, CompiledDataDescriptor>>(
MultiMap.create(), PsiModificationTracker.MODIFICATION_COUNT
)
}, false
)
private val cachedClassNames = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result<MutableMap<PsiElement, List<String>>>(
ConcurrentHashMap(),
PsiModificationTracker.MODIFICATION_COUNT
)
}, false
)
private val debugInfoCache = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result(
createWeakBytecodeDebugInfoStorage(),
PsiModificationTracker.MODIFICATION_COUNT
)
}, false
)
companion object {
private val LOG = Logger.getInstance(KotlinDebuggerCaches::class.java)
@get:TestOnly
var LOG_COMPILATIONS: Boolean = false
fun getInstance(project: Project): KotlinDebuggerCaches = project.service()
fun compileCodeFragmentCacheAware(
codeFragment: KtCodeFragment,
sourcePosition: SourcePosition?,
compileCode: () -> CompiledDataDescriptor,
force: Boolean = false
): Pair<CompiledDataDescriptor, Boolean> {
if (sourcePosition == null) {
return Pair(compileCode(), false)
}
val evaluateExpressionCache = getInstance(codeFragment.project)
val text = "${codeFragment.importsToString()}\n${codeFragment.text}"
val cachedResults = synchronized<Collection<CompiledDataDescriptor>>(evaluateExpressionCache.cachedCompiledData) {
evaluateExpressionCache.cachedCompiledData.value[text]
}
val existingResult = cachedResults.firstOrNull { it.sourcePosition == sourcePosition }
if (existingResult != null) {
if (force) {
synchronized(evaluateExpressionCache.cachedCompiledData) {
evaluateExpressionCache.cachedCompiledData.value.remove(text, existingResult)
}
} else {
return Pair(existingResult, true)
}
}
val newCompiledData = compileCode()
if (LOG_COMPILATIONS) {
LOG.debug("Compile bytecode for ${codeFragment.text}")
}
synchronized(evaluateExpressionCache.cachedCompiledData) {
evaluateExpressionCache.cachedCompiledData.value.putValue(text, newCompiledData)
}
return Pair(newCompiledData, false)
}
fun <T : PsiElement> getOrComputeClassNames(psiElement: T?, create: (T) -> ComputedClassNames): List<String> {
if (psiElement == null) return Collections.emptyList()
val cache = getInstance(runReadAction { psiElement.project })
val classNamesCache = cache.cachedClassNames.value
val cachedValue = classNamesCache[psiElement]
if (cachedValue != null) return cachedValue
val computedClassNames = create(psiElement)
if (computedClassNames.shouldBeCached) {
classNamesCache[psiElement] = computedClassNames.classNames
}
return computedClassNames.classNames
}
fun getSmapCached(project: Project, jvmName: JvmClassName, file: VirtualFile): SMAP? {
return getInstance(project).debugInfoCache.value[BinaryCacheKey(project, jvmName, file)]
}
}
data class Parameter(val callText: String, val type: KotlinType, val value: Value? = null, val error: EvaluateException? = null)
class ComputedClassNames(val classNames: List<String>, val shouldBeCached: Boolean) {
@Suppress("FunctionName")
companion object {
val EMPTY = Cached(emptyList())
fun Cached(classNames: List<String>) = ComputedClassNames(classNames, true)
fun Cached(className: String) = ComputedClassNames(Collections.singletonList(className), true)
fun NonCached(classNames: List<String>) = ComputedClassNames(classNames, false)
}
fun isEmpty() = classNames.isEmpty()
fun distinct() = ComputedClassNames(classNames.distinct(), shouldBeCached)
operator fun plus(other: ComputedClassNames) = ComputedClassNames(
classNames + other.classNames, shouldBeCached && other.shouldBeCached
)
}
} | plugins/kotlin/jvm-debugger/util/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinDebuggerCaches.kt | 448764544 |
package aoc2017.kot
import java.io.File
object Day21 {
fun solve(start: String, input: List<String>, iter: Int): Int {
val lookUp = parsePatterns(input)
var current = start.split("/").map { it.toCharArray() }.toTypedArray()
repeat(iter) {
val chunkSize = if (current.size % 2 == 0) 2 else 3
val listOfBlocks = splitIntoBlocks(current, chunkSize)
current = mergeBlocks(listOfBlocks.map { lookUp[it.contentDeepHashCode()]!! })
}
return current.sumBy { it.count { it == '#' } }
}
private fun splitIntoBlocks(current: Array<CharArray>, chunkSize: Int): List<Array<CharArray>> {
if (current.size == chunkSize) return listOf(current)
val blockCount = (current.size * current.size) / (chunkSize * chunkSize)
val blocks = Array(blockCount) { Array(chunkSize) { CharArray(chunkSize) { '.' } } }
for (y in 0 until current.size) {
for (x in 0 until current.size) {
val bOff = x / blocks[0].size + (y / blocks[0].size) * Math.sqrt(blockCount.toDouble()).toInt()
val xOff = x % blocks[0].size
val yOff = y % blocks[0].size
blocks[bOff][xOff][yOff] = current[x][y]
}
}
return blocks.toList()
}
private fun mergeBlocks(blocks: List<Array<CharArray>>): Array<CharArray> {
if (blocks.size == 1) return blocks[0]
val size = Math.sqrt((blocks.size * blocks[0].size * blocks[0].size).toDouble()).toInt()
val result = Array(size) { CharArray(size) { '.' } }
for (y in 0 until result.size) {
for (x in 0 until result.size) {
val bOff = x / blocks[0].size + (y / blocks[0].size) * Math.sqrt(blocks.size.toDouble()).toInt()
val xOff = x % blocks[0].size
val yOff = y % blocks[0].size
result[x][y] = blocks[bOff][xOff][yOff]
}
}
return result
}
private fun parsePatterns(input: List<String>): Map<Int, Array<CharArray>> {
val patterns = mutableMapOf<Int, Array<CharArray>>()
input.forEach {
val (lhs, rhs) = it.split(" => ").map { it.split("/") }
val rhsArr = rhs.map { it.toCharArray() }.toTypedArray()
val permutations = generatePermutations(lhs).map { it.contentDeepHashCode() to rhsArr }
patterns.putAll(permutations)
}
return patterns
}
private fun generatePermutations(s: List<String>): List<Array<CharArray>> {
val result = mutableSetOf<List<String>>()
var next = s
repeat(4) {
result.add(next)
result.add(next.reversed())
result.add(next.map { it.reversed() })
next = rot(next)
}
return result.map { it.map { it.toCharArray() }.toTypedArray() }
}
private fun rot(grid: List<String>): List<String> = flip2DArray(grid).reversed()
private fun flip2DArray(arr: List<String>): List<String> = arr.mapIndexed { index, _ -> arr.map { it[index] }.joinToString(separator = "") }
}
fun main(args: Array<String>) {
val input = File("./input/2017/Day21_input.txt").readLines()
val start = ".#./..#/###"
println("Part One = ${Day21.solve(start, input, 5)}")
println("Part Two = ${Day21.solve(start, input, 18)}")
}
| src/aoc2017/kot/Day21.kt | 464385449 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing.diagnostic
import com.intellij.openapi.command.impl.DummyProject
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertTrue
import org.junit.Test
import java.time.Duration
import java.time.Instant
class ProjectIndexingHistoryImplTest {
@Test
fun `test observation missed the start of suspension (IDEA-281514)`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val time = Instant.now()
history.stopSuspendingStages(time)
history.startStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(1))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(2))
history.indexingFinished()
assertTrue(history.times.indexingDuration > Duration.ZERO)
assertEquals(history.times.suspendedDuration, Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ZERO)
}
@Test
fun `test there may be actions after suspension`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val time = Instant.now()
history.startStage(ProjectIndexingHistoryImpl.Stage.Indexing, time)
history.suspendStages(time.plusNanos(1))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(2))
history.indexingFinished()
assertTrue(history.times.indexingDuration > Duration.ZERO)
assertEquals(history.times.suspendedDuration, Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ZERO)
}
@Test
fun `test there may be actions after suspension 2`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val time = Instant.now()
history.startStage(ProjectIndexingHistoryImpl.Stage.Indexing, time)
history.suspendStages(time.plusNanos(1))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(2))
history.stopSuspendingStages(time.plusNanos(3))
history.indexingFinished()
assertTrue(history.times.indexingDuration > Duration.ZERO)
assertTrue(history.times.suspendedDuration > Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ZERO)
}
@Test
fun `test there may be actions after suspension 3`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val time = Instant.now()
history.suspendStages(time)
history.startStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(1))
history.stopSuspendingStages(time.plusNanos(2))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(3))
history.indexingFinished()
assertTrue(history.times.indexingDuration > Duration.ZERO)
assertTrue(history.times.suspendedDuration > Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ZERO)
}
@Test
fun `test there may be actions after suspension 4`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val time = Instant.now()
history.startStage(ProjectIndexingHistoryImpl.Stage.Indexing, time)
history.stopSuspendingStages(time.plusNanos(1))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(2))
history.indexingFinished()
assertTrue(history.times.indexingDuration > Duration.ZERO)
assertTrue(history.times.suspendedDuration > Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ZERO)
}
@Test
fun `test there may be actions after suspension 5`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val time = Instant.now()
history.startStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(1))
history.stopSuspendingStages(time.plusNanos(2))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(3))
history.suspendStages(time.plusNanos(4))
history.stopSuspendingStages(time.plusNanos(5))
history.indexingFinished()
assertTrue(history.times.indexingDuration > Duration.ZERO)
assertTrue(history.times.suspendedDuration > Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ZERO)
}
@Test
fun `test basic workflow`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val instant = Instant.now()
history.startStage(ProjectIndexingHistoryImpl.Stage.PushProperties, instant)
history.stopStage(ProjectIndexingHistoryImpl.Stage.PushProperties, instant.plusNanos(1))
history.startStage(ProjectIndexingHistoryImpl.Stage.Scanning, instant.plusNanos(2))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Scanning, instant.plusNanos(5))
history.indexingFinished()
assertEquals(history.times.indexingDuration, Duration.ZERO)
assertEquals(history.times.suspendedDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ofNanos(1))
assertEquals(history.times.scanFilesDuration, Duration.ofNanos(3))
}
@Test
fun `test stage with suspension inside`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val instant = Instant.now()
history.startStage(ProjectIndexingHistoryImpl.Stage.PushProperties, instant)
history.suspendStages(instant.plusNanos(1))
history.stopSuspendingStages(instant.plusNanos(4))
history.stopStage(ProjectIndexingHistoryImpl.Stage.PushProperties, instant.plusNanos(5))
history.indexingFinished()
assertEquals(history.times.indexingDuration, Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.suspendedDuration, Duration.ofNanos(3))
assertEquals(history.times.pushPropertiesDuration, Duration.ofNanos(2))
}
} | platform/lang-impl/testSources/com/intellij/util/indexing/diagnostic/ProjectIndexingHistoryImplTest.kt | 4246757332 |
package com.example.andrej.mit_lab_7
import android.app.Activity
import android.app.DownloadManager
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.os.Handler
import android.os.Message
import android.support.v4.content.FileProvider
import android.util.Log
import android.widget.Toast
import org.apache.http.client.ClientProtocolException
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpHead
import org.apache.http.impl.client.DefaultHttpClient
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.Socket
import java.net.URL
object Util {
fun getFile(context: Context, fileName: String) = getPath(context)
.let { File(it, "$fileName.pdf") }
fun getPath(context: Context) = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
fun downloadFile(main: Context, uri: String, fileName: String) =
DownloadManager.Request(Uri.parse(uri))
.apply {
setDestinationInExternalFilesDir(main, Environment.DIRECTORY_DOWNLOADS,
"$fileName.pdf")
setMimeType("application/pdf")
allowScanningByMediaScanner()
setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE or
DownloadManager.Request.NETWORK_WIFI)
}
.let {
(main.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager)
.enqueue(it)
}
fun showPdf(main: Activity, fileName: String) {
try {
val uri = getFile(main, fileName)
.let {
FileProvider.getUriForFile(main,
"${main.applicationContext.packageName}.provider",
it)
}
val intent = Intent(Intent.ACTION_VIEW)
.apply {
setDataAndType(uri, "application/pdf")
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
main.startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(main, "Приложение для открытия pdf файлов отсутствует\n$e", Toast.LENGTH_LONG).show()
} catch (e: Exception) {
Toast.makeText(main, e.toString(), Toast.LENGTH_LONG).show()
}
}
fun httpExists(url: String): Boolean {
val client = DefaultHttpClient()
val request = HttpGet(url)
val response = try {
client.execute(request)
} catch (e: ClientProtocolException) {
e.printStackTrace()
null
} catch (e: IOException) {
e.printStackTrace()
null
}
return response?.statusLine?.statusCode == HttpURLConnection.HTTP_OK
}
fun setPreference(context: Context, name: String, value: Boolean) = with(context) {
this.getSharedPreferences(this.javaClass.toString(), Context.MODE_PRIVATE)
.edit()
.putBoolean(name, value)
.apply()
}
fun getPreference(context: Context, name: String) = with(context) {
this.getSharedPreferences(this.javaClass.toString(), Context.MODE_PRIVATE)
.getBoolean(name, false)
}
fun clearPreference(c: Context) = with(c) {
this.getSharedPreferences(this.javaClass.toString(), Context.MODE_PRIVATE)
.edit()
.clear()
.apply()
}
}
object TaskTwo {
fun downloadUrl(myUrl: String, length: Int = 500): String = try {
with(URL(myUrl).openConnection() as HttpURLConnection) {
readTimeout = 1e4.toInt()
connectTimeout = 1.5e4.toInt()
requestMethod = "GET"
doInput = true
Log.d("DEBUG_TAG", "The response is: $responseCode")
inputStream.use { readIt(it, length) }
}
} catch (e: Exception) {
e.toString()
}
fun readIt(stream: InputStream, length: Int) = CharArray(length).let {
stream.reader(charset("UTF-8")).read(it, 0, length)
String(it)
}
fun httpGET(url: String): String {
val client = DefaultHttpClient()
val request = HttpHead(url)
// val request = HttpGet(url)
val response = try {
client.execute(request)
} catch (e: ClientProtocolException) {
e.printStackTrace()
null
} catch (e: IOException) {
e.printStackTrace()
null
}
Log.d("Response of GET request", response?.statusLine?.toString() ?: "Произошла ошибка")
return response?.statusLine?.toString() ?: "Произошла ошибка"
}
class Requester() : Thread() {
val h by lazy { Handler() }
override fun run() {
try {
Socket("remote.servername.com", 13).use { requestSocket ->
h.sendMessage(Message().apply {
obj = InputStreamReader(requestSocket.getInputStream(), "ISO-8859-1")
.readText()
what = 0
})
}
} catch (e: Exception) {
Log.d("sample application", "failed to read data ${e.message}")
}
}
}
} | MIT/MIT_lab_7/app/src/main/java/com/example/andrej/mit_lab_7/util.kt | 126668266 |
package com.acornui.time
import com.acornui.serialization.jsonParse
import com.acornui.serialization.jsonStringify
import kotlinx.serialization.Serializable
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.time.days
import kotlin.time.milliseconds
import kotlin.time.minutes
import kotlin.time.seconds
class DateTest {
@Test fun toIsoString() {
val d = Date.UTC(2019, 2, 3, 4, 5, 6, 7)
assertEquals("2019-02-03T04:05:06.007Z", d.toIsoString())
}
@Test fun serializeIso() {
val d = Date.UTC(2019, 2, 3, 4, 5, 6, 7)
val json = jsonStringify(DateSerializer, d)
assertEquals("\"2019-02-03T04:05:06.007Z\"", json)
assertEquals(d, jsonParse(DateSerializer, json))
val m = MyClassWithDate(d)
val json2 = jsonStringify(MyClassWithDate.serializer(), m)
assertEquals(m, jsonParse(MyClassWithDate.serializer(), json2))
val json3 = jsonStringify(MyClassWithDate.serializer(), MyClassWithDate(null))
assertEquals(MyClassWithDate(null), jsonParse(MyClassWithDate.serializer(), json3))
}
@Test fun plus() {
val d = Date(2019, 2, 3, 4, 5, 6, 7)
assertEquals(Date(2019, 2, 3, 4, 5, 6, 7 + 30), d + 30.milliseconds)
assertEquals(Date(2019, 2, 3, 4, 5, 6 + 30, 7), d + 30.seconds)
assertEquals(Date(2019, 2, 3, 4, 5 + 30, 6, 7), d + 30.minutes)
assertEquals(Date(2019, 2, 3, 4, 5, 6, 7), d)
assertEquals(Date(2019, 2, 5), Date(2019, 2, 3) + 2.days)
}
}
@Serializable
private data class MyClassWithDate(
@Serializable(with=DateSerializer::class)
val d: Date?
) | acornui-core/src/test/kotlin/com/acornui/time/DateTest.kt | 2948122948 |
package forpdateam.ru.forpda.model.preferences
import android.content.SharedPreferences
import com.f2prateek.rx.preferences2.RxSharedPreferences
import forpdateam.ru.forpda.common.Preferences
import io.reactivex.Observable
class OtherPreferencesHolder(
private val sharedPreferences: SharedPreferences
) {
private val rxPreferences = RxSharedPreferences.create(sharedPreferences)
private val appFirstStart by lazy {
rxPreferences.getBoolean(Preferences.Other.APP_FIRST_START, true)
}
private val appVersionsHistory by lazy {
rxPreferences.getString(Preferences.Other.APP_VERSIONS_HISTORY)
}
private val searchSettings by lazy {
rxPreferences.getString(Preferences.Other.SEARCH_SETTINGS)
}
private val messagePanelBbCodes by lazy {
rxPreferences.getString(Preferences.Other.MESSAGE_PANEL_BBCODES_SORT)
}
private val showReportWarning by lazy {
rxPreferences.getBoolean(Preferences.Other.SHOW_REPORT_WARNING, true)
}
private val tooltipSearchSettings by lazy {
rxPreferences.getBoolean(Preferences.Other.TOOLTIP_SEARCH_SETTINGS, true)
}
private val tooltipMessagePanelSorting by lazy {
rxPreferences.getBoolean(Preferences.Other.TOOLTIP_MESSAGE_PANEL_SORTING, true)
}
fun observeAppFirstStart(): Observable<Boolean> = appFirstStart.asObservable()
fun observeAppVersionsHistory(): Observable<String> = appVersionsHistory.asObservable()
fun observeSearchSettings(): Observable<String> = searchSettings.asObservable()
fun observeMessagePanelBbCodes(): Observable<String> = messagePanelBbCodes.asObservable()
fun observeShowReportWarning(): Observable<Boolean> = showReportWarning.asObservable()
fun observeTooltipSearchSettings(): Observable<Boolean> = tooltipSearchSettings.asObservable()
fun observeTooltipMessagePanelSorting(): Observable<Boolean> = tooltipMessagePanelSorting.asObservable()
fun setAppFirstStart(value: Boolean) = appFirstStart.set(value)
fun setAppVersionsHistory(value: String) = appVersionsHistory.set(value)
fun setSearchSettings(value: String) = searchSettings.set(value)
fun setMessagePanelBbCodes(value: String) = messagePanelBbCodes.set(value)
fun setShowReportWarning(value: Boolean) = showReportWarning.set(value)
fun setTooltipSearchSettings(value: Boolean) = tooltipSearchSettings.set(value)
fun setTooltipMessagePanelSorting(value: Boolean) = tooltipMessagePanelSorting.set(value)
fun deleteMessagePanelBbCodes() = messagePanelBbCodes.delete()
fun getAppFirstStart(): Boolean = appFirstStart.get()
fun getAppVersionsHistory(): String = appVersionsHistory.get()
fun getSearchSettings(): String = searchSettings.get()
fun getMessagePanelBbCodes(): String = messagePanelBbCodes.get()
fun getShowReportWarning(): Boolean = showReportWarning.get()
fun getTooltipSearchSettings(): Boolean = tooltipSearchSettings.get()
fun getTooltipMessagePanelSorting(): Boolean = tooltipMessagePanelSorting.get()
} | app/src/main/java/forpdateam/ru/forpda/model/preferences/OtherPreferencesHolder.kt | 2135245925 |
package com.firebase.hackweek.tank18thscale.model
data class DeviceInfo(val name: String, val address: String)
| app/src/main/java/com/firebase/hackweek/tank18thscale/model/DeviceInfo.kt | 639230234 |
package com.sheepsgohome.leaderboard
class LeaderBoardResult (
var myResult: LeaderBoardRow?,
var leaderboardRows: List<LeaderBoardRow>
)
| core/src/com/sheepsgohome/leaderboard/LeaderBoardResult.kt | 1611767295 |
package org.wordpress.android.models.usecases
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.merge
import org.wordpress.android.models.usecases.BatchModerateCommentsUseCase.ModerateCommentsAction.OnModerateComments
import org.wordpress.android.models.usecases.BatchModerateCommentsUseCase.Parameters.ModerateCommentsParameters
import org.wordpress.android.models.usecases.ModerateCommentWithUndoUseCase.ModerateCommentsAction.OnModerateComment
import org.wordpress.android.models.usecases.ModerateCommentWithUndoUseCase.ModerateCommentsAction.OnPushComment
import org.wordpress.android.models.usecases.ModerateCommentWithUndoUseCase.ModerateCommentsAction.OnUndoModerateComment
import org.wordpress.android.models.usecases.ModerateCommentWithUndoUseCase.Parameters.ModerateCommentParameters
import org.wordpress.android.models.usecases.ModerateCommentWithUndoUseCase.Parameters.ModerateWithFallbackParameters
import org.wordpress.android.models.usecases.PaginateCommentsUseCase.PaginateCommentsAction.OnGetPage
import org.wordpress.android.models.usecases.PaginateCommentsUseCase.PaginateCommentsAction.OnReloadFromCache
import org.wordpress.android.models.usecases.PaginateCommentsUseCase.Parameters.GetPageParameters
import org.wordpress.android.models.usecases.PaginateCommentsUseCase.Parameters.ReloadFromCacheParameters
import javax.inject.Inject
class UnifiedCommentsListHandler @Inject constructor(
private val paginateCommentsUseCase: PaginateCommentsUseCase,
private val batchModerationUseCase: BatchModerateCommentsUseCase,
private val moderationWithUndoUseCase: ModerateCommentWithUndoUseCase
) {
private val useCases = listOf(paginateCommentsUseCase, batchModerationUseCase, moderationWithUndoUseCase)
@OptIn(ExperimentalCoroutinesApi::class)
fun subscribe() = useCases.map { it.subscribe() }.merge()
suspend fun requestPage(parameters: GetPageParameters) = paginateCommentsUseCase.manageAction(
OnGetPage(parameters)
)
suspend fun moderateComments(parameters: ModerateCommentsParameters) = batchModerationUseCase.manageAction(
OnModerateComments(parameters)
)
suspend fun preModerateWithUndo(parameters: ModerateCommentParameters) = moderationWithUndoUseCase.manageAction(
OnModerateComment(parameters)
)
suspend fun moderateAfterUndo(parameters: ModerateWithFallbackParameters) = moderationWithUndoUseCase.manageAction(
OnPushComment(parameters)
)
suspend fun undoCommentModeration(parameters: ModerateWithFallbackParameters) =
moderationWithUndoUseCase.manageAction(
OnUndoModerateComment(parameters)
)
suspend fun refreshFromCache(parameters: ReloadFromCacheParameters) = paginateCommentsUseCase.manageAction(
OnReloadFromCache(parameters)
)
}
| WordPress/src/main/java/org/wordpress/android/models/usecases/UnifiedCommentsListHandler.kt | 99459583 |
package com.asurasdevelopment.ihh.server.tasks
import org.slf4j.LoggerFactory
import com.asurasdevelopment.ihh.server.persistence.dao.League
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
class LeagueUpdateManager(var list: List<League>, var poolSize : Int = 5, var taskNumber : Int = 5,
var interval : Long = 10) {
private val winston = LoggerFactory.getLogger(LeagueUpdateManager::class.java)
private lateinit var queue : CircularQueue<League>
private lateinit var updatePool : ScheduledExecutorService
fun start() {
winston.info("starting updates with poolSize: $poolSize, taskNumber: $taskNumber, interval: $interval")
queue = CircularQueue(list.toMutableList())
updatePool = Executors.newScheduledThreadPool(poolSize)
for (i in 1..taskNumber) {
updatePool.scheduleAtFixedRate(LeagueUpdateTask(queue), 0, interval, TimeUnit.SECONDS)
}
}
fun stop() {
winston.info("stopping updates")
updatePool.shutdown()
winston.info("updates stopped")
}
fun restart() {
winston.info("restarting updates")
stop()
start()
}
} | ihh-server/src/main/kotlin/com/asurasdevelopment/ihh/server/tasks/LeagueUpdateManager.kt | 3743848467 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.breakpoints
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.ui.breakpoints.JavaLineBreakpointType
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.xdebugger.XDebuggerUtil
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.impl.XSourcePositionImpl
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.psi.getLineNumber
import org.jetbrains.kotlin.idea.base.psi.getTopmostElementAtOffset
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.util.findElementsOfClassInRange
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.inline.INLINE_ONLY_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance
import java.util.*
import org.jetbrains.kotlin.idea.debugger.core.findElementAtLine
interface KotlinBreakpointType
class ApplicabilityResult(val isApplicable: Boolean, val shouldStop: Boolean) {
companion object {
@JvmStatic
fun definitely(result: Boolean) = ApplicabilityResult(result, shouldStop = true)
@JvmStatic
fun maybe(result: Boolean) = ApplicabilityResult(result, shouldStop = false)
@JvmField
val UNKNOWN = ApplicabilityResult(isApplicable = false, shouldStop = false)
@JvmField
val DEFINITELY_YES = ApplicabilityResult(isApplicable = true, shouldStop = true)
@JvmField
val DEFINITELY_NO = ApplicabilityResult(isApplicable = false, shouldStop = true)
@JvmField
val MAYBE_YES = ApplicabilityResult(isApplicable = true, shouldStop = false)
}
}
fun isBreakpointApplicable(file: VirtualFile, line: Int, project: Project, checker: (PsiElement) -> ApplicabilityResult): Boolean {
val psiFile = PsiManager.getInstance(project).findFile(file)
if (psiFile == null || psiFile.virtualFile?.fileType != KotlinFileType.INSTANCE) {
return false
}
val document = FileDocumentManager.getInstance().getDocument(file) ?: return false
return runReadAction {
var isApplicable = false
val checked = HashSet<PsiElement>()
XDebuggerUtil.getInstance().iterateLine(
project, document, line,
fun(element: PsiElement): Boolean {
if (element is PsiWhiteSpace || element.getParentOfType<PsiComment>(false) != null || !element.isValid) {
return true
}
val parent = getTopmostParentOnLineOrSelf(element, document, line)
if (!checked.add(parent)) {
return true
}
val result = checker(parent)
if (result.shouldStop && !result.isApplicable) {
isApplicable = false
return false
}
isApplicable = isApplicable or result.isApplicable
return !result.shouldStop
},
)
return@runReadAction isApplicable
}
}
private fun getTopmostParentOnLineOrSelf(element: PsiElement, document: Document, line: Int): PsiElement {
var current = element
var parent = current.parent
while (parent != null && parent !is PsiFile) {
val offset = parent.textOffset
if (offset > document.textLength) break
if (offset >= 0 && document.getLineNumber(offset) != line) break
current = parent
parent = current.parent
}
return current
}
fun computeLineBreakpointVariants(
project: Project,
position: XSourcePosition,
kotlinBreakpointType: KotlinLineBreakpointType,
): List<JavaLineBreakpointType.JavaBreakpointVariant> {
val file = PsiManager.getInstance(project).findFile(position.file) as? KtFile ?: return emptyList()
val pos = SourcePosition.createFromLine(file, position.line)
val lambdas = getLambdasAtLineIfAny(pos)
if (lambdas.isEmpty()) return emptyList()
val result = LinkedList<JavaLineBreakpointType.JavaBreakpointVariant>()
val elementAt = pos.elementAt.parentsWithSelf.firstIsInstance<KtElement>()
val mainMethod = PsiTreeUtil.getParentOfType(elementAt, KtFunction::class.java, false)
var mainMethodAdded = false
if (mainMethod != null) {
val bodyExpression = mainMethod.bodyExpression
val isLambdaResult = bodyExpression is KtLambdaExpression && bodyExpression.functionLiteral in lambdas
if (!isLambdaResult) {
val variantElement = getTopmostElementAtOffset(elementAt, pos.offset)
result.add(kotlinBreakpointType.LineKotlinBreakpointVariant(position, variantElement, -1))
mainMethodAdded = true
}
}
lambdas.forEachIndexed { ordinal, lambda ->
val positionImpl = XSourcePositionImpl.createByElement(lambda.bodyExpression)
if (positionImpl != null) {
result.add(kotlinBreakpointType.LambdaJavaBreakpointVariant(positionImpl, lambda, ordinal))
}
}
if (mainMethodAdded && result.size > 1) {
result.add(kotlinBreakpointType.KotlinBreakpointVariant(position, lambdas.size))
}
return result
}
fun getLambdasAtLineIfAny(sourcePosition: SourcePosition): List<KtFunction> {
val file = sourcePosition.file as? KtFile ?: return emptyList()
return getLambdasAtLineIfAny(file, sourcePosition.line)
}
inline fun <reified T : PsiElement> getElementsAtLineIfAny(file: KtFile, line: Int): List<T> {
val lineElement = findElementAtLine(file, line) as? KtElement ?: return emptyList()
val start = lineElement.startOffset
var end = lineElement.endOffset
var nextSibling = lineElement.nextSibling
while (nextSibling != null && line == nextSibling.getLineNumber()) {
end = nextSibling.endOffset
nextSibling = nextSibling.nextSibling
}
return findElementsOfClassInRange(file, start, end, T::class.java).filterIsInstance<T>()
}
fun getLambdasAtLineIfAny(file: KtFile, line: Int): List<KtFunction> {
val allLiterals = getElementsAtLineIfAny<KtFunction>(file, line)
// filter function literals and functional expressions
.filter { it is KtFunctionLiteral || it.name == null }
.toSet()
return allLiterals.filter {
val statement = it.bodyBlockExpression?.statements?.firstOrNull() ?: it
statement.getLineNumber() == line && statement.getLineNumber(false) == line
}
}
internal fun KtCallableDeclaration.isInlineOnly(): Boolean {
if (!hasModifier(KtTokens.INLINE_KEYWORD)) {
return false
}
val inlineOnlyAnnotation = annotationEntries
.firstOrNull { it.shortName == INLINE_ONLY_ANNOTATION_FQ_NAME.shortName() }
?: return false
return runReadAction f@{
val bindingContext = inlineOnlyAnnotation.analyze(BodyResolveMode.PARTIAL)
val annotationDescriptor = bindingContext[BindingContext.ANNOTATION, inlineOnlyAnnotation] ?: return@f false
return@f annotationDescriptor.fqName == INLINE_ONLY_ANNOTATION_FQ_NAME
}
}
| plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/breakpoints/breakpointTypeUtils.kt | 1943169511 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.util.SystemProperties
import org.jetbrains.annotations.ApiStatus.Internal
import java.nio.file.Path
import java.util.concurrent.ThreadLocalRandom
/**
* Pass comma-separated names of build steps (see below) to this system property to skip them.
*/
private const val BUILD_STEPS_TO_SKIP_PROPERTY = "intellij.build.skip.build.steps"
class BuildOptions {
companion object {
/**
* Use this property to change the project compiled classes output directory.
*
* @see {@link org.jetbrains.intellij.build.impl.CompilationContextImpl.getProjectOutputDirectory}
*/
const val PROJECT_CLASSES_OUTPUT_DIRECTORY_PROPERTY = "intellij.project.classes.output.directory"
const val OS_LINUX = "linux"
const val OS_WINDOWS = "windows"
const val OS_MAC = "mac"
const val OS_ALL = "all"
const val OS_CURRENT = "current"
/**
* If this value is set no distributions of the product will be produced, only [non-bundled plugins][ProductModulesLayout.setPluginModulesToPublish]
* will be built.
*/
const val OS_NONE = "none"
/** Pre-builds SVG icons for all SVG resource files to speedup icons loading at runtime */
const val SVGICONS_PREBUILD_STEP = "svg_icons_prebuild"
/** Build actual searchableOptions.xml file. If skipped; the (possibly outdated) source version of the file will be used. */
const val SEARCHABLE_OPTIONS_INDEX_STEP = "search_index"
const val BROKEN_PLUGINS_LIST_STEP = "broken_plugins_list"
const val PROVIDED_MODULES_LIST_STEP = "provided_modules_list"
const val GENERATE_JAR_ORDER_STEP = "jar_order"
const val SOURCES_ARCHIVE_STEP = "sources_archive"
const val SCRAMBLING_STEP = "scramble"
const val NON_BUNDLED_PLUGINS_STEP = "non_bundled_plugins"
/** Build Maven artifacts for IDE modules. */
const val MAVEN_ARTIFACTS_STEP = "maven_artifacts"
/** Build macOS artifacts. */
const val MAC_ARTIFACTS_STEP = "mac_artifacts"
/** Build .dmg file for macOS. If skipped, only .sit archive will be produced. */
const val MAC_DMG_STEP = "mac_dmg"
/**
* Publish .sit file for macOS. If skipped, only .dmg archive will be produced.
* If skipped together with [MAC_DMG_STEP], only .zip archive will be produced.
*
* Note: .sit is required to build patches.
*/
const val MAC_SIT_PUBLICATION_STEP = "mac_sit"
/** Sign macOS distribution. */
const val MAC_SIGN_STEP = "mac_sign"
/** Build Linux artifacts. */
const val LINUX_ARTIFACTS_STEP = "linux_artifacts"
/** Build Linux tar.gz artifact without bundled JRE. */
const val LINUX_TAR_GZ_WITHOUT_BUNDLED_JRE_STEP = "linux_tar_gz_without_jre"
/** Build *.exe installer for Windows distribution. If skipped, only .zip archive will be produced. */
const val WINDOWS_EXE_INSTALLER_STEP = "windows_exe_installer"
/** Sign *.exe files in Windows distribution. */
const val WIN_SIGN_STEP = "windows_sign"
@JvmField
@Internal
val WIN_SIGN_OPTIONS = System.getProperty("intellij.build.win.sign.options", "")
.split(';')
.dropLastWhile { it.isEmpty() }
.asSequence()
.filter { !it.isBlank() }
.associate {
val item = it.split('=', limit = 2)
require(item.size == 2) { "Could not split by '=': $it" }
item[0] to item[1]
}
/** Build Frankenstein artifacts. */
const val CROSS_PLATFORM_DISTRIBUTION_STEP = "cross_platform_dist"
/** Toolbox links generator step */
const val TOOLBOX_LITE_GEN_STEP = "toolbox_lite_gen"
/** Generate files containing lists of used third-party libraries */
const val THIRD_PARTY_LIBRARIES_LIST_STEP = "third_party_libraries"
/** Build community distributives */
const val COMMUNITY_DIST_STEP = "community_dist"
const val OS_SPECIFIC_DISTRIBUTIONS_STEP = "os_specific_distributions"
const val PREBUILD_SHARED_INDEXES = "prebuild_shared_indexes"
const val SETUP_BUNDLED_MAVEN = "setup_bundled_maven"
const val VERIFY_CLASS_FILE_VERSIONS = "verify_class_file_versions"
/**
* Publish artifacts to TeamCity storage while the build is still running, immediately after the artifacts are built.
* Comprises many small publication steps.
* Note: skipping this step won't affect publication of 'Artifact paths' in TeamCity build settings and vice versa
*/
const val TEAMCITY_ARTIFACTS_PUBLICATION_STEP = "teamcity_artifacts_publication"
/**
* @see org.jetbrains.intellij.build.fus.StatisticsRecorderBundledMetadataProvider
*/
const val FUS_METADATA_BUNDLE_STEP = "fus_metadata_bundle_step"
/**
* @see org.jetbrains.intellij.build.impl.support.RepairUtilityBuilder
*/
const val REPAIR_UTILITY_BUNDLE_STEP = "repair_utility_bundle_step"
/**
* Pass 'true' to this system property to produce an additional .dmg and .sit archives for macOS without Runtime.
*/
const val BUILD_MAC_ARTIFACTS_WITHOUT_RUNTIME = "intellij.build.dmg.without.bundled.jre"
/**
* Pass 'false' to this system property to skip building .dmg and .sit with bundled Runtime.
*/
const val BUILD_MAC_ARTIFACTS_WITH_RUNTIME = "intellij.build.dmg.with.bundled.jre"
/**
* By default, build cleanup output folder before compilation, use this property to change this behaviour.
*/
const val CLEAN_OUTPUT_FOLDER_PROPERTY = "intellij.build.clean.output.root"
/**
* If `false` build scripts compile project classes to a special output directory (to not interfere with the default project output if
* invoked on a developer machine).
* If `true` compilation step is skipped and compiled classes from the project output are used instead.
* True if [BuildOptions.isInDevelopmentMode] is enabled.
*
* @see {@link org.jetbrains.intellij.build.impl.CompilationContextImpl.getProjectOutputDirectory}
*/
const val USE_COMPILED_CLASSES_PROPERTY = "intellij.build.use.compiled.classes"
/**
* Enables module structure validation, false by default
*/
const val VALIDATE_MODULES_STRUCTURE_PROPERTY = "intellij.build.module.structure"
/**
* Verify whether class files have a forbidden subpaths in them, false by default
*/
const val VALIDATE_CLASSFILE_SUBPATHS_PROPERTY = "intellij.verify.classfile.subpaths"
/**
* Max attempts of dependencies resolution on fault. "1" means no retries.
*
* @see {@link org.jetbrains.intellij.build.impl.JpsCompilationRunner.resolveProjectDependencies}
*/
const val RESOLVE_DEPENDENCIES_MAX_ATTEMPTS_PROPERTY = "intellij.build.dependencies.resolution.retry.max.attempts"
/**
* Initial delay in milliseconds between dependencies resolution retries on fault. Default is 1000
*
* @see {@link org.jetbrains.intellij.build.impl.JpsCompilationRunner.resolveProjectDependencies}
*/
const val RESOLVE_DEPENDENCIES_DELAY_MS_PROPERTY = "intellij.build.dependencies.resolution.retry.delay.ms"
const val TARGET_OS_PROPERTY = "intellij.build.target.os"
}
var projectClassesOutputDirectory: String? = System.getProperty(PROJECT_CLASSES_OUTPUT_DIRECTORY_PROPERTY)
/**
* Specifies for which operating systems distributions should be built.
*/
var targetOs: String
/**
* Specifies for which arch distributions should be built. null means all
*/
var targetArch: JvmArchitecture? = null
/**
* Pass comma-separated names of build steps (see below) to [BUILD_STEPS_TO_SKIP_PROPERTY] system property to skip them when building locally.
*/
var buildStepsToSkip: MutableSet<String> = System.getProperty(BUILD_STEPS_TO_SKIP_PROPERTY, "")
.split(',')
.dropLastWhile { it.isEmpty() }
.asSequence()
.filter { s: String -> !s.isBlank() }
.toHashSet()
var buildMacArtifactsWithoutRuntime = SystemProperties.getBooleanProperty(BUILD_MAC_ARTIFACTS_WITHOUT_RUNTIME,
SystemProperties.getBooleanProperty("artifact.mac.no.jdk", false))
var buildMacArtifactsWithRuntime = SystemProperties.getBooleanProperty(BUILD_MAC_ARTIFACTS_WITH_RUNTIME, true)
/**
* Pass 'true' to this system property to produce .snap packages.
* A build configuration should have "docker.version >= 17" in requirements.
*/
var buildUnixSnaps = SystemProperties.getBooleanProperty("intellij.build.unix.snaps", false)
/**
* Image for snap package creation. Default is "snapcore/snapcraft:stable", but can be modified mostly due to problems
* with new versions of snapcraft.
*/
var snapDockerImage: String = System.getProperty("intellij.build.snap.docker.image", "snapcore/snapcraft:stable")
var snapDockerBuildTimeoutMin: Long = System.getProperty("intellij.build.snap.timeoutMin", "20").toLong()
/**
* Path to a zip file containing 'production' and 'test' directories with compiled classes of the project modules inside.
*/
var pathToCompiledClassesArchive: Path? = System.getProperty("intellij.build.compiled.classes.archive")?.let { Path.of(it) }
/**
* Path to a metadata file containing urls with compiled classes of the project modules inside.
* Metadata is a [org.jetbrains.intellij.build.impl.compilation.CompilationPartsMetadata] serialized into json format
*/
var pathToCompiledClassesArchivesMetadata: String? = System.getProperty("intellij.build.compiled.classes.archives.metadata")
/**
* If `true` the project modules will be compiled incrementally
*/
var incrementalCompilation = SystemProperties.getBooleanProperty("intellij.build.incremental.compilation", false)
/**
* By default, some build steps are executed in parallel threads. Set this property to `false` to disable this.
*/
var runBuildStepsInParallel = SystemProperties.getBooleanProperty("intellij.build.run.steps.in.parallel", true)
/**
* Build number without product code (e.g. '162.500.10'), if `null` '<baseline>.SNAPSHOT' will be used. Use [BuildContext.buildNumber] to
* get the actual build number in build scripts.
*/
var buildNumber: String? = System.getProperty("build.number")
/**
* By default, build process produces temporary and resulting files under projectHome/out/productName directory, use this property to
* change the output directory.
*/
var outputRootPath: String? = System.getProperty("intellij.build.output.root")
var logPath: String? = System.getProperty("intellij.build.log.root")
/**
* If `true` write a separate compilation.log for all compilation messages
*/
var compilationLogEnabled = SystemProperties.getBooleanProperty("intellij.build.compilation.log.enabled", true)
var cleanOutputFolder = SystemProperties.getBooleanProperty(CLEAN_OUTPUT_FOLDER_PROPERTY, true)
/**
* If `true` the build is running in 'Development mode' i.e. its artifacts aren't supposed to be used in production. In development
* mode build scripts won't fail if some non-mandatory dependencies are missing and will just show warnings.
*
* By default, 'development mode' is enabled if build is not running under continuous integration server (TeamCity).
*/
var isInDevelopmentMode = SystemProperties.getBooleanProperty("intellij.build.dev.mode", System.getenv("TEAMCITY_VERSION") == null)
var useCompiledClassesFromProjectOutput = SystemProperties.getBooleanProperty(USE_COMPILED_CLASSES_PROPERTY, isInDevelopmentMode)
/**
* If `true` the build is running as a unit test
*/
var isTestBuild = SystemProperties.getBooleanProperty("intellij.build.test.mode", false)
var skipDependencySetup = false
/**
* Specifies list of names of directories of bundled plugins which shouldn't be included into the product distribution. This option can be
* used to speed up updating the IDE from sources.
*/
val bundledPluginDirectoriesToSkip = getSetProperty("intellij.build.bundled.plugin.dirs.to.skip")
/**
* Specifies list of names of directories of non-bundled plugins (determined by [ProductModulesLayout.pluginsToPublish] and
* [ProductModulesLayout.buildAllCompatiblePlugins]) which should be actually built. This option can be used to speed up updating
* the IDE from sources. By default, all plugins determined by [ProductModulesLayout.pluginsToPublish] and
* [ProductModulesLayout.buildAllCompatiblePlugins] are built. In order to skip building all non-bundled plugins, set the property to
* `none`.
*/
val nonBundledPluginDirectoriesToInclude = getSetProperty("intellij.build.non.bundled.plugin.dirs.to.include")
/**
* Specifies [org.jetbrains.intellij.build.JetBrainsRuntimeDistribution] build to be bundled with distributions. If `null` then `runtimeBuild` from gradle.properties will be used.
*/
var bundledRuntimeBuild: String? = System.getProperty("intellij.build.bundled.jre.build")
/**
* Specifies a prefix to use when looking for an artifact of a [org.jetbrains.intellij.build.JetBrainsRuntimeDistribution] to be bundled with distributions.
* If `null`, `"jbr_jcef-"` will be used.
*/
var bundledRuntimePrefix: String? = System.getProperty("intellij.build.bundled.jre.prefix")
/**
* Enables fastdebug runtime
*/
var runtimeDebug = parseBooleanValue(System.getProperty("intellij.build.bundled.jre.debug", "false"))
/**
* Specifies an algorithm to build distribution checksums.
*/
val hashAlgorithm = "SHA-384"
var validateModuleStructure = parseBooleanValue(System.getProperty(VALIDATE_MODULES_STRUCTURE_PROPERTY, "false"))
var validateClassFileSubpaths = parseBooleanValue(System.getProperty(VALIDATE_CLASSFILE_SUBPATHS_PROPERTY, "false"))
@Internal
var compressNonBundledPluginArchive = true
var resolveDependenciesMaxAttempts = System.getProperty(RESOLVE_DEPENDENCIES_MAX_ATTEMPTS_PROPERTY, "2").toInt()
var resolveDependenciesDelayMs = System.getProperty(RESOLVE_DEPENDENCIES_DELAY_MS_PROPERTY, "1000").toLong()
/**
* See https://reproducible-builds.org/specs/source-date-epoch/
*/
var buildDateInSeconds: Long = 0
var randomSeedNumber: Long = 0
init {
var targetOs = System.getProperty(TARGET_OS_PROPERTY, OS_ALL)
if (targetOs == OS_CURRENT) {
targetOs = when {
SystemInfoRt.isWindows -> OS_WINDOWS
SystemInfoRt.isMac -> OS_MAC
SystemInfoRt.isLinux -> OS_LINUX
else -> throw RuntimeException("Unknown OS")
}
}
else if (targetOs.isEmpty()) {
targetOs = OS_ALL
}
this.targetOs = targetOs
val sourceDateEpoch = System.getenv("SOURCE_DATE_EPOCH")
buildDateInSeconds = sourceDateEpoch?.toLong() ?: (System.currentTimeMillis() / 1000)
val randomSeedString = System.getProperty("intellij.build.randomSeed")
randomSeedNumber = if (randomSeedString == null || randomSeedString.isBlank()) {
ThreadLocalRandom.current().nextLong()
}
else {
randomSeedString.toLong()
}
}
}
private fun parseBooleanValue(text: String): Boolean {
return when {
text.toBoolean() -> true
text.equals(java.lang.Boolean.FALSE.toString(), ignoreCase = true) -> false
else -> throw IllegalArgumentException("Could not parse as boolean, accepted values are only 'true' or 'false': $text")
}
}
private fun getSetProperty(name: String): Set<String> {
return java.util.Set.copyOf((System.getProperty(name) ?: return emptySet()).split(','))
}
| platform/build-scripts/groovy/org/jetbrains/intellij/build/BuildOptions.kt | 1514750533 |
// "Replace with 'test.Bar'" "true"
package test
@Deprecated("Replace with bar", ReplaceWith("test.Bar"))
annotation class Foo(val p1: String, val p2: Int)
annotation class Bar(val p1: String, val p2: Int)
@Foo<caret>("", 1) class C {} | plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/classUsages/annotation2.kt | 2151860685 |
package instep.dao.sql
@Suppress("MemberVisibilityCanBePrivate", "CanBeParameter")
open class ColumnCondition(val column: Column<*>, val operation: String, val value: Any? = null) :
Condition("${column.qualifiedName} $operation") {
init {
if (null != value) {
this.addParameters(value)
}
}
}
| dao/src/main/kotlin/instep/dao/sql/ColumnCondition.kt | 3610340175 |
package au.id.micolous.metrodroid.transit.troika
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Parcelable
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.*
import au.id.micolous.metrodroid.transit.Subscription
import au.id.micolous.metrodroid.transit.TransitBalance
import au.id.micolous.metrodroid.transit.TransitIdentity
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.ui.ListItem
import au.id.micolous.metrodroid.util.NumberUtils
import au.id.micolous.metrodroid.util.ImmutableByteArray
abstract class TroikaBlock private constructor(private val mSerial: Long,
protected val mLayout: Int,
protected val mTicketType: Int,
/**
* Last transport type
*/
private val mLastTransportLeadingCode: Int?,
private val mLastTransportLongCode: Int?,
private val mLastTransportRaw: String?,
/**
* ID of the last validator.
*/
protected val mLastValidator: Int?,
/**
* Validity length in minutes.
*/
protected val mValidityLengthMinutes: Int?,
/**
* Expiry date of the card.
*/
protected val mExpiryDate: Timestamp?,
/**
* Time of the last validation.
*/
protected val mLastValidationTime: TimestampFull?,
/**
* Start of validity period
*/
private val mValidityStart: Timestamp?,
/**
* End of validity period
*/
protected val mValidityEnd: Timestamp?,
/**
* Number of trips remaining
*/
private val mRemainingTrips: Int?,
/**
* Last transfer in minutes after validation
*/
protected val mLastTransfer: Int?,
/**
* Text description of last fare.
*/
private val mFareDesc: String?) : Parcelable {
val serialNumber: String
get() = formatSerial(mSerial)
open val subscription: Subscription?
get() = TroikaSubscription(mExpiryDate, mValidityStart, mValidityEnd,
mRemainingTrips, mValidityLengthMinutes, mTicketType)
open val info: List<ListItem>?
get() = null
val trips: List<Trip>
get() {
val t = mutableListOf<Trip>()
val rawTransport = mLastTransportRaw ?: (mLastTransportLeadingCode?.shl(8)?.or(mLastTransportLongCode ?: 0))?.toString(16)
if (mLastValidationTime != null) {
if (mLastTransfer != null && mLastTransfer != 0) {
val lastTransfer = mLastValidationTime.plus(Duration.mins(mLastTransfer))
t.add(TroikaTrip(lastTransfer, getTransportType(true), mLastValidator, rawTransport, mFareDesc))
t.add(TroikaTrip(mLastValidationTime, getTransportType(false), null, rawTransport, mFareDesc))
} else
t.add(TroikaTrip(mLastValidationTime, getTransportType(true), mLastValidator, rawTransport, mFareDesc))
}
return t
}
val cardName: String
get() = Localizer.localizeString(R.string.card_name_troika)
open val balance: TransitBalance?
get() = null
constructor(rawData: ImmutableByteArray,
mLastTransportLeadingCode: Int? = null,
mLastTransportLongCode: Int? = null,
mLastTransportRaw: String? = null,
mLastValidator: Int? = null,
mValidityLengthMinutes: Int? = null,
mExpiryDate: Timestamp? = null,
mLastValidationTime: TimestampFull? = null,
mValidityStart: Timestamp? = null,
mValidityEnd: Timestamp? = null,
mRemainingTrips: Int? = null,
mLastTransfer: Int? = null,
mFareDesc: String? = null) : this(
mSerial = getSerial(rawData),
mLayout = getLayout(rawData),
mTicketType = getTicketType(rawData),
mLastTransportLeadingCode = mLastTransportLeadingCode,
mLastTransportLongCode = mLastTransportLongCode,
mLastTransportRaw = mLastTransportRaw,
mLastValidator = mLastValidator,
mValidityLengthMinutes = mValidityLengthMinutes,
mExpiryDate = mExpiryDate,
mLastValidationTime = mLastValidationTime,
mValidityStart = mValidityStart,
mValidityEnd = mValidityEnd,
mRemainingTrips = mRemainingTrips,
mLastTransfer = mLastTransfer,
mFareDesc = mFareDesc
)
internal enum class TroikaTransportType {
NONE,
UNKNOWN,
SUBWAY,
MONORAIL,
GROUND,
MCC
}
internal open fun getTransportType(getLast: Boolean): TroikaTransportType? {
when (mLastTransportLeadingCode) {
0 -> return TroikaTransportType.NONE
1 -> {
}
2 -> {
return if (getLast) TroikaTransportType.GROUND else TroikaTransportType.UNKNOWN
}
/* Fallthrough */
else -> return TroikaTransportType.UNKNOWN
}
if (mLastTransportLongCode == 0 || mLastTransportLongCode == null)
return TroikaTransportType.UNKNOWN
// This is actually 4 fields used in sequence.
var first: TroikaTransportType? = null
var last: TroikaTransportType? = null
var i = 6
var found = 0
while (i >= 0) {
val shortCode = mLastTransportLongCode shr i and 3
if (shortCode == 0) {
i -= 2
continue
}
var type: TroikaTransportType? = null
when (shortCode) {
1 -> type = TroikaTransportType.SUBWAY
2 -> type = TroikaTransportType.MONORAIL
3 -> type = TroikaTransportType.MCC
}
if (first == null)
first = type
last = type
found++
i -= 2
}
if (found == 1 && !getLast)
return TroikaTransportType.UNKNOWN
return if (getLast) last else first
}
companion object {
private val TROIKA_EPOCH_1992 = Epoch.local(1992, MetroTimeZone.MOSCOW)
private val TROIKA_EPOCH_2016 = Epoch.local(2016, MetroTimeZone.MOSCOW)
fun convertDateTime1992(days: Int, mins: Int): TimestampFull? {
if (days == 0 && mins == 0)
return null
return TROIKA_EPOCH_1992.dayMinute(days - 1, mins)
}
fun convertDateTime1992(days: Int): Daystamp? {
if (days == 0)
return null
return TROIKA_EPOCH_1992.days(days - 1)
}
fun convertDateTime2016(days: Int, mins: Int): TimestampFull? {
if (days == 0 && mins == 0)
return null
return TROIKA_EPOCH_2016.dayMinute(days - 1, mins)
}
fun formatSerial(sn: Long): String {
return NumberUtils.formatNumber(sn, " ", 4, 3, 3)
}
fun getSerial(rawData: ImmutableByteArray): Long {
return rawData.getBitsFromBuffer(20, 32).toLong() and 0xffffffffL
}
private fun getTicketType(rawData: ImmutableByteArray): Int {
return rawData.getBitsFromBuffer(4, 16)
}
private fun getLayout(rawData: ImmutableByteArray): Int {
return rawData.getBitsFromBuffer(52, 4)
}
fun parseTransitIdentity(rawData: ImmutableByteArray): TransitIdentity {
return TransitIdentity(Localizer.localizeString(R.string.card_name_troika),
formatSerial(getSerial(rawData)))
}
fun getHeader(ticketType: Int): String {
when (ticketType) {
0x5d3d, 0x5d3e, 0x5d48, 0x2135 ->
// This should never be shown to user, don't localize.
return "Empty ticket holder"
0x183d, 0x2129 -> return Localizer.localizeString(R.string.troika_druzhinnik_card)
0x5d9b -> return troikaRides(1)
0x5d9c -> return troikaRides(2)
0x5da0 -> return troikaRides(20)
0x5db1 ->
// This should never be shown to user, don't localize.
return "Troika purse"
0x5dd3 -> return troikaRides(60)
}
return Localizer.localizeString(R.string.troika_unknown_ticket, ticketType.toString(16))
}
private fun troikaRides(rides: Int): String {
return Localizer.localizePlural(R.plurals.troika_rides, rides, rides)
}
fun check(rawData: ImmutableByteArray): Boolean =
rawData.getBitsFromBuffer(0, 10) in listOf(0x117, 0x108, 0x106)
fun parseBlock(rawData: ImmutableByteArray): TroikaBlock {
val layout = getLayout(rawData)
when (layout) {
0x2 -> return TroikaLayout2(rawData)
0xa -> return TroikaLayoutA(rawData)
0xd -> return TroikaLayoutD(rawData)
0xe -> {
val sublayout = rawData.getBitsFromBuffer(56, 5)
when (sublayout) {
2 -> return TroikaLayoutE(rawData)
3 -> return TroikaPurse(rawData)
}
}
}
return TroikaUnknownBlock(rawData)
}
}
}
| src/commonMain/kotlin/au/id/micolous/metrodroid/transit/troika/TroikaBlock.kt | 1567393881 |
package com.eden.orchid.forms
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.generators.OrchidGenerator
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.forms.model.Form
import com.eden.orchid.forms.model.FormsModel
import com.eden.orchid.utilities.OrchidUtils
@Description("Indexes form definitions so they can be easily referenced from components on different pages.",
name = "Forms"
)
class FormsGenerator : OrchidGenerator<FormsModel>(GENERATOR_KEY, Stage.CONTENT) {
companion object {
const val GENERATOR_KEY = "forms"
}
@Option
@StringDefault("forms")
@Description("The base directory in local resources to look for forms in.")
lateinit var baseDir: String
override fun startIndexing(context: OrchidContext): FormsModel {
val forms = getFormsByDatafiles(context)
return FormsModel(forms)
}
private fun getFormsByDatafiles(context: OrchidContext) : List<Form> {
return context
.getDefaultResourceSource(null, null)
.getResourceEntries(
context,
OrchidUtils.normalizePath(baseDir),
context.parserExtensions.toTypedArray(),
false
)
.map { resource ->
resource.reference.isUsePrettyUrl = false
val fileData = context.parse(resource.reference.extension, resource.content)
val key = resource.reference.originalFileName
Form(context, key, fileData)
}
}
}
| plugins/OrchidForms/src/main/kotlin/com/eden/orchid/forms/FormsGenerator.kt | 3863669140 |
/*
* Copyright (C) 2019. Zac Sweers
*
* 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.sweers.catchup.ui.debug
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.core.content.res.use
import androidx.core.view.ViewCompat
import io.sweers.catchup.R
/**
* A layout that draws something in the insets passed to [.fitSystemWindows], i.e. the
* area above UI chrome (status and navigation bars, overlay action bars).
*
*
* Unlike the `ScrimInsetsFrameLayout` in the design support library, this variant does not
* consume the insets.
*/
class NonConsumingScrimInsetsFrameLayout : FrameLayout {
private var insetForeground: Drawable? = null
private var insets: Rect? = null
private val tempRect = Rect()
constructor(context: Context) : super(context) {
init(context, null, 0)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, attrs, 0)
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
context,
attrs,
defStyle
) {
init(context, attrs, defStyle)
}
private fun init(context: Context, attrs: AttributeSet?, defStyle: Int) {
context.obtainStyledAttributes(
attrs,
R.styleable.NonConsumingScrimInsetsView,
defStyle,
0
).use {
insetForeground = it.getDrawable(R.styleable.NonConsumingScrimInsetsView_insetForeground)
}
setWillNotDraw(true)
}
override fun fitSystemWindows(insets: Rect): Boolean {
this.insets = Rect(insets)
setWillNotDraw(insetForeground == null)
ViewCompat.postInvalidateOnAnimation(this)
return false // Do not consume insets.
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
val width = width
val height = height
if (insets != null && insetForeground != null) {
val sc = canvas.save()
canvas.translate(scrollX.toFloat(), scrollY.toFloat())
// Top
tempRect.set(0, 0, width, insets!!.top)
insetForeground!!.bounds = tempRect
insetForeground!!.draw(canvas)
// Bottom
tempRect.set(0, height - insets!!.bottom, width, height)
insetForeground!!.bounds = tempRect
insetForeground!!.draw(canvas)
// Left
tempRect.set(0, insets!!.top, insets!!.left, height - insets!!.bottom)
insetForeground!!.bounds = tempRect
insetForeground!!.draw(canvas)
// Right
tempRect.set(width - insets!!.right, insets!!.top, width, height - insets!!.bottom)
insetForeground!!.bounds = tempRect
insetForeground!!.draw(canvas)
canvas.restoreToCount(sc)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
insetForeground?.callback = this
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
insetForeground?.callback = null
}
}
| app/src/debug/kotlin/io/sweers/catchup/ui/debug/NonConsumingScrimInsetsFrameLayout.kt | 1357143519 |
package ksp.kos.ideaplugin.refactoring
import ksp.kos.ideaplugin.KerboScriptPlatformTestBase
import org.intellij.lang.annotations.Language
class KerboScriptNormalizeTest : KerboScriptPlatformTestBase() {
fun testNormalizeBasic() = doTest(
"""
LOCAL <caret>x TO (a/b) + c + c + a*a + b/b.
""",
"""
LOCAL x TO (a + 2*c*b + a^2*b + b)/b.
"""
)
private fun doTest(
@Language("KerboScript") before: String,
@Language("KerboScript") after: String,
) {
checkEditorAction(before, after, "ksp.kos.ideaplugin.actions.Normalize")
}
}
| IDEA/src/test/kotlin/ksp/kos/ideaplugin/refactoring/KerboScriptNormalizeTest.kt | 3853407953 |
/*
* Copyright (c) 2017
*
* 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.acra.interaction
import android.content.Context
import org.acra.config.CoreConfiguration
import org.acra.log.debug
import org.acra.log.warn
import org.acra.plugins.loadEnabled
import java.io.File
import java.util.concurrent.ExecutionException
import java.util.concurrent.Executors
import java.util.concurrent.Future
/**
* Manages and executes all report interactions
*
* @author F43nd1r
* @since 10.10.2017
*/
class ReportInteractionExecutor(private val context: Context, private val config: CoreConfiguration) {
private val reportInteractions: List<ReportInteraction> = config.pluginLoader.loadEnabled(config)
fun hasInteractions(): Boolean = reportInteractions.isNotEmpty()
fun performInteractions(reportFile: File): Boolean {
val executorService = Executors.newCachedThreadPool()
val futures: List<Future<Boolean>> = reportInteractions.map {
executorService.submit<Boolean> {
debug { "Calling ReportInteraction of class ${it.javaClass.name}" }
it.performInteraction(context, config, reportFile)
}
}
var sendReports = true
for (future in futures) {
do {
try {
sendReports = sendReports and future.get()
} catch (ignored: InterruptedException) {
} catch (e: ExecutionException) {
warn(e) { "Report interaction threw exception, will be ignored." }
//ReportInteraction crashed, so ignore it
break
}
} while (!future.isDone)
}
return sendReports
}
} | acra-core/src/main/java/org/acra/interaction/ReportInteractionExecutor.kt | 2924012815 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pullUp
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiNamedElement
import com.intellij.refactoring.HelpID
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.util.CommonRefactoringUtil
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.refactoring.AbstractPullPushMembersHandler
import org.jetbrains.kotlin.idea.refactoring.canRefactor
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfoStorage
import org.jetbrains.kotlin.idea.refactoring.memberInfo.qualifiedClassNameForRendering
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.types.typeUtil.supertypes
class KotlinPullUpHandler : AbstractPullPushMembersHandler(
refactoringName = PULL_MEMBERS_UP,
helpId = HelpID.MEMBERS_PULL_UP,
wrongPositionMessage = RefactoringBundle.message("the.caret.should.be.positioned.inside.a.class.to.pull.members.from")
) {
companion object {
@NonNls
const val PULL_UP_TEST_HELPER_KEY = "PULL_UP_TEST_HELPER_KEY"
}
interface TestHelper {
fun adjustMembers(members: List<KotlinMemberInfo>): List<KotlinMemberInfo>
fun chooseSuperClass(superClasses: List<PsiNamedElement>): PsiNamedElement
}
private fun reportNoSuperClasses(project: Project, editor: Editor?, classOrObject: KtClassOrObject) {
val message = RefactoringBundle.getCannotRefactorMessage(
RefactoringBundle.message(
"class.does.not.have.base.classes.interfaces.in.current.project",
classOrObject.qualifiedClassNameForRendering()
)
)
CommonRefactoringUtil.showErrorHint(project, editor, message, PULL_MEMBERS_UP, HelpID.MEMBERS_PULL_UP)
}
override fun invoke(
project: Project,
editor: Editor?,
classOrObject: KtClassOrObject?,
member: KtNamedDeclaration?,
dataContext: DataContext?
) {
if (classOrObject == null) {
reportWrongContext(project, editor)
return
}
val classDescriptor = classOrObject.unsafeResolveToDescriptor() as ClassDescriptor
val superClasses = classDescriptor.defaultType
.supertypes()
.mapNotNull {
val descriptor = it.constructor.declarationDescriptor
val declaration = descriptor?.let { classifierDescriptor ->
DescriptorToSourceUtilsIde.getAnyDeclaration(project, classifierDescriptor)
}
if ((declaration is KtClass || declaration is PsiClass)
&& declaration.canRefactor()
) declaration as PsiNamedElement else null
}
.sortedBy { it.qualifiedClassNameForRendering() }
if (superClasses.isEmpty()) {
val containingClass = classOrObject.getStrictParentOfType<KtClassOrObject>()
if (containingClass != null) {
invoke(project, editor, containingClass, classOrObject, dataContext)
} else {
reportNoSuperClasses(project, editor, classOrObject)
}
return
}
val memberInfoStorage = KotlinMemberInfoStorage(classOrObject)
val members = memberInfoStorage.getClassMemberInfos(classOrObject)
if (isUnitTestMode()) {
val helper = dataContext?.getData(PULL_UP_TEST_HELPER_KEY) as TestHelper
val selectedMembers = helper.adjustMembers(members)
val targetClass = helper.chooseSuperClass(superClasses)
checkConflicts(project, classOrObject, targetClass, selectedMembers) {
KotlinPullUpDialog.createProcessor(classOrObject, targetClass, selectedMembers).run()
}
} else {
val manager = classOrObject.manager
members.filter { manager.areElementsEquivalent(it.member, member) }.forEach { it.isChecked = true }
KotlinPullUpDialog(project, classOrObject, superClasses, memberInfoStorage).show()
}
}
}
val PULL_MEMBERS_UP: String get() = RefactoringBundle.message("pull.members.up.title") | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHandler.kt | 1346231570 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.facet
import com.intellij.facet.ui.FacetEditorContext
import com.intellij.facet.ui.FacetEditorTab
import com.intellij.facet.ui.FacetValidatorsManager
import org.jdom.Element
import org.jetbrains.kotlin.config.KotlinFacetSettings
import org.jetbrains.kotlin.config.deserializeFacetSettings
import org.jetbrains.kotlin.config.serializeFacetSettings
class KotlinFacetConfigurationImpl : KotlinFacetConfiguration {
override var settings = KotlinFacetSettings()
private set
@Suppress("OVERRIDE_DEPRECATION")
override fun readExternal(element: Element) {
settings = deserializeFacetSettings(element).also { it.updateMergedArguments() }
}
@Suppress("OVERRIDE_DEPRECATION")
override fun writeExternal(element: Element) {
settings.serializeFacetSettings(element)
}
override fun createEditorTabs(
editorContext: FacetEditorContext,
validatorsManager: FacetValidatorsManager
): Array<FacetEditorTab> {
settings.initializeIfNeeded(editorContext.module, editorContext.rootModel)
val tabs = arrayListOf<FacetEditorTab>()
tabs += KotlinFacetEditorProviderService.getInstance(editorContext.project).getEditorTabs(this, editorContext, validatorsManager)
KotlinFacetConfigurationExtension.EP_NAME.extensionList.flatMapTo(tabs) { it.createEditorTabs(editorContext, validatorsManager) }
return tabs.toTypedArray()
}
}
| plugins/kotlin/base/facet/src/org/jetbrains/kotlin/idea/facet/KotlinFacetConfigurationImpl.kt | 3486127329 |
enum class InnerClassEnumEntry {
ENTRY {
inner class InnerClass
}
} | plugins/kotlin/idea/tests/testData/decompiler/stubBuilder/InnerClassEnumEntry/InnerClassEnumEntry.kt | 2347328092 |
// FIR_COMPARISON
// RUNTIME
@file:JvmName("TopLevelMultifile")
@file:JvmMultifileClass
package test
val x = 1
fun getX() = 1
| plugins/kotlin/idea/tests/testData/checker/duplicateJvmSignature/functionAndProperty/topLevelMultifileRuntime.kt | 4258127034 |
package org.thoughtcrime.securesms.components.settings.app.privacy.advanced
data class AdvancedPrivacySettingsState(
val isPushEnabled: Boolean,
val alwaysRelayCalls: Boolean,
val censorshipCircumventionState: CensorshipCircumventionState,
val censorshipCircumventionEnabled: Boolean,
val showSealedSenderStatusIcon: Boolean,
val allowSealedSenderFromAnyone: Boolean,
val showProgressSpinner: Boolean
)
enum class CensorshipCircumventionState(val available: Boolean) {
/** The setting is unavailable because you're connected to the websocket */
UNAVAILABLE_CONNECTED(false),
/** The setting is unavailable because you have no network access at all */
UNAVAILABLE_NO_INTERNET(false),
/** The setting is available, and the user manually disabled it even though we thought they were censored */
AVAILABLE_MANUALLY_DISABLED(true),
/** The setting is available, and it's on because we think the user is censored */
AVAILABLE_AUTOMATICALLY_ENABLED(true),
/** The setting is generically available */
AVAILABLE(true),
}
| app/src/main/java/org/thoughtcrime/securesms/components/settings/app/privacy/advanced/AdvancedPrivacySettingsState.kt | 3547986933 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.