path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/openfoodfacts/github/scrachx/openfood/utils/RxEx.kt
oona988
333,890,968
false
null
package openfoodfacts.github.scrachx.openfood.utils import android.util.Log import androidx.lifecycle.LifecycleOwner import io.reactivex.Observable fun <T> Observable<T>.subscribeLifecycle(lifecycleOwner: LifecycleOwner, observer: (T) -> Unit) { RxLifecycleHandler(lifecycleOwner, this, observer) } /** * Logs all lifecycle events of the [io.reactivex.Observable]. * Should NOT be used in code at all, only for temporary debugging purposes. */ fun <T> Observable<T>.log(streamName: String, message: String? = null): Observable<T> { val msg = if (message == null) "" else " $message" return this .doOnNext { Log.d(streamName, "$msg: $it") } .doOnError { Log.w(streamName, "$msg [Error]: $it: ${it.message}") } .doOnComplete { Log.w(streamName, "$msg [Complete]") } .doOnSubscribe { Log.w(streamName, "$msg [Subscribed]") } .doOnDispose { Log.w(streamName, "$msg [Disposed]") } }
1
null
1
1
5dd057b1c5668c22016c254de3396a430bca5ee6
1,098
openfoodfacts-androidapp
Apache License 2.0
app/src/main/java/org/simple/clinic/settings/AppVersionFetcher.kt
simpledotorg
132,515,649
false
{"Kotlin": 6129044, "Shell": 1660, "HTML": 545}
package org.simple.clinic.settings import android.content.pm.PackageInfo import android.os.Build import javax.inject.Inject class AppVersionFetcher @Inject constructor( private val packageInfo: PackageInfo ) { fun appVersion(): String { return packageInfo.versionName } fun appVersionCode(): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { packageInfo.longVersionCode.toInt() } else { packageInfo.versionCode } } }
13
Kotlin
73
236
ff699800fbe1bea2ed0492df484777e583c53714
478
simple-android
MIT License
Lesson05a-Android-Lifecycle/T05a.03-Exercise-FixLifecycleDisplayBug/app/src/main/java/com/example/android/lifecycle/MainActivity.kt
Stropek
103,762,850
false
{"Python": 1, "Text": 7, "Markdown": 1, "Gradle": 420, "Java Properties": 270, "Shell": 134, "Ignore List": 256, "Batchfile": 134, "XML": 1476, "Java": 518, "Kotlin": 104, "Proguard": 30, "JSON": 219}
package com.example.android.lifecycle import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.View import android.widget.TextView class MainActivity : AppCompatActivity() { /* * This TextView will contain a running log of every lifecycle callback method called from this * Activity. This TextView can be reset to its default state by clicking the Button labeled * "Reset Log" */ private var mLifecycleDisplay: TextView? = null /** * Called when the activity is first created. This is where you should do all of your normal * static set up: create views, bind data to lists, etc. * * Always followed by onStart(). * * @param savedInstanceState The Activity's previously frozen state, if there was one. */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mLifecycleDisplay = findViewById(R.id.tv_lifecycle_events_display) as TextView /* * If savedInstanceState is not null, that means our Activity is not being started for the * first time. Even if the savedInstanceState is not null, it is smart to check if the * bundle contains the key we are looking for. In our case, the key we are looking for maps * to the contents of the TextView that displays our list of callbacks. If the bundle * contains that key, we set the contents of the TextView accordingly. */ if (savedInstanceState != null) { if (savedInstanceState.containsKey(LIFECYCLE_CALLBACKS_TEXT_KEY)) { val allPreviousLifecycleCallbacks = savedInstanceState .getString(LIFECYCLE_CALLBACKS_TEXT_KEY) mLifecycleDisplay!!.text = allPreviousLifecycleCallbacks } } for (callback in mLifecycleCallbacks){ mLifecycleDisplay?.append(callback) } mLifecycleCallbacks.clear() logAndAppend(ON_CREATE) } /** * Called when the activity is becoming visible to the user. * * Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes * hidden. */ override fun onStart() { super.onStart() logAndAppend(ON_START) } /** * Called when the activity will start interacting with the user. At this point your activity * is at the top of the activity stack, with user input going to it. * * Always followed by onPause(). */ override fun onResume() { super.onResume() logAndAppend(ON_RESUME) } /** * Called when the system is about to start resuming a previous activity. This is typically * used to commit unsaved changes to persistent data, stop animations and other things that may * be consuming CPU, etc. Implementations of this method must be very quick because the next * activity will not be resumed until this method returns. * * Followed by either onResume() if the activity returns back to the front, or onStop() if it * becomes invisible to the user. */ override fun onPause() { super.onPause() logAndAppend(ON_PAUSE) } /** * Called when the activity is no longer visible to the user, because another activity has been * resumed and is covering this one. This may happen either because a new activity is being * started, an existing one is being brought in front of this one, or this one is being * destroyed. * * Followed by either onRestart() if this activity is coming back to interact with the user, or * onDestroy() if this activity is going away. */ override fun onStop() { super.onStop() mLifecycleCallbacks.add(ON_STOP) logAndAppend(ON_STOP) } /** * Called after your activity has been stopped, prior to it being started again. * * Always followed by onStart() */ override fun onRestart() { super.onRestart() logAndAppend(ON_RESTART) } /** * The final call you receive before your activity is destroyed. This can happen either because * the activity is finishing (someone called finish() on it, or because the system is * temporarily destroying this instance of the activity to save space. You can distinguish * between these two scenarios with the isFinishing() method. */ override fun onDestroy() { super.onDestroy() mLifecycleCallbacks.add(ON_DESTROY) logAndAppend(ON_DESTROY) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) logAndAppend(ON_SAVE_INSTANCE_STATE) val lifecycleDisplayTextViewContents = mLifecycleDisplay!!.text.toString() outState.putString(LIFECYCLE_CALLBACKS_TEXT_KEY, lifecycleDisplayTextViewContents) } /** * Logs to the console and appends the lifecycle method name to the TextView so that you can * view the series of method callbacks that are called both from the app and from within * Android Studio's Logcat. * * @param lifecycleEvent The name of the event to be logged. */ private fun logAndAppend(lifecycleEvent: String) { Log.d(TAG, "Lifecycle Event: " + lifecycleEvent) mLifecycleDisplay!!.append(lifecycleEvent + "\n") } /** * This method resets the contents of the TextView to its default text of "Lifecycle callbacks" * * @param view The View that was clicked. In this case, it is the Button from our layout. */ fun resetLifecycleDisplay(view: View) { mLifecycleDisplay!!.text = "Lifecycle callbacks:\n" } companion object { private var mLifecycleCallbacks : ArrayList<String> = arrayListOf<String>() /* * This tag will be used for logging. It is best practice to use the class's name using * getSimpleName as that will greatly help to identify the location from which your logs are * being posted. */ private val TAG = MainActivity::class.java.simpleName /* * This constant String will be used to store the content of the TextView used to display the * list of callbacks. The reason we are storing the contents of the TextView is so that you can * see the entire set of callbacks as they are called. */ private val LIFECYCLE_CALLBACKS_TEXT_KEY = "callbacks" /* Constant values for the names of each respective lifecycle callback */ private val ON_CREATE = "onCreate" private val ON_START = "onStart" private val ON_RESUME = "onResume" private val ON_PAUSE = "onPause" private val ON_STOP = "onStop" private val ON_RESTART = "onRestart" private val ON_DESTROY = "onDestroy" private val ON_SAVE_INSTANCE_STATE = "onSaveInstanceState" } }
1
null
1
1
feb1e04f77f7e08306e163887ed67fbbbbc270f4
7,020
ud851-Exercises
Apache License 2.0
vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/ext/unit/TestSuite.kt
jo5ef
138,613,796
true
{"Maven POM": 7, "Ignore List": 1, "EditorConfig": 1, "Text": 1, "Markdown": 1, "JAR Manifest": 2, "Java": 198, "AsciiDoc": 66, "XML": 10, "Java Properties": 1, "Groovy": 14, "Ruby": 26, "Kotlin": 276, "JavaScript": 40, "FreeMarker": 1, "JSON": 1}
package io.vertx.kotlin.ext.unit import io.vertx.ext.unit.TestContext import io.vertx.ext.unit.TestSuite import io.vertx.kotlin.coroutines.awaitEvent suspend fun TestSuite.beforeAwait() : TestContext { return awaitEvent{ this.before(it) } } suspend fun TestSuite.beforeEachAwait() : TestContext { return awaitEvent{ this.beforeEach(it) } } suspend fun TestSuite.afterAwait() : TestContext { return awaitEvent{ this.after(it) } } suspend fun TestSuite.afterEachAwait() : TestContext { return awaitEvent{ this.afterEach(it) } } suspend fun TestSuite.testAwait(name : String) : TestContext { return awaitEvent{ this.test(name, it) } } suspend fun TestSuite.testAwait(name : String, repeat : Int) : TestContext { return awaitEvent{ this.test(name, repeat, it) } }
0
Java
0
0
15be5c0e93e68aa64e4daffe97d60580c081d1cc
864
vertx-stack-generation
Apache License 2.0
2020/fsSnmpAg/src/firestoreInterOp/FirestoreInterOp.kt
kyoya-p
253,926,918
false
{"Kotlin": 953042, "JavaScript": 86232, "HTML": 72159, "TypeScript": 56942, "Java": 30207, "C++": 29172, "CMake": 20891, "Dart": 14886, "Shell": 7841, "CSS": 6307, "Batchfile": 6227, "Dockerfile": 5012, "C": 3042, "Swift": 2246, "PowerShell": 234, "Objective-C": 78}
package firestoreInterOp import com.google.cloud.firestore.* import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.map import kotlinx.serialization.json.* inline fun Firestore.firestoreEventFlow(noinline query: Firestore.() -> DocumentReference) = channelFlow<DocumentSnapshot> { val listener = query().addSnapshotListener(object : EventListener<DocumentSnapshot?> { override fun onEvent(snapshot: DocumentSnapshot?, ex: FirestoreException?) { // ドキュメントRead/Update時ハンドラ if (ex == null && snapshot != null && snapshot.exists() && snapshot.data != null) offer(snapshot) else close() } }) awaitClose { listener.remove() } } inline fun <reified T : Any> Firestore.firestoreDocumentFlow(noinline query: Firestore.() -> DocumentReference) = firestoreEventFlow(query).map { snapshot -> Json { ignoreUnknownKeys = true }.decodeFromJsonElement<T>(snapshot.data!!.toJsonObject()) } fun Map<String, Any>.toJsonObject(): JsonObject = buildJsonObject { forEach { (k, v) -> when (v) { is Number -> put(k, v) is String -> put(k, v) is Boolean -> put(k, v) is Map<*, *> -> put(k, (v as Map<String, Any>).toJsonObject()) is List<*> -> put(k, (v as List<Any>).toJsonArray()) } } } fun List<Any>.toJsonArray(): JsonArray = buildJsonArray { forEach { v -> when (v) { is Number -> add(v) is String -> add(v) is Boolean -> add(v) is Map<*, *> -> add((v as Map<String, Any>).toJsonObject()) is List<*> -> add((v as List<Any>).toJsonArray()) } } }
16
Kotlin
1
2
37d1f1df3e512b968c3677239316130f21d4836f
1,724
samples
Apache License 2.0
sample-kotlin/src/main/kotlin/io/nrbtech/rxandroidble/samplekotlin/util/LocationPermission.kt
NRB-Tech
344,305,734
false
null
package io.nrbtech.rxandroidble.samplekotlin.util import android.app.Activity import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import io.nrbtech.rxandroidble.RxBleClient private const val REQUEST_PERMISSION_BLE_SCAN = 101 internal fun Activity.requestLocationPermission(client: RxBleClient) = ActivityCompat.requestPermissions( this, /* * the below would cause a ArrayIndexOutOfBoundsException on API < 23. Yet it should not be called then as runtime * permissions are not needed and RxBleClient.isScanRuntimePermissionGranted() returns `true` */ arrayOf(client.recommendedScanRuntimePermissions[0]), REQUEST_PERMISSION_BLE_SCAN ) internal fun isLocationPermissionGranted(requestCode: Int, grantResults: IntArray) = requestCode == REQUEST_PERMISSION_BLE_SCAN && grantResults[0] == PackageManager.PERMISSION_GRANTED
1
null
1
8
03aee7d68725de31b89cde8100038fce3de97098
922
RxAndroidBle
Apache License 2.0
core/commonMain/src/kotlinx/serialization/SealedSerializer.kt
Kotlin
97,827,246
false
{"Kotlin": 2262082, "Java": 1343}
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization import kotlinx.serialization.builtins.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* import kotlinx.serialization.internal.* import kotlinx.serialization.modules.* import kotlin.reflect.* /** * This class provides support for multiplatform polymorphic serialization of sealed classes. * * In contrary to [PolymorphicSerializer], all known subclasses with serializers must be passed * in `subclasses` and `subSerializers` constructor parameters. * If a subclass is a sealed class itself, all its subclasses are registered as well. * * If a sealed hierarchy is marked with [@Serializable][Serializable], an instance of this class is provided automatically. * In most of the cases, you won't need to perform any manual setup: * * ``` * @Serializable * sealed class SimpleSealed { * @Serializable * public data class SubSealedA(val s: String) : SimpleSealed() * * @Serializable * public data class SubSealedB(val i: Int) : SimpleSealed() * } * * // will perform correct polymorphic serialization and deserialization: * Json.encodeToString(SimpleSealed.serializer(), SubSealedA("foo")) * ``` * * However, it is possible to register additional subclasses using regular [SerializersModule]. * It is required when one of the subclasses is an abstract class itself: * * ``` * @Serializable * sealed class ProtocolWithAbstractClass { * @Serializable * abstract class Message : ProtocolWithAbstractClass() { * @Serializable * data class StringMessage(val description: String, val message: String) : Message() * * @Serializable * data class IntMessage(val description: String, val message: Int) : Message() * } * * @Serializable * data class ErrorMessage(val error: String) : ProtocolWithAbstractClass() * } * ``` * * In this case, `ErrorMessage` would be registered automatically by the plugin, * but `StringMessage` and `IntMessage` require manual registration, as described in [PolymorphicSerializer] documentation: * * ``` * val abstractContext = SerializersModule { * polymorphic(ProtocolWithAbstractClass::class) { * subclass(ProtocolWithAbstractClass.Message.IntMessage::class) * subclass(ProtocolWithAbstractClass.Message.StringMessage::class) * // no need to register ProtocolWithAbstractClass.ErrorMessage * } * } * ``` */ @InternalSerializationApi @OptIn(ExperimentalSerializationApi::class) public class SealedClassSerializer<T : Any>( serialName: String, override val baseClass: KClass<T>, subclasses: Array<KClass<out T>>, subclassSerializers: Array<KSerializer<out T>> ) : AbstractPolymorphicSerializer<T>() { /** * This constructor is needed to store serial info annotations defined on the sealed class. * Support for such annotations was added in Kotlin 1.5.30; previous plugins used primary constructor of this class * directly, therefore this constructor is secondary. * * This constructor can (and should) became primary when Require-Kotlin-Version is raised to at least 1.5.30 * to remove necessity to store annotations separately and calculate descriptor via `lazy {}`. * * When doing this change, also migrate secondary constructors from [PolymorphicSerializer] and [ObjectSerializer]. */ @PublishedApi internal constructor( serialName: String, baseClass: KClass<T>, subclasses: Array<KClass<out T>>, subclassSerializers: Array<KSerializer<out T>>, classAnnotations: Array<Annotation> ) : this(serialName, baseClass, subclasses, subclassSerializers) { this._annotations = classAnnotations.asList() } private var _annotations: List<Annotation> = emptyList() override val descriptor: SerialDescriptor by lazy(LazyThreadSafetyMode.PUBLICATION) { buildSerialDescriptor(serialName, PolymorphicKind.SEALED) { element("type", String.serializer().descriptor) val elementDescriptor = buildSerialDescriptor("kotlinx.serialization.Sealed<${baseClass.simpleName}>", SerialKind.CONTEXTUAL) { // serialName2Serializer is guaranteed to have no duplicates — checked in `init`. serialName2Serializer.forEach { (name, serializer) -> element(name, serializer.descriptor) } } element("value", elementDescriptor) annotations = _annotations } } private val class2Serializer: Map<KClass<out T>, KSerializer<out T>> private val serialName2Serializer: Map<String, KSerializer<out T>> init { if (subclasses.size != subclassSerializers.size) { throw IllegalArgumentException("All subclasses of sealed class ${baseClass.simpleName} should be marked @Serializable") } // Note: we do not check whether different serializers are provided if the same KClass duplicated in the `subclasses`. // Plugin should produce identical serializers, although they are not always strictly equal (e.g. new ObjectSerializer // may be created every time) class2Serializer = subclasses.zip(subclassSerializers).toMap() serialName2Serializer = class2Serializer.entries.groupingBy { it.value.descriptor.serialName } .aggregate<Map.Entry<KClass<out T>, KSerializer<out T>>, String, Map.Entry<KClass<*>, KSerializer<out T>>> { key, accumulator, element, _ -> if (accumulator != null) { error( "Multiple sealed subclasses of '$baseClass' have the same serial name '$key':" + " '${accumulator.key}', '${element.key}'" ) } element }.mapValues { it.value.value } } override fun findPolymorphicSerializerOrNull( decoder: CompositeDecoder, klassName: String? ): DeserializationStrategy<T>? { return serialName2Serializer[klassName] ?: super.findPolymorphicSerializerOrNull(decoder, klassName) } override fun findPolymorphicSerializerOrNull(encoder: Encoder, value: T): SerializationStrategy<T>? { return (class2Serializer[value::class] ?: super.findPolymorphicSerializerOrNull(encoder, value))?.cast() } }
407
Kotlin
621
5,396
d4d066d72a9f92f06c640be5a36a22f75d0d7659
6,540
kotlinx.serialization
Apache License 2.0
app/src/main/java/college/wyk/app/model/timetable/Timetable.kt
WYKCode
81,462,363
false
null
package college.wyk.app.model.timetable import java.util.* class Timetable { val entries = ArrayList<LinkedHashMap<Period, List<TimetableEntry>>>() fun append(day: LinkedHashMap<Period, List<TimetableEntry>>): Timetable { entries.add(day) return this } operator fun set(index: Int, day: LinkedHashMap<Period, List<TimetableEntry>>): Timetable { entries[index] = day return this } companion object { var current: Timetable? = null } } class Period(private val nameIn: String) { val name: String get() = nameIn.replace("-", "~") }
1
null
1
7
4205693ca71267b2d149380588bb94a334104435
612
WYK-Android
MIT License
agent/src/main/java/com/bytedance/applog/exposure/ViewExposureData.kt
volcengine
522,854,593
false
{"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "Markdown": 2, "INI": 5, "Proguard": 5, "XML": 21, "Kotlin": 32, "Java": 196}
// Copyright 2022 Beijing Volcano Engine Technology Ltd. All Rights Reserved. package com.bytedance.applog.exposure import org.json.JSONObject /** * * @author: [email protected] * @date: 2022/3/30 */ /** * View 曝光数据 * @param eventName 自定义曝光事件名称,默认为 "$bav2b_exposure" * @param properties 自定义事件的 params 参数 * @param config 自定义曝光的配置,只有当前 View 有效,全局配置可在 [com.bytedance.applog.InitConfig] 中配置 */ data class ViewExposureData<Config : IExposureConfig>( val eventName: String? = null, val properties: JSONObject? = null, var config: Config? = null ) interface IExposureConfig /** * 用于保存待检测 View 的相关信息 * @param data 曝光的相关数据 * @param viewExposureTriggerType 记录上次曝光状态 */ internal class ViewExposureHolder( val data: ViewExposureData<ViewExposureConfig>, var lastVisible: Boolean = false, var viewExposureTriggerType: ViewExposureTriggerType = ViewExposureTriggerType.NOT_EXPOSURE, var lastVisibleTime: Long = 0 ) { fun updateViewExposureTriggerTypeAndRestLastVisible(isFromBack: Boolean) { viewExposureTriggerType = if (viewExposureTriggerType != ViewExposureTriggerType.NOT_EXPOSURE) { if (isFromBack) { ViewExposureTriggerType.RESUME_FORM_BACK } else { ViewExposureTriggerType.RESUME_FORM_PAGE } } else { ViewExposureTriggerType.NOT_EXPOSURE } lastVisible = false lastVisibleTime = 0 } fun updateLastVisibleTime(isVisibleInViewport: Boolean) { lastVisibleTime = if (isVisibleInViewport) { if (lastVisibleTime == 0L) { System.currentTimeMillis() } else { lastVisibleTime } } else { 0 } } fun checkVisibleTime(data: ViewExposureData<ViewExposureConfig>): Boolean { return System.currentTimeMillis() - lastVisibleTime >= (data.config?.stayTriggerTime ?: 0) } } enum class ViewExposureTriggerType(val value: Int) { // 首次 EXPOSURE_ONCE(0), // 页面生命周期内多次曝光 EXPOSURE_MORE_THAN_ONCE(3), // 从其他页面返回 RESUME_FORM_PAGE(6), // 从后台返回 RESUME_FORM_BACK(7), // 未触发 NOT_EXPOSURE(-1); }
0
Java
4
3
4d23bdf04ff1508ca6cc6537a56e237af2c71c0c
2,260
datarangers-sdk-android
FSF All Permissive License
faker/tvshows/src/main/kotlin/io/github/serpro69/kfaker/tv/provider/Community.kt
serpro69
174,969,439
false
null
package io.github.serpro69.kfaker.tv.provider import io.github.serpro69.kfaker.FakerService import io.github.serpro69.kfaker.dictionary.YamlCategory import io.github.serpro69.kfaker.provider.FakeDataProvider import io.github.serpro69.kfaker.provider.YamlFakeDataProvider import io.github.serpro69.kfaker.provider.unique.LocalUniqueDataProvider import io.github.serpro69.kfaker.provider.unique.UniqueProviderDelegate /** * [FakeDataProvider] implementation for [YamlCategory.COMMUNITY] category. */ @Suppress("unused") class Community internal constructor(fakerService: FakerService) : YamlFakeDataProvider<Community>(fakerService) { override val yamlCategory = YamlCategory.COMMUNITY override val localUniqueDataProvider = LocalUniqueDataProvider<Community>() override val unique by UniqueProviderDelegate(localUniqueDataProvider, fakerService) init { fakerService.load(yamlCategory) } fun characters() = resolve("characters") fun quotes() = resolve("quotes") }
33
null
42
462
22b0f971c9f699045b30d913c6cbca02060ed9b3
1,004
kotlin-faker
MIT License
openrndr-jvm/openrndr-gl3/src/jvmMain/kotlin/org/openrndr/internal/gl3/IconLoader.kt
openrndr
122,222,767
false
null
package org.openrndr.internal.gl3 import org.lwjgl.BufferUtils import org.lwjgl.stb.STBImage import org.openrndr.resourceUrl import java.net.URL import java.nio.Buffer import java.nio.ByteBuffer internal fun loadIcon(url: String): ByteBuffer { val byteArray = URL(resourceUrl(url)).readBytes() val buffer = BufferUtils.createByteBuffer(byteArray.size) (buffer as Buffer).rewind() buffer.put(byteArray) (buffer as Buffer).rewind() val wa = IntArray(1) val ha = IntArray(1) val ca = IntArray(1) STBImage.stbi_set_flip_vertically_on_load(true) STBImage.stbi_set_unpremultiply_on_load(false) val data = STBImage.stbi_load_from_memory(buffer, wa, ha, ca, 4) return data!! }
21
null
73
880
2ef3c463ecb66701771dc0cf8fb3364e960a5e3c
722
openrndr
BSD 2-Clause FreeBSD License
mobile_app1/module364/src/main/java/module364packageKt0/Foo1779.kt
uber-common
294,831,672
false
null
package module364packageKt0; annotation class Foo1779Fancy @Foo1779Fancy class Foo1779 { fun foo0(){ module364packageKt0.Foo1778().foo6() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } fun foo4(){ foo3() } fun foo5(){ foo4() } fun foo6(){ foo5() } }
6
null
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
331
android-build-eval
Apache License 2.0
app/src/main/java/ir/rainyday/listexample/modules/layoumanager/LayoutManagerActivity.kt
MostafaTaghipour
119,284,187
false
null
package ir.rainyday.listexample.modules.layoumanager import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.xiaofeng.flowlayoutmanager.Alignment import com.xiaofeng.flowlayoutmanager.FlowLayoutManager import ir.rainyday.easylist.SpacingItemDecoration import ir.rainyday.listexample.R import kotlinx.android.synthetic.main.content_layout_manager.* import kotlinx.android.synthetic.main.layout_regular_appbar.* class LayoutManagerActivity : AppCompatActivity() { private lateinit var adapter: LayoutManagerAdapter private lateinit var layoutManager: RecyclerView.LayoutManager private var spacingItemDecoration: SpacingItemDecoration? = null private var sixteen: Int = 0 private var eight: Int = 0 private val viewModel: LayoutManagerViewModel by lazy { ViewModelProviders.of(this).get(LayoutManagerViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_layout_manager) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) sixteen = resources.getDimension(R.dimen.activity_margin).toInt() eight = resources.getDimension(R.dimen.activity_margin_half).toInt() adapter = LayoutManagerAdapter(this) main_recycler.adapter = adapter setRecyclerViewLayoutManager(LayoutType.Linear) viewModel.items.observe(this, Observer { list -> adapter.items = list }) } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_layout_manager, menu) menu?.findItem(R.id.linear)?.isChecked = true return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { var type = LayoutType.Linear when (item?.itemId) { R.id.linear -> { item.isChecked = true type = LayoutType.Linear } R.id.grid -> { item.isChecked = true type = LayoutType.Grid } R.id.staggered -> { item.isChecked = true type = LayoutType.Staggered } R.id.spanned -> { item.isChecked = true type = LayoutType.Spanned } R.id.flow -> { item.isChecked = true type = LayoutType.Flow } } setRecyclerViewLayoutManager(type) return super.onOptionsItemSelected(item) } private fun setRecyclerViewLayoutManager(layoutManagerType: LayoutType) { var scrollPosition = 0 // If a layout manager has already been set, get current scroll position. if (main_recycler.layoutManager != null) { scrollPosition = (main_recycler.layoutManager as? LinearLayoutManager) ?.findFirstCompletelyVisibleItemPosition() ?: 0 } if (spacingItemDecoration != null) { main_recycler.removeItemDecoration(spacingItemDecoration!!) spacingItemDecoration = null } layoutManager = when (layoutManagerType) { LayoutType.Linear -> { val linearLayoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false) spacingItemDecoration = SpacingItemDecoration(sixteen) main_recycler.addItemDecoration(spacingItemDecoration!!) main_recycler.setPadding(sixteen, sixteen, sixteen, sixteen) linearLayoutManager } LayoutType.Grid -> { val gridLayoutManager = GridLayoutManager(this, 2) spacingItemDecoration = SpacingItemDecoration(sixteen) main_recycler.addItemDecoration(spacingItemDecoration!!) main_recycler.setPadding(sixteen, sixteen, sixteen, sixteen) gridLayoutManager } LayoutType.Spanned -> { val gridLayoutManager = GridLayoutManager(this, 4) gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { if (position < 4) return 2 return 1 } } main_recycler.setPadding(eight, eight, eight, eight) gridLayoutManager } LayoutType.Staggered -> { val staggeredGridLayoutManager = StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL) spacingItemDecoration = SpacingItemDecoration(sixteen) main_recycler.addItemDecoration(spacingItemDecoration!!) main_recycler.setPadding(sixteen, sixteen, sixteen, sixteen) staggeredGridLayoutManager } LayoutType.Flow -> { val flowLayoutManager = FlowLayoutManager() flowLayoutManager.setAlignment(Alignment.LEFT) flowLayoutManager.isAutoMeasureEnabled = true main_recycler.setPadding(eight, eight, eight, eight) flowLayoutManager } } main_recycler.layoutManager = layoutManager adapter.layoutType = layoutManagerType main_recycler.scrollToPosition(scrollPosition) } } enum class LayoutType(val value: Int) { Linear(1), Grid(2), Spanned(3), Staggered(4), Flow(5) }
0
null
3
15
817ca24021293493f6b085014c1a4af30dd0d75c
6,158
AndroidEasyList
MIT License
tinbo-time/src/main/kotlin/io/gitlab/arturbosch/tinbo/time/DummyTime.kt
arturbosch
66,214,435
false
null
package io.gitlab.arturbosch.tinbo.time import io.gitlab.arturbosch.tinbo.api.model.DummyEntry import java.time.LocalDate /** * @author artur */ class DummyTime(var category: String?, var message: String?, var hours: Long?, var minutes: Long?, var seconds: Long?, var date: LocalDate?) : DummyEntry()
1
Kotlin
1
6
85a74b80b081e374360475f4979e5adffbf91436
385
Tinbo
Apache License 2.0
src/main/java/top/zbeboy/isy/web/bean/graduate/design/proposal/GraduationDesignDatumBean.kt
zbeboy
71,459,176
false
null
package top.zbeboy.isy.web.bean.graduate.design.proposal import top.zbeboy.isy.domain.tables.pojos.GraduationDesignDatum /** * Created by zbeboy 2018-01-29 . **/ class GraduationDesignDatumBean : GraduationDesignDatum() { var size: String? = null var originalFileName: String? = null var newName: String? = null var relativePath: String? = null var ext: String? = null var updateTimeStr: String? = null var graduationDesignReleaseId: String? = null var graduationDesignDatumTypeName: String? = null var realName: String? = null var studentNumber: String? = null var staffId: Int = 0 var studentId: Int = 0 var organizeName: String? = null }
7
JavaScript
2
7
9634602adba558dbdb945c114692019accdb50a9
696
ISY
MIT License
TachiServer/src/main/java/xyz/nulldev/ts/api/v2/java/impl/util/ProxyList.kt
TachiWeb
63,995,519
false
null
package xyz.nulldev.ts.api.v2.java.impl.util class ProxyList<T, V>(private val orig: List<T>, private val proxy: (T) -> V): AbstractList<V>() { override val size = orig.size override fun get(index: Int) = proxy(orig[index]) }
45
null
44
376
756aed147f9d3ad64b0620ab69c3eb4575264177
257
TachiWeb-Server
Apache License 2.0
example/android/app/src/main/kotlin/com/example/example/MainActivity.kt
Timeware-Innovation
304,801,063
false
{"YAML": 3, "Markdown": 4, "Text": 1, "Ignore List": 6, "Git Attributes": 1, "Dart": 45, "Gradle": 5, "INI": 2, "Java Properties": 2, "XML": 18, "Java": 23, "Kotlin": 5, "Ruby": 2, "OpenStep Property List": 4, "Objective-C": 11, "Swift": 1, "JSON": 3}
package de.jonasbark.stripepaymentexample import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
1
null
1
1
2e6aab436fec7f1a0db03654efe6e3ef74cb64f2
138
flutter_stripe_payment
MIT License
listactivity/src/main/java/com/sovegetables/listactivity/PageBuilder.kt
sovegetables
217,002,321
false
null
package com.sovegetables.listactivity class PageBuilder{ internal var enableLoadMore = false internal var enableRefresh = false internal var enableAutoLoadMore = false fun enableLoadMore(enable: Boolean): PageBuilder { enableLoadMore = enable return this } fun enableAutoLoadMore(enable: Boolean): PageBuilder { enableAutoLoadMore = enable return this } fun enableRefresh(enable: Boolean) : PageBuilder { enableRefresh = enable return this } }
1
null
1
7
38ecff18409fe08ef43136d3f8c96b2e12fc1573
531
shineandroid
Apache License 2.0
app/src/main/java/com/a10miaomiao/bilimiao/netword/MiaoHttp.kt
10miaomiao
115,510,569
false
null
package com.a10miaomiao.bilimiao.netword import okhttp3.* import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers /** * Created by 10喵喵 on 2017/11/14. */ object MiaoHttp { var GET = 1 var POST = 2 fun <T> newClient( url: String, method: Int = GET, headers: Map<String,String> = mapOf(), body: Map<String,String> = mapOf(), onResponse: ((response: T) -> Unit)? = null, onError: ((e: Throwable) -> Unit)? = null, parseNetworkResponse: ((response: Response) -> T) ) { val client = OkHttpClient() val request = Request.Builder() for (key in headers.keys) { request.addHeader(key, headers[key]) } if (method == GET) { request.get() .url(url) } else if (method == POST) { val formBody = FormBody.Builder() for (key in body.keys) { formBody.add(key, body[key]) } //创建一个Request request.post(formBody.build()) .url(url) } //通过client发起请求 Observable.create<T> { val response = client.newCall(request.build()).execute() it.onNext(parseNetworkResponse(response)) it.onCompleted() } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe ({ response -> onResponse?.invoke(response) },{ err -> onError?.invoke(err) }) } fun newStringClient(url: String, method: Int = GET, headers: Map<String,String> = mapOf(), body: Map<String,String> = mapOf(), onResponse: ((response: String) -> Unit)? = null, onError: ((e: Throwable) -> Unit)? = null) { newClient<String>( url = url, method = method, headers = headers, body = body, onResponse = onResponse, onError = onError, parseNetworkResponse = { it.body()!!.string() } ) } }
1
Kotlin
1
20
dfd78b56b5c41eb49454836ee2bce5cefc667db7
2,358
bilimiao
Apache License 2.0
kotlin/kotlin-formal/examples/fuzzer/localVal.kt881595124.kt_minimized.kt
antlr
5,958,314
false
{"ANTLR": 6775610, "Java": 1331797, "Python": 537677, "C#": 213155, "Shell": 151939, "PowerShell": 91780, "C++": 85503, "JavaScript": 80796, "TypeScript": 56835, "Go": 36584, "Dart": 24575, "CMake": 16349, "Objective-C": 10524, "Swift": 9106, "PHP": 7650, "Smalltalk": 6699, "C": 6406, "Yacc": 5177, "TSQL": 4935, "PLSQL": 4213, "Lex": 4090, "StringTemplate": 2226, "Makefile": 1491, "sed": 718, "Fortran": 516, "Batchfile": 192, "Lua": 137}
suspend fun suspendHere(v: String): String = suspendCoroutineOrReturn((if (true) { ({x -> }) } else { ({x -> }) }))
529
ANTLR
3668
9,910
6581f29d0cb63e3e337cd6dacec6602e34aa88d3
115
grammars-v4
MIT License
Series/Building_DRAG_forAndroid/project/app/src/main/java/edu/sempreacodar/drag/model/drawing.kt
palbp
249,798,469
false
null
package edu.sempreacodar.drag.model /** * Represents points in the drawing. */ data class Point(val x: Float = 0F, val y: Float = 0F) /** * Represents lines in the drawing. A line is sequence of [Point]. */ data class Line(val points: List<Point> = listOf()) /** * Creates a line starting at the given point * @param [point] the point where the line starts at * @return the new line */ fun startNewLineAt(point: Point) = Line(listOf(point)) /** * Extension function that adds [point] to this line. * @return the new line instance */ operator fun Line.plus(point: Point) = Line(points + point) /** * Represents the drawing, which is comprised of a set of [Line]. */ class Drawing private constructor(val lines: List<Line> = listOf(), val lastLine: Line? = null) { companion object { fun from(lines: List<Line> = listOf()) = when (lines.size) { 0 -> Drawing() 1 -> Drawing(lastLine = lines.last()) else -> Drawing(lines = lines.dropLast(1), lines.last()) } fun from(lines: List<Line>, lastLine: Line) = Drawing(lines, lastLine) val EMPTY = Drawing() } } /** * Iterates over the drawing's lines applying [action] to each line of the drawing. * @param [action] the action to be applied to each line */ fun Drawing.forEach(action: (Line) -> Unit) { lines.forEach(action) if (lastLine != null) action(lastLine) } /** * Extension function that adds [line] to the current drawing. * @return the new drawing instance */ operator fun Drawing.plus(line: Line) = Drawing.from( if (lastLine == null) lines else lines + lastLine, line ) /** * Extension function that adds a point to the drawing's last line. * @param [point] the point to be added * @return the new [Drawing] instance */ fun Drawing.addToLastLine(point: Point): Drawing = Drawing.from(lines, if (lastLine == null) startNewLineAt(point) else lastLine + point)
2
Kotlin
7
44
a13802274b32e90b20c15ffe8d38629b0c84dbd4
1,941
sempre_a_codar
MIT License
src/microservice/auth-api/src/main/kotlin/kr/latera/sibylla/authapi/dto/LoginRequestDto.kt
Laterality
147,147,572
false
null
package kr.latera.sibylla.authapi.dto data class LoginRequestDto(val email: String, val password: String)
3
Kotlin
0
0
3b2475f0843fe6009d3c4bb438bc4355f7f9d0e2
133
sibylla
MIT License
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/brands/Firefox.kt
DevSrSouza
311,134,756
false
null
package compose.icons.fontawesomeicons.brands import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.fontawesomeicons.BrandsGroup public val BrandsGroup.Firefox: ImageVector get() { if (_firefox != null) { return _firefox!! } _firefox = Builder(name = "Firefox", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 512.0f, viewportHeight = 512.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(503.52f, 241.48f) curveToRelative(-0.12f, -1.56f, -0.24f, -3.12f, -0.24f, -4.68f) verticalLineToRelative(-0.12f) lineToRelative(-0.36f, -4.68f) verticalLineToRelative(-0.12f) arcToRelative(245.86f, 245.86f, 0.0f, false, false, -7.32f, -41.15f) curveToRelative(0.0f, -0.12f, 0.0f, -0.12f, -0.12f, -0.24f) lineToRelative(-1.08f, -4.0f) curveToRelative(-0.12f, -0.24f, -0.12f, -0.48f, -0.24f, -0.6f) curveToRelative(-0.36f, -1.2f, -0.72f, -2.52f, -1.08f, -3.72f) curveToRelative(-0.12f, -0.24f, -0.12f, -0.6f, -0.24f, -0.84f) curveToRelative(-0.36f, -1.2f, -0.72f, -2.4f, -1.08f, -3.48f) curveToRelative(-0.12f, -0.36f, -0.24f, -0.6f, -0.36f, -1.0f) curveToRelative(-0.36f, -1.2f, -0.72f, -2.28f, -1.2f, -3.48f) lineToRelative(-0.36f, -1.08f) curveToRelative(-0.36f, -1.08f, -0.84f, -2.28f, -1.2f, -3.36f) arcToRelative(8.27f, 8.27f, 0.0f, false, false, -0.36f, -1.0f) curveToRelative(-0.48f, -1.08f, -0.84f, -2.28f, -1.32f, -3.36f) curveToRelative(-0.12f, -0.24f, -0.24f, -0.6f, -0.36f, -0.84f) curveToRelative(-0.48f, -1.2f, -1.0f, -2.28f, -1.44f, -3.48f) curveToRelative(0.0f, -0.12f, -0.12f, -0.24f, -0.12f, -0.36f) curveToRelative(-1.56f, -3.84f, -3.24f, -7.68f, -5.0f, -11.4f) lineToRelative(-0.36f, -0.72f) curveToRelative(-0.48f, -1.0f, -0.84f, -1.8f, -1.32f, -2.64f) curveToRelative(-0.24f, -0.48f, -0.48f, -1.08f, -0.72f, -1.56f) curveToRelative(-0.36f, -0.84f, -0.84f, -1.56f, -1.2f, -2.4f) curveToRelative(-0.36f, -0.6f, -0.6f, -1.2f, -1.0f, -1.8f) reflectiveCurveToRelative(-0.84f, -1.44f, -1.2f, -2.28f) curveToRelative(-0.36f, -0.6f, -0.72f, -1.32f, -1.08f, -1.92f) reflectiveCurveToRelative(-0.84f, -1.44f, -1.2f, -2.16f) arcToRelative(18.07f, 18.07f, 0.0f, false, false, -1.2f, -2.0f) curveToRelative(-0.36f, -0.72f, -0.84f, -1.32f, -1.2f, -2.0f) reflectiveCurveToRelative(-0.84f, -1.32f, -1.2f, -2.0f) reflectiveCurveToRelative(-0.84f, -1.32f, -1.2f, -1.92f) reflectiveCurveToRelative(-0.84f, -1.44f, -1.32f, -2.16f) arcToRelative(15.63f, 15.63f, 0.0f, false, false, -1.2f, -1.8f) lineTo(463.2f, 119.0f) arcToRelative(15.63f, 15.63f, 0.0f, false, false, -1.2f, -1.8f) curveToRelative(-0.48f, -0.72f, -1.08f, -1.56f, -1.56f, -2.28f) curveToRelative(-0.36f, -0.48f, -0.72f, -1.08f, -1.08f, -1.56f) lineToRelative(-1.8f, -2.52f) curveToRelative(-0.36f, -0.48f, -0.6f, -0.84f, -1.0f, -1.32f) curveToRelative(-1.0f, -1.32f, -1.8f, -2.52f, -2.76f, -3.72f) arcToRelative(248.76f, 248.76f, 0.0f, false, false, -23.51f, -26.64f) arcTo(186.82f, 186.82f, 0.0f, false, false, 412.0f, 62.46f) curveToRelative(-4.0f, -3.48f, -8.16f, -6.72f, -12.48f, -9.84f) arcToRelative(162.49f, 162.49f, 0.0f, false, false, -24.6f, -15.12f) curveToRelative(-2.4f, -1.32f, -4.8f, -2.52f, -7.2f, -3.72f) arcToRelative(254.0f, 254.0f, 0.0f, false, false, -55.43f, -19.56f) curveToRelative(-1.92f, -0.36f, -3.84f, -0.84f, -5.64f, -1.2f) horizontalLineToRelative(-0.12f) curveToRelative(-1.0f, -0.12f, -1.8f, -0.36f, -2.76f, -0.48f) arcToRelative(236.35f, 236.35f, 0.0f, false, false, -38.0f, -4.0f) horizontalLineTo(255.14f) arcToRelative(234.62f, 234.62f, 0.0f, false, false, -45.48f, 5.0f) curveToRelative(-33.59f, 7.08f, -63.23f, 21.24f, -82.91f, 39.0f) curveToRelative(-1.08f, 1.0f, -1.92f, 1.68f, -2.4f, 2.16f) lineToRelative(-0.48f, 0.48f) horizontalLineTo(124.0f) lineToRelative(-0.12f, 0.12f) lineToRelative(0.12f, -0.12f) arcToRelative(0.12f, 0.12f, 0.0f, false, false, 0.12f, -0.12f) lineToRelative(-0.12f, 0.12f) arcToRelative(0.42f, 0.42f, 0.0f, false, true, 0.24f, -0.12f) curveToRelative(14.64f, -8.76f, 34.92f, -16.0f, 49.44f, -19.56f) lineToRelative(5.88f, -1.44f) curveToRelative(0.36f, -0.12f, 0.84f, -0.12f, 1.2f, -0.24f) curveToRelative(1.68f, -0.36f, 3.36f, -0.72f, 5.16f, -1.08f) curveToRelative(0.24f, 0.0f, 0.6f, -0.12f, 0.84f, -0.12f) curveTo(250.94f, 20.94f, 319.34f, 40.14f, 367.0f, 85.61f) arcToRelative(171.49f, 171.49f, 0.0f, false, true, 26.88f, 32.76f) curveToRelative(30.36f, 49.2f, 27.48f, 111.11f, 3.84f, 147.59f) curveToRelative(-34.44f, 53.0f, -111.35f, 71.27f, -159.0f, 24.84f) arcToRelative(84.19f, 84.19f, 0.0f, false, true, -25.56f, -59.0f) arcToRelative(74.05f, 74.05f, 0.0f, false, true, 6.24f, -31.0f) curveToRelative(1.68f, -3.84f, 13.08f, -25.67f, 18.24f, -24.59f) curveToRelative(-13.08f, -2.76f, -37.55f, 2.64f, -54.71f, 28.19f) curveToRelative(-15.36f, 22.92f, -14.52f, 58.2f, -5.0f, 83.28f) arcToRelative(132.85f, 132.85f, 0.0f, false, true, -12.12f, -39.24f) curveToRelative(-12.24f, -82.55f, 43.31f, -153.0f, 94.31f, -170.51f) curveToRelative(-27.48f, -24.0f, -96.47f, -22.31f, -147.71f, 15.36f) curveToRelative(-29.88f, 22.0f, -51.23f, 53.16f, -62.51f, 90.36f) curveToRelative(1.68f, -20.88f, 9.6f, -52.08f, 25.8f, -83.88f) curveToRelative(-17.16f, 8.88f, -39.0f, 37.0f, -49.8f, 62.88f) curveToRelative(-15.6f, 37.43f, -21.0f, 82.19f, -16.08f, 124.79f) curveToRelative(0.36f, 3.24f, 0.72f, 6.36f, 1.08f, 9.6f) curveToRelative(19.92f, 117.11f, 122.0f, 206.38f, 244.78f, 206.38f) curveTo(392.77f, 503.42f, 504.0f, 392.19f, 504.0f, 255.0f) curveTo(503.88f, 250.48f, 503.76f, 245.92f, 503.52f, 241.48f) close() } } .build() return _firefox!! } private var _firefox: ImageVector? = null
17
null
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
7,712
compose-icons
MIT License
favorite/src/main/java/com/centaury/cataloguemovie/favorite/viewmodel/FavoriteMovieContract.kt
Centauryal
213,598,833
false
null
package com.centaury.cataloguemovie.favorite.viewmodel import com.centaury.domain.model.MoviesDB /** * @Author Centaury (<EMAIL>) * Created by Centaury on 7/27/2020. */ interface FavoriteMovieContract { fun getAllFavoriteMovieContract() fun getFavoriteMovieByIdContract(movieId: Int) fun getDeleteFavoriteMovieContract(movie: MoviesDB) }
0
Kotlin
0
0
5a369b2f509e2d11eb298774533e40ec63d7fa0d
357
CatalogueMovie-Jetpack
Apache License 2.0
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/s3/CfnBucketServerSideEncryptionByDefaultPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.s3 import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.s3.CfnBucket /** * Describes the default server-side encryption to apply to new objects in the bucket. * * If a PUT Object request doesn't specify any server-side encryption, this default encryption will * be applied. If you don't specify a customer managed key at configuration, Amazon S3 automatically * creates an AWS KMS key in your AWS account the first time that you add an object encrypted with * SSE-KMS to a bucket. By default, Amazon S3 uses this KMS key for SSE-KMS. For more information, see * [PUT Bucket * encryption](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTencryption.html) in the * *Amazon S3 API Reference* . * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.s3.*; * ServerSideEncryptionByDefaultProperty serverSideEncryptionByDefaultProperty = * ServerSideEncryptionByDefaultProperty.builder() * .sseAlgorithm("sseAlgorithm") * // the properties below are optional * .kmsMasterKeyId("kmsMasterKeyId") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-serversideencryptionbydefault.html) */ @CdkDslMarker public class CfnBucketServerSideEncryptionByDefaultPropertyDsl { private val cdkBuilder: CfnBucket.ServerSideEncryptionByDefaultProperty.Builder = CfnBucket.ServerSideEncryptionByDefaultProperty.builder() /** * @param kmsMasterKeyId KMS key ID to use for the default encryption. This parameter is allowed * if SSEAlgorithm is aws:kms. * You can specify the key ID, key alias, or the Amazon Resource Name (ARN) of the CMK. However, * if you are using encryption with cross-account operations, you must use a fully qualified CMK ARN. * For more information, see [Using encryption for cross-account * operations](https://docs.aws.amazon.com/AmazonS3/latest/dev/bucket-encryption.html#bucket-encryption-update-bucket-policy) * . * * For example: * * * Key ID: `1234abcd-12ab-34cd-56ef-1234567890ab` * * Key ARN: `arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab` * * * Amazon S3 only supports symmetric KMS keys and not asymmetric KMS keys. For more information, * see [Using Symmetric and Asymmetric * Keys](https://docs.aws.amazon.com//kms/latest/developerguide/symmetric-asymmetric.html) in the * *AWS Key Management Service Developer Guide* . */ public fun kmsMasterKeyId(kmsMasterKeyId: String) { cdkBuilder.kmsMasterKeyId(kmsMasterKeyId) } /** * @param sseAlgorithm Server-side encryption algorithm to use for the default encryption. */ public fun sseAlgorithm(sseAlgorithm: String) { cdkBuilder.sseAlgorithm(sseAlgorithm) } public fun build(): CfnBucket.ServerSideEncryptionByDefaultProperty = cdkBuilder.build() }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
3,246
awscdk-dsl-kotlin
Apache License 2.0
app/src/main/java/com/fpr0001/nasaimages/utils/SchedulerProvider.kt
fpr0001
196,883,640
false
null
package com.fpr0001.nasaimages.utils import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Inject import javax.inject.Provider interface SchedulerProvider { fun <T> async(single: Single<T>): Single<T> fun <T> async(single: (observeOn: Scheduler) -> Single<T>): Single<T> fun <T> async(observable: Observable<T>): Observable<T> fun async(completable: Completable): Completable fun async(completable: (observeOn: Scheduler) -> Completable): Completable } abstract class BaseSchedulerImpl : SchedulerProvider { private lateinit var providerIo: Provider<Scheduler> private lateinit var providerMain: Provider<Scheduler> protected constructor() constructor( providerIo: Provider<Scheduler>, providerMain: Provider<Scheduler> ) : this() { this.providerIo = providerIo this.providerMain = providerMain } constructor(provider: Provider<Scheduler>) : this() { this.providerMain = provider this.providerIo = provider } override fun async(completable: Completable): Completable { return completable .subscribeOn(providerIo.get()) .observeOn(providerMain.get()) } override fun async(completable: (observeOn: Scheduler) -> Completable): Completable { return completable(providerIo.get()) .subscribeOn(providerIo.get()) .observeOn(providerMain.get()) } override fun <T> async(observable: Observable<T>): Observable<T> { return observable .subscribeOn(providerIo.get()) .observeOn(providerMain.get()) } override fun <T> async(single: Single<T>): Single<T> { return single .subscribeOn(providerIo.get()) .observeOn(providerMain.get()) } override fun <T> async(single: (observeOn: Scheduler) -> Single<T>): Single<T> { return single(providerIo.get()) .subscribeOn(providerIo.get()) .observeOn(providerMain.get()) } } open class SchedulerProviderImpl @Inject constructor() : BaseSchedulerImpl( providerIo = Provider { Schedulers.io() }, providerMain = Provider { AndroidSchedulers.mainThread() }) open class SchedulerProviderTestImpl @Inject constructor() : BaseSchedulerImpl(Provider { Schedulers.trampoline() })
0
Kotlin
0
0
5cca1eca98ed8d599bc3e83d1278d74d7bba8176
2,502
nasa_images_android_app
MIT License
app/src/main/java/com/hobeez/passwordlessfirebase/ui/login/LoginCodeFragment.kt
icodeyou
233,945,687
false
null
package com.hobeez.passwordlessfirebase.ui.login import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.findNavController import com.hobeez.passwordlessfirebase.R import com.hobeez.passwordlessfirebase.ui.util.BaseFragment import com.hobeez.passwordlessfirebase.util.extensions.isValidPhoneCode import com.hobeez.passwordlessfirebase.util.firebase.AuthUtil import kotlinx.android.synthetic.main.fragment_login_code.* class LoginCodeFragment : BaseFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_login_code, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { etCode.requestFocus() btSendBackCode.setOnClickListener { val code = etCode.text.toString() if (code.isValidPhoneCode()) { AuthUtil.sendBackVerificationCode( activity as LoginActivity, code ) view.findNavController().navigate(R.id.action_send_back_code) } else { toast(getString(R.string.error_phone_code)) } } btResendPhoneCode.setOnClickListener { AuthUtil.resendPhoneVerificationCode(activity as LoginActivity) toast(getString(R.string.code_resent)) } } }
2
Kotlin
0
2
2b4bab9eeb4101e5037286d0dc869f7b25cfcf93
1,539
passwordless-authentification-firebase
MIT License
src/main/kotlin/com/bada/app/models/Salary.kt
RouNNdeL
326,284,153
false
{"HTML": 66241, "Kotlin": 55527, "JavaScript": 8923, "Dockerfile": 664, "CSS": 281}
package com.bada.app.models import java.util.* import javax.persistence.Column import javax.persistence.Entity import javax.persistence.Table @Entity @Table(name = "salaries") class Salary( @Column(name = "salary_date") val date: Date, val salary: Double ) : AbstractEntity<Long>()
0
HTML
1
0
67964e704e3cdc2137b33641099f6c31a03b95f9
296
bada-project
MIT License
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/sourceToSink/UntaintedConfiguration.kt
NipunaRanasinghe
160,032,869
true
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInspection.sourceToSink data class UntaintedConfiguration(val taintedAnnotations: List<String?>, val unTaintedAnnotations: List<String?>, val firstAnnotation: String?, val methodClass: List<String?>, val methodNames: List<String?>, val fieldClass: List<String?>, val fieldNames: List<String?>, val processMethodAsQualifierAndArguments: Boolean, val skipClasses: List<String?>) { fun copy(): UntaintedConfiguration { return UntaintedConfiguration(ArrayList(taintedAnnotations), ArrayList( unTaintedAnnotations), firstAnnotation, ArrayList(methodClass), ArrayList(methodNames), ArrayList(fieldClass), ArrayList(fieldNames), processMethodAsQualifierAndArguments, ArrayList(skipClasses)) } }
0
null
0
0
326a84d0aef968a80e21276dc7cc696a619429d3
1,363
intellij-community
Apache License 2.0
app/src/main/java/my/dzeko/weatherforecast/entity/response/Coordinate.kt
dzeko14
168,175,566
false
null
package my.dzeko.weatherforecast.entity.response import com.google.gson.annotations.Expose data class Coordinate( @Expose val lat :Double, @Expose val lon :Double )
0
Kotlin
0
0
bcf7bdfd6fb14eced160c7377d8e4471297825ef
183
weather-forecast
MIT License
common/src/main/java/io/homeassistant/companion/android/common/data/websocket/impl/entities/DeviceRegistryUpdatedEvent.kt
nesror
328,856,313
true
null
package io.homeassistant.companion.android.common.data.websocket.impl.entities data class DeviceRegistryUpdatedEvent( val action: String, val deviceId: String )
0
Kotlin
15
61
b36bb0f67fd884b0f8c938c048b51134063784f2
170
Home-Assistant-Companion-for-Android
Apache License 2.0
app/src/main/java/be/digitalia/fosdem/viewmodels/TrackScheduleEventViewModel.kt
oraluben
219,161,297
true
{"Kotlin": 293346}
package be.digitalia.fosdem.viewmodels import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.switchMap import be.digitalia.fosdem.db.AppDatabase import be.digitalia.fosdem.model.Day import be.digitalia.fosdem.model.Event import be.digitalia.fosdem.model.Track class TrackScheduleEventViewModel(application: Application) : AndroidViewModel(application) { private val appDatabase = AppDatabase.getInstance(application) private val dayTrackLiveData = MutableLiveData<Pair<Day, Track>>() val scheduleSnapshot: LiveData<List<Event>> = dayTrackLiveData.switchMap { (day, track) -> MutableLiveData<List<Event>>().also { appDatabase.queryExecutor.execute { it.postValue(appDatabase.scheduleDao.getEventsSnapshot(day, track)) } } } fun setDayAndTrack(day: Day, track: Track) { val dayTrack = day to track if (dayTrack != dayTrackLiveData.value) { dayTrackLiveData.value = dayTrack } } }
0
Kotlin
0
0
64188a1bd67ea8748d48db8f31b44865347397dd
1,121
fosdem-companion-android
Apache License 2.0
extensions-android/src/main/java/com/arkivanov/decompose/extensions/android/Utils.kt
arkivanov
437,015,897
false
null
package com.arkivanov.decompose.extensions.android import android.view.View import android.view.ViewGroup internal inline fun ViewGroup.forEachChild(block: (View) -> Unit) { for (i in 0 until childCount) { block(getChildAt(i)) } }
6
Kotlin
37
976
5e9d7de05b3c4d15a9036b72a99e5927683c5742
249
Decompose
Apache License 2.0
src/main/kotlin/no/nav/arbeidsgiver/min_side/services/tiltak/RefusjonStatusService.kt
navikt
170,528,339
false
{"Kotlin": 289801, "Dockerfile": 85}
package no.nav.arbeidsgiver.min_side.services.tiltak import no.nav.arbeidsgiver.min_side.models.Organisasjon import no.nav.arbeidsgiver.min_side.services.altinn.AltinnService import org.springframework.stereotype.Service @Service class RefusjonStatusService( private val altinnService: AltinnService, private val refusjonStatusRepository: RefusjonStatusRepository, ) { fun statusoversikt(fnr: String): List<Statusoversikt> { val orgnr = altinnService .hentOrganisasjonerBasertPaRettigheter(fnr, TJENESTEKODE, TJENESTEVERSJON) .mapNotNull(Organisasjon::organizationNumber) return refusjonStatusRepository .statusoversikt(orgnr) .map(Statusoversikt.Companion::from) } data class Statusoversikt( val virksomhetsnummer: String, val statusoversikt: Map<String, Int>, ) { val tilgang: Boolean = statusoversikt.values.any { it > 0 } companion object { fun from(statusoversikt: RefusjonStatusRepository.Statusoversikt) = Statusoversikt( statusoversikt.virksomhetsnummer, statusoversikt.statusoversikt ) } } companion object { const val TJENESTEKODE = "4936" const val TJENESTEVERSJON = "1" } }
0
Kotlin
0
1
440ffb2440e544d8811f5e8c30ab5f4fa65270d8
1,333
min-side-arbeidsgiver-api
MIT License
src/commonMain/kotlin/com/cherrio/sheetsdb/database/ReadDB.kt
ayodelekehinde
552,944,499
false
{"Kotlin": 27539}
/* * Copyright (c) 2022. <NAME> */ package com.cherrio.sheetsdb.database import com.cherrio.sheetsdb.client.client import com.cherrio.sheetsdb.client.combineUrl import com.cherrio.sheetsdb.client.json import com.cherrio.sheetsdb.models.Table import com.cherrio.sheetsdb.utils.getToken import io.ktor.client.call.* import io.ktor.client.request.* import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.jsonPrimitive /** * Gets the rows in the sheet without the column names. Returns a list * of type T * @receiver [SheetTable] * @return [List] */ suspend inline fun <reified T> SheetTable<T>.get(sheetName: String? = null): List<T> { val response = tableOp { client.get(combineUrl(sheetId, SHEET_VALUES, sheetName ?: sheet)) { bearerAuth(getToken) } } val data = response.body<Table>() return data.values.filter { it.isNotEmpty() }.mapResults() } /** * Searches the table for a match of the filter * E.g: find(User::email eq "<EMAIL>") * @receiver [SheetTable] * @param filter:[Filter] * @return [List] */ suspend inline fun <reified T> SheetTable<T>.find(filter: Filter, sheetName: String? = null): List<T> { val response = tableOp { client.get(combineUrl(sheetId, SHEET_VALUES, sheetName?: sheet)) { bearerAuth(getToken) } } val data = response.body<Table>().values.filter { it.isNotEmpty() } return data.find(filter.key, filter.query) } /** * Implementation that searches the keys for a particular value * @return [List] * @receiver [List] * @param key:[String] * @param value:[String] */ @PublishedApi internal inline fun <reified T> List<List<String>>.find(key: String, value: String): List<T>{ val keys = first() val jsonObjects = removeColumnNames().map { it.toJsonObject(keys) } val result = jsonObjects.filter { val jsonKey = it[key] jsonKey != null && it.getValue(key).jsonPrimitive.content == value } val encodedValues = json.encodeToString(result) return json.decodeFromString(encodedValues) } /** * */ @PublishedApi internal inline fun <reified T> List<List<String>>.mapResults(): List<T>{ val keys = first() val jsonObjects = removeColumnNames().map { it.toJsonObject(keys) } val encodedValues = json.encodeToString(jsonObjects) return json.decodeFromString(encodedValues) } @PublishedApi internal fun <T> List<T>.removeColumnNames() = subList(1, size) @PublishedApi internal suspend fun <T> SheetTable<T>.getColumnNames(sheetName: String? = null): List<String> { val response = tableOp { client.get(combineUrl(sheetId, SHEET_VALUES, sheetName?:sheet)) { bearerAuth(getToken) } } return response.body<Table>().values.first() }
0
Kotlin
0
4
dbb3aa3f16bff820be763912170eeea80ca818a5
2,830
sheets-db
Apache License 2.0
core/data/src/main/java/com/halilozcan/animearch/core/data/dto/single/AnimeX.kt
halilozcan
572,966,235
false
null
package com.halilozcan.animearch.core.data.dto.single import com.google.gson.annotations.SerializedName data class AnimeX( @SerializedName("images") val images: Images?, @SerializedName("mal_id") val malId: Int?, @SerializedName("title") val title: String?, @SerializedName("url") val url: String? )
1
Kotlin
8
97
5903644dbabf505702d488d8ec7bb19b78174467
334
AnimeArch
Apache License 2.0
src/main/kotlin/shop/itbug/fluttercheckversionx/util/YamlExtends.kt
mdddj
390,183,676
false
null
package shop.itbug.fluttercheckversionx.util import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileFactory import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.yaml.YAMLLanguage import org.jetbrains.yaml.psi.YAMLFile import org.jetbrains.yaml.psi.impl.YAMLBlockMappingImpl import org.jetbrains.yaml.psi.impl.YAMLKeyValueImpl import org.jetbrains.yaml.psi.impl.YAMLPlainTextImpl private val devPattern = Regex("""\bdev\b""") private val betaPattern = Regex("""\bbeta\b""") enum class DartVersionType { Dev, Beta, Base } ///插件版本是不是 dev fun DartPluginVersionName.isDev(): Boolean = devPattern.containsMatchIn(version) fun DartPluginVersionName.isBeta(): Boolean = betaPattern.containsMatchIn(version) ///版本类型 val DartPluginVersionName.versionType: DartVersionType get() = when { isBeta() -> DartVersionType.Beta isDev() -> DartVersionType.Dev else -> DartVersionType.Base } val DartPluginVersionName.finalVersionText get() = version.removePrefix("^") class DartPluginVersionName(val name: String, val version: String) { override fun toString(): String { return "插件名:$name,版本:$version,插件类型:$versionType" } } /** * yaml工具类 */ class YamlExtends(val element: PsiElement) { ///判断是不是dart plugin 节点 fun isDartPluginElement(): Boolean { if (element !is YAMLKeyValueImpl) return false if (element.parent !is YAMLBlockMappingImpl) return false if (element.parent.parent !is YAMLKeyValueImpl) return false val igPluginNames = listOf("flutter_localizations", "flutter") val devTypes = listOf("dependencies", "dependency_overrides", "dev_dependencies") val rootElement: YAMLKeyValueImpl = PsiTreeUtil.getParentOfType(element, YAMLKeyValueImpl::class.java, true, 2) ?: return false if (devTypes.contains(rootElement.keyText) && !igPluginNames.contains(element.keyText)) return true return false } ///获取依赖名字 fun getDartPluginNameAndVersion(): DartPluginVersionName? { if (isDartPluginElement()) { val ele = (element as YAMLKeyValueImpl) if (ele.valueText == "any") return null return DartPluginVersionName(name = ele.keyText, version = ele.valueText) } return null } /** * 是否有path, git 指定版本 * 例子: * ```dart * vimeo_video_player: * path: ../../hlx/github/vimeo_video_player * ``` * @return true */ fun isSpecifyVersion(): Boolean = (element is YAMLKeyValueImpl) && PsiTreeUtil.findChildOfType(element, YAMLBlockMappingImpl::class.java) != null } object MyYamlPsiElementFactory { ///创建一个节点 fun createPlainPsiElement(project: Project, text: String): YAMLPlainTextImpl? { val instance = PsiFileFactory.getInstance(project) val createFileFromText: YAMLFile = instance.createFileFromText(YAMLLanguage.INSTANCE, "name: $text") as YAMLFile return PsiTreeUtil.findChildrenOfAnyType(createFileFromText, YAMLPlainTextImpl::class.java).lastOrNull() } }
4
null
4
39
ce8000941b26b703df05d5c800028c07a0e2f10a
3,121
dd_flutter_idea_plugin
MIT License
Problems/Algorithms/83. Remove Duplicates from Sorted List/RemoveDuplicates.kt
xuedong
189,745,542
false
{"Text": 1, "Ignore List": 1, "Markdown": 1, "Python": 498, "Kotlin": 443, "Java": 343, "Go": 55, "C++": 150, "Rust": 141, "Ruby": 2, "Dart": 1, "Erlang": 1, "Racket": 1, "Elixir": 1, "Scala": 2, "C": 2, "JavaScript": 22, "C#": 2, "Shell": 2, "SQL": 34, "JSON": 1, "Swift": 1, "TSX": 1}
/** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { fun deleteDuplicates(head: ListNode?): ListNode? { var dummy: ListNode? = ListNode(0) dummy?.next = head var curr: ListNode? = head while (curr?.next != null) { if (curr?.`val` == curr?.next.`val`) { curr?.next = curr?.next.next } else { curr = curr?.next } } return dummy?.next } }
0
Kotlin
0
1
64e27269784b1a31258677ab03da00f341c2fa98
620
leet-code
MIT License
wsepdkdriver/src/main/java/com/marcpoppleton/wsepdkdriver/WsEpd.kt
marcpoppleton
301,684,490
false
null
/** WS EPD Driver Copyright (C) 2020 <NAME> 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.marcpoppleton.wsepdkdriver import android.graphics.* import android.graphics.Bitmap.CompressFormat import android.util.Log import com.google.android.things.pio.Gpio import com.google.android.things.pio.PeripheralManager import com.google.android.things.pio.SpiDevice import java.io.ByteArrayOutputStream import java.io.IOException import kotlin.jvm.Throws enum class Orientation { LANDSCAPE_BOTTOM, //0° rotation LANDSCAPE_TOP, //180° rotation PORTRAIT_RIGHT, //90° rotation PORTRAIT_LEFT, //-90° rotation } open class WsEpd() { private val SPI_NAME = "SPI0.0" private val SPI_SPEED = 2_000_000 private val EPD_RST_PIN = "BCM17" private val EPD_BUSY_PIN = "BCM24" private val EPD_DC_PIN = "BCM25" private val EPD_CS_PIN = "BCM8" lateinit var spiDevice: SpiDevice private set lateinit var busyGpio: Gpio private set lateinit var resetGpio: Gpio private set lateinit var dcGpio: Gpio private set fun gpioInit(){ val manager: PeripheralManager = PeripheralManager.getInstance() busyGpio = manager.openGpio(EPD_BUSY_PIN) resetGpio = manager.openGpio(EPD_RST_PIN) dcGpio = manager.openGpio(EPD_DC_PIN) resetGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW) resetGpio.setActiveType(Gpio.ACTIVE_HIGH) dcGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW) dcGpio.setActiveType(Gpio.ACTIVE_HIGH) busyGpio.setDirection(Gpio.DIRECTION_IN) busyGpio.setActiveType(Gpio.ACTIVE_HIGH) } fun spiBegin(){ val manager: PeripheralManager = PeripheralManager.getInstance() spiDevice = manager.openSpiDevice(SPI_NAME) spiDevice.setMode(SpiDevice.MODE0) // Polarity = 0, phase = 0 spiDevice.setFrequency(SPI_SPEED) // Max speed in Hz spiDevice.setCsChange(false) spiDevice.setBitsPerWord(8) // 8 bits per clock cycle spiDevice.setBitJustification(SpiDevice.BIT_JUSTIFICATION_MSB_FIRST) // MSB first } fun moduleInit(){ gpioInit() spiBegin() } fun sendCommand(command: Int) { dcGpio.value = false val buffer = byteArrayOf((command and 0xFF).toByte()) spiDevice.write(buffer, buffer.size) } fun sendData(data: Int) { val buffer = byteArrayOf(data.toByte()) sendData(buffer) } fun sendData(data: ByteArray) { dcGpio.value = true for (b in data) { spiDevice.write(byteArrayOf(b), 1) } } @Throws(IOException::class) fun close() { resetGpio.value = false dcGpio.value = false spiDevice.close() busyGpio.close() resetGpio.close() dcGpio.close() } } /** * Convert bitmap to byte array using ByteBuffer. */ fun Bitmap.convertToByteArray(): ByteArray { val blob = ByteArrayOutputStream() this.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob) return blob.toByteArray() } fun Bitmap.toGreyScale(): Bitmap { val height = this.height val width = this.width val bmpMonochrome = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val canvas = Canvas(bmpMonochrome) val ma = ColorMatrix() ma.setSaturation(0f) val paint = Paint() paint.colorFilter = ColorMatrixColorFilter(ma) canvas.drawBitmap(this, 0f, 0f, paint) return bmpMonochrome }
2
Kotlin
0
1
77a53b938934c49bf4a03ce9bad14e4d71b4da2f
3,998
wsepdkdriver
Apache License 2.0
Outros/Exercicio69.kt
DenertSousa
613,699,145
false
null
/* Este programa carrega um array de 7 elementos inteiros e verifica a existência de elementos iguais a 30, mostrando as posições em que esses elementos apareceram. */ fun main () { var lista: Array<Int> = arrayOf(30,21,30,22,23,30,24) for (i: Int in lista.indices) { if (lista[i] == 30) println("O número 30 aparece nas posição $i") } }
0
Kotlin
0
0
6905448b0e662fafcc27316ac4390036d49d6b17
362
Programando-em-Kotlin
MIT License
search/ui/src/test/java/dev/vladimirj/tidal/search/ui/albums/AlbumsInteractions.kt
VladimirWrites
407,070,768
false
null
package dev.vladimirj.tidal.search.ui.albums import androidx.test.espresso.Espresso.onView import androidx.test.espresso.ViewInteraction import androidx.test.espresso.matcher.ViewMatchers.withId import dev.vladimirj.tidal.search.ui.R object AlbumsInteractions { fun snackbar(): ViewInteraction = onView(withId(com.google.android.material.R.id.snackbar_text)) fun noResultsView(): ViewInteraction = onView(withId(R.id.text_no_results)) }
0
Kotlin
0
2
512d67fc7e7a66efc920c93cd36cb4315140a132
446
TidalExample
Apache License 2.0
mobile_app1/module761/src/main/java/module761packageKt0/Foo9.kt
uber-common
294,831,672
false
null
package module761packageKt0; annotation class Foo9Fancy @Foo9Fancy class Foo9 { fun foo0(){ module761packageKt0.Foo8().foo3() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } }
6
null
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
229
android-build-eval
Apache License 2.0
app/src/main/java/com/nuhkoca/myapplication/data/remote/video/Pictures.kt
nuhkoca
166,842,702
false
null
package com.nuhkoca.myapplication.data.remote.video import androidx.databinding.BaseObservable import androidx.databinding.Bindable import com.google.gson.annotations.SerializedName import com.nuhkoca.myapplication.BR data class Pictures(@SerializedName("sizes") var _sizes: List<Size>) : BaseObservable() { var sizes: List<Size> @Bindable get() = _sizes set(value) { _sizes = value notifyPropertyChanged(BR.sizes) } }
1
Kotlin
9
62
9e373cd741cb243b0a1ce90c7ad88284941b56b1
474
DaggerExoPlayer
The Unlicense
feature-staking-impl/src/main/java/io/novafoundation/nova/feature_staking_impl/data/network/blockhain/bindings/HistoryDepth.kt
novasamatech
415,834,480
false
{"Kotlin": 7662708, "Java": 14723, "JavaScript": 425}
package io.novafoundation.nova.feature_staking_impl.data.network.blockhain.bindings import io.novafoundation.nova.common.data.network.runtime.binding.UseCaseBinding import io.novafoundation.nova.common.data.network.runtime.binding.bindNumber import io.novafoundation.nova.common.data.network.runtime.binding.fromHexOrIncompatible import io.novafoundation.nova.common.data.network.runtime.binding.storageReturnType import jp.co.soramitsu.fearless_utils.runtime.RuntimeSnapshot import java.math.BigInteger @UseCaseBinding fun bindHistoryDepth(scale: String, runtime: RuntimeSnapshot): BigInteger { val type = runtime.metadata.storageReturnType("Staking", "HistoryDepth") return bindNumber(type.fromHexOrIncompatible(scale, runtime)) }
13
Kotlin
5
9
66a5c0949aee03a5ebe870a1b0d5fa3ae929516f
744
nova-wallet-android
Apache License 2.0
src/test/kotlin/at/searles/parsing/grammar/RegexpGrammarTest.kt
searles
837,100,761
false
{"Kotlin": 80620}
package at.searles.parsing.grammar import at.searles.parsing.ParseSuccess import at.searles.parsing.PrintSuccess import at.searles.parsing.grammars.RegexpGrammar import at.searles.parsing.reader.CodePointSequence.Companion.asCodePointSequence import org.junit.jupiter.api.Assertions import kotlin.test.Test class RegexpGrammarTest { @Test fun `test simple regexp can be parsed`() { val regexpString = "[^0-9]+" // Act val regexp = RegexpGrammar.regexp.parse(regexpString.asCodePointSequence().toReader()) // Assert Assertions.assertTrue(regexp is ParseSuccess) } }
0
Kotlin
0
0
9124e3a6b394dcd6e395f75fe2ffc6bd807d0719
620
parsingKotlin
MIT License
src/server/DeepSeatServer/src/main/kotlin/com/deepseat/server/DeepSeatServer/service/LikedService.kt
seongjiko
456,172,826
false
null
package com.deepseat.server.DeepSeatServer.service import com.deepseat.server.DeepSeatServer.vo.Liked interface LikedService { fun insertLike(liked: Liked) fun getLikedById(likedID: Int): Liked? fun getLikedCountOfDocument(docID: Int): Int fun getLikedCountOfComment(commentID: Int): Int fun getLikedOfDocument(docID: Int, userID: String): Liked? fun getLikedOfComment(commentID: Int, userID: String): Liked? fun deleteLike(likedID: Int) fun deleteLikeFromDocument(docID: Int, userID: String) fun deleteLikeFromComment(commentID: Int, userID: String) }
0
Python
2
10
28f2dadc1960288f28ae046d5a95c206ea1f6ce9
591
DeepSeat_project
MIT License
dpadrecyclerview/src/main/java/com/rubensousa/dpadrecyclerview/layoutmanager/focus/FocusInterceptor.kt
rubensousa
530,412,665
false
{"Kotlin": 982902, "Shell": 2961}
/* * Copyright 2022 Rúben Sousa * * 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.rubensousa.dpadrecyclerview.layoutmanager.focus import android.view.View import com.rubensousa.dpadrecyclerview.DpadRecyclerView internal interface FocusInterceptor { /** * @param recyclerView the RecyclerView bound to the LayoutManager * @param focusedView the currently focused View * @param position the current pivot position * @param direction One of [View.FOCUS_LEFT], [View.FOCUS_RIGHT], [View.FOCUS_UP], * [View.FOCUS_DOWN], [View.FOCUS_FORWARD], [View.FOCUS_BACKWARD] */ fun findFocus( recyclerView: DpadRecyclerView, focusedView: View, position: Int, direction: Int ): View? }
8
Kotlin
17
91
64e8148a107887b58b91610d8fe51b468227b425
1,273
DpadRecyclerView
Apache License 2.0
src/jvmTest/kotlin/io/github/forceload/discordkt/TestBot.kt
forceload
551,748,435
false
{"Kotlin": 119782}
package io.github.forceload.discordkt import io.github.forceload.discordkt.command.argument.* import io.github.forceload.discordkt.type.DiscordLocale import io.github.forceload.discordkt.type.URLFile import io.github.forceload.discordkt.type.require suspend fun main() { bot(debug = true) { id = System.getenv("DISCORD_KT_TEST_USERID") token = System.getenv("DISCORD_KT_TEST_TOKEN") command("direct_message") { arguments( ("message" desc "Message to Send" to String.require prop { addChoice("Hello", "Hello").local(DiscordLocale.ko_KR to "인삿말") }).localDescription(DiscordLocale.ko_KR to "보낼 메시지") .localName(DiscordLocale.ko_KR to "메시지") ) description = "Send Direct Message to User" execute { println(arguments["message"]) } } command("attachment_test") { arguments( ("attachment" desc "Attachment to Test" to URLFile) .localName(DiscordLocale.ko_KR to "첨부파일") .localDesc(DiscordLocale.ko_KR to "테스트할 첨부파일") ) description = "" } }.runBlocking() }
0
Kotlin
3
5
806834c6d0cb8bbd0fa4bada99b0ffada44aaf22
1,253
discord.kt
MIT License
app/src/main/java/com/example/tophair/app/data/service/AuthInterceptor.kt
TOP-HAIR
774,715,222
false
{"Kotlin": 248739}
package com.example.tophair.app.data.service import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.runBlocking import okhttp3.Interceptor import okhttp3.Request object AuthInterceptor { private suspend fun getTokenFromDataStore(): String { return SessionManager.getTokenFlow().firstOrNull() ?: "seu_bearer_token_aqui" } fun interceptor(): Interceptor { return Interceptor { chain -> val originalRequest: Request = chain.request() val token = runBlocking { getTokenFromDataStore() } val requestBuilder: Request.Builder = originalRequest.newBuilder() .header("Authorization", "Bearer $token") val request: Request = requestBuilder.build() chain.proceed(request) } } }
0
Kotlin
1
0
4219e8ed9922f3cb0fed332cfd31a276152c797d
800
MB_TopHair.Android
MIT License
untitled/src/main/kotlin/aula4/Get_Set_Fild.kt
leticiasaraivafontenele
765,887,801
false
{"Kotlin": 38029, "Java": 9595}
//Função SET - Atribiu um valor ao campo correspondente //Função GET - Retornar um valor ao campo correspondente // Função Field - Evita chamadas infinitas class Planet(var nome: String){ private var id = 1 var tamanho = 1000 var fala = "terra" get(){ println("acessando Get") return field } set(value) { println("acessando set") field = value } } class Planeta2(){ var nome:String = "" get(){ println("meu valor é $field") return field } set(value) { if(value == ""){ println("Todo planeta tem nome") }else{ field = value } } } fun main() { var M :Planet = Planet("Marte") println("imprimindo tamanho: ${M.tamanho}") var P :Planet = Planet("Plutao") P.fala P.fala = "novo planeta plutao" var p2:Planeta2 = Planeta2() p2.nome = "" println(p2.nome) p2.nome = "Jupiter" println(p2.nome) }
0
Kotlin
0
0
8bbd3e7aa89ce1cb7e1ec213ad0197b87924d455
1,051
CursoIntroducao-Dev-Android
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/Grill.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Outline.Grill: ImageVector get() { if (_grill != null) { return _grill!! } _grill = Builder(name = "Grill", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(23.339f, 7.129f) arcTo(2.978f, 2.978f, 0.0f, false, false, 21.0f, 6.0f) lineTo(3.0f, 6.0f) curveToRelative(-6.654f, 1.04f, -0.636f, 9.791f, 2.833f, 11.341f) lineTo(4.053f, 22.684f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, 1.9f, 0.632f) lineTo(7.654f, 18.2f) arcTo(12.329f, 12.329f, 0.0f, false, false, 11.0f, 18.957f) lineTo(11.0f, 23.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 2.0f, 0.0f) lineTo(13.0f, 18.957f) arcToRelative(12.322f, 12.322f, 0.0f, false, false, 3.345f, -0.758f) lineToRelative(1.706f, 5.117f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, 1.9f, -0.632f) lineToRelative(-1.781f, -5.345f) curveTo(21.009f, 15.85f, 25.622f, 10.4f, 23.339f, 7.129f) close() moveTo(21.972f, 9.244f) curveTo(19.488f, 19.5f, 4.506f, 19.5f, 2.026f, 9.244f) arcTo(0.993f, 0.993f, 0.0f, false, true, 3.0f, 8.0f) lineTo(21.0f, 8.0f) arcTo(0.994f, 0.994f, 0.0f, false, true, 21.972f, 9.244f) close() moveTo(11.0f, 3.0f) lineTo(11.0f, 1.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 2.0f, 0.0f) lineTo(13.0f, 3.0f) arcTo(1.0f, 1.0f, 0.0f, false, true, 11.0f, 3.0f) close() moveTo(15.0f, 3.0f) lineTo(15.0f, 1.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, true, 2.0f, 0.0f) lineTo(17.0f, 3.0f) arcTo(1.0f, 1.0f, 0.0f, false, true, 15.0f, 3.0f) close() moveTo(7.0f, 3.0f) lineTo(7.0f, 1.0f) arcTo(1.0f, 1.0f, 0.0f, true, true, 9.0f, 1.0f) lineTo(9.0f, 3.0f) arcTo(1.0f, 1.0f, 0.0f, false, true, 7.0f, 3.0f) close() } } .build() return _grill!! } private var _grill: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,264
icons
MIT License
app/src/main/java/com/lordcommandev/traiveling/application/TrAIveling.kt
LordCommanDev
662,383,263
false
null
package com.lordcommandev.traiveling.application import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class TrAIveling: Application()
0
Kotlin
0
0
e55efea13e0436cba882fbddf7a85094eb140de2
171
Tr-AI-veling
MIT License
libs/angelos-core/src/commonTest/kotlin/angelos/sys/PlatformTest.kt
angelos-project
394,786,673
false
null
package angelos.sys import kotlin.test.Test import kotlin.test.assertContains import kotlin.test.assertNotEquals import kotlin.test.assertTrue class PlatformTest { @Test fun isUnknown() { val platform = Platform.UNKNOWN assertTrue(platform.isUnknown()) } @Test fun isPosix() { val platform = Platform.POSIX assertTrue(platform.isPosix()) } @Test fun isWindows() { val platform = Platform.WINDOWS assertTrue(platform.isWindows()) } @Test fun nativeApi() { assertContains(arrayOf(Platform.POSIX, Platform.WINDOWS), Platform.nativeApi()) } @Test fun testToString() { val platform = Platform.nativeApi() assertNotEquals(platform.toString(), "UNKNOWN") } }
0
Kotlin
0
1
2eae53621807a0a96c534fbdcb3b7782623286a5
789
angelos-core
MIT License
core/kmpp/libJs/src/jsMain/kotlin/com/kanastruk/mvi/ui/NavbarBrand.kt
kanawish
480,934,685
false
null
package com.kanastruk.mvi.ui import kotlinx.html.A sealed class NavbarBrand { data class Block(val block: A.()->Unit): NavbarBrand() data class Image(val src:String): NavbarBrand() data class Text(val text:String): NavbarBrand() data class ImageText(val src: String, val text: String): NavbarBrand() data class TextImage(val text:String, val src: String): NavbarBrand() }
0
Kotlin
1
1
7de3e167a4cd4f717ff5f7bf5d121c8d841b96bd
393
ks-community
MIT License
src/main/kotlin/com/github/seablue1/treeviewobject/main/PersistData.kt
seablue1
834,852,896
false
{"Kotlin": 41461}
package com.github.seablue1.treeviewobject.main import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.xmlb.XmlSerializerUtil @State(name = "PersistData", storages = [Storage("PersistData.xml")]) class PersistData : PersistentStateComponent<PersistData?> { override fun getState(): PersistData? { return this } override fun loadState(state: PersistData) { XmlSerializerUtil.copyBean(state, this) } companion object { val instance: PersistData get() = ApplicationManager.getApplication().getService(PersistData::class.java) } }
0
Kotlin
0
0
9d001926b01153cb7be4186245a1b2e494b59047
776
TreeViewObject
Apache License 2.0
src/main/kotlin/com/fujitsu/labs/challenge2021/SparqlQuery.kt
takanori-ugai
336,475,397
false
null
package com.fujitsu.labs.challenge2021 import org.apache.jena.query.Query import org.apache.jena.query.QueryExecution import org.apache.jena.query.QueryExecutionFactory import org.apache.jena.query.QueryFactory import org.apache.jena.query.ResultSet fun main(args: Array<String>) { val from = if (args.size == 0) { "http://kgc.knowledge-graph.jp/data/SpeckledBand" } else { args[0] } val queryString = """ PREFIX kgc: <http://kgc.knowledge-graph.jp/ontology/kgc.owl#> prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT DISTINCT * FROM <$from> #FROM <http://kgc.knowledge-graph.jp/data/SpeckledBand> #FROM <http://kgc.knowledge-graph.jp/data/DancingMen> #FROM <http://kgc.knowledge-graph.jp/data/ACaseOfIdentity> #FROM <http://kgc.knowledge-graph.jp/data/DevilsFoot> #FROM <http://kgc.knowledge-graph.jp/data/CrookedMan> #FROM <http://kgc.knowledge-graph.jp/data/AbbeyGrange> #FROM <http://kgc.knowledge-graph.jp/data/SilverBlaze> #FROM <http://kgc.knowledge-graph.jp/data/ResidentPatient> WHERE { ?s rdfs:label ?o . { ?s rdf:type kgc:Object . } UNION { ?s rdf:type kgc:OFobj . } UNION { ?s rdf:type kgc:PhysicalObject . } } """.trimIndent() val query: Query = QueryFactory.create(queryString) val qexec: QueryExecution = QueryExecutionFactory.sparqlService("http://kg.hozo.jp/fuseki/kgrc2020v2/sparql", query) val results: ResultSet = qexec.execSelect() printHeader() // ResultSetFormatter.out(System.out, results, query) val wikiFetch = FetchOnlineData() for (i in results) { val str = i.getLiteral("o").string // println(str) val tt = wikiFetch.getType(str) if (tt == "") { val list = wikiFetch.getClassList(wikiFetch.getId(str)) for (i2 in list) { val label4 = wikiFetch.getLabel(i2) val label3 = label4?.replace(" ", "_") println("<${i.getResource("s").uri}> rdfs:subClassOf fjs:$label3 .") println("fjs:$label3 a rdfs:Class .") println("fjs:$label3 rdfs:label \"$label4\"@en .") } } else { // println(tt) print("<${i.getResource("s").uri}> ") wikiFetch.printClassDefinition(tt) } } } fun printHeader() { println( "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n" + "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n" + "@prefix fjs: <http://challenge2021.labs.fujitsu.com/ontology/kgc.owl#> . \n" ) } class SparqlQuery
0
Kotlin
0
0
dee1605d297f0afaa644613872eb2922bf551c92
2,816
Challenge2021
MIT License
kblog/src/main/kotlin/io/kblog/service/ModelService.kt
hsdllcw
228,341,455
false
null
package io.kblog.service import io.kblog.domain.Base import io.kblog.domain.Model interface ModelService : BaseService<Model,Base.ModelVo>
0
Kotlin
0
1
659135e598e634b688e5bd31c98bec5a782c2a3f
140
KBlog
MIT License
news_kotlin_1_3/src/main/kotlin/09a_annotations.kt
yostane
167,272,961
false
{"Text": 3, "Gradle": 5, "Java Properties": 3, "Shell": 3, "Ignore List": 4, "Batchfile": 3, "Proguard": 1, "Kotlin": 23, "XML": 29, "Gradle Kotlin DSL": 2, "INI": 3, "Java": 2}
// In kotlin, we can definc static members and functions using a companion object interface OldKotlinCar { companion object { val nbWheels = 4 fun makeNoise() = "VROOM VROOM" } }
1
null
1
1
5796683474813e90e4bb9cba796f1c1ee2ed78de
202
meetup_kotlin_1_3
MIT License
src/main/kotlin/nl/orangeflamingo/voornameninliedjesbackendadmin/controller/UserController.kt
rweekers
52,724,950
false
null
package nl.orangeflamingo.voornameninliedjesbackendadmin.controller import nl.orangeflamingo.voornameninliedjesbackendadmin.domain.User import nl.orangeflamingo.voornameninliedjesbackendadmin.dto.UserDto import nl.orangeflamingo.voornameninliedjesbackendadmin.generic.InvalidCredentialsException import nl.orangeflamingo.voornameninliedjesbackendadmin.generic.ResponseError import nl.orangeflamingo.voornameninliedjesbackendadmin.generic.UserNotFoundException import nl.orangeflamingo.voornameninliedjesbackendadmin.generic.Utils.Companion.INVALID_CREDENTIALS import nl.orangeflamingo.voornameninliedjesbackendadmin.repository.UserRepository import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.security.access.prepost.PreAuthorize import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.web.bind.annotation.* import java.util.* @RestController @RequestMapping("/api") class UserController { private val log = LoggerFactory.getLogger(UserController::class.java) @Autowired private lateinit var userRepository: UserRepository @Autowired private lateinit var passwordEncoder: PasswordEncoder @PreAuthorize("hasRole('ROLE_OWNER')") @GetMapping("/users") @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun getUsers(): List<UserDto> { log.info("Requesting all users") return userRepository.findAll().map { convertToDto(it) } } @PostMapping("/authenticate") @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun authenticate(@RequestBody user: UserDto): ResponseEntity<UserDto> { log.info("Authenticating user ${user.username}") val dbUser = userRepository.findByUsername(username = user.username) ?: throw InvalidCredentialsException(INVALID_CREDENTIALS) if (!passwordEncoder.matches(user.password, dbUser.password)) { throw InvalidCredentialsException(INVALID_CREDENTIALS) } return ResponseEntity.of( Optional.of( UserDto( id = dbUser.id, username = dbUser.username, password = <PASSWORD>, roles = dbUser.roles ) ) ) } @ExceptionHandler(InvalidCredentialsException::class) fun handleInvalidCredentialsException(exception: InvalidCredentialsException): ResponseEntity<ResponseError> { return ResponseEntity(ResponseError(exception.message ?: "Onbekende fout"), HttpStatus.UNAUTHORIZED) } @ExceptionHandler(UserNotFoundException::class) fun handleUserNotFoundException(exception: UserNotFoundException): ResponseEntity<ResponseError> { return ResponseEntity(ResponseError(exception.message ?: "Onbekende fout"), HttpStatus.BAD_REQUEST) } @PreAuthorize("hasRole('ROLE_OWNER')") @GetMapping("/users/{id}") @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun getUserById(@PathVariable("id") id: String): UserDto { log.info("Requesting user with id $id") val user = userRepository.findById(id).orElseThrow { UserNotFoundException("User with $id not found") } return convertToDto(user) } @PreAuthorize("hasRole('ROLE_OWNER')") @PostMapping("/users") @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun newUser(@RequestBody newUser: UserDto): User { log.info("Requesting creation of new user ${newUser.username}") val user = convert(newUser) return userRepository.save(user) } @PreAuthorize("hasRole('ROLE_OWNER')") @DeleteMapping("/users/{userId}") @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun deleteUser(@PathVariable userId: String) { log.info("Deleting user with id $userId") userRepository.deleteById(userId) } private fun convert(userDto: UserDto): User { return User(userDto.id, userDto.username, passwordEncoder.encode(userDto.password), userDto.roles) } private fun convertToDto(user: User): UserDto { return UserDto(user.id, user.username, user.password, user.roles) } }
0
Kotlin
0
1
952322d3c88d8ab5a0b82273e016c8e1adca0cd6
4,461
voornameninliedjes-backend-admin
MIT License
src/org/jetbrains/r/refactoring/rename/RVariableInplaceRenameHandler.kt
Tryweirder
358,091,827
true
{"Kotlin": 2801208, "Java": 796605, "R": 30601, "CSS": 23692, "Lex": 14129, "HTML": 5680, "Rebol": 19}
/* * Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.r.refactoring.rename import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiNamedElement import com.intellij.refactoring.rename.inplace.VariableInplaceRenameHandler import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer import org.jetbrains.r.psi.RPsiUtil import org.jetbrains.r.psi.api.RForStatement import org.jetbrains.r.psi.api.RIdentifierExpression import org.jetbrains.r.psi.api.RPsiElement class RVariableInplaceRenameHandler : VariableInplaceRenameHandler() { override fun createRenamer(elementToRename: PsiElement, editor: Editor): VariableInplaceRenamer? { return RVariableInplaceRenamer(elementToRename as PsiNamedElement, editor) } override fun isAvailable(element: PsiElement?, editor: Editor, file: PsiFile): Boolean { if (element !is RPsiElement || RPsiUtil.isLibraryElement(element)) return false val parent = element.parent if (element is RIdentifierExpression && parent is RForStatement && parent.target == element) return true return super.isAvailable(element, editor, file) } }
0
null
0
0
30c2996d0c63c3f52a725ad7a74adcb6f29048af
1,296
Rplugin
Apache License 2.0
src/main/kotlin/dev/kahon/language/cairo/lsp/CairoLspServerDescriptor.kt
kahondev
707,663,895
false
{"Kotlin": 12661}
package dev.kahon.language.cairo.lsp import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.platform.lsp.api.Lsp4jClient import com.intellij.platform.lsp.api.LspServerNotificationsHandler import com.intellij.platform.lsp.api.ProjectWideLspServerDescriptor import com.intellij.platform.lsp.api.customization.LspFormattingSupport import dev.kahon.language.cairo.CairoBundle import dev.kahon.language.cairo.CairoFileType import dev.kahon.language.cairo.ide.showNotification import dev.kahon.language.cairo.settings.CairoSettings import dev.kahon.language.cairo.settings.CairoSettingsConfigurable import org.eclipse.lsp4j.MessageParams import org.eclipse.lsp4j.MessageType import org.eclipse.lsp4j.jsonrpc.services.JsonNotification import org.eclipse.lsp4j.services.LanguageServer import java.io.File class CairoLspServerDescriptor(project: Project) : ProjectWideLspServerDescriptor(project, "Cairo") { override fun isSupportedFile(file: VirtualFile) = file.fileType == CairoFileType override fun createCommandLine(): GeneralCommandLine { val settings = CairoSettings.getInstance(project) val scarbPath = settings.homePath if (!File(scarbPath).exists()) { showNotification( project = project, title = CairoBundle.message("settings.cairo.scarb.path.required.title"), content = CairoBundle.message("settings.cairo.scarb.path.required.content"), type = NotificationType.WARNING, NotificationAction.create(CairoBundle.message("settings.cairo.scarb.path.required.configure")) { _, notification -> ShowSettingsUtil.getInstance() .showSettingsDialog(project, CairoSettingsConfigurable::class.java) notification.expire() }, ) throw ExecutionException(CairoBundle.message("settings.cairo.scarb.not.found")) } return GeneralCommandLine().apply { withCharset(Charsets.UTF_8) withExePath(scarbPath) addParameter("cairo-language-server") addParameter("--stdio") } } override val lspGoToDefinitionSupport = true override val lspFormattingSupport = object : LspFormattingSupport() { override fun shouldFormatThisFileExclusivelyByServer( file: VirtualFile, ideCanFormatThisFileItself: Boolean, serverExplicitlyWantsToFormatThisFile: Boolean ) = file.fileType is CairoFileType } override fun createLsp4jClient(handler: LspServerNotificationsHandler): Lsp4jClient { val client = CairoLsp4jClient(handler) return client } override val lsp4jServerClass: Class<out LanguageServer> = CairoLanguageServer::class.java } class CairoLsp4jClient(handler: LspServerNotificationsHandler) : Lsp4jClient( handler ) { @JsonNotification("scarb/resolving-start") fun onResolvingStart() { this.showMessage(MessageParams(MessageType.Info, CairoBundle.message("scarb.resolving.start"))) } @JsonNotification("scarb/resolving-finish") fun onResolvingFinish() { this.showMessage(MessageParams(MessageType.Info, CairoBundle.message("scarb.resolving.finished"))) } }
0
Kotlin
0
2
e140e86214cba1ace6e6ba1b87cfaa79594bc604
3,606
cairo-jetbrains
MIT License
src_old/main/kotlin/com/pumpkin/core/Core.kt
FauxKiwi
315,724,386
false
null
package com.pumpkin.core import kotlinx.serialization.json.Json import org.lwjgl.system.MemoryStack data class Scope<out T : AutoCloseable>(private val value: T) : Referencable() { override fun destruct() { value.close() } operator fun invoke() = value } data class Ref<out T : AutoCloseable>(private val value: T) : Referencable() { @Volatile private var refCount = 0 init { refCount++ } override fun destruct() { release() } operator fun invoke() = value operator fun not() = refCount <= 0 fun take() = this.also { refCount++ } fun release() { if (--refCount <= 0) { value.close() Debug.logTraceCore("Released $value") } } } val jsonFormat = Json { prettyPrint = true } typealias Timestep = Float inline fun <R> stack(block: (memoryStack: MemoryStack) -> R): R = MemoryStack.stackPush().use(block) fun lifetimeScope(vararg scoped: AutoCloseable, block: () -> Unit) = block().also { scoped.forEach { it.close() } }
0
Kotlin
0
2
b384f2a430c0f714237e07621a01f094d9f5ee75
1,087
Pumpkin-Engine
Apache License 2.0
app/src/main/java/uk/nhs/nhsx/sonar/android/app/crypto/Constants.kt
nhsx
261,523,644
false
null
/* * Copyright © 2020 NHSX. All rights reserved. */ package uk.nhs.nhsx.sonar.android.app.crypto import org.bouncycastle.jce.provider.BouncyCastleProvider import java.nio.ByteBuffer val COUNTRY_CODE: ByteArray = ByteBuffer.wrap(ByteArray(2)).putShort(826.toShort()).array() const val PROVIDER_NAME = BouncyCastleProvider.PROVIDER_NAME const val ECDH = "ECDH" const val ELLIPTIC_CURVE = "EC" const val AES = "AES" const val AES_GCM_NoPadding = "AES/GCM/NoPadding" const val GCM_TAG_LENGTH = 128 const val EC_STANDARD_CURVE_NAME = "secp256r1"
0
Kotlin
146
793
ebcb3221b89333d9f555592aebc934d06608d784
546
COVID-19-app-Android-BETA
MIT License
kapi-openapi/src/commonMain/kotlin/com/chrynan/kapi/openapi/Encoding.kt
chRyNaN
608,768,233
false
null
package com.chrynan.kapi.openapi import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * A single encoding definition applied to a single schema property. * * This object MAY be extended with * [Specification Extensions](https://spec.openapis.org/oas/v3.1.0#specificationExtensions). * * ## Encoding Object Example * * ```yaml * requestBody: * content: * multipart/form-data: * schema: * type: object * properties: * id: * # default is text/plain * type: string * format: uuid * address: * # default is application/json * type: object * properties: {} * historyMetadata: * # need to declare XML format! * description: metadata in XML format * type: object * properties: {} * profileImage: {} * encoding: * historyMetadata: * # require XML Content-Type in utf-8 encoding * contentType: application/xml; charset=utf-8 * profileImage: * # only accept png/jpeg * contentType: image/png, image/jpeg * headers: * X-Rate-Limit-Limit: * description: The number of allowed requests in the current period * schema: * type: integer * ``` * * @property [contentType] The Content-Type for encoding a specific property. Default value depends on the property * type: for object - application/json; for array – the default is defined based on the inner type; for all other cases * the default is application/octet-stream. The value can be a specific media type (e.g. application/json), a wildcard * media type (e.g. image/\*), or a comma-separated list of the two types. * @property [headers] A map allowing additional information to be provided as headers, for example * Content-Disposition. Content-Type is described separately and SHALL be ignored in this section. This property SHALL * be ignored if the request body media type is not a multipart. * @property [style] Describes how a specific property value will be serialized depending on its type. See Parameter * Object for details on the style property. The behavior follows the same values as query parameters, including * default values. This property SHALL be ignored if the request body media type is not * application/x-www-form-urlencoded or multipart/form-data. If a value is explicitly defined, then the value of * contentType (implicit or explicit) SHALL be ignored. * @property [explode] When this is true, property values of type array or object generate separate parameters for each * value of the array, or key-value-pair of the map. For other types of properties this property has no effect. When * style is form, the default value is true. For all other styles, the default value is false. This property SHALL be * ignored if the request body media type is not application/x-www-form-urlencoded or multipart/form-data. If a value * is explicitly defined, then the value of contentType (implicit or explicit) SHALL be ignored. * @property [allowReserved] Determines whether the parameter value SHOULD allow reserved characters, as defined by * [RFC3986](https://spec.openapis.org/oas/v3.1.0#bib-RFC3986) :/?#[]@!$&'()*+,;= to be included without * percent-encoding. The default value is false. This property SHALL be ignored if the request body media type is not * application/x-www-form-urlencoded or multipart/form-data. If a value is explicitly defined, then the value of * contentType (implicit or explicit) SHALL be ignored. * * @see [OpenApi Specification](https://spec.openapis.org/oas/v3.1.0#encoding-object) */ @Serializable data class Encoding( @SerialName(value = "contentType") val contentType: String? = null, @SerialName(value = "headers") val headers: Map<String, ReferenceOrType<Header>>? = null, @SerialName(value = "style") val style: String? = null, @SerialName(value = "explode") val explode: Boolean = false, @SerialName(value = "allowReserved") val allowReserved: Boolean = false )
0
Kotlin
0
4
acc232ad59581eaea715268e6b1231c10471164b
4,197
kapi
Apache License 2.0
src/main/kotlin/com/study/avengersapi/application/web/resource/request/AvengerRequest.kt
Samuel-Ricardo
540,949,361
false
{"Kotlin": 8276, "Shell": 354}
package com.study.avengersapi.application.web.resource.request import com.study.avengersapi.domain.avenger.Avenger import org.jetbrains.annotations.NotNull import javax.validation.constraints.NotBlank import javax.validation.constraints.NotEmpty data class AvengerRequest( @field:NotNull @field:NotBlank @field:NotEmpty val nick: String, @field:NotNull @field:NotBlank @field:NotEmpty val person:String, val description: String? = null, val history: String? = null ) { fun toAvenger() = Avenger( nick = nick, person = person, description = description, history = history ) companion object { fun to(id: Long?, request: AvengerRequest) = Avenger( id = id, nick = request.nick, person = request.person, description = request.description, history = request.history ) } }
0
Kotlin
0
0
9125bc35ad3b6fe2f3d5dde81c4b60642aebaf63
937
avangers-api
MIT License
src/main/kotlin/org/sayner/student/jwtdemo/dto/request/BindEmployeeDto.kt
AlexanderSayner
297,734,193
false
null
package org.sayner.student.jwtdemo.dto.request data class BindEmployeeDto( val employeeId: Int, val bindId:Int )
0
Kotlin
0
0
251894d8cf674a73928080d170c7dcf33dfe03f9
130
JavaJWT
Apache License 2.0
app/src/main/java/name/lmj0011/courierlocker/database/ApartmentDao.kt
ashishkharcheiuforks
274,859,542
true
{"Kotlin": 253294}
package name.lmj0011.courierlocker.database import androidx.lifecycle.LiveData import androidx.room.* @Dao interface ApartmentDao: BaseDao { @Insert fun insert(apartment: Apartment) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAll(apartments: MutableList<Apartment>) @Update fun update(apartment: Apartment) @Query("SELECT * from apartments_table WHERE id = :key") fun get(key: Long): Apartment? @Query("DELETE FROM apartments_table") fun clear() @Query("SELECT * FROM apartments_table ORDER BY id DESC") fun getAllApartments(): LiveData<MutableList<Apartment>> @Query("DELETE from apartments_table WHERE id = :key") fun deleteByApartmentId(key: Long): Int @Delete fun deleteAll(apartments: MutableList<Apartment>) }
0
null
0
0
91de985cdcf7becff02d48747a09eb2ddd03d176
804
courier-locker
Apache License 2.0
sample-app/src/main/java/com/aminography/primecalendar/sample/MyApplication.kt
MiladYarmohammadi
206,528,202
true
{"Kotlin": 133739, "Java": 3252, "Shell": 57}
package com.aminography.primecalendar.sample import android.app.Application import android.support.v7.app.AppCompatDelegate /** * Created by aminography on 7/14/2018. */ @Suppress("unused") class MyApplication : Application() { override fun onCreate() { super.onCreate() AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) } }
0
null
0
0
0dde5354b5be6fc647ee6adb0132d8552f724619
364
PrimeCalendar
Apache License 2.0
platform/platform-impl/src/com/intellij/codeInsight/daemon/impl/HighlightingPassesCache.kt
radomirm-g
115,155,706
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInsight.daemon.impl import com.intellij.openapi.vfs.VirtualFile interface HighlightingPassesCache { fun loadPasses(files: List<VirtualFile>) }
1
null
1
1
4c461a784f8fa77287bc9b51b5dd0b887bb72b43
292
intellij-community
Apache License 2.0
platform/platform-impl/src/com/intellij/codeInsight/daemon/impl/HighlightingPassesCache.kt
radomirm-g
115,155,706
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInsight.daemon.impl import com.intellij.openapi.vfs.VirtualFile interface HighlightingPassesCache { fun loadPasses(files: List<VirtualFile>) }
1
null
1
1
4c461a784f8fa77287bc9b51b5dd0b887bb72b43
292
intellij-community
Apache License 2.0
katana-server/src/main/kotlin/jp/katana/server/event/player/MutablePlayerEvent.kt
hiroki19990625
194,672,872
false
null
package jp.katana.server.event.player import jp.katana.core.actor.IActorPlayer import jp.katana.core.event.IEvent abstract class MutablePlayerEvent(var player: IActorPlayer?) : IEvent
0
Kotlin
1
2
aab8ae69beed267ea0ef9eab2ebd23b994ac0f25
185
katana
MIT License
app/src/main/java/org/sehproject/sss/view/PlanInviteDialogFragment.kt
urarik
426,300,081
false
{"Kotlin": 225112}
package org.sehproject.sss.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.RecyclerView import org.sehproject.sss.R import org.sehproject.sss.databinding.FragmentPlanInviteBinding import org.sehproject.sss.view.dialog.DialogFragment import org.sehproject.sss.viewmodel.PlanViewModel class PlanInviteDialogFragment: DialogFragment() { private val safeArgs: PlanInviteDialogFragmentArgs by navArgs() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { planViewModel = ViewModelProvider(this).get(PlanViewModel::class.java) val inviteFriendBinding: FragmentPlanInviteBinding = DataBindingUtil.inflate(layoutInflater, R.layout.fragment_plan_invite, container, false) val recyclerView = inviteFriendBinding.searchRecyclerView initObserver(recyclerView, safeArgs.pid) if(!safeArgs.isInvite) inviteFriendBinding.buttonPlanInviteDone.text = "퇴장" inviteFriendBinding.isInvite = safeArgs.isInvite inviteFriendBinding.planLogic = planViewModel!!.planLogic inviteFriendBinding.pid = safeArgs.pid if(safeArgs.isInvite) planViewModel?.setFriendList(-1) else planViewModel?.setFriendList(safeArgs.pid) return inviteFriendBinding.root } fun initObserver(recyclerView: RecyclerView, pid: Int) { val navController = findNavController() planViewModel!!.invitePlanCompleteEvent.observe(viewLifecycleOwner, { navController.popBackStack() }) planViewModel!!.kickOutPlanCompleteEvent.observe(viewLifecycleOwner, { val action = PlanInviteDialogFragmentDirections.actionPlanInviteDialogFragmentToPlanDetailFragment(pid) navController.navigate(action) }) planViewModel?.friendListLiveData?.observe(viewLifecycleOwner, Observer { adapter = UserAdapter(it) recyclerView.adapter = adapter }) planViewModel!!.cancelInvitePlanEvent.observe(viewLifecycleOwner, Observer { navController.popBackStack() }) } }
0
Kotlin
1
2
f851dd57b2d6e350d02a58870b8d5b417a599d7e
2,493
SSS
MIT License
skulpt/src/main/java/org/skulpt/render/FilamentWindow.kt
timbrueggenthies
461,235,201
false
{"Kotlin": 29054}
package org.skulpt.render import android.view.Choreographer import android.view.Surface import android.view.SurfaceView import com.google.android.filament.Engine import com.google.android.filament.Renderer import com.google.android.filament.SwapChain import com.google.android.filament.android.DisplayHelper import com.google.android.filament.android.UiHelper import kotlinx.coroutines.awaitCancellation internal class FilamentWindow( private val sceneView: SceneView, private val engine: Engine, private val surfaceView: SurfaceView ) : Choreographer.FrameCallback { private val uiHelper: UiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK) private var displayHelper: DisplayHelper = DisplayHelper(surfaceView.context) private var swapChain: SwapChain? = null private lateinit var renderer: Renderer private var active: Boolean = false init { uiHelper.renderCallback = SurfaceCallback() uiHelper.attachTo(surfaceView) addDetachListener(surfaceView) } suspend fun resumeUntilCancelled() { Choreographer.getInstance().postFrameCallback(this) active = true try { awaitCancellation() } finally { Choreographer.getInstance().removeFrameCallback(this) } } override fun doFrame(frameTimeNanos: Long) { if (!active) return Choreographer.getInstance().postFrameCallback(this) render(frameTimeNanos) } private fun render(frameTimeNanos: Long) { if (!uiHelper.isReadyToRender) { return } // Render the scene, unless the renderer wants to skip the frame. if (renderer.beginFrame(swapChain!!, frameTimeNanos)) { sceneView.render(renderer) renderer.endFrame() } } private fun addDetachListener(view: android.view.View) { class AttachListener : android.view.View.OnAttachStateChangeListener { var detached = false override fun onViewAttachedToWindow(v: android.view.View?) { renderer = engine.createRenderer() detached = false } override fun onViewDetachedFromWindow(v: android.view.View?) { if (!detached) { uiHelper.detach() engine.destroyRenderer(renderer) detached = true } } } view.addOnAttachStateChangeListener(AttachListener()) } inner class SurfaceCallback : UiHelper.RendererCallback { override fun onNativeWindowChanged(surface: Surface) { swapChain?.let { engine.destroySwapChain(it) } swapChain = engine.createSwapChain(surface) displayHelper.attach(renderer, surfaceView.display) } override fun onDetachedFromSurface() { displayHelper.detach() swapChain?.let { engine.destroySwapChain(it) engine.flushAndWait() swapChain = null } } override fun onResized(width: Int, height: Int) { sceneView.onResized(width, height) } } }
0
Kotlin
0
0
6e83bddfddcb98e3fc9e58730f6ec3afb639259d
3,203
skulpt
Apache License 2.0
samples/client/3_1_0_unit_test/kotlin/src/main/kotlin/org/openapijsonschematools/client/schemas/validation/OneOfValidator.kt
openapi-json-schema-tools
544,314,254
false
{"Git Config": 1, "Ignore List": 17, "Maven POM": 7, "Dockerfile": 1, "Text": 15, "Git Attributes": 1, "Markdown": 2937, "Java": 2292, "OASv3-json": 4, "OASv2-json": 1, "OASv3-yaml": 193, "JSON": 65, "YAML": 55, "XML": 5, "OASv2-yaml": 2, "Python": 7593, "Handlebars": 848, "Mustache": 18, "Kotlin": 710, "INI": 10, "Shell": 38, "CODEOWNERS": 1, "JavaScript": 2, "Ruby": 2, "Dart": 1, "Batchfile": 1, "Gradle": 1, "Gradle Kotlin DSL": 7, "TOML": 5, "Makefile": 5, "AsciiDoc": 2}
package org.openapijsonschematools.client.schemas.validation import org.openapijsonschematools.client.exceptions.ValidationException class OneOfValidator : KeywordValidator { @Throws(ValidationException::class) override fun validate( data: ValidationData ): PathToSchemasMap? { val oneOf: List<Class<out JsonSchema<*>>> = data.schema.oneOf ?: return null val pathToSchemas = PathToSchemasMap() val validatedOneOfClasses: MutableList<Class<out JsonSchema<*>>> = ArrayList() for (oneOfClass in oneOf) { if (oneOfClass == data.schema.javaClass) { /* optimistically assume that schema will pass validation do not invoke validate on it because that is recursive */ validatedOneOfClasses.add(oneOfClass) continue } try { val oneOfSchema = JsonSchemaFactory.getInstance(oneOfClass) val otherPathToSchemas = JsonSchema.validate(oneOfSchema, data.arg, data.validationMetadata) validatedOneOfClasses.add(oneOfClass) pathToSchemas.update(otherPathToSchemas) } catch (e: ValidationException) { // silence exceptions because the code needs to accumulate validatedOneOfClasses } } if (validatedOneOfClasses.isEmpty()) { throw ValidationException( "Invalid inputs given to generate an instance of " + data.schema.javaClass + ". None " + "of the oneOf schemas matched the input data." ) } if (validatedOneOfClasses.size > 1) { throw ValidationException( "Invalid inputs given to generate an instance of " + data.schema.javaClass + ". Multiple oneOf schemas validated the data, but a max of one is allowed." ) } return pathToSchemas } }
1
Java
11
128
9006de722f74b7ca917e4e5d38e4cd6ab5ea6e78
1,981
openapi-json-schema-generator
Apache License 2.0
client/app/src/main/java/cn/xtev/netty/MainActivity.kt
liuhedev
139,215,206
false
null
package cn.xtev.netty import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.* /** * https://blog.gmem.cc/netty-study-note * https://blog.csdn.net/yulinxx/article/details/51085782 * @author liuhe * @date 2018-06-29 */ class MainActivity : AppCompatActivity() { private val TAG = MainActivity::class.java.simpleName override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btn_main_conn.setOnClickListener { connectServer() } } private fun connectServer() { val client = NettyClientThread() client?.start() } }
1
null
1
1
61e8d19e0c573a959b7c482f37bd31c5845882d2
719
NettyProject
Apache License 2.0
app/src/main/java/com/sukacolab/app/util/form/validators/NotEmptyValidator.kt
cahyadiantoni
757,308,387
false
{"Kotlin": 898794}
package com.sukacolab.app.util.form.validators import com.sukacolab.app.util.form.Validator class NotEmptyValidator<T>(errorText: String? = null) : Validator<T>( validate = { it != null }, errorText = errorText ?: "This field should not be empty" )
0
Kotlin
0
0
e189385bc897cfe187d87d70138e260027a1a640
270
sukacolab
MIT License
app/src/main/java/io/github/joaogouveia89/checkmarket/marketListItemCreate/ItemCreateViewModel.kt
joaogouveia89
842,192,758
false
{"Kotlin": 58445}
package io.github.joaogouveia89.checkmarket.marketListItemCreate import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import io.github.joaogouveia89.checkmarket.core.presentation.navigation.NEW_ITEM_NAME_KEY import javax.inject.Inject @HiltViewModel class ItemCreateViewModel @Inject constructor( savedStateHandle: SavedStateHandle ): ViewModel() { // Public for now val itemName = savedStateHandle.get<String>(key = NEW_ITEM_NAME_KEY) }
0
Kotlin
0
0
7a4c831668e4ec9d4cfecdca83c3feffb6469830
528
CheckMarket
MIT License
core/components/src/main/java/de/cleema/android/core/components/RemoteImageView.kt
sandstorm
840,235,083
false
{"Kotlin": 955115, "Ruby": 1773}
/* * Created by Kumpels and Friends on 2022-11-18 * Copyright © 2022 Kumpels and Friends. All rights reserved. */ package de.cleema.android.core.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.DefaultAlpha import androidx.compose.ui.graphics.drawscope.scale import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest @Composable fun RemoteImageView( remoteImage: de.cleema.android.core.models.RemoteImage?, modifier: Modifier = Modifier, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, colorFilter: ColorFilter? = null, alpha: Float = DefaultAlpha, ) { val painter = painterResource(R.drawable.ic_image_placeholder) val placeholder: (drawBackground: Boolean) -> Painter = { drawBackground -> forwardingPainter( painter = painter, colorFilter = ColorFilter.tint(Color.LightGray), alpha = 1f ) { info -> if (drawBackground) { drawRect(Color.LightGray.copy(alpha = 0.25f)) } scale(0.25f) { with(info.painter) { draw(size, info.alpha, info.colorFilter) } } } } remoteImage?.let { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(it.url) .crossfade(true) .build(), placeholder = placeholder(true), alignment = alignment, contentDescription = null, contentScale = contentScale, modifier = modifier.size(it.size.width.dp, it.size.height.dp), colorFilter = colorFilter, alpha = alpha ) } ?: androidx.compose.foundation.Image( painter = placeholder(false), contentDescription = null, modifier = modifier.background(Color.LightGray.copy(alpha = 0.25f)), colorFilter = colorFilter ) }
0
Kotlin
0
1
ddcb7ddedbbefb8045e7299e14a2ad47329fc53e
2,489
cleema-android
MIT License
src/main/kotlin/com/charlesmuchene/prefeditor/app/AppSetup.kt
charlesmuchene
744,829,675
false
{"Kotlin": 344385, "Shell": 5546}
/* * Copyright (c) 2024 <NAME> * * 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.charlesmuchene.prefeditor.app import com.charlesmuchene.prefeditor.bridge.Bridge import com.charlesmuchene.prefeditor.bridge.BridgeStatus import com.charlesmuchene.prefeditor.command.DesktopWriteCommand import com.charlesmuchene.prefeditor.files.EditorFiles import com.charlesmuchene.prefeditor.models.AppStatus import com.charlesmuchene.prefeditor.processor.Processor import com.charlesmuchene.prefeditor.screens.preferences.PreferenceWriter import com.charlesmuchene.prefeditor.screens.preferences.codec.PreferencesCodec import com.charlesmuchene.prefeditor.screens.preferences.desktop.AppPreferences import java.nio.file.Path import kotlin.io.path.pathString /** * Set app up * * TODO Add some DI framework if these get crazy! */ suspend fun appSetup( pathOverride: Path? = null, processor: Processor = Processor(), ): AppStatus { val codec = PreferencesCodec() EditorFiles.initialize(codec = codec, appPathOverride = pathOverride) val path = EditorFiles.preferencesPath(appPathOverride = pathOverride?.resolve(EditorFiles.ROOT_DIR)) val command = DesktopWriteCommand(path = path.pathString) val editor = PreferenceWriter(command = command, processor = processor) val preferences = AppPreferences(codec = codec, writer = editor, path = path).apply { initialize() } val appState = AppState(preferences = preferences) val bridgeStatus = Bridge(processor = processor) .checkBridge(executablePath = preferences.executable.path.value) return when (bridgeStatus) { is BridgeStatus.Available -> { appState.executable = bridgeStatus.path AppStatus.Ready(state = appState) } BridgeStatus.Unavailable -> AppStatus.NoBridge(state = appState) } }
0
Kotlin
0
1
ce64b4e889775cfd70176b8fa617c02ecb78150f
2,370
pref-editor-desktop
Apache License 2.0
konfigure/dsl/dsl.kt
rjhdby
139,546,129
false
null
package php.extension.dsl import php.extension.generator.Generator import php.extension.share.ArgumentType fun extension(name: String, version: String, body: Extension.() -> Unit = {}): Extension { val ext = Extension(name, version) ext.body() return ext } class Extension(val name: String, val version: String) { val functions = ArrayList<Function>() val constants = ArrayList<Constant>() val ini = ArrayList<Ini>() val classes = ArrayList<PhpClass>() fun function(name: String, type: ArgumentType = ArgumentType.PHP_NULL, body: Function.() -> Unit = {}) { val function = Function(name, type) function.body() functions.add(function) } fun constant(name: String, value: Any) { val constant = Constant(name, value) constants.add(constant) } fun ini(name: String, default: String) { ini.add(Ini(name, default)) } fun phpClass(name: String, body: PhpClass.() -> Unit = {}) { val phpClass = PhpClass(name) phpClass.body() classes.add(phpClass) } fun make(): String { Generator(this).generate() return name } } class Argument(val type: ArgumentType, val name: String, val isOptional: Boolean) { var firstOptional = false; } open class Constant(val name: String, value: Any?) { var type: ArgumentType = ArgumentType.PHP_NULL private var stringVal: String = "" private var longVal: Long = 0L private var doubleVal: Double = 0.0 private var boolVal: Boolean = false init { when (value) { null -> { type = ArgumentType.PHP_NULL } is String -> { type = ArgumentType.PHP_STRING stringVal = value } is Long -> { type = ArgumentType.PHP_LONG longVal = value } is Int -> { type = ArgumentType.PHP_LONG longVal = value.toLong() } is Double -> { type = ArgumentType.PHP_DOUBLE doubleVal = value } is Boolean -> { type = ArgumentType.PHP_BOOL boolVal = value } else -> type = ArgumentType.PHP_NULL } } fun getValue() = when (type) { ArgumentType.PHP_STRING -> "\"$stringVal\"" ArgumentType.PHP_LONG -> "$longVal" ArgumentType.PHP_STRICT_LONG -> "$longVal" ArgumentType.PHP_DOUBLE -> "$doubleVal" ArgumentType.PHP_BOOL -> if (boolVal) "1" else "0" ArgumentType.PHP_NULL -> "" ArgumentType.PHP_MIXED -> "" ArgumentType.PHP_ARRAY -> "" ArgumentType.PHP_OBJECT -> "" } } class Ini(val name: String, val default: String) //TODO typed INI
1
Kotlin
0
16
2b674554b075d840be269f3fb48aa585dd336324
2,914
kotlin-native-php-extension
MIT License
app/src/main/java/de/jepfa/yapm/service/autofill/CredentialFillService.kt
jenspfahl
378,141,282
false
null
package de.jepfa.yapm.service.autofill import android.os.Build import android.os.CancellationSignal import android.service.autofill.* import androidx.annotation.RequiresApi import de.jepfa.yapm.service.autofill.ResponseFiller.createFillResponse @RequiresApi(Build.VERSION_CODES.O) class CredentialFillService: AutofillService() { @RequiresApi(Build.VERSION_CODES.O) override fun onFillRequest( fillRequest: FillRequest, cancellationSignal: CancellationSignal, fillCallback: FillCallback ) { if (cancellationSignal.isCanceled) { fillCallback.onSuccess(null) return } val contexts = fillRequest.fillContexts val structure = contexts.get(contexts.size - 1).structure val fillResponse = createFillResponse(structure, allowCreateAuthentication = true, context = applicationContext) fillCallback.onSuccess(fillResponse) } override fun onSaveRequest(saveRequest: SaveRequest, saveCallback: SaveCallback) { } }
0
Kotlin
0
6
6e3735dfd5aebecb3fdb283e444cdab0247e511a
1,045
ANOTHERpass
MIT License
app/src/test/kotlin/org/artembogomolova/demo/webapp/test/domain/core/PhysicalAddressEntityTest.kt
bogomolov-a-a
307,182,964
false
null
package org.artembogomolova.demo.webapp.test.domain.core import org.artembogomolova.demo.webapp.main.domain.core.CountryCode import org.artembogomolova.demo.webapp.main.domain.core.PhysicalAddress import org.artembogomolova.demo.webapp.main.domain.core.PhysicalAddress_ import org.artembogomolova.demo.webapp.test.domain.AbstractAccessorEntityTest import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.DisplayName @DisplayName("Entity test: PhysicalAddress") internal class PhysicalAddressEntityTest : AbstractAccessorEntityTest<PhysicalAddress>( PhysicalAddress::class.java, PhysicalAddress::from ) { override fun buildStandardEntity(): PhysicalAddress = PhysicalAddress( postalCode = POSTAL_CODE_VALUE, countryCode = COUNTRY_CODE_VALUE, state = STATE_VALUE, city = CITY_VALUE, district = DISTRICT_VALUE, street = STREET_VALUE, house = HOUSE_VALUE, room = ROOM_VALUE, specificPart = SPECIFIC_PART_VALUE ) override fun containFieldCorrectValuesTest(standardEntity: PhysicalAddress) { Assertions.assertEquals(POSTAL_CODE_VALUE, standardEntity.postalCode) Assertions.assertEquals(COUNTRY_CODE_VALUE, standardEntity.countryCode) Assertions.assertEquals(STATE_VALUE, standardEntity.state) Assertions.assertEquals(CITY_VALUE, standardEntity.city) Assertions.assertEquals(DISTRICT_VALUE, standardEntity.district) Assertions.assertEquals(STREET_VALUE, standardEntity.street) Assertions.assertEquals(HOUSE_VALUE, standardEntity.house) Assertions.assertEquals(ROOM_VALUE, standardEntity.room) Assertions.assertEquals(SPECIFIC_PART_VALUE, standardEntity.specificPart) } override fun buildAnotherEntityForTest(): PhysicalAddress { val result = buildStandardEntity() with(result) { postalCode = "523152" countryCode = CountryCode.US city = "City1" house = "42" } return result } override fun withoutBasicConstraint(standardEntity: PhysicalAddress, columnName: String): Boolean { if (isCountryPartColumnName(columnName)) { return withoutCountryPartEqualTest(standardEntity, columnName) } if (isCityLevelPartColumnName(columnName)) { return withoutCityPartEqualTest(standardEntity, columnName) } return if (isHouseLevelPartColumnName(columnName)) { withoutHousePartEqualTest(standardEntity, columnName) } else false } private fun withoutHousePartEqualTest(standardEntity: PhysicalAddress, columnName: String): Boolean { return when (columnName) { PhysicalAddress_.HOUSE -> { withoutColumnEqualTest(standardEntity, PhysicalAddress::house) true } PhysicalAddress_.ROOM -> { withoutColumnEqualTest(standardEntity, PhysicalAddress::room) true } PhysicalAddress_.SPECIFIC_PART -> { withoutColumnEqualTest(standardEntity, PhysicalAddress::specificPart) true } else -> { false } } } private fun isHouseLevelPartColumnName(columnName: String): Boolean { return PhysicalAddress_.HOUSE == columnName || PhysicalAddress_.ROOM == columnName || PhysicalAddress_.SPECIFIC_PART == columnName } private fun withoutCityPartEqualTest(standardEntity: PhysicalAddress, columnName: String): Boolean { return when (columnName) { PhysicalAddress_.CITY -> { withoutColumnEqualTest(standardEntity, PhysicalAddress::city) true } PhysicalAddress_.DISTRICT -> { withoutColumnEqualTest(standardEntity, PhysicalAddress::district) true } PhysicalAddress_.STREET -> { withoutColumnEqualTest(standardEntity, PhysicalAddress::street) true } else -> { false } } } private fun isCityLevelPartColumnName(columnName: String): Boolean { return PhysicalAddress_.CITY == columnName || PhysicalAddress_.DISTRICT == columnName || PhysicalAddress_.STREET == columnName } private fun withoutCountryPartEqualTest(standardEntity: PhysicalAddress, columnName: String): Boolean { return when (columnName) { PhysicalAddress_.POSTAL_CODE -> { withoutColumnEqualTest(standardEntity, PhysicalAddress::postalCode) true } PhysicalAddress_.COUNTRY_CODE -> { withoutColumnEqualTest(standardEntity, PhysicalAddress::countryCode) true } PhysicalAddress_.STATE -> { withoutColumnEqualTest(standardEntity, PhysicalAddress::state) true } else -> false } } private fun isCountryPartColumnName(columnName: String): Boolean { return PhysicalAddress_.POSTAL_CODE == columnName || PhysicalAddress_.COUNTRY_CODE == columnName || PhysicalAddress_.STATE == columnName } companion object { private const val POSTAL_CODE_VALUE = "190000" private val COUNTRY_CODE_VALUE = CountryCode.RU private const val STATE_VALUE = "Saint Petersburg" private const val CITY_VALUE = "Saint Petersburg" private const val DISTRICT_VALUE = "District1" private const val STREET_VALUE = "Street1" private const val HOUSE_VALUE = "House1" private const val ROOM_VALUE = 10 private const val SPECIFIC_PART_VALUE = "SpecificPart1" } }
1
Kotlin
0
0
8b533b736e75ab2fca39888b3a3953e3810c121d
5,845
demo-spring-simple-webapp-with-tls
Apache License 2.0
src/main/kotlin/frc/kyberlib/math/units/test/Dim.kt
Kanishk-Pandey
625,399,371
false
null
package frc.kyberlib.math.units.test /** * Tate was messing around trying to have completely dynamic SI unit math. * Doesn't really work without creating a mess */ open class Dim { // the power of each unit open val angle = 0 open val length = 0 open val time = 0 open val temperature = 0 open val amount = 0 open val current = 0 open val luminosity = 0 open val mass = 0 private val powerMap get() = mapOf( "rad" to angle, "m" to length, "sec" to time, "K" to temperature, "amp" to current, "cd" to luminosity, "kg" to mass ) override fun toString(): String { val string = StringBuilder() powerMap.forEach { unit, power -> if (power > 1) string.append("$unit^$power") } return string.toString() } operator fun times(other: Dim): Dim { val caller = this return object : Dim() { override val angle = caller.angle + other.angle override val length = caller.length + other.length override val time = caller.time + other.time override val temperature = caller.temperature + other.temperature override val amount = caller.amount + other.amount override val current = caller.current + other.current override val luminosity = caller.luminosity + other.luminosity override val mass = caller.mass + other.mass } } operator fun div(other: Dim): Dim { val caller = this return object : Dim() { override val angle = caller.angle - other.angle override val length = caller.length - other.length override val time = caller.time - other.time override val temperature = caller.temperature - other.temperature override val amount = caller.amount - other.amount override val current = caller.current - other.current override val luminosity = caller.luminosity - other.luminosity override val mass = caller.mass - other.mass } } } object Unitless : Dim() // unitless Unit object Radian : Dim() { override val angle = 1 } // base unit for angle object Meter : Dim() { override val length = 1 } // base unit for length object Second : Dim() { override val time = 1 } // base unit for time object Kelvin : Dim() { override val temperature = 1 } // base unit for temp object Mole : Dim() { override val amount = 1 } // base unit for amount object Amp : Dim() { override val current = 1 } // base unit for current object Candela : Dim() { override val luminosity = 1 } // base unit for luminosity object Kilogram : Dim() { override val mass = 1 } // base unit for mass val unitKeyMap = mapOf( Radian::class.simpleName to Radian, Meter::class.simpleName to Meter, Second::class.simpleName to Second, Kelvin::class.simpleName to Kelvin, Mole::class.simpleName to Mole, Amp::class.simpleName to Amp, Candela::class.simpleName to Candela, Kilogram::class.simpleName to Kilogram )
0
Kotlin
0
0
e5d6c96397e1b4ab703e638db2361418fd9d4939
3,176
MyRoboticsCode
Apache License 2.0
shared/src/commonMain/kotlin/com/mocoding/pokedex/ui/main/MainScreen.kt
MohamedRejeb
606,436,499
false
{"Kotlin": 123809, "Swift": 6252, "Ruby": 2298}
package com.mocoding.pokedex.ui.main import androidx.compose.foundation.layout.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.outlined.Favorite import androidx.compose.material.icons.outlined.Home import androidx.compose.material.icons.rounded.Menu import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.mocoding.pokedex.ui.helper.LocalSafeArea import com.mocoding.pokedex.ui.main.components.MainContent import com.mocoding.pokedex.ui.main.components.MainModalDrawerSheet import com.mocoding.pokedex.ui.main.store.MainStore import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @Composable internal fun MainScreen(component: MainComponent) { val state by component.state.collectAsState() val items = listOf("Home" to Icons.Outlined.Home, "Favorite" to Icons.Outlined.Favorite) var selectedItem by remember { mutableStateOf(items[0]) } LaunchedEffect(selectedItem) { if (selectedItem.first == "Favorite") { component.onOutput(MainComponent.Output.FavoriteClicked) } } BoxWithConstraints { if (maxWidth > 1199.dp) { MainContentLarge( state = state, onEvent = component::onEvent, onOutput = component::onOutput, items = items, selectedItem = selectedItem, updateSelectedItem = { selectedItem = it } ) } else { MainContentDefault( state = state, onEvent = component::onEvent, onOutput = component::onOutput, items = items, selectedItem = selectedItem, updateSelectedItem = { selectedItem = it } ) } } } @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun MainContentDefault( state: MainStore.State, onEvent: (MainStore.Intent) -> Unit, onOutput: (MainComponent.Output) -> Unit, items: List<Pair<String, ImageVector>>, selectedItem: Pair<String, ImageVector>, updateSelectedItem: (Pair<String, ImageVector>) -> Unit ) { val scope = rememberCoroutineScope() val drawerState = rememberDrawerState(DrawerValue.Closed) ModalNavigationDrawer( drawerState = drawerState, drawerContent = { MainModalDrawerSheet( items = items, selectedItem = selectedItem, onItemsClick = { item -> scope.launch { drawerState.close() } updateSelectedItem(item) } ) }, content = { Scaffold( topBar = { TopAppBar( title = {}, navigationIcon = { IconButton( onClick = { scope.launch { drawerState.open() } }, ) { Icon(Icons.Rounded.Menu, contentDescription = null) } }, colors = TopAppBarDefaults.largeTopAppBarColors( containerColor = MaterialTheme.colorScheme.background ) ) }, modifier = Modifier.padding(LocalSafeArea.current) ) { paddingValues -> MainContent( state = state, onEvent = onEvent, onOutput = onOutput, modifier = Modifier.padding(paddingValues) ) } } ) } @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun MainContentLarge( state: MainStore.State, onEvent: (MainStore.Intent) -> Unit, onOutput: (MainComponent.Output) -> Unit, items: List<Pair<String, ImageVector>>, selectedItem: Pair<String, ImageVector>, updateSelectedItem: (Pair<String, ImageVector>) -> Unit ) { Row( modifier = Modifier.fillMaxWidth() ) { MainModalDrawerSheet( items = items, selectedItem = selectedItem, onItemsClick = { item -> updateSelectedItem(item) } ) Scaffold( topBar = { TopAppBar( title = {}, colors = TopAppBarDefaults.largeTopAppBarColors( containerColor = MaterialTheme.colorScheme.background ) ) }, modifier = Modifier.padding(LocalSafeArea.current) ) { paddingValues -> MainContent( state = state, onEvent = onEvent, onOutput = onOutput, modifier = Modifier.padding(paddingValues) ) } } }
4
Kotlin
48
569
e13c46fdcff7b21353019da9a85438e2088c529d
5,321
Pokedex
Apache License 2.0
core/src/main/kotlin/xyz/laxus/entities/starboard/Star.kt
LaxusBot
126,445,364
false
null
/* * Copyright 2018 <NAME> * * 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 xyz.laxus.entities.starboard import net.dv8tion.jda.core.entities.Message /** * @author <NAME> */ data class Star(val message: Message, val userId: Long)
1
Kotlin
1
11
9cb4362e282acfcff950adeb1911cbb5b81ef20a
755
Laxus
Apache License 2.0
account/data/src/commonMain/kotlin/com/amc/acieslinski/simplegiftapp/account/repository/AccountData.kt
acieslinski
777,244,363
false
{"Kotlin": 71875, "Swift": 15526}
package com.amc.acieslinski.simplegiftapp.account.repository data class AccountData( val name: String, val surname: String, val public: String, val private: String, )
0
Kotlin
0
0
b8f62adb8b31d612df1cc222302d787816224cf4
183
simplegiftapp
Apache License 2.0
modules/logging-testdouble/src/main/java/uk/gov/logging/testdouble/di/CrashLoggerModule.kt
govuk-one-login
784,723,752
false
{"Kotlin": 128828, "Shell": 1822, "Ruby": 1232}
package uk.gov.logging.testdouble.di import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton import uk.gov.logging.api.CrashLogger import uk.gov.logging.testdouble.FakeCrashLogger @InstallIn(SingletonComponent::class) @Module interface CrashLoggerModule { @Binds @Singleton fun bindsCrashLogger(logger: FakeCrashLogger): CrashLogger }
3
Kotlin
0
2
dd1fccefe4f48fed029941c0c7f4500b75796a8b
443
mobile-android-logging
MIT License
app/src/main/java/com/wreckingballsoftware/fiveoclocksomewhere/ui/theme/CustomType.kt
leewaggoner
691,900,392
false
{"Kotlin": 68083}
package com.wreckingballsoftware.fiveoclocksomewhere.ui.theme import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.sp data class CustomTypeStyles( val fiveTitle: TextStyle = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Bold, fontSize = 32.sp, lineHeight = 40.sp, textAlign = TextAlign.Center, ), val fiveSubtitle: TextStyle = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 24.sp, lineHeight = 28.sp, textAlign = TextAlign.Center, ), val fiveBody: TextStyle = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 20.sp, lineHeight = 24.sp, textAlign = TextAlign.Center, ), val fiveInstructions: TextStyle = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 20.sp, textAlign = TextAlign.Center, ) ) val FiveCustomTypography = CustomTypeStyles() val LocalCustomTypography = staticCompositionLocalOf { CustomTypeStyles() } val MaterialTheme.customTypography: CustomTypeStyles @Composable @ReadOnlyComposable get() = LocalCustomTypography.current
0
Kotlin
0
0
9027cd1378daac84fe93ec6098414158ff876b32
1,671
fiveoclocksomewhere
Apache License 2.0
example/android/app/src/main/kotlin/com/hellobike/thrio_example/Native2Activity.kt
flutter-thrio
340,541,219
false
null
package com.hellobike.thrio_example import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import androidx.appcompat.app.AppCompatActivity import com.hellobike.flutter.thrio.navigator.PageNotifyListener import com.hellobike.flutter.thrio.navigator.RouteSettings import com.hellobike.flutter.thrio.navigator.ThrioNavigator import com.hellobike.thrio_example.databinding.ActivityNative2Binding import io.flutter.Log class Native2Activity : AppCompatActivity(), PageNotifyListener { private lateinit var binding: ActivityNative2Binding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityNative2Binding.inflate(LayoutInflater.from(this)) setContentView(binding.root) initView() } private fun initView() { binding.tvNative.text = "native 2" binding.btn10.setOnClickListener { ThrioNavigator.push("/biz2/flutter2", params = mapOf("k1" to 1), result = { Log.i("Thrio", "push result data $it") }, poppedResult = { Log.i("Thrio", "/biz2/native2 poppedResult call params $it") } ) } binding.btn11.setOnClickListener { ThrioNavigator.remove("/biz2/flutter2") { Log.i("Thrio", "push result data $it") } } binding.btn12.setOnClickListener { ThrioNavigator.push("/biz1/native1", params = mapOf("k1" to 1), result = { Log.i("Thrio", "push result data $it") }, poppedResult = { Log.i("Thrio", "/biz2/native2 poppedResult call params $it") } ) } binding.btn13.setOnClickListener { ThrioNavigator.remove("/biz1/native1") { Log.i("Thrio", "push result data $it") } } binding.btn20.setOnClickListener { ThrioNavigator.popTo("/biz1/native1") } binding.btn21.setOnClickListener { val intent = Intent(this, Native1Activity::class.java) startActivity(intent) } binding.btn3.setOnClickListener { ThrioNavigator.pop("native 2 popResult") } binding.btnNotifyAll.setOnClickListener { ThrioNavigator.notify(name = "notify_all_page") } } override fun onResume() { super.onResume() val data = intent.getSerializableExtra("NAVIGATION_ROUTE_SETTINGS") if (data != null) { @Suppress("UNCHECKED_CAST") RouteSettings.fromArguments(data as Map<String, Any?>)?.apply { binding.tvNative.text = "/biz2/native2 index $index" } } } override fun onNotify(name: String, params: Any?) { Log.i("Thrio", "/biz2/native2 onNotify name $name params $params") // result with url } }
4
null
29
226
6f1cffedd8772f7466e6c62504dad15b500c4d47
3,070
flutter_thrio
MIT License
kategory/src/main/kotlin/kategory/instances/Function0Bimonad.kt
klappvisor
96,400,685
true
{"Kotlin": 238183}
package kategory fun <A> (() -> A).k(): HK<Function0.F, A> = Function0(this) fun <A> HK<Function0.F, A>.ev(): () -> A = (this as Function0<A>).f // We don't we want an inherited class to avoid equivalence issues, so a simple HK wrapper will do data class Function0<out A>(internal val f: () -> A) : HK<Function0.F, A> { class F private constructor() companion object : Bimonad<Function0.F>, GlobalInstance<Bimonad<Function0.F>>() { override fun <A, B> flatMap(fa: HK<Function0.F, A>, f: (A) -> HK<Function0.F, B>): HK<Function0.F, B> = f(fa.ev().invoke()) override fun <A, B> coflatMap(fa: HK<Function0.F, A>, f: (HK<Function0.F, A>) -> B): HK<Function0.F, B> = { f(fa) }.k() override fun <A> pure(a: A): HK<Function0.F, A> = { a }.k() override fun <A> extract(fa: HK<Function0.F, A>): A = fa.ev().invoke() override fun <A, B> map(fa: HK<F, A>, f: (A) -> B): HK<F, B> = pure(f(fa.ev().invoke())) override fun <A, B> tailRecM(a: A, f: (A) -> HK<F, Either<A, B>>): HK<F, B> = Function0 { tailrec fun loop(thisA: A): B = f(thisA).ev().invoke().fold({ loop(it) }, { it }) loop(a) } } }
0
Kotlin
0
0
d1c8aa29cdfe751e30a79129bee3b7ed02cafb33
1,349
kategory
Apache License 2.0
app/src/main/java/cn/devifish/readme/util/RxJavaUtil.kt
Devifish
84,722,892
false
null
package cn.devifish.readme.util import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.functions.Consumer import io.reactivex.schedulers.Schedulers /** * Created by zhang on 2017/6/4. * */ object RxJavaUtil { fun <T> getObservable(observable: Observable<T>): Observable<T> { return observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun <T> safeObservable(observable: Observable<T>): Observable<T> { return getObservable(observable) .doOnError(Consumer<Throwable> { it.printStackTrace() }) } fun <T> getSingle(single: Single<T>): Single<T> { return single .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } }
4
Kotlin
2
6
8831724d33eb9191f790eacc05a1fef06615fcc0
884
ReadMe
Apache License 2.0
src/main/kotlin/no/nav/utils/EnvUtils.kt
navikt
505,610,197
false
null
package no.nav.utils import no.nav.personoversikt.utils.EnvUtils val appImage: String = EnvUtils.getConfig("NAIS_APP_IMAGE") ?: "N/A" private val prodClusters = arrayOf("prod-fss", "prod-sbs", "prod-gcp") fun isProd(): Boolean = prodClusters.contains(EnvUtils.getConfig("NAIS_CLUSTER_NAME")) fun isNotProd(): Boolean = !isProd()
2
Kotlin
0
0
59466d4a6a8fff5e9868f6a5a24988160abf2cdd
332
modia-robot-api
MIT License
lib_web/src/main/java/com/lqk/web/ui/bean/PackageBean.kt
liqiankun1229
540,239,882
false
{"Kotlin": 468060, "C++": 424646, "Java": 146925, "Makefile": 105248, "Dart": 63273, "Assembly": 39872, "C": 33166, "JavaScript": 23214, "HTML": 15122, "Roff": 12367, "CMake": 9830, "Ruby": 8128, "CSS": 2767, "Groovy": 2242, "Objective-C": 1745, "Python": 1072, "Shell": 534, "AIDL": 67}
package com.lqk.web.ui.bean import java.io.Serializable /** * @author LQK * @time 2022/2/24 11:32 * @remark */ /** * @param category * @param url 下载地址 * @param home 首页相对路径 */ data class VersionInfo( var appId: String = "", var category: String = "", var name: String = "", var url: String = "", var versionCode: String = "", var versionName: String = "", var home: String = "", var packageType: Int = 0, var onlineUrl: String = "", ) : Serializable data class BaseResponse( val msg: String, val code: Int, var data: VersionInfo? ) data class ResponsePackage( val msg: String, val code: Int, var data: MutableList<VersionInfo>? )
0
Kotlin
0
0
71a44b69d89f301a967ed0df112a04c6bbfbff3f
702
ComposeCalculator
Apache License 2.0
Remote/src/test/kotlin/com/revolutan/test/ExchangeRateFakeDataFactory.kt
EslamHussein
189,711,152
false
null
package com.revolutan.test import com.revolutan.data.model.ExchangeRateEntity import com.revolutan.remote.model.ExchangeRateModel import java.util.* import java.util.concurrent.ThreadLocalRandom import kotlin.collections.HashMap object ExchangeRateFakeDataFactory { private fun randomString() = UUID.randomUUID().toString() private fun randomDouble(): Double { return ThreadLocalRandom.current().nextDouble(0.0, 100.0 + 1) } fun exchangeRateModel(): ExchangeRateModel { val rates = HashMap<String, Double>() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() return ExchangeRateModel(base = randomString(), date = randomString(), rates = rates) } fun exchangeRateEntity(): ExchangeRateEntity { val rates = HashMap<String, Double>() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() rates[randomString()] = randomDouble() return ExchangeRateEntity(base = randomString(), date = randomString(), rates = rates) } }
0
Kotlin
0
0
31ae7289630eb0d08f10efd5102fa12405b84154
1,975
Revolut-Exchange
Apache License 2.0
app/src/main/java/com/persival/realestatemanagerkotlin/ui/search/SearchFragment.kt
persival001
664,734,716
false
{"Kotlin": 298609, "HTML": 54594}
package com.persival.realestatemanagerkotlin.ui.search import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.fragment.app.viewModels import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.persival.realestatemanagerkotlin.R import com.persival.realestatemanagerkotlin.databinding.FragmentSearchBinding import com.persival.realestatemanagerkotlin.utils.viewBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class SearchFragment : BottomSheetDialogFragment() { companion object { fun newInstance() = SearchFragment() } private val binding by viewBinding { FragmentSearchBinding.bind(it) } private val viewModel by viewModels<SearchViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.fragment_search, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Initialize the type of property array val items = resources.getStringArray(R.array.property_items) val adapter = ArrayAdapter(requireContext(), R.layout.dropdown_item, items) binding.typeTextView.setAdapter(adapter) // Reinitialize the list binding.clearButton.setOnClickListener { viewModel.onResetFilter() binding.typeTextView.setText("") binding.priceMinEditText.setText("") binding.priceMaxEditText.setText("") binding.areaMinEditText.setText("") binding.areaMaxEditText.setText("") } // Get the information's of property added by the user binding.okButton.setOnClickListener { // Retrieve selected chip for poi val selectedPoisChips = listOf( binding.schoolChip, binding.publicTransportChip, binding.hospitalChip, binding.shopChip, binding.greenSpacesChip, binding.restaurantChip ).filter { it.isChecked }.map { it.text.toString() } // Retrieve chip selected for time of sale val week = binding.weekChip val month = binding.monthChip val year = binding.yearChip // Get all information's val type = binding.typeTextView.text.toString() val minPrice = binding.priceMinEditText.text.toString().toIntOrNull() val maxPrice = binding.priceMaxEditText.text.toString().toIntOrNull() val minArea = binding.areaMinEditText.text.toString().toIntOrNull() val maxArea = binding.areaMaxEditText.text.toString().toIntOrNull() viewModel.setSearchCriteria(type, minPrice, maxPrice, minArea, maxArea) dismiss() } } override fun onStart() { super.onStart() val dialog = dialog as? BottomSheetDialog dialog?.let { val bottomSheet = it.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) bottomSheet?.let { sheet -> val behavior = BottomSheetBehavior.from(sheet) behavior.state = BottomSheetBehavior.STATE_EXPANDED } } } }
0
Kotlin
0
1
019c9a57efd914e6821f43c66769107679047dc9
3,596
RealEstateManagerKotlin
MIT License
app/src/main/java/xyz/ramil/searchingit/data/model/Response.kt
ramilxyz
342,149,422
false
null
package xyz.ramil.searchingit.data.model import com.google.gson.annotations.SerializedName data class Response( @SerializedName("total_count") val totalCount: Int?, @SerializedName("incomplete_results") val incompleteResults: Boolean?, val items: List<User>, )
0
Kotlin
0
0
230817fe1496beffb6306eed2468c687d68e5ebd
303
searchingit
Apache License 2.0
0376-wiggle-subsequence/0376-wiggle-subsequence.kt
javadev
601,623,109
false
{"Kotlin": 549966, "Java": 511}
class Solution { fun wiggleMaxLength(nums: IntArray): Int { var lt = 1 var gt = 1 for (i in 1 until nums.size) { if (nums[i - 1] < nums[i]) { lt = gt + 1 } else if (nums[i - 1] > nums[i]) { gt = lt + 1 } } return Math.max(lt, gt) } }
0
Kotlin
0
0
55c7493692d92e83ef541dcf6ae2e8db8d906409
350
leethub
MIT License
1.10.02-Exercise-Functions/app/src/test/java/com/study/android11002/ExampleUnitTest.kt
ferryyuwono
350,933,363
false
null
package com.study.android11002 import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { //TODO: Simplified function to single expression fun calculateAreaOfRectangle(width: Float, height: Float): Float { val area = width * height return area } @Test fun areaOfRectangle() { //TODO: Call function using named argument val areaOfRectangle = calculateAreaOfRectangle(14f, 12f) println("Area of Rectangle: $areaOfRectangle") assertEquals(4, 2 + 2) } //TODO: Create extension function for Int. Add `Int.` at the start of the function name //fun ...printSquareArea() { //TODO: Print Square value, access Int value by using `this` //println("Square Area: ${...}") //} @Test fun callExtensionFunction() { //Given width of the square is Int val widthOfSquare = 16 //TODO: Call Int extension function to print the square area assertEquals(4, 2 + 2) } }
0
Kotlin
0
2
3a42a3b1ca5d11e1dfb5c44c986d821fb211b803
1,174
android-beginner
Apache License 2.0
core/src/test/java/com/glucose/app/presenter/ContextAccessorsTest.kt
daemontus
56,345,819
false
null
package com.glucose.app.presenter import android.app.Activity import android.app.Application import com.github.daemontus.glucose.core.BuildConfig import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import kotlin.test.assertEquals import kotlin.test.assertFailsWith @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class, sdk = intArrayOf(21)) class ContextAccessorsTest { private val activity = setupEmptyActivity() private val host = MockPresenterHost(activity) @Test fun contextAccessors_validActivityAccess() { val p = object : SimplePresenter(host) { val activity by ParentActivity(EmptyActivity::class.java) } assertEquals(activity, p.activity) //Reified methods don't work with Jacoco for some reason... //assertEquals(activityRule.activity, p.getActivity<EmptyActivity>()) } class OtherActivity : Activity() @Test fun contextAccessors_invalidActivityAccess() { val p = object : SimplePresenter(host) { val activity by ParentActivity(OtherActivity::class.java) } assertFailsWith<ClassCastException> { p.activity } } @Test fun contextAccessors_validApplicationAccess() { val p = object : SimplePresenter(host) { val app by ParentApp(Application::class.java) } assertEquals(activity.application, p.app) } class OtherApp : Application() @Test fun contextAccessors_invalidApplicationAccess() { val p = object : SimplePresenter(host) { val app by ParentApp(OtherApp::class.java) } assertFailsWith<ClassCastException> { assertEquals(activity.application, p.app) } } }
8
Kotlin
1
1
c959d5d54e8b71661f0670dac9213a5f9f2b3405
1,854
glucose
MIT License
app/src/main/java/com/tawk/github_users/features/user_deatils/domain/enities/UserDetails.kt
baraaaljabban
652,369,699
false
null
package com.tawk.github_users.features.user_deatils.domain.enities data class UserDetails( val avatar_url: String?, val bio: Any?, val blog: String?, val company: Any?, val followers: Int?, val following: Int?, val login: String?, val name: String?, val note: String = "" )
0
Kotlin
0
0
2f856c41a67e1cb2c93328213a207cf8a5a59b09
310
android_assesst
MIT License