code
stringlengths 6
1.04M
| language
stringclasses 1
value | AST_depth
int64 -1
40
| alphanumeric_fraction
float64 0
0.97
| max_line_length
int64 0
1k
| avg_line_length
float64 0
171
| num_lines
int64 0
4.25k
| source
stringclasses 1
value |
---|---|---|---|---|---|---|---|
<gh_stars>1-10
package tripleklay.util
import euklid.f.IPoint
import euklid.f.Point
import euklid.f.Rectangle
import klay.core.Surface
import klay.scene.GroupLayer
import klay.scene.Layer
import klay.scene.LayerUtil
import klay.scene.Pointer
/**
* Provides utility functions for dealing with Layers
*/
object Layers {
/** Prevents parent handling for pointer events. This is useful if you have for example a
* button inside a scrolling container and need to enable event propagation. */
val NO_PROPAGATE: Pointer.Listener = object : Pointer.Listener {
override fun onStart(iact: Pointer.Interaction) {
stop(iact)
}
override fun onEnd(iact: Pointer.Interaction) {
stop(iact)
}
override fun onDrag(iact: Pointer.Interaction) {
stop(iact)
}
override fun onCancel(iact: Pointer.Interaction?) {
stop(iact)
}
internal fun stop(iact: Pointer.Interaction?) {
// TODO: event.flags().setPropagationStopped(true);
}
}
/**
* Transforms a point from one Layer's coordinate system to another's.
*/
fun transform(p: IPoint, from: Layer, to: Layer, result: Point = Point()): Point {
LayerUtil.layerToScreen(from, p, result)
LayerUtil.screenToLayer(to, result, result)
return result
}
/**
* Removes `layer` from its current parent and adds it to `target`, modifying its
* transform in the process so that it stays in the same position on the screen.
*/
fun reparent(layer: Layer, target: GroupLayer) {
val pos = Point(layer.tx(), layer.ty())
LayerUtil.layerToScreen(layer.parent()!!, pos, pos)
target.add(layer)
LayerUtil.screenToLayer(layer.parent()!!, pos, pos)
layer.setTranslation(pos.x, pos.y)
}
/**
* Whether a GroupLayer hierarchy contains another layer somewhere in its depths.
*/
fun contains(group: GroupLayer, layer: Layer?): Boolean {
var layer = layer
while (layer != null) {
layer = layer!!.parent()
if (layer === group) return true
}
return false
}
/**
* Creates a new group with the given children.
*/
fun group(vararg children: Layer): GroupLayer {
val gl = GroupLayer()
for (l in children) gl.add(l)
return gl
}
/**
* Adds a child layer to a group and returns the child.
*/
fun <T : Layer> addChild(parent: GroupLayer, child: T): T {
parent.add(child)
return child
}
/**
* Adds a child group to a parent group and returns the child.
*/
fun addNewGroup(parent: GroupLayer): GroupLayer {
return addChild(parent, GroupLayer())
}
/**
* Creates a layer that renders a simple rectangle of the given color, width and height.
*/
fun solid(color: Int, width: Float, height: Float): Layer {
return object : Layer() {
override fun width(): Float {
return width
}
override fun height(): Float {
return height
}
override fun paintImpl(surf: Surface) {
surf.setFillColor(color).fillRect(0f, 0f, width, height)
}
}
}
/**
* Computes the total bounds of the layer hierarchy rooted at `root`.
* The returned Rectangle will be in `root`'s coordinate system.
*/
fun totalBounds(root: Layer): Rectangle {
// account for root's origin
val r = Rectangle(root.originX(), root.originY(), 0f, 0f)
addBounds(root, root, r, Point())
return r
}
/** Helper function for [.totalBounds]. */
private fun addBounds(root: Layer, l: Layer, bounds: Rectangle, scratch: Point) {
val w = l.width()
val h = l.height()
if (w != 0f || h != 0f) {
// grow bounds
bounds.add(LayerUtil.layerToParent(l, root, scratch.set(0f, 0f), scratch))
bounds.add(LayerUtil.layerToParent(l, root, scratch.set(w, h), scratch))
}
if (l is GroupLayer) {
var ii = 0
val ll = l.children()
while (ii < ll) {
addBounds(root, l.childAt(ii), bounds, scratch)
++ii
}
}
}
}
/**
* Transforms a point from one Layer's coordinate system to another's.
*/
| kotlin | 21 | 0.582156 | 93 | 28.74 | 150 | starcoderdata |
<gh_stars>1-10
package ru.tech.easysearch.fragment.dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import ru.tech.easysearch.R
import ru.tech.easysearch.application.ESearchApplication
import ru.tech.easysearch.data.SharedPreferencesAccess
import ru.tech.easysearch.database.shortcuts.Shortcut
import ru.tech.easysearch.databinding.CreateShortcutDialogBinding
import ru.tech.easysearch.extensions.Extensions.fetchFavicon
import ru.tech.easysearch.extensions.Extensions.toByteArray
import ru.tech.easysearch.functions.Functions.doInBackground
class ShortcutCreationDialog(
private val url: String = "",
private val description: String = "",
private val editing: Boolean = false,
private val uid: Int? = 0
) : DialogFragment() {
private var _binding: CreateShortcutDialogBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = CreateShortcutDialogBinding.inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onStart() {
super.onStart()
requireDialog().window?.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NO_FRAME, SharedPreferencesAccess.loadTheme(requireContext()))
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
requireDialog().window?.setWindowAnimations(
R.style.DialogAnimation
)
binding.description.editText?.setText(description)
binding.url.editText?.setText(url)
binding.done.setOnClickListener {
val dao = ESearchApplication.database.shortcutDao()
val newUrl = binding.url.editText!!.text.toString().trim()
val title = binding.description.editText!!.text.toString().trim()
if (title != "" && newUrl != "") {
if (!editing) {
doInBackground {
val icon = requireContext().fetchFavicon(newUrl).toByteArray()
dao.insert(Shortcut(title, newUrl, icon))
}
Toast.makeText(requireContext(), R.string.shortcutAdded, Toast.LENGTH_SHORT)
.show()
} else {
doInBackground {
val icon = requireContext().fetchFavicon(newUrl).toByteArray()
dao.update(Shortcut(title, newUrl, icon, uid))
}
Toast.makeText(requireContext(), R.string.shortcutSaved, Toast.LENGTH_SHORT)
.show()
}
dismiss()
} else {
Toast.makeText(requireContext(), R.string.fillAllFields, Toast.LENGTH_SHORT).show()
}
}
binding.close.setOnClickListener {
dismiss()
}
}
}
| kotlin | 30 | 0.626592 | 99 | 34.177083 | 96 | starcoderdata |
package com.olucasmoro.movieapp.feature_album.data
import androidx.lifecycle.LiveData
import com.olucasmoro.movieapp.feature_album.data.source.AlbumRemoteData
import com.olucasmoro.movieapp.app.service.model.CallResults
import com.olucasmoro.movieapp.feature_album.data.model.*
import com.olucasmoro.movieapp.feature_album.domain.repository.AlbumRepository
class AlbumRepositoryImpl(
private val remoteData: AlbumRemoteData
) : AlbumRepository {
override fun getMovies(movieType: String, apiKey: String): LiveData<CallResults<List<Movie>?>> {
return remoteData.getMovies(movieType, apiKey)
}
override fun getDetailMovie(movieId: Int, apiKey: String): LiveData<CallResults<MovieDetail?>> {
return remoteData.getDetailMovie(movieId, apiKey)
}
override fun searchMovie(str: String, apiKey: String): LiveData<CallResults<List<Search>?>> {
return remoteData.searchMovie(str, apiKey)
}
override fun addWatchlist(
accountId: Int,
sessionId: String,
apiKey: String,
movieId: Int
) = remoteData.addWatchlist(accountId, sessionId, apiKey, movieId)
}
| kotlin | 15 | 0.748025 | 100 | 34.59375 | 32 | starcoderdata |
<reponame>uditbhaskar/Cloud-notes<gh_stars>1-10
package com.example.cloudnotes.utils.rx
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Singleton
@Singleton
class RxSchedulerProvider : SchedulerProvider {
override fun computation(): Scheduler = Schedulers.computation()
override fun io(): Scheduler = Schedulers.io()
override fun ui(): Scheduler = AndroidSchedulers.mainThread()
}
| kotlin | 8 | 0.797595 | 68 | 28.352941 | 17 | starcoderdata |
<reponame>marcelloceschia/foundation<filename>foundation/src/commonMain/kotlin/net/ntworld/foundation/mocking/internal/CallFakeBuilderImpl.kt<gh_stars>1-10
package net.ntworld.foundation.mocking.internal
import net.ntworld.foundation.mocking.*
internal class CallFakeBuilderImpl<R> :
CallFakeBuilder.Start<R>,
CallFakeBuilder.Action<R>,
CallFakeBuilder.Build<R>,
CallFakeBuilder.Calls<R>,
CallFakeBuilder.Chain<R> {
private data class Call<T>(
val ordinal: Int,
var fakeImpl: Invoker<T>?,
var returned: T?,
var thrown: Throwable?,
var runFakeImpl: Boolean = false,
var hasReturned: Boolean = false,
var shouldThrow: Boolean = false
) {
fun invoke(list: ParameterList, invokeData: InvokeData): T {
if (runFakeImpl) {
return fakeImpl!!.invoke(list, invokeData)
}
if (hasReturned) {
return returned!!
}
if (shouldThrow) {
throw thrown!!
}
throw MockingException("Please provide returned value via .returns() or use .throws() to throw an exception or .runs() to provide fake implementation")
}
}
private val data = mutableMapOf<Int, Call<R>>()
private var currentOrdinal = 0
override fun alwaysReturns(result: R) = setResult(GLOBAL_ORDINAL, result)
override fun alwaysThrows(throwable: Throwable) = setThrown(GLOBAL_ORDINAL, throwable)
override fun alwaysRuns(fakeImpl: Invoker<R>) = setFakeImpl(GLOBAL_ORDINAL, fakeImpl)
override fun otherwiseReturns(result: R) = alwaysReturns(result)
override fun otherwiseThrows(throwable: Throwable) = alwaysThrows(throwable)
override fun otherwiseRuns(fakeImpl: Invoker<R>) = alwaysRuns(fakeImpl)
override fun returns(result: R): CallFakeBuilder.Chain<R> {
setResult(currentOrdinal, result)
return this
}
override fun throws(throwable: Throwable): CallFakeBuilder.Chain<R> {
setThrown(currentOrdinal, throwable)
return this
}
override fun runs(fakeImpl: (ParameterList) -> R): CallFakeBuilder.Chain<R> {
setFakeImpl(currentOrdinal) { list, _ ->
fakeImpl(list)
}
return this
}
override fun onCall(n: Int): CallFakeBuilder.Action<R> {
currentOrdinal = n
return this
}
override fun toCallFake(): (Invoker<R>)? {
if (data.isEmpty()) {
return null
}
return { list, invokedData ->
val call = data[invokedData.callIndex]
if (null !== call) {
call.invoke(list, invokedData)
} else {
val global = data[GLOBAL_ORDINAL]
if (null !== global) {
global.invoke(list, invokedData)
} else {
throw MockingException("There is no global call fake. Please provide returned value via .otherwiseReturns() or use .otherwiseThrows() to throw an exception or .otherwiseRuns() to provide fake implementation")
}
}
}
}
private fun setResult(ordinal: Int, result: R) {
val call = findCall(ordinal)
call.returned = result
call.hasReturned = true
}
private fun setThrown(ordinal: Int, throwable: Throwable) {
val call = findCall(ordinal)
call.thrown = throwable
call.shouldThrow = true
}
private fun setFakeImpl(ordinal: Int, fakedImpl: Invoker<R>) {
val call = findCall(ordinal)
call.fakeImpl = fakedImpl
call.runFakeImpl = true
}
private fun findCall(ordinal: Int): Call<R> {
val item = data[ordinal]
if (item === null) {
val new = Call<R>(ordinal, null, null, null)
data[ordinal] = new
return new
}
return item
}
companion object {
const val GLOBAL_ORDINAL = -1
}
} | kotlin | 23 | 0.607214 | 228 | 29.480916 | 131 | starcoderdata |
package com.example.cleanarchitecture.ui.explore.person.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.cleanarchitecture.R
import com.example.cleanarchitecture.databinding.ItemPersonBinding
import com.example.domain.data.person.Person
class PeopleAdapter : PagingDataAdapter<Person, PeopleAdapter.ViewHolder>(
diffItemCallback
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
R.layout.item_person,
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = getItem(position)
if (item != null) {
holder(item)
}
}
class ViewHolder(private val binding: ItemPersonBinding) :
RecyclerView.ViewHolder(binding.root) {
operator fun invoke(person: Person) {
binding.person = person
binding.executePendingBindings()
}
}
companion object {
private val diffItemCallback = object : DiffUtil.ItemCallback<Person>() {
override fun areItemsTheSame(oldItem: Person, newItem: Person): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Person, newItem: Person): Boolean {
return oldItem == newItem
}
}
}
} | kotlin | 21 | 0.66088 | 88 | 30.436364 | 55 | starcoderdata |
package com.ekino.oss.jcv.db.util
import com.ekino.oss.jcv.core.JsonComparator
import com.fasterxml.jackson.databind.ObjectMapper
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import org.json.JSONTokener
import org.skyscreamer.jsonassert.JSONCompare
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import kotlin.test.fail
object JsonConverter {
fun compareJsonAndLogResult(actual: JSONArray, expected: JSONArray, jsonComparator: JsonComparator) {
JSONCompare.compareJSON(expected, actual, jsonComparator)
.takeUnless { it.passed() }
?.also { fail("${it.message}\nActual: $actual") }
}
fun formatInput(input: String) = when (val json = input.takeIfIsJson()) {
is JSONObject -> JSONArray().put(json)
is JSONArray -> json
else -> null
}
@Throws(IOException::class)
fun loadFileAsString(inputStream: InputStream) = inputStream.bufferedReader().use(BufferedReader::readText)
}
fun Any.toJsonObject() = JSONObject(ObjectMapper().writeValueAsString(this))
fun Any.toJsonArray() = JSONArray(ObjectMapper().writeValueAsString(this))
fun String.takeIfIsJson() = try {
when (val json = JSONTokener(this).nextValue()) {
is String -> null
is JSONObject, is JSONArray -> json
else -> null
}
} catch (e: JSONException) {
null
}
| kotlin | 19 | 0.716111 | 111 | 31.022727 | 44 | starcoderdata |
package com.tourcool.ui.certify
import android.os.Bundle
import com.frame.library.core.widget.titlebar.TitleBarView
import com.tourcool.core.module.activity.BaseTitleActivity
import com.tourcool.smartcity.R
import com.tourcool.ui.base.BaseCommonTitleActivity
/**
*@description :
*@company :途酷科技
* @author :JenkinsZhou
* @date 2020年01月03日11:32
* @Email: <EMAIL>
*/
class CertifySettingPassActivity : BaseCommonTitleActivity() {
override fun getContentLayout(): Int {
return R.layout.activity_certify_setting_pass
}
override fun setTitleBar(titleBar: TitleBarView?) {
super.setTitleBar(titleBar)
titleBar!!.setTitleMainText("设置密码")
}
override fun initView(savedInstanceState: Bundle?) {
}
} | kotlin | 10 | 0.737968 | 62 | 23.966667 | 30 | starcoderdata |
package com.anangkur.wallpaper.feature
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.anangkur.wallpaper.R
import com.anangkur.wallpaper.databinding.ActivityMainBinding
import com.anangkur.wallpaper.presentation.getHomeFragment
import com.anangkur.wallpaper.presentation.getSavedFragment
import com.anangkur.wallpaper.presentation.getSearchFragment
class MainActivity: AppCompatActivity(){
private lateinit var binding: ActivityMainBinding
var activeTabId = R.id.home
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
start()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
}
fun start() {
setupNavigationView()
binding.bottomNav.selectedItemId = activeTabId
}
private fun setupNavigationView() {
binding.bottomNav.setOnNavigationItemSelectedListener {
activeTabId = it.itemId
when (it.itemId) {
R.id.home -> {
setFragment(getHomeFragment())
true
}
R.id.search -> {
setFragment(getSearchFragment())
true
}
R.id.saved -> {
setFragment(getSavedFragment())
true
}
else -> false
}
}
}
private fun setFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction().replace(R.id.fragment_container_view, fragment).commit()
}
}
| kotlin | 22 | 0.640237 | 106 | 28.903226 | 62 | starcoderdata |
//KT-1244 Frontend allows access to private members of other classes
package kt1244
class A {
private var a = ""
}
class B() {
init {
A().<!HIDDEN!>a<!> = "Hello"
}
}
| kotlin | 11 | 0.573684 | 68 | 13.615385 | 13 | starcoderdata |
package ray.eldath.sirius.type
import ray.eldath.sirius.core.ValidationScope
open class BasicOption(type: ValidatableType, require: Boolean, nullable: Boolean) : Validatable(type) {
var isRequired = require
private set
val required: Unit
get() = run { isRequired = true }
val optional: Unit
get() {
isRequired = false
nullable
}
//
var isNullable = nullable
private set
val nullable: Unit
get() = run { isNullable = true }
val nonnull: Unit
get() = run { isNullable = false }
}
typealias AnyValidationScope = ValidationScope<*, *>
@DslMarker
annotation class TopClassValidationScopeMarker | kotlin | 12 | 0.639716 | 104 | 21.0625 | 32 | starcoderdata |
<filename>app/src/main/java/info/karelov/songlink/Alerts.kt
package info.karelov.songlink
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import io.reactivex.Observable
enum class ACTIONS {
OPEN,
COPY,
SHARE,
BACK
}
fun showProviderSelectDialog(providers: List<Provider>, context: Context): Observable<Provider> {
return Observable.create { emitter ->
val alert = AlertDialog.Builder(context)
alert.setTitle(context.getString(R.string.share_title))
alert.setNegativeButton(context.getString(R.string.share_action_cancel)) { dialog, _ ->
emitter.onComplete()
dialog.dismiss()
}
alert.setItems(providers.map{ it.label }.toTypedArray()) { dialog, index ->
emitter.onNext(providers[index])
emitter.onComplete()
dialog.dismiss()
}
alert.setCancelable(false)
alert.show()
}
}
fun showActionSelectDialog(provider: Provider, context: Context): Observable<Pair<ACTIONS, Provider>> {
return Observable.create { emitter ->
val alert = AlertDialog.Builder(context)
val items = arrayOf(
context.getString(R.string.share_action_open),
context.getString(R.string.share_action_copy),
context.getString(R.string.share_action_share)
)
fun complete(dialog: DialogInterface?) {
emitter.onComplete()
dialog?.dismiss()
}
alert.setTitle(provider.label)
alert.setItems(items) { dialog, index ->
when (index) {
0 -> emitter.onNext(Pair(ACTIONS.OPEN, provider))
1 -> emitter.onNext(Pair(ACTIONS.COPY, provider))
2 -> emitter.onNext(Pair(ACTIONS.SHARE, provider))
}
complete(dialog)
}
alert.setPositiveButton(context.getString(R.string.share_action_back)) { dialog, _ ->
emitter.onNext(Pair(ACTIONS.BACK, provider))
complete(dialog)
}
alert.setNegativeButton(context.getString(R.string.share_action_cancel)) { dialog, _ ->
complete(dialog)
}
alert.setCancelable(false)
alert.show()
}
} | kotlin | 28 | 0.622301 | 103 | 30.971831 | 71 | starcoderdata |
package com.garpr.android.preferences
import com.garpr.android.data.models.PollFrequency
import com.garpr.android.data.models.SmashRosterSyncResult
interface SmashRosterPreferenceStore : PreferenceStore {
val enabled: Preference<Boolean>
val hajimeteSync: Preference<Boolean>
val pollFrequency: Preference<PollFrequency>
val syncResult: Preference<SmashRosterSyncResult>
}
| kotlin | 9 | 0.810606 | 58 | 23.75 | 16 | starcoderdata |
package com.vicidroid.amalia.core
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
class ViewEventStore<E : ViewEvent> {
private val viewEventLiveData: MutableLiveData<E> = MutableLiveData()
fun pushEvent(event: E) {
viewEventLiveData.value = event
}
fun observe(owner: LifecycleOwner, observer: (E) -> Unit) {
viewEventLiveData.observe(owner, Observer<E> { observer.invoke(it!!) })
}
} | kotlin | 20 | 0.733333 | 79 | 28.176471 | 17 | starcoderdata |
<filename>reactdroid/src/main/java/com/guymichael/kotlinflux/KotlinExtensions.kt
package com.guymichael.kotlinflux
import io.reactivex.rxjava3.schedulers.Timed
import java.util.concurrent.TimeUnit
/**
* Use to group values by their updated timestamp (date), to have 'lists' in Reducers,
* as having actual lists is forbidden.
* **Note: **this method assumes that all [Timed] items are in millis
*/
fun <T> Iterable<Timed<T>>.toTimedReducerMap(): Map<Long, T> { //THINK speed
return groupBy({ it.time() }) {
it.value()
}.mapValues { it.value.last() }
}
/**
* Use to parse previously set Reducer value using [toTimedReducerMap]
* @return a sorted [Timed] list
*/
fun <T> Map<Long, T>.fromTimedReducerMap(): List<Timed<T>> { //THINK speed
return map { Timed(it.value, it.key, TimeUnit.MILLISECONDS) }
.sortedBy { it.time() }
} | kotlin | 19 | 0.700348 | 86 | 33.48 | 25 | starcoderdata |
<reponame>stipop-development/Stipop_SDK_Android
package io.stipop.models.response
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
import io.stipop.models.StickerPackage
@Keep
internal data class StickerPackageResponse(
@SerializedName("header") val header: ResponseHeader,
@SerializedName("body") val body: ResponseBody?
){
@Keep
data class ResponseBody(@SerializedName("package") val stickerPackage: StickerPackage?)
} | kotlin | 11 | 0.798301 | 91 | 30.466667 | 15 | starcoderdata |
<filename>java/dzjforex/build.gradle.kts
import org.gradle.internal.jvm.Jvm
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
group = "com.jforex.dzplugin"
version = "0.9.71"
description = """
The Java plugin part for Zorro which lets you trade with Dukascopy
Project name: ${project.name}
"""
plugins {
kotlin("jvm") version "1.3.21"
`maven-publish`
}
repositories {
mavenLocal()
mavenCentral()
//jcenter()
maven(url = "https://www.dukascopy.com/client/jforexlib/publicrepo")
}
dependencies {
compile(kotlin("stdlib-jdk8"))
compile("com.dukascopy.dds2:DDS2-jClient-JForex:3.4.13")
compile("com.jforex:KForexUtils:0.2.0-SNAPSHOT")
compile("org.aeonbits.owner:owner:1.0.10")
testCompile("io.kotlintest:kotlintest-runner-junit5:3.1.11")
testCompile("io.mockk:mockk:1.9")
testCompile("org.slf4j:slf4j-simple:1.7.25")
testImplementation(files(Jvm.current().toolsJar))
}
val jarFileName = "${project.name}-$version"
val zorroPath: String by project
val deployFolder = "$buildDir/zorro"
val historyFolder = "$deployFolder/History"
val pluginFolder = "$deployFolder/Plugin"
val zorroDukascopyFolder = "$zorroPath/Plugin/dukascopy"
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
tasks.withType<Jar> {
baseName = project.name
manifest.attributes.apply {
put("Implementation-Title", "${project.name}")
put("Implementation-Version", "$version")
put("Class-Path", ". ${configurations.runtime.get().map { "lib/${it.name}" }.joinToString(separator = " ")}")
}
}
tasks.register<Zip>("createDeployZip") {
dependsOn("jar")
dependsOn("createZorroFolders")
baseName = project.name
from(deployFolder)
}
tasks.create("createZorroFolders") {
outputs.upToDateWhen{ false }
dependsOn("jar")
val dukascopyFolder = "$pluginFolder/dukascopy"
val configFolder = "src/main/config"
File(pluginFolder).deleteRecursively()
copy {
from("../../c++/Release/dukascopy.dll")
into(pluginFolder)
}
copy {
from("$buildDir/libs/$jarFileName.jar")
into(dukascopyFolder)
}
copy {
from("$configFolder/."){
exclude ("AssetsDukascopy.csv", "zorroDukascopy.bat")
}
into(dukascopyFolder)
}
copy {
from(configurations.runtime)
into("$dukascopyFolder/lib")
}
File(historyFolder).deleteRecursively()
copy {
from("$configFolder/AssetsDukascopy.csv")
into(historyFolder)
}
copy {
from("$configFolder/zorroDukascopy.bat")
into(deployFolder)
}
copy {
from("$configFolder/zorroDukascopy.bat")
into(deployFolder)
}
}
tasks.register<Copy>("copyFoldersToZorro") {
outputs.upToDateWhen{ false }
dependsOn("createZorroFolders")
File(zorroDukascopyFolder).deleteRecursively()
copy {
from(deployFolder)
into("$zorroPath")
}
} | kotlin | 28 | 0.661028 | 118 | 23.721311 | 122 | starcoderdata |
/*
* MIT License
*
* Copyright (c) 2019 <NAME>
*
* 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.tunjid.rcswitchcontrol.viewholders
import android.content.res.ColorStateList
import android.graphics.Color
import android.view.ViewGroup
import com.tunjid.androidx.recyclerview.viewbinding.BindingViewHolder
import com.tunjid.androidx.recyclerview.viewbinding.viewHolderDelegate
import com.tunjid.androidx.recyclerview.viewbinding.viewHolderFrom
import com.tunjid.rcswitchcontrol.control.Record
import com.tunjid.rcswitchcontrol.databinding.ViewholderCommandBinding
import com.tunjid.rcswitchcontrol.databinding.ViewholderHistoryBinding
import com.tunjid.rcswitchcontrol.utils.makeAccessibleForTV
fun ViewGroup.historyViewHolder() = viewHolderFrom(ViewholderHistoryBinding::inflate).apply {
binding.text.apply {
makeAccessibleForTV(stroked = true)
isClickable = false
strokeColor = ColorStateList.valueOf(Color.WHITE)
}
}
fun ViewGroup.commandViewHolder(listener: ((Record) -> Unit)) = viewHolderFrom(ViewholderCommandBinding::inflate).apply {
binding.text.apply {
makeAccessibleForTV(stroked = true)
setOnClickListener { listener(record) }
strokeColor = ColorStateList.valueOf(Color.WHITE)
}
}
fun BindingViewHolder<ViewholderHistoryBinding>.bind(record: Record) {
binding.text.text = record.entry
}
private var BindingViewHolder<ViewholderCommandBinding>.record by viewHolderDelegate<Record>()
fun BindingViewHolder<ViewholderCommandBinding>.bindCommand(record: Record) = binding.run {
this@bindCommand.record = record
text.text = record.entry
}
| kotlin | 22 | 0.78256 | 121 | 40.75 | 64 | starcoderdata |
<filename>lib/modules/http/retrofit/src/main/java/dev/pthomain/android/dejavu/retrofit/di/DejaVuRetrofitModule.kt<gh_stars>10-100
/*
*
* Copyright (C) 2017-2020 <NAME>
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package dev.pthomain.android.dejavu.retrofit.di
import dev.pthomain.android.dejavu.cache.metadata.token.instruction.RequestMetadata
import dev.pthomain.android.dejavu.cache.metadata.token.instruction.operation.Operation
import dev.pthomain.android.dejavu.retrofit.annotations.processor.AnnotationProcessor
import dev.pthomain.android.dejavu.retrofit.glitchy.DejaVuReturnTypeParser
import dev.pthomain.android.dejavu.retrofit.glitchy.OperationReturnType
import dev.pthomain.android.dejavu.retrofit.glitchy.OperationReturnTypeParser
import dev.pthomain.android.dejavu.retrofit.interceptors.DejaVuRetrofitInterceptorFactory
import dev.pthomain.android.dejavu.retrofit.interceptors.HeaderInterceptor
import dev.pthomain.android.dejavu.retrofit.operation.RequestBodyConverter
import dev.pthomain.android.dejavu.retrofit.operation.RetrofitOperationResolver
import dev.pthomain.android.dejavu.serialisation.SerialisationArgumentValidator
import dev.pthomain.android.glitchy.core.Glitchy
import dev.pthomain.android.glitchy.core.interceptor.error.NetworkErrorPredicate
import dev.pthomain.android.glitchy.core.interceptor.error.glitch.Glitch
import dev.pthomain.android.glitchy.retrofit.GlitchyRetrofit
import dev.pthomain.android.glitchy.retrofit.interceptors.RetrofitInterceptors
import dev.pthomain.android.glitchy.retrofit.type.ReturnTypeParser
import org.koin.core.qualifier.named
import org.koin.dsl.module
class DejaVuRetrofitModule<E>
where E : Throwable,
E : NetworkErrorPredicate {
val module = module {
single { AnnotationProcessor(get(), get()) }
single { DejaVuReturnTypeParser<E>() }
single<ReturnTypeParser<OperationReturnType>> {
OperationReturnTypeParser<E>(
get(),
get(),
get()
)
}
single { RequestBodyConverter() }
single {
RetrofitOperationResolver.Factory<E>(
get<(RequestMetadata<*>) -> Operation.Remote?>(named("operationPredicate"))::invoke,
get<RequestBodyConverter>(),
get()
)
}
single<RetrofitInterceptors<E>> {
RetrofitInterceptors.After(
DejaVuRetrofitInterceptorFactory(
get(),
get(named("dateFactory")),
get(),
get()
)
)
}
single { HeaderInterceptor() }
single {
Glitchy.builder<E>(get())
.extend(GlitchyRetrofit.extension<E, OperationReturnType>())
.withReturnTypeParser(get())
.withInterceptors(get())
.build()
.callAdapterFactory
}
}
} | kotlin | 31 | 0.681205 | 129 | 38.316327 | 98 | starcoderdata |
package io.lenses.jdbc4.queries
import io.kotlintest.matchers.collections.shouldContain
import io.kotlintest.shouldBe
import io.kotlintest.specs.FunSpec
import io.lenses.jdbc4.LensesDriver
import io.lenses.jdbc4.ProducerSetup
import io.lenses.jdbc4.resultset.toList
class CreateTableTest : FunSpec(), ProducerSetup {
init {
LensesDriver()
val conn = conn()
test("CREATE TABLE foo") {
val tableName = "testtable__" + System.currentTimeMillis()
val stmt1 = conn.createStatement()
val rs = stmt1.executeQuery("CREATE TABLE $tableName (a text, b int, c boolean) FORMAT (json, json)")
rs.metaData.columnCount shouldBe 2
List(2) { rs.metaData.getColumnLabel(it + 1) } shouldBe listOf("flag", "info")
val stmt2 = conn.createStatement()
val rs2 = stmt2.executeQuery("SHOW TABLES").toList()
rs2.shouldContain(listOf(tableName, "USER", "1", "1"))
}
}
} | kotlin | 21 | 0.703704 | 107 | 28.645161 | 31 | starcoderdata |
package com.apivideoreactnativelivestream
import android.content.Context
import androidx.constraintlayout.widget.ConstraintLayout
class ReactNativeLivestreamView(context: Context): ConstraintLayout(context) {
init {
inflate(context, R.layout.react_native_livestream, this)
}
}
| kotlin | 12 | 0.813149 | 78 | 23.083333 | 12 | starcoderdata |
<filename>backend/server/build.gradle.kts
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
kotlin("jvm")
kotlin("plugin.serialization")
application
alias(libs.plugins.shadow)
}
group = "com.varabyte.kobweb.server"
version = libs.versions.kobweb.get()
dependencies {
implementation(kotlin("stdlib"))
implementation(libs.bundles.ktor)
implementation(libs.kaml)
implementation(project(":backend:kobweb-api"))
implementation(project(":common:kobweb-common"))
testImplementation(libs.truthish)
testImplementation(libs.ktor.server.tests)
testImplementation(kotlin("test"))
}
tasks.jar {
archiveFileName.set("kobweb-server.jar")
}
val applicationClass = "com.varabyte.kobweb.server.ApplicationKt"
project.setProperty("mainClassName", applicationClass)
application {
mainClass.set(applicationClass)
}
tasks.withType<ShadowJar> {
minimize {
// Code may end up getting referenced via reflection
exclude(project(":backend:kobweb-api"))
}
} | kotlin | 19 | 0.73442 | 65 | 23.857143 | 42 | starcoderdata |
package com.siliconlabs.bledemo.gatt_configurator.models
import java.util.*
data class Service16Bit(val identifier: Int, val name: String) {
fun getIdentifierAsString(): String {
return String.format("%04X", identifier)
}
fun getFullName(): String {
val hexString: String = "(0x".plus(String.format("%04X", identifier).plus(")").toUpperCase(Locale.getDefault()))
return name.plus(" ").plus(hexString)
}
override fun toString(): String {
return "0x".plus(String.format("%04X", identifier)).plus(" - ").plus(name)
}
} | kotlin | 19 | 0.651646 | 120 | 27.9 | 20 | starcoderdata |
package org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror
import com.sun.jdi.*
import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext
import java.lang.IllegalArgumentException
sealed class MethodEvaluator<T>(val method: Method?) {
fun value(value: ObjectReference?, context: DefaultExecutionContext, vararg values: Value): T? {
return method?.let {
return when {
method.isStatic -> {
// pass extension methods like the usual ones.
val args = if (value != null) {
listOf(value) + values.toList()
} else
values.toList()
@Suppress("UNCHECKED_CAST")
context.invokeMethod(method.declaringType() as ClassType, method, args) as T?
}
value != null ->
@Suppress("UNCHECKED_CAST")
context.invokeMethod(value, method, values.toList()) as T?
else -> throw IllegalArgumentException("Exception while calling method " + method.signature() + " with an empty value.")
}
}
}
class DefaultMethodEvaluator<T>(method: Method?) : MethodEvaluator<T>(method)
class MirrorMethodEvaluator<T, F>(method: Method?, private val mirrorProvider: MirrorProvider<T, F>): MethodEvaluator<T>(method) {
fun mirror(ref: ObjectReference, context: DefaultExecutionContext, vararg values: Value): F? {
return mirrorProvider.mirror(value(ref, context, *values), context)
}
fun isCompatible(value: T) = mirrorProvider.isCompatible(value)
}
}
sealed class FieldEvaluator<T>(val field: Field?, val thisRef: ReferenceTypeProvider) {
@Suppress("UNCHECKED_CAST")
fun value(value: ObjectReference): T? =
field?.let { value.getValue(it) as T? }
@Suppress("UNCHECKED_CAST")
fun staticValue(): T? = thisRef.getCls().let { it.getValue(field) as? T }
class DefaultFieldEvaluator<T>(field: Field?, thisRef: ReferenceTypeProvider) : FieldEvaluator<T>(field, thisRef)
class MirrorFieldEvaluator<T, F>(field: Field?, thisRef: ReferenceTypeProvider, private val mirrorProvider: MirrorProvider<T, F>) : FieldEvaluator<T>(field, thisRef) {
fun mirror(ref: ObjectReference, context: DefaultExecutionContext): F? =
mirrorProvider.mirror(value(ref), context)
fun mirrorOnly(value: T, context: DefaultExecutionContext) = mirrorProvider.mirror(value, context)
fun isCompatible(value: T) = mirrorProvider.isCompatible(value)
}
}
| kotlin | 27 | 0.648098 | 171 | 44.666667 | 57 | starcoderdata |
<reponame>jiqimaogou/kotlin
public class C {
<caret>public fun bar() {}
}
| kotlin | 5 | 0.679487 | 30 | 18.5 | 4 | starcoderdata |
<reponame>Palak-Bera/AR-Furniture
package com.difrancescogianmarco.arcore_flutter_plugin.utils
import android.util.Log
import com.google.ar.sceneform.math.Quaternion
import com.google.ar.sceneform.math.Vector3
import java.util.*
class DecodableUtils {
companion object {
fun parseVector3(vector: HashMap<String, *>?): Vector3? {
if (vector != null) {
val x: Float = (vector["x"] as Double).toFloat()
val y: Float = (vector["y"] as Double).toFloat()
val z: Float = (vector["z"] as Double).toFloat()
return Vector3(x, y, z)
}
return null
}
fun parseQuaternion(vector: HashMap<String, Double>?): Quaternion? {
if (vector != null) {
val x: Float = (vector["x"] as Double).toFloat()
val y: Float = (vector["y"] as Double).toFloat()
val z: Float = (vector["z"] as Double).toFloat()
val w: Float = (vector["w"] as Double).toFloat()
return Quaternion(x, y, z, w)
}
return null
}
}
} | kotlin | 22 | 0.544974 | 76 | 33.393939 | 33 | starcoderdata |
<reponame>breedloj/aws-toolkit-jetbrains
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.utils
import com.intellij.execution.ExecutorRegistry
import com.intellij.execution.Output
import com.intellij.execution.OutputListener
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.executors.DefaultDebugExecutor
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.runners.ExecutionEnvironmentBuilder
import com.intellij.execution.runners.ProgramRunner
import com.intellij.openapi.application.runInEdt
import com.intellij.xdebugger.XDebugProcess
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.XDebuggerManager
import com.intellij.xdebugger.XDebuggerManagerListener
import com.jetbrains.rdclient.util.idea.waitAndPump
import com.jetbrains.rider.projectView.solutionDirectory
import com.jetbrains.rider.test.scriptingApi.DebugTestExecutionContext
import com.jetbrains.rider.test.scriptingApi.debugProgramAfterAttach
import com.jetbrains.rider.test.scriptingApi.dumpFullCurrentData
import com.jetbrains.rider.test.scriptingApi.resumeSession
import com.jetbrains.rider.test.scriptingApi.waitForDotNetDebuggerInitializedOrCanceled
import com.jetbrains.rider.test.scriptingApi.waitForPause
import java.time.Duration
import java.util.concurrent.CompletableFuture
import kotlin.test.assertNotNull
private fun executeAndWaitOnAttach(runConfiguration: RunConfiguration): CompletableFuture<XDebugSession> {
val project = runConfiguration.project
val executorId = DefaultDebugExecutor.EXECUTOR_ID
val sessionFuture = CompletableFuture<XDebugSession>()
project.messageBus.connect().subscribe(
XDebuggerManager.TOPIC,
object : XDebuggerManagerListener {
override fun processStarted(debugProcess: XDebugProcess) {
println("Debugger attached: $debugProcess")
debugProcess.processHandler.addProcessListener(object : OutputListener() {
override fun processTerminated(event: ProcessEvent) {
println("Debug worker terminated with exit code: ${this.output.exitCode}")
println("Debug worker stdout: ${this.output.stdout}")
println("Debug worker stderr: ${this.output.stderr}")
}
})
sessionFuture.complete(debugProcess.session)
}
}
)
val executor = ExecutorRegistry.getInstance().getExecutorById(executorId)
assertNotNull(executor)
val executionFuture = CompletableFuture<Output>()
// In the real world create and execute runs on EDT
runInEdt {
try {
@Suppress("UnsafeCallOnNullableType")
val runner = ProgramRunner.getRunner(executorId, runConfiguration)!!
val executionEnvironmentBuilder = ExecutionEnvironmentBuilder.create(executor, runConfiguration)
.runner(runner)
val executionEnvironment = executionEnvironmentBuilder.build()
// TODO: exception isn't propagated out and test is forced to wait to timeout instead of exiting immediately
executionEnvironment.runner.execute(executionEnvironment)
} catch (e: Throwable) {
executionFuture.completeExceptionally(e)
}
}
return sessionFuture
}
fun executeRunConfigurationAndWaitRider(runConfiguration: RunConfiguration, executorId: String = DefaultRunExecutor.EXECUTOR_ID): Output {
if (executorId == DefaultRunExecutor.EXECUTOR_ID) {
val executeLambda = executeRunConfiguration(runConfiguration, executorId)
// waitAndPump lets us run on EDT in the test itself without deadlocking since Rider runs tests on EDT
// 4 is arbitrary, but Image-based functions can take > 3 min on first build/run, so 4 is a safe number
waitAndPump(Duration.ofMinutes(4), { executeLambda.isDone })
if (!executeLambda.isDone) {
throw IllegalStateException("Took too long to execute Rider run configuration!")
}
return executeLambda.get()
}
val session = executeAndWaitOnAttach(runConfiguration)
waitAndPump(Duration.ofMinutes(4), { session.isDone })
val executionFuture = CompletableFuture<Output>()
val waitAndTest: DebugTestExecutionContext.() -> Unit = {
waitForDotNetDebuggerInitializedOrCanceled()
waitForPause()
this.session.debugProcess.processHandler.addProcessListener(object : OutputListener() {
override fun processTerminated(event: ProcessEvent) {
super.processTerminated(event)
executionFuture.complete(this.output)
}
})
// prints current debugger state for comparison against .gold file
dumpFullCurrentData()
resumeSession()
}
debugProgramAfterAttach(session.get(), runConfiguration.project.solutionDirectory.resolve("expected.gold"), waitAndTest, true)
return executionFuture.get()
}
| kotlin | 31 | 0.738183 | 138 | 46.118182 | 110 | starcoderdata |
package me.liangfei.databinding.workers
import android.content.Context
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import me.liangfei.databinding.data.entities.Actor
import me.liangfei.databinding.data.AppDatabase
import me.liangfei.databinding.utilities.ACTOR_DATA_FILENAME
class SeedDatabaseWorker(
context: Context,
workerParams: WorkerParameters
) : CoroutineWorker(context, workerParams) {
private val TAG by lazy { SeedDatabaseWorker::class.java.simpleName }
override val coroutineContext = Dispatchers.IO
override suspend fun doWork(): Result = coroutineScope {
try {
applicationContext.assets.open(ACTOR_DATA_FILENAME).use { inputStream ->
JsonReader(inputStream.reader()).use { jsonReader ->
val actorType = object : TypeToken<List<Actor>>() {}.type
val actorList: List<Actor> = Gson().fromJson(jsonReader, actorType)
val database = AppDatabase.getInstance(applicationContext)
database.actorDao().insertAll(actorList)
Result.success()
}
}
} catch (ex: Exception) {
Log.e(TAG, "Error seeding database", ex)
Result.failure()
}
}
} | kotlin | 34 | 0.683071 | 87 | 34.465116 | 43 | starcoderdata |
package com.chicagoroboto.features.location
import com.chicagoroboto.data.VenueProvider
import com.chicagoroboto.features.location.LocationPresenter.Event
import com.chicagoroboto.features.location.LocationPresenter.Model
import com.chicagoroboto.features.shared.Presenter
import com.chicagoroboto.model.Venue
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.Channel.Factory.BUFFERED
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject
class LocationPresenter @Inject constructor(
private val venueProvider: VenueProvider
) : Presenter<Model, Event> {
private val _models = ConflatedBroadcastChannel<Model>()
override val models: Flow<Model> get() = _models.asFlow()
private val _events = Channel<Event>(BUFFERED)
override val events: SendChannel<Event> get() = _events
override suspend fun start() = coroutineScope<Unit> {
var model = Model()
fun sendModel(newModel: Model) {
model = newModel
_models.offer(model)
}
launch {
venueProvider.venue().collect {
sendModel(model.copy(venue = it))
}
}
}
data class Model(
val venue: Venue = Venue("Conference Center")
)
sealed class Event
}
| kotlin | 28 | 0.773098 | 66 | 29.666667 | 48 | starcoderdata |
package com.instacart.formula.android.internal
import androidx.fragment.app.FragmentActivity
import com.instacart.formula.android.ActivityConfigurator
import com.instacart.formula.android.FragmentEnvironment
import kotlin.reflect.KClass
internal class ActivityStoreFactory internal constructor(
private val bindings: Map<KClass<*>, ActivityConfigurator.Binding<*>>,
private val environment: FragmentEnvironment
) {
companion object {
operator fun invoke(
environment: FragmentEnvironment,
activities: ActivityConfigurator.() -> Unit
): ActivityStoreFactory {
val bindings = ActivityConfigurator().apply(activities).bindings
return ActivityStoreFactory(bindings, environment)
}
}
internal fun <A : FragmentActivity> init(activity: A): ActivityManager<A>? {
val initializer = bindings[activity::class] as? ActivityConfigurator.Binding<A>
?: return null
val activityDelegate = ActivityStoreContextImpl<A>()
return initializer.init.invoke(activityDelegate)?.let { store ->
ActivityManager(
environment = environment,
delegate = activityDelegate,
store = store
)
}
}
}
| kotlin | 16 | 0.678906 | 87 | 35.571429 | 35 | starcoderdata |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.nodejs.protractor
import com.intellij.execution.Executor
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.LocatableConfigurationBase
import com.intellij.execution.configurations.RuntimeConfigurationError
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.javascript.nodejs.interpreter.local.NodeJsLocalInterpreter
import com.intellij.javascript.nodejs.util.NodePackage
import com.intellij.javascript.protractor.ProtractorUtil
import com.intellij.openapi.project.Project
import com.intellij.util.PathUtil
import org.jdom.Element
import java.io.File
// Based on com.intellij.javascript.protractor.ProtractorRunConfiguration
class KotlinProtractorRunConfiguration(
project: Project,
factory: ConfigurationFactory,
name: String
) : LocatableConfigurationBase(project, factory, name) {
var runSettings = KotlinProtractorRunSettings()
val protractorPackage: NodePackage
get() {
val project = project
val interpreter = runSettings.interpreterRef.resolve(project)
return ProtractorUtil.getProtractorPackage(project, null, interpreter, true)
}
override fun getState(executor: Executor, environment: ExecutionEnvironment) =
KotlinProtractorRunState(this, environment, protractorPackage)
override fun getConfigurationEditor() = KotlinProtractorRunConfigurationEditor(project)
override fun readExternal(element: Element) {
super.readExternal(element)
runSettings = KotlinProtractorRunSettings.readFromXML(element)
}
override fun writeExternal(element: Element) {
super.writeExternal(element)
runSettings.writeToXML(element)
}
fun initialize() {
setNameChangedByUser(false)
}
override fun checkConfiguration() {
val isOptionalConfig = runSettings.testFileSystemDependentPath.isNotBlank() || runSettings.seleniumAddress.isNotBlank()
if (isOptionalConfig) {
validatePath("test file", runSettings.testFileSystemDependentPath, true, false)
if (runSettings.seleniumAddress.isBlank()) {
throw RuntimeConfigurationError("Unspecified Selenium address")
}
}
if (!isOptionalConfig || runSettings.configFileSystemDependentPath.isNotBlank()) {
validatePath("configuration file", runSettings.configFileSystemDependentPath, true, false)
}
val interpreter = runSettings.interpreterRef.resolve(project)
NodeJsLocalInterpreter.checkForRunConfiguration(interpreter)
validatePath("protractor package", protractorPackage.systemDependentPath, true, true)
}
override fun suggestedName(): String? {
val name = PathUtil.getFileName(runSettings.testFileSystemDependentPath)
return if (name.isNotBlank()) name else null
}
private fun validatePath(name: String,
path: String?,
shouldBeAbsolute: Boolean,
shouldBeDirectory: Boolean
) {
if (path.isNullOrBlank()) throw RuntimeConfigurationError("Unspecified " + name)
val file = File(path!!)
if (shouldBeAbsolute && !file.isAbsolute) throw RuntimeConfigurationError("No such " + name)
val exists = if (shouldBeDirectory) file.isDirectory else file.isFile
if (!exists) throw RuntimeConfigurationError("No such " + name)
}
} | kotlin | 17 | 0.725779 | 127 | 39.194175 | 103 | starcoderdata |
/*
* Copyright 2020 Babylon Partners Limited
*
* 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.babylon.certificatetransparency.internal.utils
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Okio
internal class MaxSizeInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val response = chain.proceed(
request.newBuilder().apply {
removeHeader(HEADER)
}.build()
)
val body = response.body()
return request.headers(HEADER).firstOrNull()?.toLongOrNull()?.let { maxSize ->
response.newBuilder().body(
ResponseBody.create(
body!!.contentType(),
body.contentLength(),
Okio.buffer(Okio.source(LimitedSizeInputStream(body.byteStream(), maxSize)))
)
).build()
} ?: response
}
companion object {
private const val HEADER = "Max-Size"
}
}
| kotlin | 38 | 0.65201 | 96 | 30.84 | 50 | starcoderdata |
<reponame>sudhinm/reposilite
/*
* Copyright (c) 2021 dzikoysk
*
* 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.reposilite.token.infrastructure
import com.reposilite.shared.firstAndMap
import com.reposilite.token.AccessTokenRepository
import com.reposilite.token.api.AccessToken
import com.reposilite.token.api.AccessTokenPermission
import com.reposilite.token.api.AccessTokenPermission.Companion.findAccessTokenPermissionByIdentifier
import com.reposilite.token.api.AccessTokenType
import com.reposilite.token.api.Route
import com.reposilite.token.api.RoutePermission.Companion.findRoutePermissionByIdentifier
import net.dzikoysk.exposed.shared.UNINITIALIZED_ENTITY_ID
import net.dzikoysk.exposed.upsert.withIndex
import net.dzikoysk.exposed.upsert.withUnique
import org.jetbrains.exposed.dao.id.IntIdTable
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.ReferenceOption.CASCADE
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.deleteWhere
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.javatime.date
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.update
import java.util.UUID
const val MAX_ROUTE_LENGTH = 1024
object AccessTokenTable : IntIdTable("access_token") {
val name = varchar("name", 255).uniqueIndex("uq_name")
val secret = varchar("secret", 512)
val createdAt = date("createdAt")
val description = text("description")
}
object PermissionToAccessTokenTable : Table("permission_access_token") {
val accessTokenId = reference("access_token_id", AccessTokenTable.id, onDelete = CASCADE, onUpdate = CASCADE)
val permission = varchar("permission", 48)
init {
withIndex("index_access_token_id", columns = arrayOf(accessTokenId))
withUnique("unique_access_token_id_permission", accessTokenId, permission)
}
}
object PermissionToRouteTable : Table("permission_route") {
val accessTokenId = reference("access_token_id", AccessTokenTable.id, onDelete = CASCADE, onUpdate = CASCADE)
val routeId = uuid("route_id")
val route = varchar("route", MAX_ROUTE_LENGTH)
val permission = varchar("permission", 48)
init {
withIndex("index_access_token_id_route_id", columns = arrayOf(accessTokenId, routeId))
withUnique("unique_access_token_id_route_id_permission", accessTokenId, routeId, permission)
}
}
internal class SqlAccessTokenRepository(private val database: Database) : AccessTokenRepository {
init {
transaction(database) {
SchemaUtils.create(AccessTokenTable, PermissionToAccessTokenTable, PermissionToRouteTable)
SchemaUtils.createMissingTablesAndColumns(AccessTokenTable, PermissionToAccessTokenTable, PermissionToRouteTable)
}
}
override fun saveAccessToken(accessToken: AccessToken): AccessToken =
transaction(database) {
when(getIdByName(accessToken.name)) {
UNINITIALIZED_ENTITY_ID -> createAccessToken(accessToken)
else -> updateAccessToken(accessToken)
}
}
private fun createAccessToken(accessToken: AccessToken): AccessToken {
AccessTokenTable.insert {
it[this.name] = accessToken.name
it[this.secret] = accessToken.secret
it[this.createdAt] = accessToken.createdAt
it[this.description] = accessToken.description
}
val createdAccessToken = accessToken.copy(id = getIdByName(accessToken.name))
createPermissions(createdAccessToken)
createRoutes(createdAccessToken)
return createdAccessToken
}
private fun updateAccessToken(accessToken: AccessToken): AccessToken {
AccessTokenTable.update({ AccessTokenTable.id eq accessToken.id }, body = {
it[this.name] = accessToken.name
it[this.secret] = accessToken.secret
it[this.createdAt] = accessToken.createdAt
it[this.description] = accessToken.description
})
PermissionToAccessTokenTable.deleteWhere { PermissionToAccessTokenTable.accessTokenId eq accessToken.id }
createPermissions(accessToken)
PermissionToRouteTable.deleteWhere { PermissionToRouteTable.accessTokenId eq accessToken.id }
createRoutes(accessToken)
return accessToken
}
private fun createPermissions(accessToken: AccessToken) {
accessToken.permissions.forEach { permission ->
PermissionToAccessTokenTable.insert {
it[this.accessTokenId] = accessToken.id
it[this.permission] = permission.identifier
}
}
}
private fun createRoutes(accessToken: AccessToken) {
accessToken.routes.forEach { route ->
route.permissions.forEach { permission ->
PermissionToRouteTable.insert {
it[this.accessTokenId] = accessToken.id
it[this.routeId] = UUID.nameUUIDFromBytes(route.path.toByteArray())
it[this.route] = route.path
it[this.permission] = permission.identifier
}
}
}
}
private fun getIdByName(name: String): Int =
AccessTokenTable.select { AccessTokenTable.name eq name }
.map { it[AccessTokenTable.id] }
.firstOrNull()
?.value
?: UNINITIALIZED_ENTITY_ID
override fun deleteAccessToken(accessToken: AccessToken) {
transaction(database) {
AccessTokenTable.deleteWhere { AccessTokenTable.id eq accessToken.id }
}
}
private fun findAccessTokenPermissionsById(id: Int): Set<AccessTokenPermission> =
PermissionToAccessTokenTable.select { PermissionToAccessTokenTable.accessTokenId eq id }
.map { findAccessTokenPermissionByIdentifier(it[PermissionToAccessTokenTable.permission])!! }
.toSet()
private fun findRoutesById(id: Int): Set<Route> =
PermissionToRouteTable.select { PermissionToRouteTable.accessTokenId eq id }
.map { Pair(it[PermissionToRouteTable.route], it[PermissionToRouteTable.permission]) }
.groupBy { it.first }
.map { (route, permissions) ->
Route(route, permissions.map { findRoutePermissionByIdentifier(it.second) }.toSet())
}
.toSet()
private fun toAccessToken(result: ResultRow): AccessToken =
result[AccessTokenTable.id].value.let { accessTokenId ->
AccessToken(
accessTokenId,
AccessTokenType.PERSISTENT,
result[AccessTokenTable.name],
result[AccessTokenTable.secret],
result[AccessTokenTable.createdAt],
result[AccessTokenTable.description],
findAccessTokenPermissionsById(accessTokenId),
findRoutesById(accessTokenId)
)
}
override fun findAccessTokenByName(name: String): AccessToken? =
transaction(database) {
AccessTokenTable.select { AccessTokenTable.name eq name }.firstAndMap { toAccessToken(it) }
}
override fun findAll(): Collection<AccessToken> =
transaction(database) {
AccessTokenTable.selectAll().map { toAccessToken(it) }
}
override fun countAccessTokens(): Long =
transaction(database) {
AccessTokenTable.selectAll().count()
}
} | kotlin | 30 | 0.694492 | 125 | 39.053922 | 204 | starcoderdata |
package io.github.rybalkinsd.kohttp.dsl
import io.github.rybalkinsd.kohttp.client.defaultHttpClient
import io.github.rybalkinsd.kohttp.dsl.context.UploadContext
import okhttp3.Call
import okhttp3.Response
/**
* Method provides a synchronous DSL call of HTTP POST to UPLOAD file
*
* @return a `Response` instance.
*
* Usage example with default `defaultHttpClient`:
*
* <pre>
* val response: Response = upload {
* url("http://postman-echo.com/post")
* val fileUri = this.javaClass.getResource("/cat.gif").toURI()
* file(fileUri)
* }
* response.use { ... }
* </pre>
*
* @param client allow to use your own implementation of HttpClient.
* `defaultHttpClient` is used by default.
*
* <pre>
* val response: Response = upload(customHttpClient) {
* ...
* }
* </pre>
*
* @see Response
* @see HttpDeleteContext
*
* @since 0.8.0
* @author sergey
*/
fun upload(client: Call.Factory = defaultHttpClient, init: UploadContext.() -> Unit): Response {
val context = UploadContext().apply(init)
return client.newCall(context.makeRequest()).execute()
}
| kotlin | 14 | 0.68087 | 96 | 25.261905 | 42 | starcoderdata |
<filename>compiler/testData/psi/recovery/objects/declarations/Everything.kt
object Foo<T, R> private (x: Int, y: Int) : Bar, Baz {
fun foo() {}
} | kotlin | 8 | 0.697987 | 75 | 36.5 | 4 | starcoderdata |
<filename>compiler/testData/diagnostics/tests/enum/enumStarImport.kt<gh_stars>1000+
// FILE: enum.kt
package enum
enum class HappyEnum {
CASE1,
CASE2
}
// FILE: user.kt
import enum.HappyEnum
import enum.HappyEnum.*
fun f(e: HappyEnum) {
when (e) {
CASE1 -> throw UnsupportedOperationException() // unresolved reference
CASE2 -> throw UnsupportedOperationException() // unresolved references
}
} | kotlin | 11 | 0.705336 | 83 | 19.571429 | 21 | starcoderdata |
<reponame>vitekkor/bbfgradle
// !JVM_DEFAULT_MODE: compatibility
// TARGET_BACKEND: JVM
// JVM_TARGET: 1.8
// WITH_REFLECT
annotation class Property(val value: String)
annotation class Accessor(val value: String)
interface Z {
@Property("OK")
@JvmDefault
val z: String
@Accessor("OK")
get() = "OK"
}
class Test : Z
fun box() : String {
val value = Z::z.annotations.filterIsInstance<Property>().single().value
if (value != "OK") return value
return (Z::z.getter.annotations.single() as Accessor).value
}
| kotlin | 13 | 0.662409 | 76 | 20.92 | 25 | starcoderdata |
package com.mdmy.v3.viewholder
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.mdmy.v3.R
class PlaceResultViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val mPlaceAddress = view.findViewById<TextView>(R.id.tv_list_item)
fun update(place: String) {
mPlaceAddress.text = place
}
}
| kotlin | 11 | 0.762887 | 78 | 26.714286 | 14 | starcoderdata |
package kscript.app
import kscript.app.ShellUtils.requireInPath
import java.io.*
import java.net.URL
import java.nio.file.Files
import java.nio.file.Paths
import java.security.MessageDigest
import java.util.function.Consumer
import kotlin.system.exitProcess
data class ProcessResult(val command: String, val exitCode: Int, val stdout: String, val stderr: String) {
override fun toString(): String {
return """
Exit Code : ${exitCode}Comand : ${command}
Stdout : ${stdout}
Stderr : """.trimIndent() + "\n" + stderr
}
}
fun evalBash(cmd: String, wd: File? = null,
stdoutConsumer: Consumer<String> = StringBuilderConsumer(),
stderrConsumer: Consumer<String> = StringBuilderConsumer()): ProcessResult {
return runProcess("bash", "-c", cmd,
wd = wd, stderrConsumer = stderrConsumer, stdoutConsumer = stdoutConsumer)
}
fun runProcess(cmd: String, wd: File? = null): ProcessResult {
val parts = cmd.split("\\s".toRegex())
return runProcess(cmd = *parts.toTypedArray(), wd = wd)
}
fun runProcess(vararg cmd: String, wd: File? = null,
stdoutConsumer: Consumer<String> = StringBuilderConsumer(),
stderrConsumer: Consumer<String> = StringBuilderConsumer()): ProcessResult {
try {
// simplify with https://stackoverflow.com/questions/35421699/how-to-invoke-external-command-from-within-kotlin-code
val proc = ProcessBuilder(cmd.asList()).
directory(wd).
// see https://youtrack.jetbrains.com/issue/KT-20785
apply { environment()["KOTLIN_RUNNER"] = "" }.
start();
// we need to gobble the streams to prevent that the internal pipes hit their respecitive buffer limits, which
// would lock the sub-process execution (see see https://github.com/holgerbrandl/kscript/issues/55
// https://stackoverflow.com/questions/14165517/processbuilder-forwarding-stdout-and-stderr-of-started-processes-without-blocki
val stdoutGobbler = StreamGobbler(proc.inputStream, stdoutConsumer).apply { start() }
val stderrGobbler = StreamGobbler(proc.errorStream, stderrConsumer).apply { start() }
val exitVal = proc.waitFor()
// we need to wait for the gobbler threads or we may loose some output (e.g. in case of short-lived processes
stderrGobbler.join()
stdoutGobbler.join()
return ProcessResult(cmd.joinToString(" "), exitVal, stdoutConsumer.toString(), stderrConsumer.toString())
} catch (t: Throwable) {
throw RuntimeException(t)
}
}
internal class StreamGobbler(private val inputStream: InputStream, private val consumeInputLine: Consumer<String>) : Thread() {
override fun run() {
BufferedReader(InputStreamReader(inputStream)).lines().forEach(consumeInputLine)
}
}
internal open class StringBuilderConsumer : Consumer<String> {
val sb = StringBuilder()
override fun accept(t: String) {
sb.appendln(t)
}
override fun toString(): String {
return sb.toString()
}
}
object ShellUtils {
fun isInPath(tool: String) = evalBash("which $tool").stdout.trim().isNotBlank()
fun requireInPath(tool: String, msg: String = "$tool is not in PATH") = errorIf(!isInPath(tool)) { msg }
}
fun info(msg: String) = System.err.println(msg)
fun infoMsg(msg: String) = System.err.println("[kscript] " + msg)
fun warnMsg(msg: String) = System.err.println("[kscript] [WARN] " + msg)
fun errorMsg(msg: String) = System.err.println("[kscript] [ERROR] " + msg)
fun errorIf(value: Boolean, lazyMessage: () -> Any) {
if (value) {
errorMsg(lazyMessage().toString())
quit(1)
}
}
fun quit(status: Int): Nothing {
print(if (status == 0) "true" else "false")
exitProcess(status)
}
/** see discussion on https://github.com/holgerbrandl/kscript/issues/15*/
fun guessKotlinHome(): String? {
return evalBash("KOTLIN_RUNNER=1 JAVACMD=echo kotlinc").stdout.run {
"kotlin.home=([^\\s]*)".toRegex()
.find(this)?.groups?.get(1)?.value
}
}
fun createTmpScript(scriptText: String, extension: String = "kts"): File {
return File(SCRIPT_TEMP_DIR, "scriptlet.${md5(scriptText)}.$extension").apply {
writeText(scriptText)
}
}
fun fetchFromURL(scriptURL: String): File {
val urlHash = md5(scriptURL)
val urlExtension = if (scriptURL.endsWith(".kt")) "kt" else "kts"
val urlCache = File(KSCRIPT_CACHE_DIR, "/url_cache_${urlHash}.$urlExtension")
if (!urlCache.isFile) {
urlCache.writeText(URL(scriptURL).readText())
}
return urlCache
}
fun md5(byteProvider: () -> ByteArray): String {
// from https://stackoverflow.com/questions/304268/getting-a-files-md5-checksum-in-java
val md = MessageDigest.getInstance("MD5")
md.update(byteProvider())
// disabled to support java9 which dropeed DataTypeConverter
// md.update(byteProvider())
// val digestInHex = DatatypeConverter.printHexBinary(md.digest()).toLowerCase()
val digestInHex = bytesToHex(md.digest()).toLowerCase()
return digestInHex.substring(0, 16)
}
fun md5(msg: String) = md5 { msg.toByteArray() }
fun md5(file: File) = md5 { Files.readAllBytes(Paths.get(file.toURI())) }
// from https://github.com/frontporch/pikitis/blob/master/src/test/kotlin/repacker.tests.kt
private fun bytesToHex(buffer: ByteArray): String {
val HEX_CHARS = "0123456789ABCDEF".toCharArray()
val len = buffer.count()
val result = StringBuffer(len * 2)
var ix = 0
while (ix < len) {
val octet = buffer[ix].toInt()
val firstIndex = (octet and 0xF0).ushr(4)
val secondIndex = octet and 0x0F
result.append(HEX_CHARS[firstIndex])
result.append(HEX_CHARS[secondIndex])
ix++
}
return result.toString()
}
fun numLines(str: String) = str.split("\r\n|\r|\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size
fun launchIdeaWithKscriptlet(scriptFile: File, dependencies: List<String>, customRepos: List<MavenRepo>, includeURLs: List<URL>): String {
requireInPath("idea", "Could not find 'idea' in your PATH. It can be created in IntelliJ under `Tools -> Create Command-line Launcher`")
infoMsg("Setting up idea project from ${scriptFile}")
// val tmpProjectDir = createTempDir("edit_kscript", suffix="")
// .run { File(this, "kscript_tmp_project") }
// .apply { mkdir() }
// fixme use tmp instead of cachdir. Fails for now because idea gradle import does not seem to like tmp
val tmpProjectDir = KSCRIPT_CACHE_DIR
.run { File(this, "kscript_tmp_project__${scriptFile.name}_${System.currentTimeMillis()}") }
.apply { mkdir() }
// val tmpProjectDir = File("/Users/brandl/Desktop/")
// .run { File(this, "kscript_tmp_project") }
// .apply { mkdir() }
val stringifiedDeps = dependencies.map { " compile \"$it\"" }.joinToString("\n")
val stringifiedRepos = customRepos.map { " maven {\n url '${it.url}'\n }\n" }.joinToString("\n")
val gradleScript = """
plugins {
id "org.jetbrains.kotlin.jvm" version "${KotlinVersion.CURRENT}"
}
repositories {
mavenLocal()
jcenter()
$stringifiedRepos
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib"
compile "org.jetbrains.kotlin:kotlin-script-runtime"
$stringifiedDeps
}
sourceSets.main.java.srcDirs 'src'
""".trimIndent()
File(tmpProjectDir, "build.gradle").writeText(gradleScript)
// also copy/symlink script resource in
File(tmpProjectDir, "src").run {
mkdir()
// https://stackoverflow.com/questions/17926459/creating-a-symbolic-link-with-java
createSymLink(File(this, scriptFile.name), scriptFile)
// also symlink all includes
includeURLs.distinctBy { it.fileName() }
.forEach {
val includeFile = when {
it.protocol == "file" -> File(it.toURI())
else -> fetchFromURL(it.toString())
}
createSymLink(File(this, it.fileName()), includeFile)
}
}
return "idea \"${tmpProjectDir.absolutePath}\""
}
private fun URL.fileName() = this.toURI().path.split("/").last()
private fun createSymLink(link: File, target: File) {
try {
Files.createSymbolicLink(link.toPath(), target.absoluteFile.toPath());
} catch (e: IOException) {
errorMsg("Failed to create symbolic link to script. Copying instead...")
target.copyTo(link)
}
}
/**
* Create and use a temporary gradle project to package the compiled script using capsule.
* See https://github.com/puniverse/capsule
*/
fun packageKscript(scriptJar: File, wrapperClassName: String, dependencies: List<String>, customRepos: List<MavenRepo>, runtimeOptions: String, appName: String) {
requireInPath("gradle", "gradle is required to package kscripts")
infoMsg("Packaging script '$appName' into standalone executable...")
val tmpProjectDir = KSCRIPT_CACHE_DIR
.run { File(this, "kscript_tmp_project__${scriptJar.name}_${System.currentTimeMillis()}") }
.apply { mkdir() }
val stringifiedDeps = dependencies.map { " compile \"$it\"" }.joinToString("\n")
val stringifiedRepos = customRepos.map { " maven {\n url '${it.url}'\n }\n" }.joinToString("\n")
val jvmOptions = runtimeOptions.split(" ")
.filter { it.startsWith("-J") }
.map { it.removePrefix("-J") }
.map { '"' + it + '"' }
.joinToString(", ")
// https://shekhargulati.com/2015/09/10/gradle-tip-using-gradle-plugin-from-local-maven-repository/
val gradleScript = """
plugins {
id "org.jetbrains.kotlin.jvm" version "${KotlinVersion.CURRENT}"
id "us.kirchmeier.capsule" version "1.0.2"
}
repositories {
mavenLocal()
jcenter()
$stringifiedRepos
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib"
$stringifiedDeps
compile group: 'org.jetbrains.kotlin', name: 'kotlin-script-runtime', version: '${KotlinVersion.CURRENT}'
// https://stackoverflow.com/questions/20700053/how-to-add-local-jar-file-dependency-to-build-gradle-file
compile files('${scriptJar.invariantSeparatorsPath}')
}
task simpleCapsule(type: FatCapsule){
applicationClass '$wrapperClassName'
archiveName '$appName'
// http://www.capsule.io/user-guide/#really-executable-capsules
reallyExecutable
capsuleManifest {
jvmArgs = [$jvmOptions]
//args = []
//systemProperties['java.awt.headless'] = true
}
}
""".trimIndent()
val pckgedJar = File(Paths.get("").toAbsolutePath().toFile(), appName).absoluteFile
// create exec_header to allow for direction execution (see http://www.capsule.io/user-guide/#really-executable-capsules)
// from https://github.com/puniverse/capsule/blob/master/capsule-util/src/main/resources/capsule/execheader.sh
File(tmpProjectDir, "exec_header.sh").writeText("""#!/usr/bin/env bash
exec java -jar ${'$'}0 "${'$'}@"
""")
File(tmpProjectDir, "build.gradle").writeText(gradleScript)
val pckgResult = evalBash("cd '${tmpProjectDir}' && gradle simpleCapsule")
with(pckgResult) {
kscript.app.errorIf(exitCode != 0) { "packaging of '$appName' failed:\n$pckgResult" }
}
pckgedJar.delete()
File(tmpProjectDir, "build/libs/${appName}").copyTo(pckgedJar, true).setExecutable(true)
infoMsg("Finished packaging into ${pckgedJar}")
}
| kotlin | 25 | 0.660054 | 162 | 31.424157 | 356 | starcoderdata |
<reponame>AllanWang/kord<filename>core/src/main/kotlin/com/gitlab/kordlib/core/cache/DataCacheView.kt
package com.gitlab.kordlib.core.cache
import com.gitlab.kordlib.cache.api.DataCache
import com.gitlab.kordlib.cache.api.DataEntryCache
import com.gitlab.kordlib.cache.api.Query
import com.gitlab.kordlib.cache.api.QueryBuilder
import com.gitlab.kordlib.cache.api.data.DataDescription
import kotlin.reflect.KProperty1
import kotlin.reflect.KType
class ViewKeys(private val keySet: MutableSet<Any> = mutableSetOf()) {
val keys: Set<Any> = keySet
fun add(key: Any) {
keySet.add(key)
}
}
/**
* A [DataCacheView] that limits removal of cached instances to those inserted in this cache,
* and not the underlying [cache].
*/
class DataCacheView(private val cache: DataCache) : DataCache by cache {
private val keys = ViewKeys()
private val descriptions = mutableMapOf<KType, DataDescription<out Any, out Any>>()
@Suppress("UNCHECKED_CAST")
private fun <T : Any> getDescription(type: KType) = descriptions[type]!! as DataDescription<T, out Any>
override suspend fun register(description: DataDescription<out Any, out Any>) {
descriptions[description.type] = description
}
override suspend fun register(vararg descriptions: DataDescription<out Any, out Any>) {
descriptions.forEach { register(it) }
}
override suspend fun register(descriptions: Iterable<DataDescription<out Any, out Any>>) {
descriptions.forEach { register(it) }
}
override fun <T : Any> getEntry(type: KType): DataEntryCache<T>? {
return cache.getEntry<T>(type)?.let { DataEntryCacheView(it, getDescription(type), keys) }
}
}
private class DataEntryCacheView<T : Any>(
private val entryCache: DataEntryCache<T>,
private val description: DataDescription<T, out Any>,
private val viewKeys: ViewKeys
) : DataEntryCache<T> by entryCache {
override suspend fun put(item: T) {
entryCache.put(item)
viewKeys.add(description.indexField.property.get(item))
}
override fun query(): QueryBuilder<T> {
return QueryBuilderView(entryCache.query(), description.indexField.property, viewKeys.keys)
}
}
private class QueryBuilderView<T : Any>(
private val builder: QueryBuilder<T>,
private val property: KProperty1<T, Any>,
private val keys: Set<Any>
) : QueryBuilder<T> by builder {
override fun build(): Query<T> = QueryView(builder, property, keys)
}
private class QueryView<T : Any>(
private val builder: QueryBuilder<T>,
private val property: KProperty1<T, Any>,
private val keys: Set<Any>
) : Query<T> by builder.build() {
override suspend fun remove() = builder.apply { property `in` keys }.build().remove()
} | kotlin | 26 | 0.705861 | 107 | 33.9875 | 80 | starcoderdata |
/*
* Copyright (C) 2019-2021 HERE Europe B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package org.ossreviewtoolkit.model.utils
import java.io.File
import java.io.IOException
import kotlin.io.path.createTempFile
import kotlin.time.measureTime
import kotlin.time.measureTimedValue
import org.ossreviewtoolkit.model.KnownProvenance
import org.ossreviewtoolkit.utils.common.FileMatcher
import org.ossreviewtoolkit.utils.common.collectMessagesAsString
import org.ossreviewtoolkit.utils.common.packZip
import org.ossreviewtoolkit.utils.common.unpackZip
import org.ossreviewtoolkit.utils.core.ORT_NAME
import org.ossreviewtoolkit.utils.core.log
import org.ossreviewtoolkit.utils.core.ortDataDirectory
import org.ossreviewtoolkit.utils.core.perf
import org.ossreviewtoolkit.utils.core.showStackTrace
import org.ossreviewtoolkit.utils.core.storage.FileStorage
/**
* A class to archive files matched by provided patterns in a ZIP file that is stored in a [FileStorage][storage].
*/
class FileArchiver(
/**
* A collection of globs to match the paths of files that shall be archived. For details about the glob pattern see
* [java.nio.file.FileSystem.getPathMatcher].
*/
patterns: Collection<String>,
/**
* The [FileArchiverStorage] to use for archiving files.
*/
internal val storage: FileArchiverStorage
) {
constructor(
/**
* A collection of globs to match the paths of files that shall be archived. For details about the glob pattern
* see [java.nio.file.FileSystem.getPathMatcher].
*/
patterns: Collection<String>,
/**
* The [FileStorage] to use for archiving files.
*/
storage: FileStorage
) : this(patterns, FileArchiverFileStorage(storage))
companion object {
val DEFAULT_ARCHIVE_DIR by lazy { ortDataDirectory.resolve("scanner/archive") }
}
private val matcher = FileMatcher(
patterns = patterns,
ignoreCase = true
)
/**
* Return whether an archive corresponding to [provenance] exists.
*/
fun hasArchive(provenance: KnownProvenance): Boolean = storage.hasArchive(provenance)
/**
* Archive all files in [directory] matching any of the configured patterns in the [storage].
*/
fun archive(directory: File, provenance: KnownProvenance) {
val zipFile = createTempFile(ORT_NAME, ".zip").toFile()
val zipDuration = measureTime {
directory.packZip(zipFile, overwrite = true) { file ->
val relativePath = file.relativeTo(directory).invariantSeparatorsPath
matcher.matches(relativePath).also { result ->
log.debug {
if (result) {
"Adding '$relativePath' to archive."
} else {
"Not adding '$relativePath' to archive."
}
}
}
}
}
log.perf {
"Archived directory '${directory.invariantSeparatorsPath}' in $zipDuration."
}
val writeDuration = measureTime { storage.addArchive(provenance, zipFile) }
log.perf {
"Wrote archive of directory '${directory.invariantSeparatorsPath}' to storage in $writeDuration."
}
zipFile.delete()
}
/**
* Unarchive the archive corresponding to [provenance].
*/
fun unarchive(directory: File, provenance: KnownProvenance): Boolean {
val (zipFile, readDuration) = measureTimedValue { storage.getArchive(provenance) }
log.perf {
"Read archive of directory '${directory.invariantSeparatorsPath}' from storage in $readDuration."
}
if (zipFile == null) return false
return try {
val unzipDuration = measureTime { zipFile.inputStream().use { it.unpackZip(directory) } }
log.perf {
"Unarchived directory '${directory.invariantSeparatorsPath}' in $unzipDuration."
}
true
} catch (e: IOException) {
e.showStackTrace()
log.error { "Could not extract ${zipFile.absolutePath}: ${e.collectMessagesAsString()}" }
false
} finally {
zipFile.delete()
}
}
}
| kotlin | 31 | 0.650832 | 119 | 32.283784 | 148 | starcoderdata |
<gh_stars>0
package org.promethist.core.dialogue
import com.fasterxml.jackson.core.type.TypeReference
import org.promethist.common.ObjectUtil
import org.promethist.core.Context
import org.promethist.core.dialogue.attribute.*
import org.promethist.core.dialogue.metric.MetricDelegate
import org.promethist.core.model.ClientCommand
import org.promethist.core.model.enumContains
import org.promethist.core.runtime.Api
import org.promethist.core.type.*
import org.promethist.util.TextExpander
import java.io.File
import java.io.FileInputStream
import java.net.URL
import java.time.Duration
import kotlin.random.Random
import kotlin.reflect.full.memberProperties
import org.promethist.core.dialogue.attribute.ContextualAttributeDelegate.Scope as ContextScope
abstract class BasicDialogue : AbstractDialogue() {
companion object {
const val LOW = 0
const val MEDIUM = 1
const val HIGH = 2
val pass: Transition? = null
@Deprecated("Use pass instead, toIntent will be removed")
val toIntent = pass
val api = Api()
}
enum class SpeechDirection {
Unknown, Front, FrontLeft, FrontRight, Left, Right, BackLeft, BackRight, Back
}
val now: DateTime get() = DateTime.now(run.context.turn.input.zoneId)
val today get() = now.date
val tomorrow get() = today + 1.day
val yesterday get() = today - 1.day
val DateTime.isToday get() = this isDay 0..0
val DateTime.isTomorrow get() = this isDay 1..1
val DateTime.isYesterday get() = this isDay -1..-1
val DateTime.isHoliday get() = isWeekend // && TODO check holidays in context.turn.input.locale.country
val DateTime.holidayName get() = null // && TODO check holidays in context.turn.input.locale.country
val DateTime.isPast get() = !Duration.between(this, now).isNegative
infix fun DateTime.isDay(range: IntRange) =
this >= today + range.first.day && this < today + range.last.day + 1.day
infix fun DateTime.isDay(day: Int) = this isDay day..day
override val clientLocation get() = clientUserLocation.value
val clientUserLocation by client { Memory(Location()) }
var clientType by client { "unknown" }
var clientScreen by client { false }
var clientTemperature by client { -273.15 }
var clientAmbientLight by client { 0.0 }
var clientSpatialMotion by client { 0.0 }
var clientSpeechAngle by client { -1 }
var clientSpeechDetected by client { false }
val clientSpeechDirection get() = clientSpeechAngle.let {
when (it) {
in 0..21 -> SpeechDirection.Right
in 22..67 -> SpeechDirection.FrontRight
in 68..111 -> SpeechDirection.Front
in 112..157 -> SpeechDirection.FrontLeft
in 158..201 -> SpeechDirection.Left
in 202..247 -> SpeechDirection.BackLeft
in 248..291 -> SpeechDirection.Back
in 292..337 -> SpeechDirection.BackRight
in 338..359 -> SpeechDirection.Right
else -> SpeechDirection.Unknown
}
}
var nickname by user(defaultNamespace, true) { user.nickname }
var gender by user(defaultNamespace) { "" }
var dynamic by turn { Dynamic.EMPTY }
var turnSpeakingRate by turn(defaultNamespace) { 1.0 }
var sessionSpeakingRate by session(defaultNamespace) { 1.0 }
var userSpeakingRate by user(defaultNamespace) { 1.0 }
var turnSpeakingPitch by turn(defaultNamespace) { 0.0 }
var sessionSpeakingPitch by session(defaultNamespace) { 0.0 }
var userSpeakingPitch by user(defaultNamespace) { 0.0 }
var turnSpeakingVolumeGain by turn(defaultNamespace) { 1.0 }
var sessionSpeakingVolumeGain by session(defaultNamespace) { 1.0 }
var userSpeakingVolumeGain by user(defaultNamespace) { 1.0 }
var _basicId = 1
val _basicStop = GlobalIntent(_basicId++, "basicStopGlobalIntent", 0.99F, "stop")
init {
_basicStop.next = stopSession
}
inline fun <reified V: Any> temp(noinline default: (Context.() -> V)? = null) = TempAttributeDelegate(default)
inline fun <reified V: Any> turn(namespace: String? = null, noinline default: (Context.() -> V)) =
ContextualAttributeDelegate(ContextScope.Turn, V::class, { namespace ?: dialogueNameWithoutVersion }, default)
inline fun <reified V: Any> session(namespace: String? = null, noinline default: (Context.() -> V)) =
ContextualAttributeDelegate(ContextScope.Session, V::class, { namespace ?: dialogueNameWithoutVersion }, default)
inline fun <reified V: Any> client(expiration: DateTimeUnit, noinline default: (Context.() -> V)) =
ContextualAttributeDelegate(ContextScope.Client, V::class, { defaultNamespace }, expiration, default)
inline fun <reified V: Any> client(noinline default: (Context.() -> V)) = client(1.hour, default)
inline fun <reified V: Any> user(namespace: String? = null, localize: Boolean = false, expiration: DateTimeUnit? = null, noinline default: (Context.() -> V)) =
ContextualAttributeDelegate(ContextScope.User, V::class, {
(namespace ?: dialogueNameWithoutVersion) + (if (localize) "/$language" else "")
}, expiration, default)
inline fun <reified V: Any> user(namespace: String? = null, localize: Boolean = false, noinline default: (Context.() -> V)) =
user(namespace, localize, null, default)
inline fun <reified V: Any> community(communityName: String, namespace: String? = null, localize: Boolean = false, noinline default: (Context.() -> V)) =
CommunityAttributeDelegate(V::class, communityName, {
(namespace ?: dialogueNameWithoutVersion) + (if (localize) "/$language" else "")
}, default)
inline fun sessionSequence(list: List<String>, namespace: String? = null, noinline nextValue: (SequenceAttribute<String, String>.() -> String?) = { nextRandom() }) =
StringSequenceAttributeDelegate(list, ContextScope.Session, { namespace ?: dialogueNameWithoutVersion }, nextValue)
inline fun userSequence(list: List<String>, namespace: String? = null, noinline nextValue: (SequenceAttribute<String, String>.() -> String?) = { nextRandom() }) =
StringSequenceAttributeDelegate(list, ContextScope.User, { namespace ?: dialogueNameWithoutVersion }, nextValue)
inline fun <reified E: NamedEntity> sessionSequence(entities: List<E>, namespace: String? = null, noinline nextValue: (SequenceAttribute<E, String>.() -> E?) = { nextRandom() }) =
EntitySequenceAttributeDelegate(entities, ContextScope.Session, { namespace ?: dialogueNameWithoutVersion }, nextValue)
inline fun <reified E: NamedEntity> userSequence(entities: List<E>, namespace: String? = null, noinline nextValue: (SequenceAttribute<E, String>.() -> E?) = { nextRandom() }) =
EntitySequenceAttributeDelegate(entities, ContextScope.User, { namespace ?: dialogueNameWithoutVersion }, nextValue)
inline fun <reified E: NamedEntity> turnEntityList(entities: Collection<E>, namespace: String? = null) =
NamedEntityListAttributeDelegate(entities, ContextScope.Turn) { namespace ?: dialogueNameWithoutVersion }
inline fun <reified E: NamedEntity> sessionEntityList(entities: Collection<E>, namespace: String? = null) =
NamedEntityListAttributeDelegate(entities, ContextScope.Session) { namespace ?: dialogueNameWithoutVersion }
inline fun <reified E: NamedEntity> userEntityList(entities: Collection<E>, namespace: String? = null) =
NamedEntityListAttributeDelegate(entities, ContextScope.User) { namespace ?: dialogueNameWithoutVersion }
inline fun <reified E: NamedEntity> turnEntitySet(entities: Collection<E>, namespace: String? = null) =
NamedEntitySetAttributeDelegate(entities, ContextScope.Turn) { namespace ?: dialogueNameWithoutVersion }
inline fun <reified E: NamedEntity> sessionEntitySet(entities: Collection<E>, namespace: String? = null) =
NamedEntitySetAttributeDelegate(entities, ContextScope.Session) { namespace ?: dialogueNameWithoutVersion }
inline fun <reified E: NamedEntity> userEntitySet(entities: Collection<E>, namespace: String? = null) =
NamedEntitySetAttributeDelegate(entities, ContextScope.User) { namespace ?: dialogueNameWithoutVersion }
inline fun <reified E: Any> sessionMap(entities: Map<String, E>, namespace: String? = null) =
MapAttributeDelegate(entities, ContextScope.Session) { namespace ?: dialogueNameWithoutVersion }
inline fun <reified E: Any> turnMap(entities: Map<String, E>, namespace: String? = null) =
MapAttributeDelegate(entities, ContextScope.Turn) { namespace ?: dialogueNameWithoutVersion }
inline fun <reified E: Any> userMap(entities: Map<String, E>, namespace: String? = null) =
MapAttributeDelegate(entities, ContextScope.User) { namespace ?: dialogueNameWithoutVersion }
// deprecated delegates with *Attribute suffix in name
@Deprecated("Use turn instead", replaceWith = ReplaceWith("turn"))
inline fun <reified V: Any> turnAttribute(namespace: String? = null, noinline default: (Context.() -> V)) =
ContextualAttributeDelegate(ContextScope.Turn, V::class, { namespace ?: dialogueNameWithoutVersion }, default)
@Deprecated("Use session instead", replaceWith = ReplaceWith("session"))
inline fun <reified V: Any> sessionAttribute(namespace: String? = null, noinline default: (Context.() -> V)) =
ContextualAttributeDelegate(ContextScope.Session, V::class, { namespace ?: dialogueNameWithoutVersion }, default)
@Deprecated("Use user instead", replaceWith = ReplaceWith("user"))
inline fun <reified V: Any> userAttribute(namespace: String? = null, noinline default: (Context.() -> V)) =
ContextualAttributeDelegate(ContextScope.User, V::class, { namespace ?: dialogueNameWithoutVersion }, default)
@Deprecated("Use community instead", replaceWith = ReplaceWith("community"))
inline fun <reified V: Any> communityAttribute(communityName: String, namespace: String? = null, noinline default: (Context.() -> V)) =
CommunityAttributeDelegate(V::class, communityName, { namespace?:dialogueNameWithoutVersion }, default)
@Deprecated("Use sessionSequence instead", replaceWith = ReplaceWith("sessionSequence"))
inline fun sessionSequenceAttribute(list: List<String>, namespace: String? = null, noinline nextValue: (SequenceAttribute<String, String>.() -> String?) = { nextRandom() }) =
StringSequenceAttributeDelegate(list, ContextScope.Session, { namespace ?: dialogueNameWithoutVersion }, nextValue)
@Deprecated("Use userSequence instead", replaceWith = ReplaceWith("userSequence"))
inline fun userSequenceAttribute(list: List<String>, namespace: String? = null, noinline nextValue: (SequenceAttribute<String, String>.() -> String?) = { nextRandom() }) =
StringSequenceAttributeDelegate(list, ContextScope.User, { namespace ?: dialogueNameWithoutVersion }, nextValue)
@Deprecated("Use sessionSequence instead", replaceWith = ReplaceWith("sessionSequence"))
inline fun <reified E: NamedEntity> sessionSequenceAttribute(entities: List<E>, namespace: String? = null, noinline nextValue: (SequenceAttribute<E, String>.() -> E?) = { nextRandom() }) =
EntitySequenceAttributeDelegate(entities, ContextScope.Session, { namespace ?: dialogueNameWithoutVersion }, nextValue)
@Deprecated("Use userSequence instead", replaceWith = ReplaceWith("userSequence"))
inline fun <reified E: NamedEntity> userSequenceAttribute(entities: List<E>, namespace: String? = null, noinline nextValue: (SequenceAttribute<E, String>.() -> E?) = { nextRandom() }) =
EntitySequenceAttributeDelegate(entities, ContextScope.User, { namespace ?: dialogueNameWithoutVersion }, nextValue)
@Deprecated("Use turnEntityList instead", replaceWith = ReplaceWith("turnEntityList"))
inline fun <reified E: NamedEntity> turnEntityListAttribute(entities: Collection<E>, namespace: String? = null) =
NamedEntityListAttributeDelegate(entities, ContextScope.Turn) { namespace ?: dialogueNameWithoutVersion }
@Deprecated("Use sessionEntityList instead", replaceWith = ReplaceWith("sessionEntityList"))
inline fun <reified E: NamedEntity> sessionEntityListAttribute(entities: Collection<E>, namespace: String? = null) =
NamedEntityListAttributeDelegate(entities, ContextScope.Session) { namespace ?: dialogueNameWithoutVersion }
@Deprecated("Use userEntityList instead", replaceWith = ReplaceWith("userEntityList"))
inline fun <reified E: NamedEntity> userEntityListAttribute(entities: Collection<E>, namespace: String? = null) =
NamedEntityListAttributeDelegate(entities, ContextScope.User) { namespace ?: dialogueNameWithoutVersion }
@Deprecated("Use turnEntitySet instead", replaceWith = ReplaceWith("turnEntitySet"))
inline fun <reified E: NamedEntity> turnEntitySetAttribute(entities: Collection<E>, namespace: String? = null) =
NamedEntitySetAttributeDelegate(entities, ContextScope.Turn) { namespace ?: dialogueNameWithoutVersion }
@Deprecated("Use sessionEntitySet instead", replaceWith = ReplaceWith("sessionEntitySet"))
inline fun <reified E: NamedEntity> sessionEntitySetAttribute(entities: Collection<E>, namespace: String? = null) =
NamedEntitySetAttributeDelegate(entities, ContextScope.Session) { namespace ?: dialogueNameWithoutVersion }
@Deprecated("Use userEntitySet instead", replaceWith = ReplaceWith("userEntitySet"))
inline fun <reified E: NamedEntity> userEntitySetAttribute(entities: Collection<E>, namespace: String? = null) =
NamedEntitySetAttributeDelegate(entities, ContextScope.User) { namespace ?: dialogueNameWithoutVersion }
@Deprecated("Use sessionMap instead", replaceWith = ReplaceWith("sessionMap"))
inline fun <reified E: Any> sessionMapAttribute(entities: Map<String, E>, namespace: String? = null) =
MapAttributeDelegate(entities, ContextScope.Session) { namespace ?: dialogueNameWithoutVersion }
@Deprecated("Use turnMap instead", replaceWith = ReplaceWith("turnMap"))
inline fun <reified E: Any> turnMapAttribute(entities: Map<String, E>, namespace: String? = null) =
MapAttributeDelegate(entities, ContextScope.Turn) { namespace ?: dialogueNameWithoutVersion }
@Deprecated("Use userMap instead", replaceWith = ReplaceWith("userMap"))
inline fun <reified E: Any> userMapAttribute(entities: Map<String, E>, namespace: String? = null) =
MapAttributeDelegate(entities, ContextScope.User) { namespace ?: dialogueNameWithoutVersion }
fun metric(metricSpec: String) = MetricDelegate(metricSpec)
@Deprecated("Use metric instead", replaceWith = ReplaceWith("metric"))
fun metricValue(metricSpec: String) = MetricDelegate(metricSpec)
inline fun <reified T: Any> loader(path: String): Lazy<T> = lazy {
val typeRef = object : TypeReference<T>() {}
when {
path.startsWith("file:///") ->
FileInputStream(File(path.substring(7))).use {
ObjectUtil.defaultMapper.readValue<T>(it, typeRef)
}
path.startsWith("http") ->
URL(path).openStream().use {
ObjectUtil.defaultMapper.readValue<T>(it, typeRef)
}
path.startsWith("./") ->
loader.loadObject(dialogueId + path.substring(1).substringBeforeLast(".json"), typeRef)
else ->
loader.loadObject(path.substringBeforeLast(".json"), typeRef)
}
}
// This method was not used anywhere but it won't work since communityResource.get() requires space ID which is not accessible in this class
// fun communityAttributes(communityName: String) =
// run.context.communityResource.get(communityName, null)?.attributes ?: Dynamic.EMPTY
fun addResponseItem(text: String?, image: String? = null, audio: String? = null, video: String? = null, code: String? = null, background: String? = null, repeatable: Boolean = true) =
run.context.turn.addResponseItem(text?.let { evaluateTextTemplate(it) }, image, audio, video, code, background, repeatable, voice)
fun addResponseItem(text: String?, image: String? = null, audio: String? = null, video: String? = null, background: String? = null, repeatable: Boolean = true) =
addResponseItem(text, image, audio, video, null, background, repeatable)
/**
* evaluate # in response text
*/
open fun evaluateTextTemplate(text: String) = TextExpander.expand(text).run {
enumerate(this[Random.nextInt(size)]).
replace(Regex("#([\\w\\.\\d]+)")) {
if (enumContains<ClientCommand>(it.groupValues[1])) {
"#" + it.groupValues[1]
} else {
var obj: Any? = this@BasicDialogue
var point = false
for (name in it.groupValues[1].split(".")) {
if (name.isBlank()) {
point = true
break
} else {
val prop = obj!!.javaClass.kotlin.memberProperties.firstOrNull { it.name == name }
obj = prop?.call(obj)
if (obj == null)
break
}
}
describe(obj) + (if (point) "." else "")
}
}/*.
replace(Regex("\\s+"), " "). //replace multiple whitespaces with single
replace(Regex("\\s+(?=[.,;?!])"), ""). //Remove ws in front of punctuation
replace(Regex(",{2,}"), ","). //remove multiple commas in a row
replace(Regex("\\.{4,}"), "..."). //replace more then 3 dots
replace(Regex("(?<!\\.)\\.\\.(?!\\.)"), "."). //remove double dots
replace(Regex("[.,;?!](?![.\\s])")) {
it.value+" "
}. //add space behind punctuation
trim().
replace(Regex("(?<=[\\!\\?]\\s).")) {
it.value.capitalize()
}. //capitalize after "!" and "?"
replace(Regex(",$"), "..."). //replace trailing comma with "..."
replace(Regex("(?<![,\\.\\!\\?])$"), "."). //add a "." when the text doesnt end with a mark
capitalize()*/
}
inline fun unsupportedLanguage(): Nothing {
val stackTraceElement = Thread.currentThread().stackTrace[1]
throw error("${stackTraceElement.className}.${stackTraceElement.methodName} does not support language ${language} of dialogue ${dialogueName}")
}
fun indent(value: Any?, separator: String = " ") = (value?.let { separator + describe(value) } ?: "")
infix fun Number.of(subj: String) =
if (this == 0)
empty(plural(subj, 0))
else
describe(this) + " " + plural(subj, this.toInt())
infix fun Array<*>.of(subj: String) = size of subj
infix fun Map<*, *>.of(subj: String) = size of subj
infix fun Collection<String>.of(subj: String) = enumerate(this, subj)
}
| kotlin | 31 | 0.677293 | 192 | 56.996979 | 331 | starcoderdata |
package com.github.mvysny.karibudsl.v10
import com.vaadin.flow.component.Component
import com.vaadin.flow.component.HasComponents
// annotating DSL functions with @VaadinDsl will make Intellij mark the DSL functions in a special way
// which makes them stand out apart from the common functions, which is very nice.
@Target(AnnotationTarget.CLASS, AnnotationTarget.TYPE, AnnotationTarget.FUNCTION)
@DslMarker
annotation class VaadinDsl
/**
* When introducing extensions for your custom components, just call [init] in your extension function. For example:
*
* `fun HasComponents.shinyComponent(caption: String? = null, block: ShinyComponent.()->Unit = {}) = init(ShinyComponent(caption), block)`
*
* Adds [component] to receiver, see [HasComponents.add] for details.
*
* @param component the component to attach
* @param block optional block to run over the component, allowing you to add children to the [component]
*/
@VaadinDsl
fun <T : Component> (@VaadinDsl HasComponents).init(component: T, block: T.() -> Unit = {}): T {
add(component)
component.block()
return component
}
| kotlin | 8 | 0.755435 | 138 | 39.888889 | 27 | starcoderdata |
package com.github.vhromada.catalog.repository
import com.github.vhromada.catalog.TestConfiguration
import com.github.vhromada.catalog.utils.AuditUtils
import com.github.vhromada.catalog.utils.EpisodeUtils
import com.github.vhromada.catalog.utils.SeasonUtils
import com.github.vhromada.catalog.utils.ShowUtils
import com.github.vhromada.catalog.utils.TestConstants
import com.github.vhromada.catalog.utils.fillAudit
import com.github.vhromada.catalog.utils.updated
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.SoftAssertions.assertSoftly
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.annotation.Rollback
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.transaction.annotation.Transactional
import javax.persistence.EntityManager
import javax.persistence.PersistenceContext
/**
* A class represents test for class [SeasonRepository].
*
* @author <NAME>
*/
@ExtendWith(SpringExtension::class)
@ContextConfiguration(classes = [TestConfiguration::class])
@Transactional
@Rollback
class SeasonRepositorySpringTest {
/**
* Instance of [EntityManager]
*/
@PersistenceContext
private lateinit var entityManager: EntityManager
/**
* Instance of [SeasonRepository]
*/
@Autowired
private lateinit var repository: SeasonRepository
/**
* Test method for get season.
*/
@Test
fun getSeason() {
for (i in 1..ShowUtils.SHOWS_COUNT) {
for (j in 1..SeasonUtils.SEASONS_PER_SHOW_COUNT) {
val id = (i - 1) * SeasonUtils.SEASONS_PER_SHOW_COUNT + j
val season = repository.findById(id).orElse(null)
SeasonUtils.assertSeasonDeepEquals(expected = ShowUtils.getDomainShow(index = i).seasons[j - 1], actual = season)
}
}
assertThat(repository.findById(Int.MAX_VALUE)).isNotPresent
assertSoftly {
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
}
}
/**
* Test method for add season.
*/
@Test
@DirtiesContext
fun add() {
val season = SeasonUtils.newDomainSeason(id = null)
.copy(position = SeasonUtils.SEASONS_COUNT)
season.show = ShowUtils.getDomainShow(entityManager = entityManager, id = 1)
val expectedSeason = SeasonUtils.newDomainSeason(id = SeasonUtils.SEASONS_COUNT + 1)
.fillAudit(audit = AuditUtils.newAudit())
expectedSeason.show = ShowUtils.getDomainShow(entityManager = entityManager, id = 1)
repository.saveAndFlush(season)
assertSoftly {
it.assertThat(season.id).isEqualTo(SeasonUtils.SEASONS_COUNT + 1)
it.assertThat(season.createdUser).isEqualTo(TestConstants.ACCOUNT.uuid)
it.assertThat(season.createdTime).isEqualTo(TestConstants.TIME)
it.assertThat(season.updatedUser).isEqualTo(TestConstants.ACCOUNT.uuid)
it.assertThat(season.updatedTime).isEqualTo(TestConstants.TIME)
}
SeasonUtils.assertSeasonDeepEquals(expected = expectedSeason, actual = SeasonUtils.getDomainSeason(entityManager = entityManager, id = SeasonUtils.SEASONS_COUNT + 1))
assertSoftly {
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT + 1)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
}
}
/**
* Test method for update season.
*/
@Test
fun update() {
val season = SeasonUtils.getDomainSeason(entityManager = entityManager, id = 1)!!
.updated()
val expectedSeason = ShowUtils.getDomainShow(index = 1).seasons.first()
.updated()
.fillAudit(audit = AuditUtils.updatedAudit())
repository.saveAndFlush(season)
SeasonUtils.assertSeasonDeepEquals(expected = expectedSeason, actual = SeasonUtils.getDomainSeason(entityManager = entityManager, id = 1))
assertSoftly {
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
}
}
/**
* Test method for get seasons by show ID.
*/
@Test
fun findAllByShowId() {
for (i in 1..ShowUtils.SHOWS_COUNT) {
val seasons = repository.findAllByShowId(id = i)
SeasonUtils.assertDomainSeasonsDeepEquals(expected = ShowUtils.getDomainShow(index = i).seasons, actual = seasons)
}
assertThat(repository.findAllByShowId(id = Int.MAX_VALUE)).isEmpty()
assertSoftly {
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
}
}
/**
* Test method for get seasons by show ID and created user UUID.
*/
@Test
fun findAllByShowIdAndCreatedUser() {
val user = AuditUtils.getAudit().createdUser!!
for (i in 1..ShowUtils.SHOWS_COUNT) {
val seasons = repository.findAllByShowIdAndCreatedUser(id = i, user = user)
SeasonUtils.assertDomainSeasonsDeepEquals(expected = ShowUtils.getDomainShow(index = i).seasons, actual = seasons)
}
assertThat(repository.findAllByShowIdAndCreatedUser(id = Int.MAX_VALUE, user = user)).isEmpty()
assertSoftly {
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
}
}
/**
* Test method for find season by UUID.
*/
@Test
fun findByUuid() {
for (i in 1..ShowUtils.SHOWS_COUNT) {
val show = ShowUtils.getDomainShow(index = i)
for (season in show.seasons) {
val result = repository.findByUuid(uuid = season.uuid).orElse(null)
SeasonUtils.assertSeasonDeepEquals(expected = season, actual = result)
}
}
assertThat(repository.findByUuid(uuid = TestConstants.UUID)).isNotPresent
assertSoftly {
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
}
}
/**
* Test method for find season by UUID and created user UUID.
*/
@Test
fun findByUuidAndCreatedUser() {
val user = AuditUtils.getAudit().createdUser!!
for (i in 1..ShowUtils.SHOWS_COUNT) {
val show = ShowUtils.getDomainShow(index = i)
for (season in show.seasons) {
val result = repository.findByUuidAndCreatedUser(uuid = season.uuid, user = user).orElse(null)
SeasonUtils.assertSeasonDeepEquals(expected = season, actual = result)
}
}
assertThat(repository.findByUuidAndCreatedUser(uuid = TestConstants.UUID, user = user)).isNotPresent
assertSoftly {
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
}
}
}
| kotlin | 22 | 0.701021 | 174 | 41.061321 | 212 | starcoderdata |
<gh_stars>0
package team.genki.chotto.server
import team.genki.chotto.core.*
interface ChottoTransaction {
open class Controller<out Transaction : ChottoTransaction>(
val transaction: Transaction
) {
open fun onRequestReceived(request: CommandRequest<*, *>) {}
}
}
| kotlin | 14 | 0.747292 | 62 | 17.466667 | 15 | starcoderdata |
/*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("DuplicatedCode")
package org.jetbrains.kotlin.gradle.kpm.idea.testFixtures
import org.jetbrains.kotlin.gradle.kpm.idea.*
import kotlin.test.fail
fun IdeaKotlinProjectModel.assertIsNotEmpty(): IdeaKotlinProjectModel = apply {
if (this.modules.isEmpty()) fail("Expected at least one module in model")
}
fun IdeaKotlinProjectModel.assertContainsModule(name: String): IdeaKotlinModule {
return modules.find { it.name == name }
?: fail("Missing module with name '$name'. Found: ${modules.map { it.name }}")
}
fun IdeaKotlinModule.assertContainsFragment(name: String): IdeaKotlinFragment {
return fragments.find { it.name == name }
?: fail("Missing fragment with name '$name'. Found: ${fragments.map { it.name }}")
}
fun IdeaKotlinFragment.assertResolvedBinaryDependencies(
binaryType: String,
matchers: Set<IdeaKotlinBinaryDependencyMatcher>
): Set<IdeaKotlinResolvedBinaryDependency> {
val resolvedBinaryDependencies = dependencies
.mapNotNull { dependency ->
when (dependency) {
is IdeaKotlinResolvedBinaryDependencyImpl -> dependency
is IdeaKotlinUnresolvedBinaryDependencyImpl -> fail("Unexpected unresolved dependency: $dependency")
is IdeaKotlinFragmentDependencyImpl -> null
}
}
.filter { it.binaryType == binaryType }
.toSet()
val unexpectedResolvedBinaryDependencies = resolvedBinaryDependencies
.filter { dependency -> matchers.none { matcher -> matcher.matches(dependency) } }
val missingDependencies = matchers.filter { matcher ->
resolvedBinaryDependencies.none { dependency -> matcher.matches(dependency) }
}
if (unexpectedResolvedBinaryDependencies.isEmpty() && missingDependencies.isEmpty()) {
return resolvedBinaryDependencies
}
fail(
buildString {
if (unexpectedResolvedBinaryDependencies.isNotEmpty()) {
appendLine("${name}: Unexpected dependencies found:")
unexpectedResolvedBinaryDependencies.forEach { unexpectedDependency ->
appendLine(unexpectedDependency)
}
appendLine()
appendLine("${name}: Unexpected dependency coordinates:")
unexpectedResolvedBinaryDependencies.forEach { unexpectedDependency ->
appendLine("\"${unexpectedDependency.coordinates}\",")
}
}
if (missingDependencies.isNotEmpty()) {
appendLine()
appendLine("${name}: Missing dependencies:")
missingDependencies.forEach { missingDependency ->
appendLine(missingDependency.description)
}
}
appendLine()
appendLine("${name}: Resolved Dependency Coordinates:")
resolvedBinaryDependencies.mapNotNull { it.coordinates }.forEach { coordinates ->
appendLine("\"$coordinates\",")
}
}
)
}
@JvmName("assertResolvedBinaryDependenciesByAnyMatcher")
fun IdeaKotlinFragment.assertResolvedBinaryDependencies(
binaryType: String, matchers: Set<Any?>,
) = assertResolvedBinaryDependencies(binaryType, matchers.flatMap { buildIdeaKotlinBinaryDependencyMatchers(it) }.toSet())
fun IdeaKotlinFragment.assertResolvedBinaryDependencies(
binaryType: String, vararg matchers: Any?
) = assertResolvedBinaryDependencies(binaryType, matchers.toSet())
fun IdeaKotlinFragment.assertFragmentDependencies(matchers: Set<IdeaKotlinFragmentDependencyMatcher>): Set<IdeaKotlinFragmentDependency> {
val sourceDependencies = dependencies.filterIsInstance<IdeaKotlinFragmentDependency>().toSet()
val unexpectedDependencies = sourceDependencies
.filter { dependency -> matchers.none { matcher -> matcher.matches(dependency) } }
val missingDependencies = matchers.filter { matcher ->
sourceDependencies.none { dependency -> matcher.matches(dependency) }
}
if (unexpectedDependencies.isEmpty() && missingDependencies.isEmpty()) {
return sourceDependencies
}
fail(
buildString {
if (unexpectedDependencies.isNotEmpty()) {
appendLine()
appendLine("${coordinates.path}: Unexpected source dependency found:")
unexpectedDependencies.forEach { unexpectedDependency ->
appendLine("\"${unexpectedDependency}\",")
}
}
if (missingDependencies.isNotEmpty()) {
appendLine()
appendLine("${coordinates.path}: Missing fragment dependencies:")
missingDependencies.forEach { missingDependency ->
appendLine(missingDependency.description)
}
}
appendLine()
appendLine("${coordinates.path}: Resolved source dependency paths:")
sourceDependencies.forEach { dependency ->
appendLine("\"${dependency}\",")
}
}
)
}
@JvmName("assertSourceDependenciesByAnyMatcher")
fun IdeaKotlinFragment.assertFragmentDependencies(matchers: Set<Any?>): Set<IdeaKotlinFragmentDependency> =
assertFragmentDependencies(matchers.flatMap { buildIdeaKotlinFragmentDependencyMatchers(it) }.toSet())
fun IdeaKotlinFragment.assertFragmentDependencies(vararg matchers: Any?) =
assertFragmentDependencies(matchers.toSet())
| kotlin | 29 | 0.669594 | 138 | 39.664286 | 140 | starcoderdata |
<reponame>overpas/Solicitor
package by.overpass.android.solicitor.sample
import by.overpass.android.solicitor.core.Permissions
fun Permissions.print(separator: String = ", "): String = reduce { acc, current ->
"$acc$separator$current"
}
| kotlin | 9 | 0.761317 | 82 | 29.375 | 8 | starcoderdata |
package io.collapp.model
import ch.digitalfondue.npjt.ConstructorAnnotationRowMapper.Column
import io.collapp.common.Json
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.builder.EqualsBuilder
import org.apache.commons.lang3.builder.HashCodeBuilder
import java.util.*
open class User(@Column("USER_ID") val id: Int,
@Column("USER_PROVIDER") val provider: String?,
@Column("USER_NAME") val username: String?,
@Column("USER_EMAIL") val email: String?,
@Column("USER_DISPLAY_NAME") val displayName: String?,
@Column("USER_ENABLED") enabled: Boolean?,
@Column("USER_EMAIL_NOTIFICATION") val emailNotification: Boolean,
@Column("USER_MEMBER_SINCE") val memberSince: Date?,
@Column("USER_SKIP_OWN_NOTIFICATIONS") val skipOwnNotifications: Boolean,
@Column("USER_METADATA") @Transient val userMetadataRaw: String?) {
val enabled: Boolean
val userMetadata: UserMetadata?
init {
this.enabled = enabled ?: true
this.userMetadata = Json.GSON.fromJson(userMetadataRaw, UserMetadata::class.java)
}
public open operator override fun equals(obj: Any?): Boolean {
if (obj == null || obj !is User) {
return false
}
return EqualsBuilder().append(id, obj.id).append(provider, obj.provider).append(username, obj.username).append(email, obj.email).append(displayName, obj.displayName).append(enabled, obj.enabled).append(emailNotification, obj.emailNotification).append(skipOwnNotifications, obj.skipOwnNotifications).append(userMetadata, obj.userMetadata).isEquals
}
public open override fun hashCode(): Int {
return HashCodeBuilder().append(id).append(provider).append(username).append(email).append(displayName).append(enabled).append(emailNotification).append(skipOwnNotifications).toHashCode()
}
val anonymous: Boolean
get() = "system" == provider && "anonymous" == username
fun canSendEmail(): Boolean {
return enabled && emailNotification && StringUtils.isNotBlank(email)
}
}
| kotlin | 30 | 0.685794 | 354 | 45.978261 | 46 | starcoderdata |
package util
const val ONE_MILLION = 1_000_000
const val TWO_MILLION = 2_000_000
| kotlin | 3 | 0.743902 | 33 | 19.5 | 4 | starcoderdata |
package com.avito.report
import com.avito.report.model.AndroidTest
import com.avito.report.model.ReportCoordinates
import com.avito.report.model.TestRuntimeDataPackage
import com.avito.report.model.createStubInstance
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.util.Date
@ExtendWith(MockReportsExtension::class)
class TestDurationTest {
@Test
fun `startTime set`(reports: MockReportApi) {
val now = Date().time
reports.addTest(
reportCoordinates = ReportCoordinates.createStubInstance(),
buildId = "1234",
test = AndroidTest.Completed.createStubInstance(
testRuntimeData = TestRuntimeDataPackage.createStubInstance(
startTime = now
)
)
)
.singleRequestCaptured()
.bodyContains("\"start_time\":$now")
}
@Test
fun `endTime set`(reports: MockReportApi) {
val now = Date().time
reports.addTest(
reportCoordinates = ReportCoordinates.createStubInstance(),
buildId = "1234",
test = AndroidTest.Completed.createStubInstance(
testRuntimeData = TestRuntimeDataPackage.createStubInstance(
endTime = now
)
)
)
.singleRequestCaptured()
.bodyContains("\"end_time\":$now")
}
}
| kotlin | 22 | 0.622655 | 76 | 30.977778 | 45 | starcoderdata |
package br.ufpe.cin.if710.rss
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import br.ufpe.cin.if710.rss.adapters.RssAdapter
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
class MainActivity : Activity() {
private var dynBroadcastReceiver: DynBroadcastReceiver? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Inicia o layout da recycler view
conteudoRSS.layoutManager = LinearLayoutManager(this)
conteudoRSS.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL))
dynBroadcastReceiver = DynBroadcastReceiver()
// Para testar
// doAsync {
// database.deleteItems()
// }
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.settings -> {
// Quando o menú de configurações é ativado
startActivity(Intent(applicationContext,PrefsMenuActivity::class.java))
true
}
else -> super.onOptionsItemSelected(item)
}
override fun onResume() {
super.onResume()
active = true // Valor acessado pelo RssLoadService e tem como finalidade informar se a activity está em primeiro plano
// Cadastra o broadCastReceiver e a action que o aciona
val intentFilter = IntentFilter(RssLoadService.ACTION_UPDATE_FEED)
registerReceiver(dynBroadcastReceiver, intentFilter)
// Recebe a shared Preference
val prefs = PreferenceManager.getDefaultSharedPreferences(this)
val rssFeed = prefs.getString(RSS_FEED, "default")
// Inicializa um novo serviço para carregar o a lista de notícias
val serviceIntent = Intent(this, RssLoadService::class.java)
serviceIntent.putExtra("url", rssFeed)
startService(serviceIntent)
}
override fun onPause(){
super.onPause()
unregisterReceiver(dynBroadcastReceiver)
active = false
}
companion object {
const val RSS_FEED = "rssfeed"
var active = false
}
inner class DynBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
doAsync {
val dbItemsRss = database.getItems() // Recebe os ítens não lídos do banco
uiThread {
conteudoRSS.adapter = RssAdapter(dbItemsRss, context) // atualiza a lista de ítens
}
}
}
}
}
| kotlin | 23 | 0.687716 | 129 | 31.151515 | 99 | starcoderdata |
<filename>reaktive/src/commonMain/kotlin/com/badoo/reaktive/maybe/AsSingleOrError.kt<gh_stars>0
package com.badoo.reaktive.maybe
import com.badoo.reaktive.single.Single
fun <T> Maybe<T>.asSingleOrError(error: Throwable = NoSuchElementException()): Single<T> =
asSingleOrAction { observer ->
observer.onError(error)
}
fun <T> Maybe<T>.asSingleOrError(errorSupplier: () -> Throwable): Single<T> =
asSingleOrAction { observer ->
try {
errorSupplier()
} catch (e: Throwable) {
e
}
.also(observer::onError)
}
| kotlin | 15 | 0.649746 | 95 | 30.105263 | 19 | starcoderdata |
<filename>src/main/kotlin/org/rust/ide/inspections/RsLiftInspection.kt
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapiext.Testmark
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.RsElement
class RsLiftInspection : RsLocalInspectionTool() {
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor? {
return object : RsVisitor() {
override fun visitIfExpr(o: RsIfExpr) {
checkExpr(o, o.`if`)
}
override fun visitMatchExpr(o: RsMatchExpr) {
checkExpr(o, o.match)
}
private fun checkExpr(e: RsExpr, keyword: PsiElement) {
if (e.hasFoldableReturns) {
holder.register(e, keyword)
}
}
}
}
private fun RsProblemsHolder.register(expr: RsExpr, keyword: PsiElement) {
val keywordName = keyword.text
registerProblem(expr, keyword.textRangeInParent,
"Return can be lifted out of '$keywordName'", LiftReturnOutFix(keywordName))
}
private class LiftReturnOutFix(private val keyword: String) : LocalQuickFix {
override fun getName(): String = "Lift return out of '$keyword'"
override fun getFamilyName(): String = "Lift return"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expr = descriptor.psiElement as RsExpr
val foldableReturns = expr.getFoldableReturns() ?: return
val factory = RsPsiFactory(project)
for (foldableReturn in foldableReturns) {
foldableReturn.elementToReplace.replace(factory.createExpression(foldableReturn.expr.text))
}
if (expr.parent !is RsRetExpr) {
expr.replace(factory.createRetExpr(expr.text))
} else {
Testmarks.insideRetExpr.hit()
}
}
}
object Testmarks {
val insideRetExpr = Testmark("insideRetExpr")
}
}
private data class FoldableElement(val expr: RsExpr, val elementToReplace: RsElement)
private val RsExpr.hasFoldableReturns: Boolean get() = getFoldableReturns() != null
private fun RsExpr.getFoldableReturns(): List<FoldableElement>? {
val result = mutableListOf<FoldableElement>()
fun RsElement.collectFoldableReturns(): Boolean {
when (this) {
is RsRetExpr -> {
val expr = expr ?: return false
result += FoldableElement(expr, this)
}
is RsExprStmt -> {
val retExpr = expr as? RsRetExpr ?: return false
val expr = retExpr.expr ?: return false
result += FoldableElement(expr, this)
}
is RsBlock -> {
val lastChild = children.lastOrNull() as? RsElement ?: return false
if (!lastChild.collectFoldableReturns()) return false
}
is RsBlockExpr -> {
if (!block.collectFoldableReturns()) return false
}
is RsIfExpr -> {
if (block?.collectFoldableReturns() != true) return false
if (elseBranch?.block?.collectFoldableReturns() != true) return false
}
is RsMatchExpr -> {
val arms = matchBody?.matchArmList ?: return false
for (arm in arms) {
if (arm.expr?.collectFoldableReturns() != true) return false
}
}
else -> return false
}
return true
}
return if (collectFoldableReturns()) result else null
}
| kotlin | 22 | 0.60986 | 107 | 35.66055 | 109 | starcoderdata |
package com.acmerobotics.roadrunner
import com.acmerobotics.roadrunner.geometry.Pose2d
import com.acmerobotics.roadrunner.geometry.Vector2d
import com.acmerobotics.roadrunner.path.Path
import com.acmerobotics.roadrunner.path.PathSegment
import com.acmerobotics.roadrunner.path.QuinticSpline
import com.acmerobotics.roadrunner.path.heading.TangentInterpolator
import com.acmerobotics.roadrunner.path.heading.WiggleInterpolator
import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder
import com.acmerobotics.roadrunner.trajectory.TrajectoryGenerator
import com.acmerobotics.roadrunner.trajectory.constraints.DriveConstraints
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import kotlin.math.PI
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class TrajectoryTest {
@Test
fun testTrajectoryDerivatives() {
val cryptoColWidth = 7.5
val stonePose = Pose2d(48.0, -47.5, PI)
val trajectory = TrajectoryBuilder(stonePose, constraints = DriveConstraints(5.0, 10.0, 0.0, 2.0, 3.0, 0.0))
.lineTo(Vector2d(12 - cryptoColWidth, -47.5))
.splineTo(Pose2d(16.0, -24.0, PI / 3))
.splineTo(
Pose2d(24.0, -10.0, PI / 4),
WiggleInterpolator(Math.toRadians(15.0), 6.0, TangentInterpolator()))
.build()
val dt = trajectory.duration() / 10000.0
val t = (0..10000).map { it * dt }
val x = t.map { trajectory[it].x }
val velX = t.map { trajectory.velocity(it).x }
val accelX = t.map { trajectory.acceleration(it).x }
val y = t.map { trajectory[it].y }
val velY = t.map { trajectory.velocity(it).y }
val accelY = t.map { trajectory.acceleration(it).y }
// there is a lot of noise in these numerical derivatives from the new parametrization
// however the analytic ones are perfect
TestUtil.assertDerivEquals(x, velX, dt, 0.05, 0.1)
TestUtil.assertDerivEquals(velX, accelX, dt, 0.05, 0.1)
TestUtil.assertDerivEquals(y, velY, dt, 0.05, 0.1)
TestUtil.assertDerivEquals(velY, accelY, dt, 0.05, 0.1)
}
@Test
fun testShortTrajectory() {
val path = Path(listOf(PathSegment(QuinticSpline(
QuinticSpline.Waypoint(0.0, 0.0, 0.0, -1.0),
QuinticSpline.Waypoint(1e-4, 1e-4, 0.707, 0.707)
)), PathSegment(QuinticSpline(
QuinticSpline.Waypoint(1e-4, 1e-4, 0.707, 0.707),
QuinticSpline.Waypoint(2e-4, 0.0, -1.0, 0.0)
))))
TrajectoryGenerator.generateTrajectory(path, DriveConstraints(5.0, 10.0, 0.0, 2.0, 3.0, 0.0), resolution = 1.0)
}
@Test
fun testTrajectoryEnd() {
val endPose = Pose2d(25.0, 25.0, 0.0)
repeat(50) {
val traj = TrajectoryBuilder(Pose2d(), constraints = DriveConstraints(5.0, 10.0, 0.0, 2.0, 3.0, 0.0))
.splineTo(Pose2d(50 * Math.random(), 50 * Math.random(), 2 * PI * Math.random()))
.splineTo(Pose2d(50 * Math.random(), 50 * Math.random(), 2 * PI * Math.random()))
.splineTo(endPose)
.build()
assert(traj.end() epsilonEquals endPose)
}
}
}
| kotlin | 30 | 0.640297 | 119 | 42.146667 | 75 | starcoderdata |
<gh_stars>0
package moe.tlaster.shiba.type
data class ShibaExtension(val type: String, val value: Any?, val scriptName: String?) {
// override fun toString(): String {
// return if (value != null) "\$$type $value $script" else "\$$type $script"
// }
} | kotlin | 6 | 0.645283 | 87 | 32.25 | 8 | starcoderdata |
package com.simplemobiletools.calculator.activities
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.AppLaunchChecker
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import com.simplemobiletools.calculator.BuildConfig
import com.simplemobiletools.calculator.R
import com.simplemobiletools.calculator.extensions.config
import com.simplemobiletools.calculator.extensions.updateViewColors
import com.simplemobiletools.calculator.helpers.*
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.LICENSE_AUTOFITTEXTVIEW
import com.simplemobiletools.commons.helpers.LICENSE_ESPRESSO
import com.simplemobiletools.commons.helpers.LICENSE_ROBOLECTRIC
import com.simplemobiletools.commons.models.FAQItem
import com.simplemobiletools.commons.models.Release
import kotlinx.android.synthetic.main.activity_main.*
import me.grantland.widget.AutofitHelper
class MainActivity : SimpleActivity(), Calculator {
private var storedTextColor = 0
private var vibrateOnButtonPress = true
lateinit var calc: CalculatorImpl
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
appLaunched(BuildConfig.APPLICATION_ID)
calc = CalculatorImpl(this, applicationContext)
btn_plus.setOnClickListener { calc.handleOperation(PLUS); checkHaptic(it) }
btn_minus.setOnClickListener { calc.handleOperation(MINUS); checkHaptic(it) }
btn_multiply.setOnClickListener { calc.handleOperation(MULTIPLY); checkHaptic(it) }
btn_divide.setOnClickListener { calc.handleOperation(DIVIDE); checkHaptic(it) }
btn_percent.setOnClickListener { calc.handleOperation(PERCENT); checkHaptic(it) }
btn_power.setOnClickListener { calc.handleOperation(POWER); checkHaptic(it) }
btn_root.setOnClickListener { calc.handleOperation(ROOT); checkHaptic(it) }
btn_clear.setOnClickListener { calc.handleClear(); checkHaptic(it) }
btn_clear.setOnLongClickListener { calc.handleReset(); true }
getButtonIds().forEach {
it.setOnClickListener { calc.numpadClicked(it.id); checkHaptic(it) }
}
btn_equals.setOnClickListener { calc.handleEquals(); checkHaptic(it) }
formula.setOnLongClickListener { copyToClipboard(false) }
result.setOnLongClickListener { copyToClipboard(true) }
AutofitHelper.create(result)
AutofitHelper.create(formula)
storeStateVariables()
updateViewColors(calculator_holder, config.textColor)
checkWhatsNewDialog()
checkAppOnSDCard()
}
override fun onResume() {
super.onResume()
if (storedTextColor != config.textColor) {
updateViewColors(calculator_holder, config.textColor)
}
if (config.preventPhoneFromSleeping) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
vibrateOnButtonPress = config.vibrateOnButtonPress
}
override fun onPause() {
super.onPause()
storeStateVariables()
if (config.preventPhoneFromSleeping) {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.settings -> launchSettings()
R.id.about -> launchAbout()
R.id.calculator -> launchCalculator()
R.id.unit -> launchUnit()
R.id.discountCalculator -> launchDiscount()
R.id.taxCalculator -> launchTax()
else -> return super.onOptionsItemSelected(item)
}
return true
}
private fun storeStateVariables() {
config.apply {
storedTextColor = textColor
}
}
private fun checkHaptic(view: View) {
if (vibrateOnButtonPress) {
view.performHapticFeedback()
}
}
private fun launchCalculator(){
startActivity(Intent(applicationContext, MainActivity:: class.java))
}
private fun launchUnit() {
startActivity(Intent(applicationContext, UnitActivity::class.java))
}
private fun launchDiscount(){
startActivity(Intent(applicationContext, DiscountActivity:: class.java))
}
private fun launchTax(){
startActivity(Intent(applicationContext, TaxActivity:: class.java))
}
private fun launchSettings() {
startActivity(Intent(applicationContext, SettingsActivity::class.java))
}
private fun launchAbout() {
val licenses = LICENSE_AUTOFITTEXTVIEW or LICENSE_ROBOLECTRIC or LICENSE_ESPRESSO
val faqItems = arrayListOf(
FAQItem(R.string.faq_1_title, R.string.faq_1_text),
FAQItem(R.string.faq_1_title_commons, R.string.faq_1_text_commons),
FAQItem(R.string.faq_4_title_commons, R.string.faq_4_text_commons),
FAQItem(R.string.faq_2_title_commons, R.string.faq_2_text_commons)
)
startAboutActivity(R.string.app_name, licenses, BuildConfig.VERSION_NAME, faqItems, true)
}
private fun getButtonIds() = arrayOf(btn_decimal, btn_0, btn_1, btn_2, btn_3, btn_4, btn_5, btn_6, btn_7, btn_8, btn_9)
private fun copyToClipboard(copyResult: Boolean): Boolean {
var value = formula.value
if (copyResult) {
value = result.value
}
return if (value.isEmpty()) {
false
} else {
copyToClipboard(value)
true
}
}
override fun setValue(value: String, context: Context) {
result.text = value
}
private fun checkWhatsNewDialog() {
arrayListOf<Release>().apply {
add(Release(18, R.string.release_18))
checkWhatsNew(this, BuildConfig.VERSION_CODE)
}
}
// used only by Robolectric
override fun setValueDouble(d: Double) {
calc.setValue(Formatter.doubleToString(d))
calc.lastKey = DIGIT
}
override fun setFormula(value: String, context: Context) {
formula.text = value
}
}
| kotlin | 22 | 0.681372 | 123 | 33.86413 | 184 | starcoderdata |
<reponame>greck2908/MinecraftDev
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.aw.psi.mixins.impl
import com.demonwav.mcdev.platform.mcp.aw.gen.psi.AwFieldEntry
import com.demonwav.mcdev.platform.mcp.aw.gen.psi.AwMethodEntry
import com.demonwav.mcdev.platform.mcp.aw.psi.mixins.AwEntryMixin
import com.demonwav.mcdev.platform.mcp.aw.psi.mixins.AwMemberNameMixin
import com.demonwav.mcdev.util.MemberReference
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.util.parentOfType
import com.intellij.util.ArrayUtil
import com.intellij.util.IncorrectOperationException
abstract class AwMemberNameImplMixin(node: ASTNode) : ASTWrapperPsiElement(node), AwMemberNameMixin {
override fun getElement(): PsiElement = this
override fun getReference(): PsiReference? = this
override fun resolve(): PsiElement? {
val entry = this.parentOfType<AwEntryMixin>() ?: return null
return when (entry) {
is AwMethodEntry -> {
val name = entry.methodName ?: return null
MemberReference(name, entry.methodDescriptor, entry.targetClassName?.replace('/', '.'))
.resolveMember(project, resolveScope)
}
is AwFieldEntry -> {
val name = entry.fieldName ?: return null
MemberReference(name, null, entry.targetClassName?.replace('/', '.'))
.resolveMember(project, resolveScope)
}
else -> null
}
}
override fun getVariants(): Array<*> {
val entry = this.parentOfType<AwEntryMixin>() ?: return ArrayUtil.EMPTY_OBJECT_ARRAY
val targetClassName = entry.targetClassName ?: return ArrayUtil.EMPTY_OBJECT_ARRAY
val targetClass = JavaPsiFacade.getInstance(project)?.findClass(targetClassName, resolveScope)
?: return ArrayUtil.EMPTY_OBJECT_ARRAY
return ArrayUtil.mergeArrays(targetClass.methods, targetClass.fields)
}
override fun getRangeInElement(): TextRange = TextRange(0, text.length)
override fun getCanonicalText(): String = text
override fun handleElementRename(newElementName: String): PsiElement {
throw IncorrectOperationException()
}
override fun bindToElement(element: PsiElement): PsiElement {
throw IncorrectOperationException()
}
override fun isReferenceTo(element: PsiElement): Boolean {
return element is PsiClass && element.qualifiedName == text.replace('/', '.')
}
override fun isSoft(): Boolean = false
}
| kotlin | 22 | 0.706944 | 103 | 35.923077 | 78 | starcoderdata |
<reponame>treech/CustomViewStudy
package com.treech.custom.viewstudy.view.image
import android.content.Context
import android.util.AttributeSet
import android.view.View
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
class FacePreView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null,
defStyle: Int = 0,
) : View(context, attrs, defStyle) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
override fun onDetachedFromWindow() {
scope.cancel()
super.onDetachedFromWindow()
}
} | kotlin | 12 | 0.770925 | 84 | 22.517241 | 29 | starcoderdata |
<gh_stars>0
package model.editorPlugin
import com.jetbrains.rider.generator.nova.*
import com.jetbrains.rider.generator.nova.PredefinedType.*
import com.jetbrains.rider.generator.nova.csharp.CSharp50Generator
import com.jetbrains.rider.generator.nova.kotlin.Kotlin11Generator
import java.io.File
@Suppress("unused")
object EditorPluginModel: Root(
CSharp50Generator(FlowTransform.AsIs, "JetBrains.Platform.Unity.EditorPluginModel", File("../resharper/resharper-unity/src/Rider/RdEditorProtocol")),
CSharp50Generator(FlowTransform.Reversed, "JetBrains.Platform.Unity.EditorPluginModel", File("../unity/EditorPlugin/NonUnity/RdEditorProtocol")),
Kotlin11Generator(FlowTransform.AsIs, "com.jetbrains.rider.plugins.unity.editorPlugin.model", File("src/main/kotlin/com/jetbrains/rider/protocol/RdEditorProtocol"))
){
var RdOpenFileArgs = structdef {
field("path", string)
field("line", int)
field("col", int)
}
val RdLogEvent = structdef {
field("time", long)
field("type", RdLogEventType)
field("mode", RdLogEventMode)
field("message", string)
field("stackTrace", string)
}
val RdLogEventType = enum {
+"Error"
+"Warning"
+"Message"
}
val RdLogEventMode = enum {
+"Edit"
+"Play"
}
val TestResult = structdef {
field("testId", string)
field("output", string)
field("duration", int)
field("status", enum {
+"Pending"
+"Running"
+"Inconclusive"
+"Ignored"
+"Success"
+"Failure"
})
field("parentId", string)
}
val RunResult = structdef {
field("passed", bool)
}
val TestMode = enum {
+"Edit"
+"Play"
}
val UnitTestLaunch = classdef {
field("testNames", immutableList(string))
field("testGroups", immutableList(string))
field("testCategories", immutableList(string))
field("testMode", TestMode)
sink("testResult", TestResult)
sink("runResult", RunResult)
call("abort", void, bool)
}
val UnityEditorState = enum {
+"Disconnected"
+"Idle"
+"Play"
+"Refresh"
}
init {
property("play", bool)
property("pause", bool)
source("step", void)
property("unityPluginVersion", string)
property("riderProcessId", int)
property("applicationPath", string)
property("applicationContentsPath", string)
property("applicationVersion", string)
property("scriptingRuntime", int)
sink("log", RdLogEvent)
callback("isBackendConnected", void, bool)
call("getUnityEditorState", void, UnityEditorState)
callback("openFileLineCol", RdOpenFileArgs, bool)
call("updateUnityPlugin", string, bool)
call("refresh", bool, void)
property("unitTestLaunch", UnitTestLaunch)
property("fullPluginPath", string)
property("editorLogPath", string)
property("playerLogPath", string)
}
}
| kotlin | 24 | 0.619853 | 168 | 27.481818 | 110 | starcoderdata |
<reponame>eboshare/TelegramBotAPI<gh_stars>0
package dev.inmo.tgbotapi.types.message.content
import dev.inmo.tgbotapi.requests.abstracts.Request
import dev.inmo.tgbotapi.requests.send.SendVenue
import dev.inmo.tgbotapi.types.ChatIdentifier
import dev.inmo.tgbotapi.types.MessageIdentifier
import dev.inmo.tgbotapi.types.buttons.KeyboardMarkup
import dev.inmo.tgbotapi.types.message.abstracts.ContentMessage
import dev.inmo.tgbotapi.types.message.content.abstracts.MessageContent
import dev.inmo.tgbotapi.types.venue.Venue
data class VenueContent(
val venue: Venue
) : MessageContent {
override fun createResend(
chatId: ChatIdentifier,
disableNotification: Boolean,
replyToMessageId: MessageIdentifier?,
allowSendingWithoutReply: Boolean?,
replyMarkup: KeyboardMarkup?
): Request<ContentMessage<VenueContent>> = SendVenue(
chatId, venue, disableNotification, replyToMessageId, allowSendingWithoutReply, replyMarkup
)
} | kotlin | 11 | 0.792683 | 99 | 38.4 | 25 | starcoderdata |
package solutions.mckee.crux.xslt
import net.sf.saxon.s9api.Processor
import net.sf.saxon.s9api.Serializer
import java.io.InputStream
import java.io.StringReader
import javax.xml.transform.stream.StreamSource
private val processor = Processor(false)
private val xsltCompiler = processor.newXsltCompiler()
fun executeScript(xmlInput: InputStream, xsltScript: String) {
val source = StreamSource(xmlInput)
val xsltExecutable = xsltCompiler.compile(StreamSource(StringReader(xsltScript), "http://localhost/string"))
val transformer = xsltExecutable.load30()
val outputSerializer = processor.newSerializer(System.out)
transformer.transform(source, outputSerializer)
}
| kotlin | 17 | 0.815362 | 110 | 36.611111 | 18 | starcoderdata |
<filename>support-core/src/main/java/android/support/core/livedata/SingleLiveEvent.kt<gh_stars>0
package android.support.core.livedata
import androidx.annotation.MainThread
import androidx.annotation.Nullable
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean
open class SingleLiveEvent<T> : MediatorLiveData<T>() {
private val mPending = AtomicBoolean(false)
@MainThread
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
super.observe(owner, Observer {
if (mPending.compareAndSet(true, false)) {
observer.onChanged(it)
}
})
}
@MainThread
override fun setValue(@Nullable t: T?) {
mPending.set(true)
super.setValue(t)
}
} | kotlin | 22 | 0.714451 | 96 | 27.866667 | 30 | starcoderdata |
package com.bugsnag.android
import android.app.ActivityManager
import android.app.ActivityManager.ProcessErrorStateInfo
import android.content.Context
import android.os.Handler
import android.os.HandlerThread
import android.os.Process
import androidx.annotation.VisibleForTesting
import java.util.concurrent.atomic.AtomicInteger
internal class AnrDetailsCollector {
companion object {
private const val INFO_POLL_THRESHOLD_MS: Long = 100
private const val MAX_ATTEMPTS: Int = 300
}
private val handlerThread = HandlerThread("bugsnag-anr-collector")
init {
handlerThread.start()
}
internal fun collectAnrDetails(ctx: Context): ProcessErrorStateInfo? {
val am = ctx.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
return captureProcessErrorState(am, Process.myPid())
}
/**
* Collects information about an ANR, by querying an activity manager for information about
* any proceses which are currently in an error condition.
*
* See https://developer.android.com/reference/android/app/ActivityManager.html#getProcessesInErrorState()
*/
@VisibleForTesting
internal fun captureProcessErrorState(am: ActivityManager, pid: Int): ProcessErrorStateInfo? {
return try {
val processes = am.processesInErrorState ?: emptyList()
processes.firstOrNull { it.pid == pid }
} catch (exc: RuntimeException) {
null
}
}
internal fun addErrorStateInfo(error: Error, anrState: ProcessErrorStateInfo) {
val msg = anrState.shortMsg
error.exceptionMessage = when {
msg.startsWith("ANR") -> msg.replaceFirst("ANR", "")
else -> msg
}
}
internal fun collectAnrErrorDetails(client: Client, error: Error) {
val handler = Handler(handlerThread.looper)
val attempts = AtomicInteger()
handler.post(object : Runnable {
override fun run() {
val anrDetails = collectAnrDetails(client.appContext)
if (anrDetails == null) {
if (attempts.getAndIncrement() < MAX_ATTEMPTS) {
handler.postDelayed(this, INFO_POLL_THRESHOLD_MS)
}
} else {
addErrorStateInfo(error, anrDetails)
client.notify(error, DeliveryStyle.ASYNC_WITH_CACHE, null)
}
}
})
}
}
| kotlin | 26 | 0.644641 | 110 | 33 | 73 | starcoderdata |
<reponame>UTN-FRBA-Mobile/Play2Play<filename>app/src/main/java/ar/com/play2play/presentation/tuttifrutti/create/rounds/TuttiFruttiRoundsNumberFragment.kt
package ar.com.play2play.presentation.tuttifrutti.create.rounds
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import ar.com.play2play.databinding.FragmentRoundsNumberBinding
import ar.com.play2play.presentation.base.BaseDialogFragment
import ar.com.play2play.presentation.tuttifrutti.TuttiFruttiViewModel
class TuttiFruttiRoundsNumberFragment :
BaseDialogFragment<FragmentRoundsNumberBinding, Unit, RoundsNumberViewModel>() {
override val viewModel: RoundsNumberViewModel by viewModels()
private val gameViewModel: TuttiFruttiViewModel by activityViewModels()
override val inflater: (LayoutInflater, ViewGroup?, Boolean) -> FragmentRoundsNumberBinding =
FragmentRoundsNumberBinding::inflate
override fun initUI() {
binding.arrowRight.setOnClickListener { viewModel.increase() }
binding.arrowLeft.setOnClickListener { viewModel.decrease() }
binding.createButton.setOnClickListener {
gameViewModel.setTotalRounds(binding.number.text.toString().toInt())
gameViewModel.goToLobby()
}
}
override fun setupObservers() =
observe(viewModel.roundsNumber) {
binding.number.text = it.toString()
}
companion object {
/** Create a new instance of the [TuttiFruttiRoundsNumberFragment]. */
fun newInstance() = TuttiFruttiRoundsNumberFragment()
}
}
| kotlin | 22 | 0.766242 | 153 | 39.170732 | 41 | starcoderdata |
package de.rki.coronawarnapp.ui.submission.yourconsent
import androidx.lifecycle.asLiveData
import com.squareup.inject.assisted.AssistedInject
import de.rki.coronawarnapp.storage.SubmissionRepository
import de.rki.coronawarnapp.storage.interoperability.InteroperabilityRepository
import de.rki.coronawarnapp.ui.SingleLiveEvent
import de.rki.coronawarnapp.util.coroutine.DispatcherProvider
import de.rki.coronawarnapp.util.viewmodel.CWAViewModel
import de.rki.coronawarnapp.util.viewmodel.SimpleCWAViewModelFactory
import kotlinx.coroutines.flow.first
class SubmissionYourConsentViewModel @AssistedInject constructor(
val dispatcherProvider: DispatcherProvider,
interoperabilityRepository: InteroperabilityRepository,
val submissionRepository: SubmissionRepository
) : CWAViewModel(dispatcherProvider = dispatcherProvider) {
val clickEvent: SingleLiveEvent<SubmissionYourConsentEvents> = SingleLiveEvent()
val consent = submissionRepository.hasGivenConsentToSubmission.asLiveData()
val countryList = interoperabilityRepository.countryListFlow.asLiveData()
fun goBack() {
clickEvent.postValue(SubmissionYourConsentEvents.GoBack)
}
fun switchConsent() {
launch {
if (submissionRepository.hasGivenConsentToSubmission.first()) {
submissionRepository.revokeConsentToSubmission()
} else {
submissionRepository.giveConsentToSubmission()
}
}
}
fun goLegal() {
clickEvent.postValue(SubmissionYourConsentEvents.GoLegal)
}
@AssistedInject.Factory
interface Factory : SimpleCWAViewModelFactory<SubmissionYourConsentViewModel>
}
| kotlin | 17 | 0.784863 | 84 | 38.023256 | 43 | starcoderdata |
<reponame>lincolnppires/sample-cqrs<filename>command-server/src/main/kotlin/hsenasilva/com/github/sample/cqrs/aggregate/SampleAggregate.kt
package hsenasilva.com.github.sample.cqrs.aggregate
import hsenasilva.com.github.sample.cqrs.core.domain.*
import hsenasilva.com.github.sample.cqrs.domain.CancelCreateSampleCommand
import hsenasilva.com.github.sample.cqrs.domain.CreateSampleCommand
import hsenasilva.com.github.sample.cqrs.domain.RequestSampleCommand
import org.axonframework.commandhandling.CommandHandler
import org.axonframework.eventsourcing.EventSourcingHandler
import org.axonframework.modelling.command.AggregateIdentifier
import org.axonframework.modelling.command.AggregateLifecycle.apply
import org.axonframework.spring.stereotype.Aggregate
/**
* @author hsena
*/
@Aggregate
class SampleAggregate {
@AggregateIdentifier
private lateinit var id: SampleId
private var status: SampleStatus? = null
constructor()
@CommandHandler
constructor(command: RequestSampleCommand) {
apply(RequestedSampleEvent(
sampleId = command.id,
sample = Sample(
id = command.createSampleParameter.id.id,
stuff = command.createSampleParameter.stuff,
action = command.createSampleParameter.action,
status = SampleStatus.REQUESTED
)
))
}
@CommandHandler
fun handle(command: CreateSampleCommand) {
apply(CreatedSampleEvent(
sampleId = command.id,
sample = Sample(
id = command.createSampleParameter.id.id,
stuff = command.createSampleParameter.stuff,
action = command.createSampleParameter.action,
status = SampleStatus.CREATED
)
))
}
@CommandHandler
fun handle(command: CancelCreateSampleCommand) {
apply(CanceledCreateSampleEvent(
sampleId = command.id,
sample = Sample(
id = command.createSampleParameter.id.id,
stuff = command.createSampleParameter.stuff,
action = command.createSampleParameter.action,
status = SampleStatus.CANCELED
)
))
}
@EventSourcingHandler
fun on(event: CreatedSampleEvent) {
this.id = event.id
this.status = event.sample.status
}
@EventSourcingHandler
fun on(event: RequestedSampleEvent) {
this.id = event.id
this.status = event.sample.status
}
@EventSourcingHandler
fun on(event: CanceledCreateSampleEvent) {
this.id = SampleId(event.sampleId.id)
this.status = event.sample.status
}
private fun applyYourBusinessRulesHere(command: CreateSampleCommand) = command.createSampleParameter.action
} | kotlin | 22 | 0.651495 | 138 | 33.647059 | 85 | starcoderdata |
package no.njoh.pulseengine.modules.scene.entities
import com.fasterxml.jackson.annotation.JsonIgnore
import no.njoh.pulseengine.PulseEngine
import no.njoh.pulseengine.modules.graphics.Surface2D
import no.njoh.pulseengine.modules.scene.systems.physics.BodyType
import no.njoh.pulseengine.modules.scene.systems.physics.PhysicsEntity
import no.njoh.pulseengine.modules.scene.systems.physics.bodies.PhysicsBody
import kotlin.math.sqrt
open class Spring : SceneEntity(), PhysicsEntity
{
var bodyRef0 = 0L
var bodyRef1 = 0L
var bodyPoint0 = 0
var bodyPoint1 = 0
var stiffness = 1f
@JsonIgnore
private var targetLength = Float.NaN
override fun init(engine: PulseEngine) { }
override fun beginStep(engine: PulseEngine, timeStep: Float, gravity: Float)
{
if (targetLength.isNaN())
getPoints(engine) { x0, y0, x1, y1 -> targetLength = sqrt((x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1)) }
}
override fun iterateStep(engine: PulseEngine, iteration: Int, totalIterations: Int, worldWidth: Int, worldHeight: Int)
{
val body0 = engine.scene.getEntityOfType<PhysicsBody>(bodyRef0)
val body1 = engine.scene.getEntityOfType<PhysicsBody>(bodyRef1)
body0?.shape?.getPoint(bodyPoint0)?.let { p0 ->
val p0x = p0.x
val p0y = p0.y
body1?.shape?.getPoint(bodyPoint1)?.let { p1 ->
// Calculate displacement
val xDelta = p0x - p1.x
val yDelta = p0y - p1.y
val actualLength = sqrt(xDelta * xDelta + yDelta * yDelta).takeIf { it != 0f } ?: 0.000001f
val deltaLength = (targetLength - actualLength) * 0.5f * stiffness
val xDisp = (xDelta / actualLength) * deltaLength
val yDisp = (yDelta / actualLength) * deltaLength
// Calculate displacement ratios based on mass
val mass0 = body0.getMass()
val mass1 = body1.getMass()
val invTotalMass= 1.0f / (mass0 + mass1)
val ratio0 = if (body1.bodyType == BodyType.STATIC) 1f else mass1 * invTotalMass
val ratio1 = if (body0.bodyType == BodyType.STATIC) 1f else mass0 * invTotalMass
if (body0.bodyType != BodyType.STATIC)
{
body0.shape.setPoint(bodyPoint0, p0x + xDisp * ratio0, p0y + yDisp * ratio0)
body0.wakeUp()
}
if (body1.bodyType != BodyType.STATIC)
{
body1.shape.setPoint(bodyPoint1, p1.x - xDisp * ratio1, p1.y - yDisp * ratio1)
body1.wakeUp()
}
}
}
}
override fun render(engine: PulseEngine, surface: Surface2D)
{
getPoints(engine) { x0, y0, x1, y1 ->
if (x0 == 0f || y0 == 0f || x1 == 0f || y1 == 0f )
return
if (stiffness == 1f)
{
// Draw simple line
surface.setDrawColor(1f, 1f, 1f, 1f)
surface.drawLine(x0, y0, x1, y1)
return
}
val xDelta = x1 - x0
val yDelta = y1 - y0
val length = sqrt(xDelta * xDelta + yDelta * yDelta)
val xNormal = (yDelta / length) * 50f
val yNormal = (-xDelta / length) * 50f
val nPoints = 40
val xStep = xDelta / nPoints
val yStep = yDelta / nPoints
var xLast = x0
var yLast = y0
// Draw spring as zigzag line
for (i in 1 until nPoints + 1)
{
val x = x0 + xStep * i - xNormal * ((i % 3) - 1f)
val y = y0 + yStep * i - yNormal * ((i % 3) - 1f)
surface.setDrawColor(1f, 1f, 1f, 1f)
surface.drawLine(xLast, yLast, x, y)
xLast = x
yLast = y
}
}
}
private inline fun getPoints(engine: PulseEngine, block: (x0: Float, y0: Float, x1: Float, y1: Float) -> Unit)
{
val body0 = engine.scene.getEntityOfType<PhysicsBody>(bodyRef0)
val body1 = engine.scene.getEntityOfType<PhysicsBody>(bodyRef1)
body0?.shape?.getPoint(bodyPoint0)?.let { p0 ->
val x0 = p0.x
val y0 = p0.y
body1?.shape?.getPoint(bodyPoint1)?.let { p1 ->
block(x0, y0, p1.x, p1.y)
}
}
}
} | kotlin | 26 | 0.544013 | 122 | 36.621849 | 119 | starcoderdata |
package com.common
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
/**
* Author : wxz
* Time : 2021/12/07
* Desc :
*/
interface ILoginService {
fun launch(context: Context, targetClass: String)
fun newUserInfoFragment(fragmentManager: FragmentManager, viewId: Int, bundle: Bundle): Fragment?
} | kotlin | 7 | 0.740291 | 101 | 23.294118 | 17 | starcoderdata |
// Automatically generated by the Fast Binary Encoding compiler, do not modify!
// https://github.com/chronoxor/FastBinaryEncoding
// Source: enums.fbe
// Version: 1.7.0.0
@file:Suppress("UnusedImport", "unused")
package com.chronoxor.enums
@Suppress("MemberVisibilityCanBePrivate", "RemoveRedundantCallsOfConversionMethods")
class EnumUInt16 : Comparable<EnumUInt16>
{
companion object
{
val ENUM_VALUE_0 = EnumUInt16(EnumUInt16Enum.ENUM_VALUE_0)
val ENUM_VALUE_1 = EnumUInt16(EnumUInt16Enum.ENUM_VALUE_1)
val ENUM_VALUE_2 = EnumUInt16(EnumUInt16Enum.ENUM_VALUE_2)
val ENUM_VALUE_3 = EnumUInt16(EnumUInt16Enum.ENUM_VALUE_3)
val ENUM_VALUE_4 = EnumUInt16(EnumUInt16Enum.ENUM_VALUE_4)
val ENUM_VALUE_5 = EnumUInt16(EnumUInt16Enum.ENUM_VALUE_5)
}
var value: EnumUInt16Enum? = EnumUInt16Enum.values()[0]
private set
val raw: UShort
get() = value!!.raw
constructor()
constructor(value: UShort) { setEnum(value) }
constructor(value: EnumUInt16Enum) { setEnum(value) }
constructor(value: EnumUInt16) { setEnum(value) }
fun setDefault() { setEnum(0.toUShort()) }
fun setEnum(value: UShort) { this.value = EnumUInt16Enum.mapValue(value) }
fun setEnum(value: EnumUInt16Enum) { this.value = value }
fun setEnum(value: EnumUInt16) { this.value = value.value }
override fun compareTo(other: EnumUInt16): Int
{
if (value == null)
return -1
if (other.value == null)
return 1
return (value!!.raw - other.value!!.raw).toInt()
}
override fun equals(other: Any?): Boolean
{
if (other == null)
return false
if (!EnumUInt16::class.java.isAssignableFrom(other.javaClass))
return false
val enm = other as EnumUInt16? ?: return false
if (enm.value == null)
return false
if (value!!.raw != enm.value!!.raw)
return false
return true
}
override fun hashCode(): Int
{
var hash = 17
hash = hash * 31 + if (value != null) value!!.hashCode() else 0
return hash
}
override fun toString(): String
{
return if (value != null) value!!.toString() else "<unknown>"
}
}
| kotlin | 16 | 0.628934 | 84 | 28.714286 | 77 | starcoderdata |
import kotlin.system.measureTimeMillis
import java.util.Scanner
/**
* Kotlin Script to automate wifi adb connection with the connected device:
*
* 1. retrieve the connected device IP address
* 2. perform tcpip port forwarding
* 3. connect to the ip address retrieved
*
*/
val process = Runtime.getRuntime().exec("adb shell ip addr show wlan0")
val stream = process.inputStream
val errStream = process.errorStream
errStream?.let {
val errorScanner = Scanner(it)
errorScanner.useDelimiter("\n")
while (errorScanner.hasNext()) {
println(errorScanner.next())
}
}
var myIp: String = ""
val scanner = Scanner(stream)
scanner.useDelimiter("\n")
while (scanner.hasNext()) {
val str = scanner.next().trim()
if (str.startsWith("inet ")) {
var startIndex = str.indexOf("inet ")
startIndex += "inet ".length
val pos = str.indexOf('/')
myIp = str.substring(startIndex, pos)
if (myIp.length > 0) {
break
}
}
}
if (myIp.isNotEmpty()) {
Runtime.getRuntime().exec("adb tcpip 5555")
Runtime.getRuntime().exec("adb connect $myIp")
}
| kotlin | 16 | 0.651101 | 75 | 22.163265 | 49 | starcoderdata |
package com.yuyakaido.android.cardstackview.sample
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
class TouristSpotCardAdapter(context: Context) : ArrayAdapter<TouristSpot>(context, 0) {
override fun getView(position: Int, contentView: View?, parent: ViewGroup): View {
var localContentView = contentView
val holder: ViewHolder
if (localContentView == null) {
val inflater = LayoutInflater.from(context)
localContentView = inflater.inflate(R.layout.item_tourist_spot_card, parent, false)
holder = ViewHolder(localContentView)
localContentView.tag = holder
} else {
holder = localContentView.tag as ViewHolder
}
val spot = getItem(position)
holder.name.text = spot!!.name
holder.city.text = spot.city
Glide.with(context).load(spot.url).into(holder.image)
return localContentView!!
}
private class ViewHolder(view: View) {
var name: TextView = view.findViewById(R.id.item_tourist_spot_card_name)
var city: TextView = view.findViewById(R.id.item_tourist_spot_card_city)
var image: ImageView = view.findViewById(R.id.item_tourist_spot_card_image)
}
}
| kotlin | 17 | 0.696949 | 95 | 31.772727 | 44 | starcoderdata |
<filename>app/src/main/java/com/udacity/shoestore/ui/instructionList/InstructionListFragment.kt
package com.udacity.shoestore.ui.instructionList
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.udacity.shoestore.R
import com.udacity.shoestore.ShareViewModel
import com.udacity.shoestore.databinding.FragmentInstructionListBinding
class InstructionListFragment : Fragment() {
private lateinit var binding: FragmentInstructionListBinding
private lateinit var listViewModel: ShareViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_instruction_list, container, false)
initViewModel()
initObservers()
(activity as AppCompatActivity).supportActionBar?.hide()
return binding.root
}
private fun initViewModel() {
listViewModel = ViewModelProvider(requireActivity()).get(ShareViewModel::class.java)
binding.instructionListShareViewModel = listViewModel
}
private fun initObservers() {
listViewModel.eventNextInstructionPress.observe(viewLifecycleOwner, {
if (it) {
goToInstructionDetail()
listViewModel.goToInstructionDetailComplete()
}
})
}
private fun goToInstructionDetail() {
findNavController().navigate(R.id.action_instructionList_to_instructionDetail)
}
} | kotlin | 18 | 0.751805 | 105 | 31.763636 | 55 | starcoderdata |
<reponame>ALikhachev/kotlinx-benchmark
package kotlinx.benchmark.gradle
import groovy.lang.*
import org.gradle.api.*
import org.gradle.api.tasks.*
import java.io.*
import java.time.*
import java.time.format.*
fun cleanup(file: File) {
if (file.exists()) {
val listing = file.listFiles()
if (listing != null) {
for (sub in listing) {
cleanup(sub)
}
}
file.delete()
}
}
inline fun <reified T : Task> Project.task(
name: String,
depends: String? = null,
noinline configuration: T.() -> Unit
): TaskProvider<T> {
@Suppress("UnstableApiUsage")
val task = tasks.register(name, T::class.java, Action(configuration))
if (depends != null) {
tasks.getByName(depends).dependsOn(task)
}
return task
}
fun Project.benchmarkBuildDir(target: BenchmarkTarget): File =
file(buildDir.resolve(target.extension.buildDir).resolve(target.name))
fun Project.benchmarkReportsDir(config: BenchmarkConfiguration, target: BenchmarkTarget): File {
val ext = project.extensions.extraProperties
val time = if (ext.has("reportTime")) {
ext.get("reportTime") as LocalDateTime
} else {
LocalDateTime.now().also {
ext.set("reportTime", it)
}
}
val timestamp = time.format(DateTimeFormatter.ISO_DATE_TIME)
val compatibleTime = timestamp.replace(":", ".") // Windows doesn't allow ':' in path
return file(buildDir.resolve(target.extension.reportsDir).resolve(config.name).resolve(compatibleTime))
}
class KotlinClosure1<in T : Any?, V : Any>(
val function: T.() -> V?,
owner: Any? = null,
thisObject: Any? = null
) : Closure<V?>(owner, thisObject) {
@Suppress("unused") // to be called dynamically by Groovy
fun doCall(it: T): V? = it.function()
}
fun <T> Any.closureOf(action: T.() -> Unit): Closure<Any?> =
KotlinClosure1(action, this, this)
fun <T> Any.tryGetClass(className: String): Class<T>? {
val classLoader = javaClass.classLoader
return try {
Class.forName(className, false, classLoader) as Class<T>
} catch (e: ClassNotFoundException) {
null
}
}
fun writeParameters(
name: String,
reportFile: File,
format: String,
config: BenchmarkConfiguration
): File {
validateConfig(config)
val file = createTempFile("benchmarks")
file.writeText(buildString {
appendln("name:$name")
appendln("reportFile:$reportFile")
appendln("traceFormat:$format")
config.reportFormat?.let { appendln("reportFormat:$it") }
config.iterations?.let { appendln("iterations:$it") }
config.warmups?.let { appendln("warmups:$it") }
config.iterationTime?.let { appendln("iterationTime:$it") }
config.iterationTimeUnit?.let { appendln("iterationTimeUnit:$it") }
config.outputTimeUnit?.let { appendln("outputTimeUnit:$it") }
config.mode?.let { appendln("mode:$it") }
config.includes.forEach {
appendln("include:$it")
}
config.excludes.forEach {
appendln("exclude:$it")
}
config.params.forEach { (param, values) ->
values.forEach { value -> appendln("param:$param=$value") }
}
config.advanced.forEach { (param, value) ->
appendln("$param:$value")
}
})
return file
}
private fun validateConfig(config: BenchmarkConfiguration) {
config.reportFormat?.let {
require(it.toLowerCase() in setOf("json", "csv", "scsv", "text")) {
"Report format '$it' is not supported."
}
}
}
| kotlin | 29 | 0.626862 | 107 | 29.728814 | 118 | starcoderdata |
package com.github.kotlintelegrambot
import com.github.kotlintelegrambot.entities.CallbackQuery
import com.github.kotlintelegrambot.entities.Chat
import com.github.kotlintelegrambot.entities.InlineKeyboardMarkup
import com.github.kotlintelegrambot.entities.Message
import com.github.kotlintelegrambot.entities.Update
import com.github.kotlintelegrambot.entities.User
import com.github.kotlintelegrambot.entities.keyboard.InlineKeyboardButton.CallbackData
import com.github.kotlintelegrambot.network.serialization.GsonFactory
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class UpdateMapperTest {
private val sut = UpdateMapper(
gson = GsonFactory.createForApiClient()
)
@Test
fun `update with callback query containing an inline keyboard is mapped correctly`() {
val updateJson = """
{
"update_id": 1,
"callback_query": {
"id": "1",
"from": {
"id": 1,
"is_bot": false,
"first_name": "TestName",
"username": "testname",
"language_code": "de"
},
"message": {
"message_id": 1,
"from": {
"id": 1,
"is_bot": true,
"first_name": "testbot",
"username": "testbot"
},
"chat": {
"id": 1,
"first_name": "TestName",
"username": "testname",
"type": "private"
},
"date": 1606317592,
"text": "Hello, inline buttons!",
"reply_markup": {
"inline_keyboard": [
[
{
"text": "Test Inline Button",
"callback_data": "testButton"
}
],
[
{
"text": "Show alert",
"callback_data": "showAlert"
}
]
]
}
},
"chat_instance": "1",
"data": "showAlert"
}
}
""".trimIndent()
val actualUpdate = sut.jsonToUpdate(updateJson)
val expectedUpdate = Update(
updateId = 1,
callbackQuery = CallbackQuery(
id = "1",
from = User(
id = 1,
isBot = false,
firstName = "TestName",
username = "testname",
languageCode = "de"
),
message = Message(
messageId = 1,
from = User(
id = 1,
isBot = true,
firstName = "testbot",
username = "testbot"
),
chat = Chat(
id = 1,
firstName = "TestName",
username = "testname",
type = "private"
),
date = 1606317592,
text = "Hello, inline buttons!",
replyMarkup = InlineKeyboardMarkup.create(
listOf(
CallbackData(
text = "Test Inline Button",
callbackData = "testButton"
)
),
listOf(
CallbackData(
text = "Show alert",
callbackData = "showAlert"
)
)
)
),
chatInstance = "1",
data = "showAlert"
)
)
assertEquals(expectedUpdate, actualUpdate)
}
}
| kotlin | 31 | 0.357627 | 90 | 36.146341 | 123 | starcoderdata |
package io.stud.forest.springsamples.todo_rest_client.data_source
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.functions.Consumer
import io.stud.forest.springsamples.todo_rest_client.Printer
import io.stud.forest.springsamples.todo_rest_client.model.User
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class UsersService
@Autowired
constructor(
private val api: UsersApi
) {
companion object {
private val log = LoggerFactory.getLogger(Printer::class.java)
}
fun users(): Single<List<User>> {
return api
.users()
.flatMapIterable { it }
.flatMap { user ->
api
.tasksByUser(user.id)
.flatMap {
user.tasks = it;
Observable.just(user)
}
}.toList()
}
} | kotlin | 26 | 0.600367 | 70 | 30.2 | 35 | starcoderdata |
<filename>domain/src/main/java/com/ericampire/android/androidstudycase/domain/di/UseCaseModule.kt
package com.ericampire.android.androidstudycase.domain.di
object UseCaseModule {
} | kotlin | 12 | 0.84153 | 97 | 25.285714 | 7 | starcoderdata |
package com.rxf113.networktest
import android.util.Log
import org.xml.sax.helpers.DefaultHandler
import org.xml.sax.Attributes
class ContentHandler : DefaultHandler() {
private var nodeName = ""
private lateinit var id: StringBuilder
private lateinit var name: StringBuilder
private lateinit var version: StringBuilder
override fun startDocument() {
id = StringBuilder()
name = StringBuilder()
version = StringBuilder()
}
override fun startElement(uri: String, localName: String, qName: String, attributes: Attributes) {
// 记录当前节点名
nodeName = localName
Log.d("ContentHandler", "uri is $uri")
Log.d("ContentHandler", "localName is $localName")
Log.d("ContentHandler", "qName is $qName")
Log.d("ContentHandler", "attributes is $attributes")
}
override fun characters(ch: CharArray, start: Int, length: Int) {
// 根据当前的节点名判断将内容添加到哪一个StringBuilder对象中
when (nodeName) {
"id" -> id.append(ch, start, length)
"name" -> name.append(ch, start, length)
"version" -> version.append(ch, start, length)
}
}
override fun endElement(uri: String, localName: String, qName: String) {
if ("app" == localName) {
Log.d("ContentHandler", "id is ${id.toString().trim()}")
Log.d("ContentHandler", "name is ${name.toString().trim()}")
Log.d("ContentHandler", "version is ${version.toString().trim()}")
// 最后要将StringBuilder清空掉
id.setLength(0)
name.setLength(0)
version.setLength(0)
}
}
override fun endDocument() {
}
} | kotlin | 20 | 0.61052 | 102 | 29.232143 | 56 | starcoderdata |
<filename>app/src/main/java/dog/snow/androidrecruittest/data/model/raw/RawPhoto.kt
package dog.snow.androidrecruittest.data.model.raw
import android.os.Parcelable
import com.fasterxml.jackson.annotation.JsonProperty
import dog.snow.androidrecruittest.data.model.type.common.Title
import dog.snow.androidrecruittest.data.model.type.common.UId
import dog.snow.androidrecruittest.data.model.type.photo.Url
import dog.snow.androidrecruittest.utils.Converters
import dog.snow.androidrecruittest.utils.JsonLabels
import io.objectbox.annotation.Convert
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import io.objectbox.annotation.Unique
import kotlinx.android.parcel.Parcelize
@Entity
@Parcelize
data class RawPhoto(
@Id
@JsonProperty(JsonLabels.UNKNOWN) // For some reason @JsonIgnore does not work
var id: Long = 0,
@Unique
@JsonProperty(JsonLabels.ID)
@Convert(converter = Converters.UID::class, dbType = Long::class)
val uId: UId,
@JsonProperty(JsonLabels.ALBUMID)
@Convert(converter = Converters.UID::class, dbType = Long::class)
val albumUId: UId,
@JsonProperty(JsonLabels.TITLE)
@Convert(converter = Converters.TITLE::class, dbType = String::class)
val title: Title,
@JsonProperty(JsonLabels.URL)
@Convert(converter = Converters.URL::class, dbType = String::class)
val url: Url,
@JsonProperty(JsonLabels.THUMBNAILURL)
@Convert(converter = Converters.URL::class, dbType = String::class)
val thumbnailUrl: Url
) : Parcelable | kotlin | 12 | 0.768078 | 89 | 36.463415 | 41 | starcoderdata |
<gh_stars>0
package com.app.vanillacamera
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.util.DisplayMetrics
import android.view.TextureView
import android.view.WindowManager
/**
* A [TextureView] that can be adjusted to a specified aspect ratio.
*/
class AutoFitTextureView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : TextureView(context, attrs, defStyle) {
private var mRatioWidth = 0
private var mRatioHeight = 0
var dim: Rect? = null
/**
* Sets the aspect ratio for this view. The size of the view will be measured based on the ratio
* calculated from the parameters. Note that the actual sizes of parameters don't matter, that
* is, calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result.
*
* @param width Relative horizontal size
* @param height Relative vertical size
*/
fun setAspectRatio(width: Int, height: Int) {
require(!(width < 0 || height < 0)) { "Size cannot be negative." }
mRatioWidth = width
mRatioHeight = height
requestLayout()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
var metrics = DisplayMetrics()
(context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay.getMetrics(
metrics
)
var aspectRatio = 4 / 3
val width = metrics.widthPixels
val height = metrics.widthPixels * aspectRatio
if (0 == mRatioWidth || 0 == mRatioHeight)
setMeasuredDimension(width, height)
//setMeasuredDimension(metrics.widthPixels, metrics.heightPixels)
}
}
| kotlin | 21 | 0.686674 | 102 | 31.428571 | 56 | starcoderdata |
package homework_6
import org.jfree.chart.ChartFactory
import org.jfree.chart.ChartPanel
import org.jfree.chart.JFreeChart
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer
import org.jfree.chart.ui.ApplicationFrame
import org.jfree.data.xy.XYSeries
import org.jfree.data.xy.XYDataset
import org.jfree.data.xy.XYSeriesCollection
import java.awt.Color
import java.awt.Dimension
import kotlin.random.Random
class DrawPlot(
mergeSorter: MergeSorter,
numbersOfThreads: List<Int>,
maxNumberOfElements: Int,
step: Int,
) {
private companion object {
const val HEIGHT = 1000
const val WIDTH = 1000
val listOfColours = listOf(
Color.RED,
Color.ORANGE,
Color.YELLOW,
Color.GREEN,
Color.GRAY,
Color.BLUE,
Color.CYAN,
Color.DARK_GRAY,
Color.MAGENTA,
Color.PINK,
Color.DARK_GRAY
)
}
init {
val dataset = createDataset(mergeSorter, numbersOfThreads, maxNumberOfElements, step)
val chart = ChartFactory.createXYLineChart(
"dependence of sorting time on the number of elements",
"number of elements",
"time",
dataset,
org.jfree.chart.plot.PlotOrientation.VERTICAL,
true,
false,
false
)
val rendererForPlot = XYLineAndShapeRenderer()
listOfColours.forEachIndexed { index, element -> rendererForPlot.setSeriesPaint(index, element) }
chart.xyPlot.renderer = rendererForPlot
displayChart(chart)
}
private fun createXYSeries(
mergeSorter: MergeSorter,
array: LongArray,
step: Int,
numberOfThreads: Int
): XYSeries {
val xySeries = XYSeries(
"number of ${mergeSorter.nameOfMethodUsed} - $numberOfThreads"
)
array.forEachIndexed { index, element -> xySeries.add(index * step, element) }
return xySeries
}
private fun measureTime(mergeSorter: MergeSorter, numberOfThreadsOrCoroutines: Int, numberOfElements: Int): Long {
val array = IntArray(numberOfElements) { Random.nextInt() }
var time = System.nanoTime()
mergeSorter.sort(array, numberOfThreadsOrCoroutines)
time = System.nanoTime() - time
return time
}
private fun createDataset(
mergeSorter: MergeSorter,
numbersOfThreads: List<Int>,
maxNumberOfElements: Int,
step: Int
): XYDataset {
val xySeriesCollection = XYSeriesCollection()
numbersOfThreads.forEach {
val time = LongArray(maxNumberOfElements / step) { 0 }
for (index in 1 until maxNumberOfElements / step) {
time[index] = measureTime(mergeSorter, it, step * index)
}
xySeriesCollection.addSeries(createXYSeries(mergeSorter, time, step, it))
}
return xySeriesCollection
}
private fun displayChart(chart: JFreeChart) {
val frame = ApplicationFrame("Merge sort")
frame.contentPane = ChartPanel(chart).apply {
fillZoomRectangle = true
isMouseWheelEnabled = true
preferredSize = Dimension(WIDTH, HEIGHT)
}
frame.pack()
frame.isVisible = true
}
}
| kotlin | 20 | 0.626528 | 118 | 30.952381 | 105 | starcoderdata |
<reponame>osmar-jr/orange-talents-07-template-pix-keymanager-grpc<filename>src/main/kotlin/br/com/zup/osmarjunior/clients/ErpItauClient.kt
package br.com.zup.osmarjunior.clients
import br.com.zup.osmarjunior.clients.response.DadosDaContaResponse
import br.com.zup.osmarjunior.clients.response.DadosDoTitularResponse
import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.PathVariable
import io.micronaut.http.annotation.QueryValue
import io.micronaut.http.client.annotation.Client
@Client(value = "\${erp_itau.host}")
interface ErpItauClient {
@Get(value = "/api/v1/clientes/{clienteId}/contas{?tipo}")
fun consultaClientePorTipoDeConta(@PathVariable("clienteId") clienteId: String, @QueryValue tipo: String): HttpResponse<DadosDaContaResponse>
@Get(value = "/api/v1/clientes/{clienteId}")
fun consultaPorClienteId(@PathVariable("clienteId") clienteId: String): HttpResponse<DadosDoTitularResponse>
} | kotlin | 12 | 0.809184 | 145 | 45.714286 | 21 | starcoderdata |
package com.idex.ui.components
import androidx.compose.foundation.Indication
import androidx.compose.foundation.IndicationInstance
import androidx.compose.foundation.Interaction
import androidx.compose.foundation.InteractionState
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
val IdexIndication: @Composable () -> Indication = {
val color = AmbientContentColor.current
object : Indication {
override fun createInstance() = object : IndicationInstance {
override fun ContentDrawScope.drawIndication(interactionState: InteractionState) {
when(interactionState.value.first()) {
Interaction.Pressed -> drawRect(color.copy(alpha = .15f))
Interaction.Dragged -> drawRect(color.copy(alpha = .18f))
Interaction.Focused -> drawRect(color.copy(alpha = .05f))
// Interaction.Hovered -> drawRect(color.copy(alpha = .1f))
}
}
}
}
}
| kotlin | 24 | 0.766486 | 85 | 34.576923 | 26 | starcoderdata |
class A {
var a: String = "Fail"
{
a = object {
override fun toString(): String = "OK"
}.toString()
}
}
fun box() : String {
return A().a
} | kotlin | 17 | 0.443243 | 50 | 13.307692 | 13 | starcoderdata |
<filename>travako-core/travako-core-function/travako-core-function-processor/src/main/java/io/arkitik/travako/function/processor/Processor.kt
package io.arkitik.travako.function.processor
/**
* Created By [*<NAME> *](https://www.linkedin.com/in/iloom/)
* Created At 28 9:00 PM, **Tue, December 2021**
* Project *travako* [arkitik.io](https://arkitik.io)
*/
interface Processor<T : Any> {
val type: Class<T>
fun process()
}
| kotlin | 12 | 0.716247 | 141 | 35.416667 | 12 | starcoderdata |
<reponame>claraf3/androidx
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build.resources
import androidx.build.AndroidXPlugin.Companion.TASK_GROUP_API
import androidx.build.addToBuildOnServer
import androidx.build.addToCheckTask
import androidx.build.checkapi.ApiLocation
import androidx.build.checkapi.getRequiredCompatibilityApiLocation
import androidx.build.dependencyTracker.AffectedModuleDetector
import androidx.build.metalava.UpdateApiTask
import androidx.build.uptodatedness.cacheEvenIfNoOutputs
import org.gradle.api.Project
import java.util.Locale
object ResourceTasks {
private const val GENERATE_RESOURCE_API_TASK = "generateResourceApi"
private const val CHECK_RESOURCE_API_RELEASE_TASK = "checkResourceApiRelease"
private const val CHECK_RESOURCE_API_TASK = "checkResourceApi"
private const val UPDATE_RESOURCE_API_TASK = "updateResourceApi"
fun setupProject(
project: Project,
variantName: String,
builtApiLocation: ApiLocation,
outputApiLocations: List<ApiLocation>
) {
@OptIn(ExperimentalStdlibApi::class)
val packageResTask = project.tasks
.named(
"package${variantName.replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.US) else it.toString()
}}Resources"
)
@Suppress("UnstableApiUsage") // flatMap
val builtApiFile = packageResTask.flatMap { task ->
(task as com.android.build.gradle.tasks.MergeResources).publicFile
}
val outputApiFiles = outputApiLocations.map { location ->
location.resourceFile
}
val generateResourceApi = project.tasks.register(
GENERATE_RESOURCE_API_TASK,
GenerateResourceApiTask::class.java
) { task ->
task.group = "API"
task.description = "Generates resource API files from source"
task.builtApi.set(builtApiFile)
task.apiLocation.set(builtApiLocation)
AffectedModuleDetector.configureTaskGuard(task)
}
// Policy: If the artifact has previously been released, e.g. has a beta or later API file
// checked in, then we must verify "release compatibility" against the work-in-progress
// API file.
@Suppress("UnstableApiUsage") // flatMap
val checkResourceApiRelease = project.getRequiredCompatibilityApiLocation()?.let {
lastReleasedApiFile ->
project.tasks.register(
CHECK_RESOURCE_API_RELEASE_TASK,
CheckResourceApiReleaseTask::class.java
) { task ->
task.referenceApiFile.set(lastReleasedApiFile.resourceFile)
task.apiLocation.set(generateResourceApi.flatMap { it.apiLocation })
// Since apiLocation isn't a File, we have to manually set up the dependency.
task.dependsOn(generateResourceApi)
task.cacheEvenIfNoOutputs()
AffectedModuleDetector.configureTaskGuard(task)
}
}
// Policy: All changes to API surfaces for which compatibility is enforced must be
// explicitly confirmed by running the updateApi task. To enforce this, the implementation
// checks the "work-in-progress" built API file against the checked in current API file.
@Suppress("UnstableApiUsage") // flatMap
val checkResourceApi = project.tasks.register(
CHECK_RESOURCE_API_TASK,
CheckResourceApiTask::class.java
) { task ->
task.group = TASK_GROUP_API
task.description = "Checks that the resource API generated from source matches the " +
"checked in resource API file"
task.apiLocation.set(generateResourceApi.flatMap { it.apiLocation })
// Since apiLocation isn't a File, we have to manually set up the dependency.
task.dependsOn(generateResourceApi)
task.cacheEvenIfNoOutputs()
task.checkedInApiFiles.set(outputApiFiles)
checkResourceApiRelease?.let {
task.dependsOn(it)
}
AffectedModuleDetector.configureTaskGuard(task)
}
@Suppress("UnstableApiUsage") // flatMap
val updateResourceApi = project.tasks.register(
UPDATE_RESOURCE_API_TASK,
UpdateResourceApiTask::class.java
) { task ->
task.group = TASK_GROUP_API
task.description = "Updates the checked in resource API files to match source code API"
task.apiLocation.set(generateResourceApi.flatMap { it.apiLocation })
// Since apiLocation isn't a File, we have to manually set up the dependency.
task.dependsOn(generateResourceApi)
task.outputApiLocations.set(outputApiLocations)
task.forceUpdate.set(project.hasProperty("force"))
checkResourceApiRelease?.let {
// If a developer (accidentally) makes a non-backwards compatible change to an
// API, the developer will want to be informed of it as soon as possible.
// So, whenever a developer updates an API, if backwards compatibility checks are
// enabled in the library, then we want to check that the changes are backwards
// compatible
task.dependsOn(it)
}
AffectedModuleDetector.configureTaskGuard(task)
}
// Ensure that this task runs as part of "updateApi" task from MetalavaTasks.
project.tasks.withType(UpdateApiTask::class.java).configureEach { task ->
task.dependsOn(updateResourceApi)
}
project.addToCheckTask(checkResourceApi)
project.addToBuildOnServer(checkResourceApi)
}
}
| kotlin | 28 | 0.664954 | 99 | 44.232394 | 142 | starcoderdata |
<filename>src/main/kotlin/no/nav/helse/common/Datetime.kt<gh_stars>1-10
package no.nav.helse.common
import java.time.LocalDate
import java.time.YearMonth
import java.time.ZoneOffset
import java.util.*
import javax.xml.datatype.DatatypeConstants
import javax.xml.datatype.DatatypeFactory
import javax.xml.datatype.XMLGregorianCalendar
private val datatypeFactory = DatatypeFactory.newInstance()
fun XMLGregorianCalendar.toLocalDate() = LocalDate.of(year, month, if (day == DatatypeConstants.FIELD_UNDEFINED) 1 else day)
fun LocalDate.toXmlGregorianCalendar() = this.let {
val gcal = GregorianCalendar.from(this.atStartOfDay(ZoneOffset.UTC))
datatypeFactory.newXMLGregorianCalendar(gcal)
}
fun YearMonth.toXmlGregorianCalendar() = atDay(1).toXmlGregorianCalendar()
| kotlin | 19 | 0.815722 | 124 | 35.952381 | 21 | starcoderdata |
<filename>app/src/main/kotlin/com/kazakago/cueue/model/WorkspaceType.kt
package com.kazakago.cueue.model
import com.kazakago.cueue.mapper.rawValue
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
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
@Serializable(with = WorkspaceType.Serializer::class)
enum class WorkspaceType {
Personal;
companion object {
fun resolve(value: String): WorkspaceType {
return values().first { it.rawValue() == value }
}
}
object Serializer : KSerializer<WorkspaceType> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("workspace_type", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: WorkspaceType) {
encoder.encodeString(value.rawValue())
}
override fun deserialize(decoder: Decoder): WorkspaceType {
val rawValue = decoder.decodeString()
return values().first { it.rawValue() == rawValue }
}
}
}
| kotlin | 18 | 0.739889 | 117 | 34.027778 | 36 | starcoderdata |
<reponame>rohankumardubey/kotlin<gh_stars>1-10
fun foo(result: String = "OK") = result
fun box(): String = ::foo.callBy(mapOf())
| kotlin | 10 | 0.7 | 46 | 31.5 | 4 | starcoderdata |
<filename>sample/src/main/java/com/esafirm/sample/screen/SimpleTextScreen.kt<gh_stars>1-10
package com.esafirm.sample.screen
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.support.annotation.AttrRes
import android.widget.TextView
import com.bluelinelabs.conductor.RouterTransaction
import com.esafirm.sample.R
import nolambda.screen.Screen
import nolambda.screen.ScreenViewProvider
import java.util.*
class SimpleTextScreen : Screen() {
private val random = Random()
override fun createView(): ScreenViewProvider = { _, group -> TextView(group.context) }
override fun render() {
val text = view as TextView
text.textSize = 22f
text.text = "${random.nextInt(10)} - $random"
text.background = activity.attrDrawable(R.attr.selectableItemBackground)
text.setOnClickListener {
router.pushController(RouterTransaction.with(SimpleTextScreen()))
}
}
fun Context?.attrDrawable(@AttrRes attr: Int): Drawable {
this?.let {
val attrs = intArrayOf(attr)
val typedArray = it.obtainStyledAttributes(attrs)
val drawable = typedArray.getDrawable(0)
typedArray.recycle()
return drawable
}
return ColorDrawable()
}
}
| kotlin | 28 | 0.703676 | 91 | 32.170732 | 41 | starcoderdata |
<reponame>mchllngr/design-patterns<gh_stars>1-10
/* Description
*
* The interpreter pattern is used to
* define the grammar for instructions
* that form part of a language or
* notation, whilst allowing the
* grammar to be easily extended.
*/
/* Context */
class IntegerContext(private var data: MutableMap<Char, Int> = mutableMapOf()) {
fun lookup(name: Char) = data[name]!!
fun assign(expression: IntegerVariableExpression, value: Int) {
data[expression.name] = value
}
}
/* AbstractExpression */
interface IntegerExpression {
fun evaluate(context: IntegerContext): Int
}
/* TerminalExpression */
class IntegerVariableExpression(val name: Char) : IntegerExpression {
override fun evaluate(context: IntegerContext) = context.lookup(name)
}
/* NonterminalExpressionA */
class AddExpression(private var operand1: IntegerExpression, private var operand2: IntegerExpression) : IntegerExpression {
override fun evaluate(context: IntegerContext) = operand1.evaluate(context) + operand2.evaluate(context)
}
/* NonterminalExpressionB */
class SubstractExpression(private var operand1: IntegerExpression, private var operand2: IntegerExpression) : IntegerExpression {
override fun evaluate(context: IntegerContext) = operand1.evaluate(context) - operand2.evaluate(context)
}
/* Kotlin Syntax Sugar - see 'expressionKt' below */
operator fun IntegerExpression.plus(other: IntegerExpression) = AddExpression(this, other)
operator fun IntegerExpression.minus(other: IntegerExpression) = SubstractExpression(this, other)
/* Usage */
fun main() {
val context = IntegerContext()
val a = IntegerVariableExpression('a')
val b = IntegerVariableExpression('b')
val c = IntegerVariableExpression('c')
context.assign(a, 15)
context.assign(b, 5)
context.assign(c, 10)
// a + (b - c)
val expression = AddExpression(a, SubstractExpression(b, c))
val expressionKt = a + (b - c)
println("Expression: ${expression.evaluate(context)}")
println("ExpressionKt: ${expressionKt.evaluate(context)}")
}
/* Output
*
* Expression: 10
* ExpressionKt: 10
*/
| kotlin | 14 | 0.729616 | 129 | 28.232877 | 73 | starcoderdata |
import com.raccoon.backend.arithmetic.ExpressionEvaluator
import com.raccoon.backend.arithmetic.UnexpectedTokenException
import com.raccoon.backend.arithmetic.internal.SimpleParser
import com.raccoon.backend.arithmetic.internal.SimpleStackMachine
import java.lang.IllegalArgumentException
import kotlin.math.abs
import kotlin.math.absoluteValue
import kotlin.test.*
class SimpleEvaluatorTest {
private fun assertEvaluate(input: String, expected: Double, epsilon: Double = 0.0) {
check(epsilon >= 0)
val actual = ExpressionEvaluator.simpleEvaluator().evaluate(input)
val message = """
For input: $input.
Expected :$expected
Actual :$actual
Epsilon :$epsilon
""".trimIndent()
when {
expected.isInfinite() -> assertEquals(expected, actual)
expected.isNaN() -> assertTrue(actual.isNaN(), message)
else -> assertTrue(abs(expected - actual) <= epsilon, message)
}
}
@Test
fun `Smoke test`() {
val expressions = listOf(
"2+3" to 5.0,
"2+2*2" to 6.0,
"25/5" to 5.0,
"-1+2" to 1.0,
"0*1000" to 0.0,
"2-1" to 1.0,
"(2+2)*2" to 8.0,
"++1--2" to 3.0,
"4.2 * 4" to 16.8,
"2 / 8" to 0.25,
"2 * -(2 + 2)" to -8.0,
"25 % 2" to 1.0
)
expressions.forEach { (input, expected) ->
assertEvaluate(input, expected)
}
}
@Test
fun `Parser can be reused`() {
val stackMachine = SimpleStackMachine()
val parser = SimpleParser(stackMachine = stackMachine)
assertEquals(4.0, parser.parse("2+2"))
assertFailsWith<IndexOutOfBoundsException> { stackMachine.dPop() }
stackMachine.dPush(1.0)
assertEquals(6.0, parser.parse("2+2*2"))
assertFailsWith<IndexOutOfBoundsException> { stackMachine.dPop() }
}
@Test
fun `Parser throws correct exceptions`() {
val inputs = listOf(
"10 11" to 3,
"5*/10" to 2,
")10(" to 0,
"()" to 1,
"(42" to 3,
"2*2)" to 3
)
inputs.forEach { (input, expectedOffset) ->
assertFailsWith<UnexpectedTokenException>("Input: ${input}") {
ExpressionEvaluator.simpleEvaluator().evaluate(input)
}.also {
assertEquals(input, it.expression, "Input: ${input}")
assertEquals(expectedOffset, it.offset, "Input: ${input}")
}
}
}
@Test
fun `Evaluator supports border cases`() {
// Division by 0 -> Inf (with a correct sign).
assertEvaluate("42/0.0", Double.POSITIVE_INFINITY)
assertEvaluate("42/+0.0", Double.POSITIVE_INFINITY)
assertEvaluate("42/-0.0", Double.NEGATIVE_INFINITY)
assertEvaluate("-42/0.0", Double.NEGATIVE_INFINITY)
assertEvaluate("-42/-0.0", Double.POSITIVE_INFINITY)
assertEvaluate("-(42/+0.0)", Double.NEGATIVE_INFINITY)
assertEvaluate("-(42/-0.0)", Double.POSITIVE_INFINITY)
// 0 / 0 -> NaN.
val evaluator = ExpressionEvaluator.simpleEvaluator()
assertTrue(evaluator.evaluate("0 / 0").isNaN())
assertTrue(evaluator.evaluate("0 / -0").isNaN())
assertTrue(evaluator.evaluate("-0 / 0").isNaN())
assertTrue(evaluator.evaluate("-0 / -0").isNaN())
// 0 % x -> 0.
assertEvaluate("0 % 42", 0.0)
assertEvaluate("-0 % 42", -0.0)
// x % 0 -> NaN.
assertTrue(evaluator.evaluate("42 % 0").isNaN())
assertTrue(evaluator.evaluate("42 % -0").isNaN())
}
@Test
fun `Evaluator supports all actions with different numbers`() {
val inputs = listOf(
// Zero.
"42+0" to 42.0,
"42-0" to 42.0,
"42*0" to 0.0,
"0/42" to 0.0,
"42*-0.0" to -0.0,
// Positive integer numbers.
"42+2" to 44.0,
"42-2" to 40.0,
"40/4" to 10.0,
"10*4" to 40.0,
"41%3" to 2.0,
// Negative integer numbers.
"-42+(-2)" to -44.0,
"-42-(-2)" to -40.0,
"-40/(-4)" to 10.0,
"-10*(-4)" to 40.0,
"-41%(-3)" to -2.0,
"-2+42" to 40.0,
"2-42" to -40.0,
"-40/4" to -10.0,
"-10*4" to -40.0,
"-41%3" to -2.0,
"41%-3" to 2.0,
// Positive real numbers.
"42.5+2.25" to 44.75,
"42.5-2.25" to 40.25,
"40.5/2.5" to 16.2,
"10.5*4.5" to 47.25,
"11.5%1.5" to 1.0,
// Negative real numbers.
"-42.5+(-2.25)" to -44.75,
"-42.5-(-2.25)" to -40.25,
"-40.5/(-2.5)" to 16.2,
"-10.5*(-4.5)" to 47.25,
"-11.5%(-1.5)" to -1.0,
"-2.25+42.5" to 40.25,
"2.25-42.5" to -40.25,
"-40.5/2.5" to -16.2,
"-10.5*4.5 " to -47.25,
"-11.5%1.5" to -1.0,
// Positive big numbers.
"25e12+1e13" to 3.5e13,
"1e13-2e12" to 8e12,
"2e3*3e2" to 6e5,
"8e10/4e2" to 2e8,
"8e10%3e10" to 2e10,
// Negative big numbers.
"-25e12+(-1e13)" to -3.5e13,
"-1e13-(-2e12)" to -8e12,
"-2e3*(-3e2)" to 6e5,
"-8e10/(-4e2)" to 2e8,
"-8e10%(-3e10)" to -2e10,
"-10e12+1.5e13" to 5e12,
"10e12-1.5e13" to -5e12,
"-2e3*3e2" to -6e5,
"-8e10/4e2" to -2e8,
"-8e10%3e10" to -2e10,
// Positive small numbers.
"1e-12+25e-13" to 3.5e-12,
"3e-12-20e-13" to 10e-13,
"2e-3*3e-2" to 6e-5,
"8e-10/4e-2" to 2e-8,
"8e-10%3e-10" to 2e-10,
// Negative small numbers.
"-1e-12+(-25e-13)" to -3.5e-12,
"-3e-12-(-20e-13)" to -10e-13,
"-2e-3*(-3e-2)" to 6e-5,
"-8e-10/(-4e-2)" to 2e-8,
"-8e-10%(-3e-10)" to -2e-10,
"-1e-12+3e-12" to 2e-12,
"1e-12-3e-12" to -2e-12,
"-2e-3*3e-2" to -6e-5,
"-8e-10/4e-2" to -2e-8,
"-8e-10%3e-10" to -2e-10
)
inputs.forEach { (input, expected) ->
assertEvaluate(input, expected, expected.absoluteValue * EPSILON_FACTOR)
}
}
@Test
fun `Evaluator support correct operator priority`() {
val inputs = listOf(
"1+2*3" to 7.0,
"1+8/2" to 5.0,
"9-2*3" to 3.0,
"9-8/2" to 5.0,
"2+5%2" to 3.0,
"(1+2)*3" to 9.0,
"(1+8)/2" to 4.5,
"(9-2)*3" to 21.0,
"(9-8)/2" to 0.5,
"(2+5)%2" to 1.0,
"((1+2))*3" to 9.0,
"((1+8))/2" to 4.5,
"((9-2))*3" to 21.0,
"((9-8))/2" to 0.5,
"((2+5))%2" to 1.0,
"2*((1+2)*3+1)" to 20.0,
"22/((1+8)/2+1)" to 4.0
)
inputs.forEach { (input, expected) ->
assertEvaluate(input, expected, expected.absoluteValue * EPSILON_FACTOR)
}
}
@Test
fun `Simple stack machine reallocates storage for stack if needed`() {
assertFailsWith<IllegalArgumentException> { SimpleStackMachine(0) }
assertFailsWith<IllegalArgumentException> { SimpleStackMachine(-1) }
with(SimpleStackMachine(1)) {
dPush(2.0)
dPush(2.0)
dAdd()
assertEquals(4.0, dPop())
}
}
companion object {
const val EPSILON_FACTOR = 0.000001
}
}
| kotlin | 23 | 0.470551 | 88 | 30.955285 | 246 | starcoderdata |
<reponame>echolocation19/marvel-app
package com.example.marveltestapp.data.network
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ApiFactory {
private const val BASE_URL = "https://gateway.marvel.com"
private val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build()
val apiService: ApiService = retrofit.create(ApiService::class.java) ?: throw RuntimeException("ApiService == null")
} | kotlin | 15 | 0.74856 | 120 | 29.705882 | 17 | starcoderdata |
<reponame>iambaljeet/ComposeCookBook
package com.guru.composecookbook.ui.pullrefreshdemos
import androidx.compose.animation.animate
import androidx.compose.animation.animatedFloat
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.repeatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumnFor
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.RotateRight
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.drawLayer
import androidx.compose.ui.gesture.scrollorientationlocking.Orientation
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.guru.composecookbook.ui.demoui.spotify.data.SpotifyDataProvider
import com.guru.composecookbook.ui.demoui.spotify.details.SpotifySongListItem
@Composable
fun PullRefreshList(onPullRefresh: () -> Unit) {
val albums = SpotifyDataProvider.albums
val initialYTranslate = -100f
val maximumYTranslate = 200f
val animatedProgress = animatedFloat(initVal = initialYTranslate)
val lazyListState = rememberLazyListState()
val draggableModifier = Modifier.draggable(
orientation = Orientation.Vertical,
reverseDirection = false,
enabled = lazyListState.firstVisibleItemIndex < 2,
onDrag = {
onPullRefresh.invoke()
if (animatedProgress.value < maximumYTranslate) {
animatedProgress.animateTo(
targetValue = maximumYTranslate,
anim = tween(durationMillis = 1200, easing = LinearEasing),
)
}
},
onDragStopped = {
animatedProgress.animateTo(
targetValue = 3000f,
anim = repeatable(
iterations = 1,
animation = tween(durationMillis = 3000, easing = LinearEasing),
),
onEnd = { _, _ ->
animatedProgress.animateTo(
targetValue = initialYTranslate,
anim = tween(durationMillis = 300, easing = LinearEasing),
)
}
)
}
)
Box(modifier = draggableModifier) {
LazyColumnFor(
items = albums,
state = lazyListState,
) {
SpotifySongListItem(album = it)
}
//Animated Icon
Icon(
imageVector = Icons.Default.RotateRight,
tint = Color.Black,
modifier = Modifier.align(Alignment.TopCenter)
.drawLayer(
translationY = animate(
animatedProgress.value.coerceIn(
initialYTranslate,
maximumYTranslate
)
),
rotationZ = animate(
animatedProgress.value
)
).background(Color.LightGray, shape = CircleShape).padding(2.dp)
)
}
}
| kotlin | 30 | 0.639172 | 84 | 36.935484 | 93 | starcoderdata |
package com.tabesto.printer.model.error
import android.os.Parcelable
import com.tabesto.printer.utils.Constants.PRINTER_UNKNOWN_ACTION
import com.tabesto.printer.utils.Constants.PRINTER_UNKNOWN_CODE
import kotlinx.android.parcel.Parcelize
@Parcelize
open class PrinterException(
override val message: String,
val printerCode: String = PRINTER_UNKNOWN_CODE,
val action: String = PRINTER_UNKNOWN_ACTION
) : Parcelable,
Exception() {
constructor (printerExceptionBuilder: PrinterExceptionBuilder) : this(
printerExceptionBuilder.message,
printerExceptionBuilder.printerCode,
printerExceptionBuilder.action
)
class PrinterExceptionBuilder {
var message: String = ""
private set
var printerCode: String = PRINTER_UNKNOWN_CODE
private set
var action: String = PRINTER_UNKNOWN_ACTION
private set
@Suppress("unused")
fun reset() {
this.message = ""
this.printerCode = PRINTER_UNKNOWN_CODE
this.action = PRINTER_UNKNOWN_ACTION
}
fun withPrinterError(
printerError: PrinterError = PrinterError.ERR_UNKNOWN,
errorMessage: String? = null
): PrinterExceptionBuilder {
if (errorMessage != null) {
this.message = errorMessage
} else {
this.message = printerError.message
}
this.printerCode = printerError.eposException.codeString
this.action = printerError.action
return this
}
fun withMessage(message: String): PrinterExceptionBuilder {
this.message = message
return this
}
fun withCode(printerCode: String): PrinterExceptionBuilder {
this.printerCode = printerCode
return this
}
fun withAction(action: String): PrinterExceptionBuilder {
this.action = action
return this
}
fun build(): PrinterException {
return PrinterException(this)
}
}
}
| kotlin | 14 | 0.622338 | 74 | 29.185714 | 70 | starcoderdata |
<gh_stars>1-10
package slatekit.tools.docs
data class Doc(
val name : String,
val proj : String,
val source : String,
val version : String,
val example : String,
val available: Boolean,
val multi : Boolean,
val readme : Boolean,
val group : String,
val folder : String,
val jar : String,
val depends : String,
val desc : String
)
{
fun namespace():String {
//"slate.common.args.Args"
return source.substring(0, source.lastIndexOf("."))
}
fun sourceFolder(files:DocFiles):String
{
//"slate.common.args.Args"
val path = namespace().replace(".", "/")
val proj = path.split('/')[0]
val nsfolder = path.split('/').last()
// Adjust for file in root namespace ( e.g. slatekit.common.Result.kt )
val finalNSFolder = if(nsfolder.endsWith("common")) "" else nsfolder
val sourceFolderPath = "src/lib/${files.lang}/${proj}/" + files.buildSourceFolder(proj, finalNSFolder)
return sourceFolderPath
}
fun dependsOn():String {
var items = ""
val tokens = depends.split(',')
tokens.forEach { token ->
when(token) {
"com" -> items += " slatekit.common.jar"
"ent" -> items += " slatekit.entities.jar"
"core" -> items += " slatekit.core.jar"
"cloud" -> items += " slatekit.cloud.jar"
"ext" -> items += " slatekit.ext.jar"
"tools" -> items += " slatekit.tools.jar"
else -> {}
}
}
return items
}
fun layout():String {
return when (group) {
"infra" -> "_mods_infra"
"feat" -> "_mods_fea"
"utils" -> "_mods_utils"
else -> "_mods_utils"
}
}
} | kotlin | 16 | 0.502893 | 110 | 27.38806 | 67 | starcoderdata |
package script.base
import com.slack.api.bolt.App
import com.slack.api.bolt.handler.builtin.BlockActionHandler
import com.slack.api.model.event.AppHomeOpenedEvent
import com.slack.api.model.event.MessageEvent
import model.blockaction.BlockActionId
import model.script.ScriptId
import model.user.UserId
import repository.admin.AdminRepository
import script.home.HomeScript
import util.slack.context.getUser
import util.slack.user.isBotAdmin
class ScriptHandler(
private val adminRepo: AdminRepository
) {
private val scripts = mutableMapOf<ScriptId, Script>()
private var registered = false
fun addScript(script: Script) {
if (registered) throw IllegalStateException("already registered")
if (script.id.id.isBlank()) throw IllegalStateException("a ScriptId must not be blank")
if (script.id in scripts) throw IllegalStateException("a Script with the id '${script.id}' was already added")
scripts += script.id to script
}
fun registerScripts(app: App) {
if (registered) throw IllegalStateException("already registered")
registered = true
app.apply {
registerAppHomeOpenedScripts()
registerMessageScripts()
registerBlockActionScripts()
}
scripts.values.forEach { script ->
adminRepo.insertScript(script.id)
}
}
fun getScriptIds() = scripts.keys.toSet()
private fun App.registerAppHomeOpenedScripts() {
val appHomeOpenedScripts = scripts.values.filterIsInstance<AppHomeOpenedScript>()
event(AppHomeOpenedEvent::class.java) { event, ctx ->
// #13 find some other way to always show admins the home-tab in a more general concept
val userIsBotAdmin = ctx.getUser(UserId(event.event.user)).isBotAdmin
if (!userIsBotAdmin && !adminRepo.isBotEnabled()) return@event ctx.ack()
appHomeOpenedScripts
.filter { it.id == HomeScript.ID && userIsBotAdmin || adminRepo.isScriptEnabled(it.id) } // #14 improve performance when checking if scripts are enabled
.forEach { it.onAppHomeOpenedEvent(event, ctx) }
ctx.ack()
}
}
private fun App.registerMessageScripts() {
val messageScripts = scripts.values.filterIsInstance<MessageScript>()
event(MessageEvent::class.java) { event, ctx ->
if (!adminRepo.isBotEnabled()) return@event ctx.ack()
messageScripts
.filter { adminRepo.isScriptEnabled(it.id) } // #14 improve performance when checking if scripts are enabled
.forEach { it.onMessageEvent(event, ctx) }
ctx.ack()
}
}
private fun App.registerBlockActionScripts() {
val blockActionScripts = scripts.values.filterIsInstance<BlockActionScript>()
val blockActionIdToScript = blockActionScripts.toMapOfBlockActionIdToScripts()
blockActionIdToScript
.forEach { (blockActionId, scripts) ->
when (blockActionId) {
is BlockActionId.User -> registerUserBlockActionScripts(blockActionId, scripts)
is BlockActionId.Admin -> registerAdminBlockActionScripts(blockActionId, scripts)
}
}
}
private fun List<BlockActionScript>.toMapOfBlockActionIdToScripts(): Map<BlockActionId, List<BlockActionScript>> {
val blockActionIdToScript = mutableMapOf<BlockActionId, MutableList<BlockActionScript>>()
forEach { script ->
script.blockActionIds.forEach { id ->
val scriptsForId = blockActionIdToScript[id]
if (scriptsForId == null) blockActionIdToScript[id] = mutableListOf(script)
else scriptsForId += script
}
}
return blockActionIdToScript
}
private fun App.registerUserBlockActionScripts(
blockActionId: BlockActionId.User,
scripts: List<BlockActionScript>
) {
val handler = BlockActionHandler { request, ctx ->
if (!adminRepo.isBotEnabled()) return@BlockActionHandler ctx.ack()
scripts
.filter { adminRepo.isScriptEnabled(it.id) } // #14 improve performance when checking if scripts are enabled
.forEach { it.onBlockActionEvent(blockActionId, request, ctx) }
ctx.ack()
}
when (blockActionId) {
is BlockActionId.User.Str -> blockAction(blockActionId.id, handler)
is BlockActionId.User.Regex -> blockAction(blockActionId.idRegex.toPattern(), handler)
}
}
private fun App.registerAdminBlockActionScripts(
blockActionId: BlockActionId.Admin,
scripts: List<BlockActionScript>
) {
val handler = BlockActionHandler { request, ctx ->
if (!ctx.getUser(request).isBotAdmin) return@BlockActionHandler ctx.ack()
scripts.forEach { it.onBlockActionEvent(blockActionId, request, ctx) }
ctx.ack()
}
when (blockActionId) {
is BlockActionId.Admin.Str -> blockAction(blockActionId.id, handler)
is BlockActionId.Admin.Regex -> blockAction(blockActionId.idRegex.toPattern(), handler)
}
}
companion object {
fun create(adminRepo: AdminRepository) = ScriptHandler(adminRepo)
}
}
| kotlin | 25 | 0.65896 | 168 | 35.482993 | 147 | starcoderdata |
package io.collective.start.analyzer
import io.collective.workflow.WorkScheduler
import io.ktor.application.Application
import io.ktor.application.call
import io.ktor.application.install
import io.ktor.features.CallLogging
import io.ktor.features.DefaultHeaders
import io.ktor.http.ContentType
import io.ktor.response.respondText
import io.ktor.routing.Routing
import io.ktor.routing.get
import io.ktor.server.engine.embeddedServer
import io.ktor.server.jetty.Jetty
import java.util.*
fun Application.module() {
install(DefaultHeaders)
install(CallLogging)
install(Routing) {
get("/") {
call.respondText("hi!", ContentType.Text.Html)
}
}
val scheduler = WorkScheduler<ExampleTask>(ExampleWorkFinder(), mutableListOf(ExampleWorker()), 30)
scheduler.start()
}
fun main(args: Array<String>) {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"))
val port = System.getenv("PORT")?.toInt() ?: 8080
embeddedServer(Jetty, port, watchPaths = listOf("data-analyzer-server"), module = Application::module).start()
} | kotlin | 21 | 0.747428 | 114 | 30.470588 | 34 | starcoderdata |
<gh_stars>1-10
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath(kotlin("gradle-plugin", Version.kotlinVersion))
classpath("com.android.tools.build:gradle:4.0.2")
}
}
allprojects {
repositories {
google()
jcenter()
}
}
tasks.register("clean").configure {
delete("build")
} | kotlin | 21 | 0.577128 | 65 | 15.391304 | 23 | starcoderdata |
<gh_stars>1-10
package org.simple.clinic.settings
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import java.util.Locale
sealed class Language : Parcelable
@Parcelize
data class ProvidedLanguage(val displayName: String, val languageCode: String) : Language() {
fun matchesLocale(locale: Locale): Boolean {
val languageTag = locale.toLanguageTag()
return languageCode.equals(languageTag, ignoreCase = true)
}
fun toLocale(): Locale {
return Locale.forLanguageTag(languageCode)
}
}
@Parcelize
object SystemDefaultLanguage : Language()
| kotlin | 12 | 0.769759 | 93 | 22.28 | 25 | starcoderdata |
<reponame>woshiyezu/color-copy-camera
package jp.millennium.ncl.colorcopycamera.model
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = arrayOf(RgbColor::class), version = 1)
abstract class RgbColorDataBase: RoomDatabase() {
abstract fun rgbColorDao():RgbColorDao
companion object {
@Volatile private var instance:RgbColorDataBase? = null
private val LOCK = Any()
operator fun invoke(context: Context) = instance ?: synchronized(LOCK){
instance?: buildDataBase(context).also {
instance = it
}
}
private fun buildDataBase(context: Context) = Room.databaseBuilder(context.applicationContext,RgbColorDataBase::class.java,"rgbcolordatabase").build()
}
} | kotlin | 21 | 0.713095 | 158 | 30.148148 | 27 | starcoderdata |