path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
756M
is_fork
bool
2 classes
languages_distribution
stringlengths
12
2.44k
content
stringlengths
6
6.29M
issues
float64
0
10k
main_language
stringclasses
128 values
forks
int64
0
54.2k
stars
int64
0
157k
commit_sha
stringlengths
40
40
size
int64
6
6.29M
name
stringlengths
1
100
license
stringclasses
104 values
persistence/src/main/java/io/github/reactivecircus/streamlined/persistence/StoryDaoImpl.kt
ReactiveCircus
233,422,078
false
null
package io.github.reactivecircus.streamlined.persistence import com.squareup.sqldelight.runtime.coroutines.asFlow import com.squareup.sqldelight.runtime.coroutines.mapToList import javax.inject.Inject import kotlinx.coroutines.flow.Flow internal class StoryDaoImpl @Inject constructor( private val queries: StoryEntityQueries, private val databaseConfigs: DatabaseConfigs, ) : StoryDao { override fun allStories(): Flow<List<StoryEntity>> { return queries.findAllStories().asFlow().mapToList(databaseConfigs.coroutineContext) } override fun headlineStories(): Flow<List<StoryEntity>> { return queries.findStories(isHeadline = true).asFlow() .mapToList(databaseConfigs.coroutineContext) } override fun nonHeadlineStories(): Flow<List<StoryEntity>> { return queries.findStories(isHeadline = false).asFlow() .mapToList(databaseConfigs.coroutineContext) } override fun storyById(id: Long): StoryEntity? { return queries.findStoryById(id).executeAsOneOrNull() } override suspend fun updateStories(forHeadlines: Boolean, stories: List<StoryEntity>) { queries.transaction { val ids = queries.findStoryIds(isHeadline = forHeadlines).executeAsList().toMutableSet() stories.forEach { val existingStoryId = queries.findStoryIdByTitleAndPublishedTime( title = it.title, publishedTime = it.publishedTime ).executeAsOneOrNull() if (existingStoryId != null) { ids -= existingStoryId queries.updateStory( title = it.title, publishedTime = it.publishedTime, author = it.author, description = it.description, url = it.url, imageUrl = it.imageUrl ) } else { queries.insertStory( title = it.title, source = it.source, author = it.author, description = it.description, url = it.url, imageUrl = it.imageUrl, publishedTime = it.publishedTime, isHeadline = forHeadlines ) } } ids.chunked(MAX_PARAMETERS_PER_STATEMENT).forEach { chunk -> // TODO check if the story to be deleted is bookmarked. // if bookmarked, remove all relevant records in StoryFilter but leave it in StoryEntity // otherwise delete (cascade?) it (and relevant records in other tables e.g. StoryFilter) queries.deleteStoriesByIds(chunk) } } } override suspend fun deleteAll() { queries.deleteAll() } override suspend fun deleteHeadlineStories() { queries.deleteHeadlineStories() } override suspend fun deleteNonHeadlineStories() { queries.deleteNonHeadlineStories() } }
2
Kotlin
5
70
64b3bddcfe66bb376770b506107e307669de8005
3,177
streamlined
Apache License 2.0
app/src/main/java/com/leokuyper/recipeexpress/RegisterFragment.kt
LukeRamsay
288,948,145
false
null
package com.leokuyper.recipeexpress import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.navigation.fragment.findNavController import com.google.android.gms.tasks.Task import com.google.firebase.auth.AuthResult import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.leokuyper.recipeexpress.databinding.FragmentRegisterBinding import kotlinx.android.synthetic.main.fragment_register.* class RegisterFragment : Fragment() { private lateinit var auth: FirebaseAuth private lateinit var binding: FragmentRegisterBinding private lateinit var db: FirebaseFirestore override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { auth = Firebase.auth db = Firebase.firestore binding = DataBindingUtil.inflate(inflater, R.layout.fragment_register, container, false) binding.registerSubmit.setOnClickListener { auth.createUserWithEmailAndPassword(binding.registerEmail.text.toString().trim(), binding.registerPassword.text.toString().trim()) .addOnCompleteListener { it: Task<AuthResult> -> if(!it.isSuccessful) return@addOnCompleteListener Log.d("Authentication", "The user was create successfully") val uid = FirebaseAuth.getInstance().uid ?: "" val user = hashMapOf( "username" to registerUsername.text.toString(), "email" to registerEmail.text.toString() ) db.collection("users") .document(uid) .set(user) .addOnSuccessListener { Log.d("Authentication", "The user was create successfully") findNavController().navigate(R.id.action_registerFragment_to_homeFragment) } .addOnFailureListener { Log.d("Authentication", "Saving user to Database Failed: ${it.message}") } } .addOnFailureListener { Log.d("Authentication", "The registration failed ${it.message}") Toast.makeText(context, "The registration failed ${it.message}", Toast.LENGTH_SHORT).show() } } binding.gotologinFragment.setOnClickListener { findNavController().navigate(R.id.action_registerFragment_to_loginFragment) } return binding.root } }
0
Kotlin
1
0
74b37983bf96e182c85e0538f54eac353910658d
2,986
Yummy
MIT License
compiler/tests-spec/testData/diagnostics/linked/expressions/constant-literals/real-literals/p-4/neg/2.1.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * KOTLIN DIAGNOSTICS SPEC TEST (NEGATIVE) * * SPEC VERSION: 0.1-100 * MAIN LINK: expressions, constant-literals, real-literals -> paragraph 4 -> sentence 2 * NUMBER: 1 * DESCRIPTION: Real literals with underscores before an exponent mark. */ // TESTCASE NUMBER: 1 val value_1 = <!ILLEGAL_UNDERSCORE!>0_E0<!> // TESTCASE NUMBER: 2 val value_2 = <!ILLEGAL_UNDERSCORE!>1.1_E2<!> // TESTCASE NUMBER: 3 val value_3 = <!ILLEGAL_UNDERSCORE!>.0__0_e-0___0<!> // TESTCASE NUMBER: 4 val value_4 = <!ILLEGAL_UNDERSCORE!>0__0.0_____e0f<!> // TESTCASE NUMBER: 5 val value_5 = <!ILLEGAL_UNDERSCORE!>9_______9______9_____9____9___9__9_9.0___E-1<!> // TESTCASE NUMBER: 6 val value_6 = <!FLOAT_LITERAL_CONFORMS_INFINITY, ILLEGAL_UNDERSCORE!>0_0_0_0_0_0_0_0_0_0.12345678___e+90F<!> // TESTCASE NUMBER: 7 val value_7 = <!ILLEGAL_UNDERSCORE!>1_2_3_4_5_6_7_8_9.2_3_4_5_6_7_8_9_e-0<!> // TESTCASE NUMBER: 8 val value_8 = <!ILLEGAL_UNDERSCORE!>456.5__e0_6<!> // TESTCASE NUMBER: 9 val value_9 = <!ILLEGAL_UNDERSCORE!>5.6_0_E+05F<!> // TESTCASE NUMBER: 10 val value_10 = <!ILLEGAL_UNDERSCORE!>6_54.76_5__e-4<!> // TESTCASE NUMBER: 11 val value_11 = <!FLOAT_LITERAL_CONFORMS_ZERO, ILLEGAL_UNDERSCORE!>9_____________87654321.0__e-9_8765432_____________1F<!> // TESTCASE NUMBER: 12 val value_12 = <!ILLEGAL_UNDERSCORE!>000000000000000000000000000000000000000000000000000000000000000000000000000000000000000___0.000000000000000000000000_e000000000000000000000000000000000000000000000000000000000000000_0F<!> // TESTCASE NUMBER: 13 val value_13 = <!ILLEGAL_UNDERSCORE!>0_000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0____E-0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000<!> // TESTCASE NUMBER: 14 val value_14 = <!FLOAT_LITERAL_CONFORMS_INFINITY, ILLEGAL_UNDERSCORE!>9999999999999999999999999999999999999999999_______________999999999999999999999999999999999999999999999.33333333333333333333333333333333333333333333333_333333333333333333333333333333333333333_e3_3f<!>
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
2,047
kotlin
Apache License 2.0
app/src/main/java/io/zluan/ghub/persistence/AccountDao.kt
zhaonian
217,457,102
false
null
package io.zluan.ghub.persistence import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import io.zluan.ghub.model.Account /** DB object for storing [Account]. */ @Dao interface AccountDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAndReplace(accountDao: Account): Long @Insert(onConflict = OnConflictStrategy.IGNORE) fun insertOrIgnore(accountDao: Account): Long // @Query("SELECT * FROM account WHERE account_id = :account_id") // fun searchByAccountId(accountId: Int): LiveData<Account> @Query(value = "SELECT * FROM account WHERE username = :username") fun searchByEmail(username: String): Account? }
4
Kotlin
1
6
3dfed1a2e86aeb519e5aae1da3a46f7815585255
724
GHub
Apache License 2.0
compiler/backend/src/org/jetbrains/kotlin/codegen/inlineClassesCodegenUtil.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.codegen import org.jetbrains.kotlin.codegen.state.GenerationState import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.load.kotlin.JvmPackagePartSource import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.resolve.descriptorUtil.classId import org.jetbrains.kotlin.resolve.descriptorUtil.inlineClassRepresentation import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedSimpleFunctionDescriptor import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny import org.jetbrains.kotlin.types.typeUtil.isTypeParameter import org.jetbrains.org.objectweb.asm.ClassReader import org.jetbrains.org.objectweb.asm.ClassVisitor import org.jetbrains.org.objectweb.asm.MethodVisitor import org.jetbrains.org.objectweb.asm.Opcodes import org.jetbrains.org.objectweb.asm.commons.Method fun KotlinType.isInlineClassWithUnderlyingTypeAnyOrAnyN(): Boolean { val classDescriptor = constructor.declarationDescriptor return classDescriptor is ClassDescriptor && classDescriptor.inlineClassRepresentation?.underlyingType?.isAnyOrNullableAny() == true } fun CallableDescriptor.isGenericParameter(): Boolean { if (this !is ValueParameterDescriptor) return false if (containingDeclaration is AnonymousFunctionDescriptor) return true val index = containingDeclaration.valueParameters.indexOf(this) return containingDeclaration.overriddenDescriptors.any { it.original.valueParameters[index].type.isTypeParameter() } } fun classFileContainsMethod(descriptor: FunctionDescriptor, state: GenerationState, method: Method): Boolean? { if (descriptor !is DeserializedSimpleFunctionDescriptor) return null if (descriptor.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) { return descriptor.overriddenDescriptors.any { classFileContainsMethod(it, state, method) == true } } val classId: ClassId = when { descriptor.containingDeclaration is DeserializedClassDescriptor -> { (descriptor.containingDeclaration as DeserializedClassDescriptor).classId ?: return null } descriptor.containerSource is JvmPackagePartSource -> { @Suppress("USELESS_CAST") // K2 warning suppression, TODO: KT-62472 (descriptor.containerSource as JvmPackagePartSource).classId } else -> { return null } } return classFileContainsMethod(classId, state, method) } fun classFileContainsMethod(classId: ClassId, state: GenerationState, method: Method): Boolean? { val bytes = VirtualFileFinder.getInstance(state.project, state.module).findVirtualFileWithHeader(classId) ?.contentsToByteArray() ?: return null var found = false ClassReader(bytes).accept(object : ClassVisitor(Opcodes.API_VERSION) { override fun visitMethod( access: Int, name: String?, descriptor: String?, signature: String?, exceptions: Array<out String>? ): MethodVisitor? { if (name == method.name && descriptor == method.descriptor) { found = true } return super.visitMethod(access, name, descriptor, signature, exceptions) } }, ClassReader.SKIP_FRAMES) return found }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
3,774
kotlin
Apache License 2.0
libraries/stdlib/js/src/kotlin/js.core.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package kotlin.js /** * Exposes the JavaScript [undefined property](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) to Kotlin. */ public external val undefined: Nothing? /** * Exposes the JavaScript [eval function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) to Kotlin. */ public external fun eval(expr: String): dynamic
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
624
kotlin
Apache License 2.0
presentation/src/main/java/com/anytypeio/anytype/presentation/editor/CloseableCoroutineScope.kt
anyproto
647,371,233
false
{"Kotlin": 9971954, "Java": 69306, "Shell": 11126, "Makefile": 1276}
package com.anytypeio.anytype.presentation.editor import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import java.io.Closeable import kotlin.coroutines.CoroutineContext internal class CloseableCoroutineScope( context: CoroutineContext = SupervisorJob() + Dispatchers.Main.immediate ) : Closeable, CoroutineScope { override val coroutineContext: CoroutineContext = context override fun close() = coroutineContext.cancel() }
33
Kotlin
26
301
8b3b7dacae68c015fb8b1b7c9cc76e53f0706430
537
anytype-kotlin
RSA Message-Digest License
app/common/src/commonJvmMain/kotlin/com/denchic45/studiversity/domain/usecase/SubmitSubmissionUseCase.kt
denchic45
435,895,363
false
{"Kotlin": 2094557, "Vue": 10384, "JavaScript": 2497, "CSS": 1496, "HTML": 867}
package com.denchic45.studiversity.domain.usecase import com.denchic45.studiversity.data.repository.SubmissionRepository import com.denchic45.studiversity.domain.resource.Resource import com.denchic45.stuiversity.api.course.work.submission.model.SubmissionResponse import me.tatarka.inject.annotations.Inject import java.util.UUID @Inject class SubmitSubmissionUseCase(private val submissionRepository: SubmissionRepository) { suspend operator fun invoke(courseId: UUID, workId: UUID, submissionId: UUID): Resource<SubmissionResponse> { return submissionRepository.submitSubmission(courseId, workId, submissionId) } }
0
Kotlin
0
5
e68f0bfe27d0566002aec30fb6e44c96bc3a434d
634
Studiversity
Apache License 2.0
sample/src/main/java/com/sanogueralorenzo/sample/domain/Gif.kt
sanogueralorenzo
115,441,256
false
null
package com.sanogueralorenzo.sample.domain /** * Domain object allows mapping from a heavily nested response to a plain object */ data class Gif( val id: String, val url: String, val title: String, val username: String, val thumbnail: String, val original: String )
3
Kotlin
327
1,713
f5b02217549698acb13388c639b076e7de42868f
293
Android-Kotlin-Clean-Architecture
Apache License 2.0
app/src/main/java/villalobos/diego/x3dpark/MySpotsActivity.kt
DiegoVillalobosFlores
132,420,679
false
null
package villalobos.diego.x3dpark import android.content.Intent import android.location.Location import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.view.View import villalobos.diego.x3dpark.R import kotlinx.android.synthetic.main.activity_my_spots.* import villalobos.diego.x3dpark.Data.Coordinates import villalobos.diego.x3dpark.Data.User class MySpotsActivity : AppCompatActivity() { private lateinit var user: User private lateinit var coordinates: Coordinates override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_my_spots) setSupportActionBar(toolbar) user = intent.getSerializableExtra("user") as User coordinates = intent.getSerializableExtra("coordinates") as Coordinates } fun onAddSpotClicked(v: View){ val intent = Intent(this,HistoryActivity::class.java) intent.putExtra("user",user) startActivity(intent) } }
0
Kotlin
0
0
d2f167e414d9d093796fabf07f27f2ac44ff4f40
1,067
3DPark-Android
MIT License
agp-7.1.0-alpha01/tools/base/lint/libs/lint-tests/src/test/java/com/android/tools/lint/ReporterTest.kt
jomof
374,736,765
false
{"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277}
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.lint import com.android.tools.lint.Reporter.Companion.encodeUrl import com.android.tools.lint.checks.BuiltinIssueRegistry import com.android.tools.lint.client.api.LintClient import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Issue import junit.framework.TestCase import java.lang.reflect.Field class ReporterTest : TestCase() { override fun setUp() { LintClient.clientName = LintClient.CLIENT_UNIT_TESTS } fun testEncodeUrl() { assertEquals("a/b/c", encodeUrl("a/b/c")) assertEquals("a/b/c", encodeUrl("a\\b\\c")) assertEquals("a/b/c/%24%26%2B%2C%3A%3B%3D%3F%40/foo+bar%25/d", encodeUrl("a/b/c/$&+,:;=?@/foo bar%/d")) assertEquals("a/%28b%29/d", encodeUrl("a/(b)/d")) assertEquals("a/b+c/d", encodeUrl("a/b c/d")) // + or %20 } fun testHasQuickFix() { // This test is used to generate a list of detector+field names for the Reporter#hasAutoFix database. // List of issue id's where the unit test suite encountered a quickfix. This list can // be generated by applying a diff like this to TestLintClient, then running the test suite // and then picking up the unique (cat /tmp/fix.txt | sort | uniq) id's and pasting them // into the below string literal: /* diff --git a/lint/libs/lint-tests/src/main/java/com/android/tools/lint/checks/infrastructure/TestLintClient.java b/lint/libs/lint-tests/src/main/java/com/android/tools/lint/checks/infrastructure/TestLintClient.java index e21784a802..58b0c261b5 100644 --- a/lint/libs/lint-tests/src/main/java/com/android/tools/lint/checks/infrastructure/TestLintClient.java +++ b/lint/libs/lint-tests/src/main/java/com/android/tools/lint/checks/infrastructure/TestLintClient.java @@ -989,6 +989,14 @@ public class TestLintClient extends LintCliClient { Issue issue = incident.getIssue(); assertNotNull(location); + if (fix != null && !(fix instanceof LintFix.ShowUrl)) { + File file = new File("/tmp/fix.txt"); + FilesKt.appendText(file, incident.getIssue().getId(), kotlin.text.Charsets.UTF_8); + } + // Ensure that we're inside a read action if we might need access to PSI. // This is one heuristic; we could add more assertions elsewhere as needed. if (context instanceof JavaContext */ // Then run the below code with the list of issue id's to search for detector names and field references val ids = "" val registry = BuiltinIssueRegistry() val fieldMap = mutableMapOf<String, Field>() for (id in ids.split("\n")) { val issue = registry.getIssue(id) if (issue == null) { println("New issue found in the registry for $id") continue } val field = findField(issue) if (field != null) { fieldMap[id] = field } } for (id in ids.split("\n")) { val issue = registry.getIssue(id) ?: continue if (issue.category == Category.LINT) { continue } val field = fieldMap[id] ?: continue println(issue.implementation.detectorClass.simpleName + "." + field.name + ",") } } private fun findField( issue: Issue, ): Field? { val id = issue.id val clz: Class<*> = issue.implementation.detectorClass findField(id, clz)?.let { return it } try { val companion: Class<*> = Class.forName(clz.name + ".Companion") findField(id, companion)?.let { return it } } catch (ignore: Throwable) { } try { val companion: Class<*> = Class.forName(clz.name + ".Kt") findField(id, companion)?.let { return it } } catch (ignore: Throwable) { } return null } private fun findField( id: String, clz: Class<*> ): Field? { val fields = clz.declaredFields for (field in fields) { try { if (field.type == Issue::class.java) { field.isAccessible = true val issue = field.get(null) as? Issue if (issue?.id == id) { return field } } } catch (ignore: Throwable) { } } return null } }
1
Java
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
5,295
CppBuildCacheWorkInProgress
Apache License 2.0
build.gradle.kts
dremme
162,707,404
false
null
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { base kotlin("jvm") version "1.3.31" apply false } allprojects { repositories { jcenter() } group = "hamburg.remme" version = "1.0" } // Configure all KotlinCompile tasks on each sub-project subprojects { tasks.withType<KotlinCompile>().configureEach { println("Configuring $name in project ${project.name}...") kotlinOptions { jvmTarget = "12" suppressWarnings = true } } } dependencies { // Make the root project archives configuration depend on every subproject subprojects.forEach { archives(it) } }
11
Kotlin
0
1
9ad1434357e75c10e6f94ce0ed9f2c9f1ab5b745
680
lwjgl-engine-kotlin
MIT License
app/src/main/java/bapspatil/flickoff/ui/details/DetailsActivityModule.kt
bapspatil
102,198,607
false
null
package bapspatil.flickoff.ui.details import dagger.Module /* ** Created by <NAME> {@link https://bapspatil.com} */ @Module class DetailsActivityModule { }
3
Kotlin
6
31
f69aa21ab00443da552e1a9085295dfc52f5ae18
167
FlickOff
Apache License 2.0
app/src/main/java/com/alialfayed/weathertask/widget/WeatherWidget.kt
alfayedoficial
413,637,765
false
{"Kotlin": 99303}
package com.alialfayed.weathertask.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.widget.RemoteViews import com.alialfayed.weathertask.R import com.alialfayed.weathertask.core.utils.AppConstants.RELOAD_START import com.alialfayed.weathertask.core.utils.AppConstants.WEATHER_API_IMAGE_ENDPOINT import com.alialfayed.weathertask.core.utils.AppConstants.WIDGET_REQUEST_CODE import com.alialfayed.weathertask.core.utils.setLogCat import com.alialfayed.weathertask.data.ResultData import com.bumptech.glide.Glide import com.bumptech.glide.request.target.AppWidgetTarget import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject /** * Created by ( Eng <NAME>) * Class do : * Date 10/5/2021 - 1:51 AM */ @AndroidEntryPoint class WeatherWidget : AppWidgetProvider() { private var views: RemoteViews? = null private var appWidgetManage: AppWidgetManager? = null private var appWidgetId = 0 @Inject lateinit var widgetRepository: WidgetRepository override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { // There may be multiple widgets active, so update all of them for (appWidgetId in appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId) } } override fun onEnabled(context: Context) { // Enter relevant functionality for when the first widget is created } override fun onDisabled(context: Context) { // Enter relevant functionality for when the last widget is disabled } override fun onReceive(context: Context, intent: Intent) { super.onReceive(context, intent) if (RELOAD_START == intent.action) { views = RemoteViews(context.packageName, R.layout.widget_weather) views?.run { CoroutineScope(Dispatchers.Main.immediate).launch{ val result = withContext(Dispatchers.Main){ widgetRepository.getCities() } when (result) { is ResultData.Failure -> result.msg?.let { msg -> setLogCat("TEST_Widget" , msg)} is ResultData.Loading -> { } is ResultData.Internet -> { } is ResultData.Success -> { result.data?.let {models -> val model = models.first() setTextViewText(R.id.tvCity, model.name) setTextViewText(R.id.tvTemp, model.temp.toString()) val appWidgetTarget = AppWidgetTarget(context, R.id.imgWeather, views, appWidgetId) val iconCode = model.icon?.replace("n", "d") val margeLink = "${WEATHER_API_IMAGE_ENDPOINT}[email protected]" Glide.with(context.applicationContext) .asBitmap() .load(margeLink) .into(appWidgetTarget) }} } } appWidgetManage!!.updateAppWidget(appWidgetId, views) } } } fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) { this.appWidgetManage = appWidgetManager this.appWidgetId = appWidgetId views = RemoteViews(context.packageName, R.layout.widget_weather) views?.run { CoroutineScope(Dispatchers.Main.immediate).launch{ val result = withContext(Dispatchers.Main){ widgetRepository.getCities() } when (result) { is ResultData.Failure -> result.msg?.let { msg -> setLogCat("TEST_Widget" , msg)} is ResultData.Loading -> { } is ResultData.Internet -> { } is ResultData.Success -> { result.data?.let {models -> val model = models.first() setTextViewText(R.id.tvCity, model.name) setTextViewText(R.id.tvTemp, model.temp.toString()) val appWidgetTarget = AppWidgetTarget(context, R.id.imgWeather, views, appWidgetId) val iconCode = model.icon?.replace("n", "d") val margeLink = "${WEATHER_API_IMAGE_ENDPOINT}[email protected]" Glide.with(context.applicationContext) .asBitmap() .load(margeLink) .into(appWidgetTarget) }} } } // Instruct the widget manager to update the widget val intent = Intent(context, WeatherWidget::class.java) val pendingIntent = PendingIntent.getBroadcast(context, WIDGET_REQUEST_CODE, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) setOnClickPendingIntent(R.id.reload, getPendingSelfIntent(context, RELOAD_START)) appWidgetManager.updateAppWidget(appWidgetId, views) } } private fun getPendingSelfIntent(context: Context?, action: String?): PendingIntent { val intent = Intent(context, WeatherWidget::class.java) intent.action = action return PendingIntent.getBroadcast(context, WIDGET_REQUEST_CODE, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) } }
0
Kotlin
3
14
35613123fa86823e09e9e75c16638183628bee19
5,845
Code95_Weather_Task
The Unlicense
spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/docs/gradle/running/boot-run-system-property.gradle.kts
spring-projects
6,296,790
false
{"Java": 24755733, "Kotlin": 451737, "HTML": 58426, "Shell": 45767, "JavaScript": 33592, "Groovy": 15015, "Ruby": 8017, "Smarty": 2882, "Batchfile": 2145, "Dockerfile": 2102, "Mustache": 449, "Vim Snippet": 135, "CSS": 117}
import org.springframework.boot.gradle.tasks.run.BootRun plugins { java id("org.springframework.boot") version "{version}" } // tag::system-property[] tasks.named<BootRun>("bootRun") { systemProperty("com.example.property", findProperty("example") ?: "default") } // end::system-property[] tasks.register("configuredSystemProperties") { doLast { tasks.getByName<BootRun>("bootRun").systemProperties.forEach { k, v -> println("$k = $v") } } }
589
Java
40,158
71,299
c3b710a1f093423d6a3c8aad2a15695a2897eb57
457
spring-boot
Apache License 2.0
expresspay/src/main/java/com/expresspay/sdk/feature/adapter/ExpresspayBaseAdapter.kt
ExpresspaySa
589,460,465
false
{"Kotlin": 442513, "Java": 48886}
/* * Property of Expresspay (https://expresspay.sa). */ package com.expresspay.sdk.feature.adapter import androidx.viewbinding.BuildConfig import com.expresspay.sdk.core.ENABLE_DEBUG import com.expresspay.sdk.core.ExpresspayCredential import com.expresspay.sdk.model.response.base.ExpresspayResponse import com.expresspay.sdk.model.response.base.error.ExpresspayError import com.expresspay.sdk.toolbox.ExpresspayUtil import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.JsonObject import com.google.gson.reflect.TypeToken import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.json.JSONObject import retrofit2.Call import retrofit2.Callback import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory /** * The base Expresspay API Adapter. * * The [Retrofit] and [OkHttpClient] used for the async request. * The [Gson] serialize/deserialize the request/response bodies. * The [HttpLoggingInterceptor] logging all operation. Only in debug. * @see ExpresspayCallback * @see com.expresspay.sdk.feature.deserializer.ExpresspayBaseDeserializer * * @param Service the operation by the [com.expresspay.sdk.model.api.ExpresspayAction]. */ abstract class ExpresspayBaseAdapter<Service> { companion object { /** * Date format pattern in the Payment Platform. * Format: yyyy-MM-dd, e.g. 1970-02-17 */ private const val DATE_FORMAT = "yyyy-MM-dd HH:mm:ss" } /** * The [Service] instance. */ protected val service: Service private val gson: Gson init { val okHttpClientBuilder = OkHttpClient.Builder() if (BuildConfig.DEBUG || ENABLE_DEBUG) { val httpLoggingInterceptor = HttpLoggingInterceptor() httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC) okHttpClientBuilder.addInterceptor(httpLoggingInterceptor) } configureOkHttpClient(okHttpClientBuilder) val gsonBuilder = GsonBuilder() gsonBuilder.setPrettyPrinting() gsonBuilder.setDateFormat(DATE_FORMAT) configureGson(gsonBuilder) gson = gsonBuilder.create() val retrofitBuilder: Retrofit.Builder = Retrofit.Builder() .baseUrl(ExpresspayUtil.validateBaseUrl(ExpresspayCredential.paymentUrl())) .addConverterFactory(GsonConverterFactory.create(gson)) .client(okHttpClientBuilder.build()) configureRetrofit(retrofitBuilder) service = retrofitBuilder.build().create(provideServiceClass()) } /** * Provides the [Service] class. * * @return class by [Service]. */ protected abstract fun provideServiceClass(): Class<Service> /** * Configures the [OkHttpClient.Builder]. * * @param builder the [OkHttpClient.Builder]. */ protected open fun configureOkHttpClient(builder: OkHttpClient.Builder) = Unit /** * Configures the [GsonBuilder]. * * @param builder the [GsonBuilder]. */ protected open fun configureGson(builder: GsonBuilder) = Unit /** * Configures the [Retrofit.Builder]. * * @param builder the [Retrofit.Builder]. */ protected open fun configureRetrofit(builder: Retrofit.Builder) = Unit /** * Provides the response [TypeToken] for the custom deserializers. * @see com.expresspay.sdk.feature.deserializer * * @param Response the response type. */ protected inline fun <reified Response> responseType() = object : TypeToken<Response>() {}.type /** * Enqueues the default Retrofit [Callback] by the inner custom [expresspayCallback]. * Stands for providing the correct [Result] and [Response]. * @see ExpresspayResponse * @see ExpresspayError * * @param Result the result type for the [Response]. * @param Response the custom response type of the request. * @param expresspayCallback the custom [ExpresspayCallback]. */ @Suppress("UNCHECKED_CAST") protected fun <Result, Response : ExpresspayResponse<Result>> Call<Response>.expresspayEnqueue( expresspayCallback: ExpresspayCallback<Result, Response> ) { return enqueue(object : Callback<Response> { override fun onResponse(call: Call<Response>, response: retrofit2.Response<Response>) { val body = response.body() val errorBody = response.errorBody() when { body != null -> { expresspayCallback.onResponse(body) when (body) { is ExpresspayResponse.Result<*> -> expresspayCallback.onResult(body.result as Result) is ExpresspayResponse.Error<*> -> expresspayCallback.onError(body.error) else -> onFailure(call, IllegalAccessException()) } } errorBody != null -> { val json = gson.toJsonTree(errorBody.charStream()) val error = gson.fromJson(errorBody.charStream(), ExpresspayError::class.java) expresspayCallback.onResponse(ExpresspayResponse.Error<Result>(error, json.asJsonObject) as Response) expresspayCallback.onError(error) } else -> { onFailure(call, NullPointerException()) } } } override fun onFailure(call: Call<Response>, t: Throwable) { expresspayCallback.onFailure(t) } }) } }
0
Kotlin
2
0
8526a6a83fd0cdc5d11260521faf19c08260217d
5,713
expresspay-android-sdk-code
MIT License
app/src/main/java/com/artamonov/millionplanets/modules/ModulesAdapter.kt
Artikmars
160,610,860
false
null
package com.artamonov.millionplanets.modules import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.artamonov.millionplanets.R import com.artamonov.millionplanets.model.Module import com.artamonov.millionplanets.model.Weapon import kotlinx.android.synthetic.main.modules_items.view.* class ModulesAdapter( private val moduleList: List<Module>, private val existedItem: List<Weapon>, private val context: Context, private val listener: ItemClickListener ) : RecyclerView.Adapter<ModulesAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context) .inflate(R.layout.modules_items, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { // if (position == 3 || position == 4) { // holder.modulesPrice.setEnabled(false); // holder.modulesName.setEnabled(false); // // holder.modulesPrice.setBackgroundColor(context.getResources().getColor(R.color.grey)); // // holder.modulesName.setBackgroundColor(context.getResources().getColor(R.color.grey)); // } holder.bindItem() } override fun getItemCount(): Int { return moduleList.size } interface ItemClickListener { fun onItemClick(position: Int) } interface DialogListener { fun onDialogCreate() // void onDialogSubmit(); } inner class ViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindItem() { itemView.modules_name.text = moduleList[adapterPosition].name itemView.modules_price.text = moduleList[adapterPosition].price.toString() itemView.setOnClickListener { listener.onItemClick(adapterPosition) } } } }
0
Kotlin
0
0
3848081064753e28ec2f031ef2b20203685be82b
2,058
MillionPlanets
Apache License 2.0
library/src/test/kotlin/ua/pp/ihorzak/aktormailbox/TransformMailboxTest.kt
IhorZak
559,614,503
false
{"Kotlin": 32740}
/* * Copyright 2023 <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 ua.pp.ihorzak.aktormailbox import org.junit.jupiter.api.Assertions.assertFalse import org.mockito.Mockito.* import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull import kotlin.test.assertTrue /** * [TransformMailbox] unit tests. */ class TransformMailboxTest { @Test fun `isEmpty in initial state should return true`() { val mailbox = TransformMailbox<String, String> { input -> "Processed $input" } val result = mailbox.isEmpty assertTrue(result) } @Test fun `isEmpty after offer() should return false`() { val mailbox = TransformMailbox<String, String> { input -> "Processed $input" } mailbox.offer("Message 1") val result = mailbox.isEmpty assertFalse(result) } @Test fun `isEmpty after offer() and poll() should return true`() { val mailbox = TransformMailbox<String, String> { input -> "Processed $input" } mailbox.offer("Message 1") mailbox.poll() val result = mailbox.isEmpty assertTrue(result) } @Test fun `isEmpty after offer(), poll() and offer() should return false`() { val mailbox = TransformMailbox<String, String> { input -> "Processed $input" } mailbox.offer("Message 1") mailbox.poll() mailbox.offer("Message 2") val result = mailbox.isEmpty assertFalse(result) } @Test fun `offer() should call transform`() { val transform: (String) -> String = spy { input -> "Processed $input" } val mailbox = TransformMailbox(transform) val message = "Message 1" mailbox.offer(message) verify(transform, times(1)).invoke(message) } @Test fun `poll() in initial state should return null`() { val transform: (String) -> String = { input -> "Processed $input" } val mailbox = TransformMailbox(transform) val result = mailbox.poll() assertNull(result) } @Test fun `poll() after offer() should return transformed using transform value`() { val transform: (String) -> String = { input -> "Processed $input" } val mailbox = TransformMailbox(transform) val message = "Message 1" mailbox.offer(message) val result = mailbox.poll() assertEquals( expected = transform(message), actual = result, ) } @Test fun `poll() after offer() and poll() should return null`() { val transform: (String) -> String = { input -> "Processed $input" } val mailbox = TransformMailbox(transform) val message = "Message 1" mailbox.offer(message) mailbox.poll() val result = mailbox.poll() assertNull(result) } }
0
Kotlin
0
0
9cfa5647d87b76345cc8ff476ee99dbf71658218
3,397
aktor-mailbox
Apache License 2.0
domain/src/main/java/com/anytypeio/anytype/domain/table/FillTableRow.kt
anyproto
647,371,233
false
{"Kotlin": 9971954, "Java": 69306, "Shell": 11126, "Makefile": 1276}
package com.anytypeio.anytype.domain.table import com.anytypeio.anytype.core_models.Id import com.anytypeio.anytype.core_models.Payload import com.anytypeio.anytype.domain.base.BaseUseCase import com.anytypeio.anytype.domain.base.Either import com.anytypeio.anytype.domain.block.repo.BlockRepository class FillTableRow( private val repo: BlockRepository ) : BaseUseCase<Payload, FillTableRow.Params>() { override suspend fun run(params: Params): Either<Throwable, Payload> = safe { repo.fillTableRow( ctx = params.ctx, targetIds = params.targetIds ) } /** * @property [targetIds] the list of rows that need to be filled in */ data class Params( val ctx: Id, val targetIds: List<Id> ) }
33
Kotlin
26
301
8b3b7dacae68c015fb8b1b7c9cc76e53f0706430
779
anytype-kotlin
RSA Message-Digest License
src/main/kotlin/com/nibado/projects/advent/y2020/Day25.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2020 import com.nibado.projects.advent.* object Day25 : Day { private val input = resourceLines(2020, 25).map { it.toLong() } override fun part1() : Long { var a = 1L var b = 1L while(true) { a = (a * 7L) % 20201227L b = (b * input[1]) % 20201227L if(a == input[0]) { return b } } } override fun part2() = 0 }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
463
adventofcode
MIT License
src/day7/second/Solution.kt
verwoerd
224,986,977
false
null
package day7.second import day7.first.generatePermutations import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import tools.executeAsyncProgram import tools.readInput import tools.timeSolution fun main() = timeSolution { val code = readInput() val permutations = generatePermutations(mutableListOf(5, 6, 7, 8, 9)) val result = permutations.map { runBlocking { val queue1 = Channel<Int>(5) val queue2 = Channel<Int>(5) val queue3 = Channel<Int>(5) val queue4 = Channel<Int>(5) val queue5 = Channel<Int>(5) queue1.send(it[1]) queue2.send(it[2]) queue3.send(it[3]) queue4.send(it[4]) queue5.send(it[0]) queue5.send(0) async { executeAsyncProgram(code, queue5, queue1) }.start() async { executeAsyncProgram(code, queue1, queue2) }.start() async { executeAsyncProgram(code, queue2, queue3) }.start() async { executeAsyncProgram(code, queue3, queue4) }.start() withContext(Dispatchers.Default) { executeAsyncProgram(code.copyOf(), queue4, queue5) } Pair(it.joinToString(","), queue5.receive()) } }.maxBy(Pair<String, Int>::second) println(result) }
0
Kotlin
0
0
554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7
1,317
AoC2019
MIT License
app/src/main/java/com/nauka/dailyassistant/fragments/titleFragments/ThoughtsFragment.kt
RustamPlanirovich
329,459,039
false
null
package com.nauka.dailyassistant.fragments.titleFragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.nauka.dailyassistant.R class ThoughtsFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_thoughts, container, false) } }
0
Kotlin
0
0
63ea4c49b38edb2f3f8109cb82875099f8eecfa9
562
DailyAssistant
Apache License 2.0
src/com/wxx/design/design_22_bridge/Computer.kt
wuxinxi
192,182,654
false
null
package com.wxx.design.design_22_bridge /** * @author :DELL on 2021/5/13 . * @packages :com.wxx.design.design_22_bridge . * TODO:一句话描述 */ open abstract class Computer constructor(private val brand: IBrand) { open fun info() { print(brand.name()) } } class Desktop(val brand: IBrand) : Computer(brand) { override fun info() { super.info() println("台式机") } } class Laptop(val brand: IBrand) : Computer(brand) { override fun info() { super.info() println("笔记本") } }
0
Kotlin
0
0
1fef75f988f384fb5f9ace7087ccca3b00d587fb
562
DesignPatternsDemo
MIT License
app/src/main/java/dubizzle/android/com/moviedb/models/network/DiscoverMovieResponse.kt
alaa7731
166,552,388
false
null
package dubizzle.android.com.moviedb.models.network import dubizzle.android.com.moviedb.models.NetworkResponseModel import dubizzle.android.com.moviedb.models.entity.Movie data class DiscoverMovieResponse( val page: Int, val results: List<Movie>, val total_results: Int, val total_pages: Int ) : NetworkResponseModel
0
Kotlin
0
0
7133e8084051937030ffc994b7b2f05957b0de8b
352
MyMoviesDB
MIT License
src/ConstraintList.kt
jonward1982
350,285,956
true
{"Kotlin": 213021, "Java": 286}
fun<T: Number> List<MutableConstraint<T>>.numVars(): Int { return this.asSequence().map { it.numVars() }.max()?:0 } fun<T: Number> List<MutableConstraint<T>>.numSlacks(): Int { return this.count { it.relation != "==" } }
0
Kotlin
0
0
621d32d5e2d9d363c753d42cd1ede6b31195e716
230
AgentBasedMCMC
MIT License
sessions-core/src/main/java/com/adyen/checkout/sessions/model/setup/SessionSetupResponse.kt
leandromagnabosco
533,836,687
false
{"Kotlin": 1679112, "Shell": 1787}
/* * Copyright (c) 2022 <NAME>. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by josephj on 17/3/2022. */ package com.adyen.checkout.sessions.model.setup import android.os.Parcel import android.os.Parcelable import com.adyen.checkout.components.model.PaymentMethodsApiResponse import com.adyen.checkout.components.model.payments.Amount import com.adyen.checkout.core.exception.ModelSerializationException import com.adyen.checkout.core.model.JsonUtils import com.adyen.checkout.core.model.ModelObject import com.adyen.checkout.core.model.ModelUtils import org.json.JSONException import org.json.JSONObject data class SessionSetupResponse( val id: String, val sessionData: String, val amount: Amount?, val expiresAt: String, val paymentMethods: PaymentMethodsApiResponse?, val returnUrl: String ) : ModelObject() { override fun writeToParcel(parcel: Parcel, flags: Int) { JsonUtils.writeToParcel(parcel, SERIALIZER.serialize(this)) } companion object { private const val ID = "id" private const val SESSION_DATA = "sessionData" private const val AMOUNT = "amount" private const val EXPIRES_AT = "expiresAt" private const val PAYMENT_METHODS = "paymentMethods" private const val RETURN_URL = "returnUrl" @JvmField val CREATOR: Parcelable.Creator<SessionSetupResponse> = Creator(SessionSetupResponse::class.java) @JvmField val SERIALIZER: Serializer<SessionSetupResponse> = object : Serializer<SessionSetupResponse> { override fun serialize(modelObject: SessionSetupResponse): JSONObject { val jsonObject = JSONObject() try { jsonObject.putOpt(ID, modelObject.id) jsonObject.putOpt(SESSION_DATA, modelObject.sessionData) jsonObject.putOpt(AMOUNT, ModelUtils.serializeOpt(modelObject.amount, Amount.SERIALIZER)) jsonObject.putOpt(EXPIRES_AT, modelObject.expiresAt) jsonObject.putOpt( PAYMENT_METHODS, ModelUtils.serializeOpt(modelObject.paymentMethods, PaymentMethodsApiResponse.SERIALIZER) ) jsonObject.putOpt(RETURN_URL, modelObject.returnUrl) } catch (e: JSONException) { throw ModelSerializationException(SessionSetupResponse::class.java, e) } return jsonObject } override fun deserialize(jsonObject: JSONObject): SessionSetupResponse { return try { SessionSetupResponse( id = jsonObject.optString(ID), sessionData = jsonObject.optString(SESSION_DATA), amount = ModelUtils.deserializeOpt(jsonObject.optJSONObject(AMOUNT), Amount.SERIALIZER), expiresAt = jsonObject.optString(EXPIRES_AT), paymentMethods = ModelUtils.deserializeOpt( jsonObject.optJSONObject(PAYMENT_METHODS), PaymentMethodsApiResponse.SERIALIZER ), returnUrl = jsonObject.optString(RETURN_URL) ) } catch (e: JSONException) { throw ModelSerializationException(SessionSetupResponse::class.java, e) } } } } }
2
Kotlin
0
0
c154e989a08f1dc76cf90f6949878621cbbfa644
3,561
testsonarcloud
MIT License
src/main/kotlin/LetterBoxedPuzzleSolver.kt
Kyle-Falconer
671,044,954
false
null
import kotlinx.coroutines.* data class BoxedWords(val word: String, val remainingLetters: Set<Char>) : Comparable<BoxedWords> { override fun compareTo(other: BoxedWords): Int { return when { remainingLetters.size < other.remainingLetters.size -> -1 remainingLetters.size > other.remainingLetters.size -> 1 else -> { word.compareTo(other.word) } } } } class LetterBoxedPuzzleSolver( private val puzzle: LetterBoxedPuzzle, private val dictionary: Dictionary, private val threadCount: Int = 16 ) { @OptIn(ExperimentalCoroutinesApi::class) private val solverContext = Dispatchers.IO.limitedParallelism(threadCount) private var possibleWordPool = mutableListOf<BoxedWords>() fun findTopSolutions(stopEarly: Boolean = true): List<PuzzleSolutionResult> { possibleWordPool = findPossibleWords().sorted().toMutableList() // val partitionedPossibleWords = possibleWordPool.chunked(possibleWordPool.size / threadCount) // work on the top ~48 at a time val bufferSize = threadCount * 3 var startIndex = 0 var endIndex = bufferSize val deferredResults = mutableListOf<Deferred<Set<PuzzleSolutionResult?>>>() val solutions: MutableSet<PuzzleSolutionResult> = mutableSetOf() runBlocking { println("checking from indices $startIndex to $endIndex") val currentSubPool = possibleWordPool.subList(startIndex, endIndex) currentSubPool.forEach { dictWords -> deferredResults.add(async { checkWordsForSolution(dictWords) }) } deferredResults.forEach { result -> result.await().let { solutionSet -> solutionSet.filterIsInstance<ValidPuzzleSolution>().forEach { solutions.add(it) } } } if (stopEarly && solutions.any { result -> result is ValidPuzzleSolution }) { println("exiting solution checker loop because a solution has been found") return@runBlocking } startIndex = endIndex endIndex += bufferSize } val validSolutions = solutions.filterIsInstance<ValidPuzzleSolution>().sorted() println("found ${validSolutions.size} valid solutions, top=${validSolutions.firstOrNull()?.words?.stringify()}") return validSolutions } private suspend fun checkWordsForSolution(boxedWords: BoxedWords): Set<PuzzleSolutionResult> = withContext(solverContext) { val checker = LetterBoxedSolutionChecker(puzzle, dictionary) val lastLetter = boxedWords.word.last() val possibleNextWords = possibleWordPool.filter { it.word.first() == lastLetter } var bestAlternateSolution: IncompletePuzzleSolution? = null val possibleValidSolutions = mutableSetOf<ValidPuzzleSolution>() // just in case if (boxedWords.remainingLetters.isEmpty()) { val maybeSingleWordSolution = checker.checkSolution(listOf(boxedWords.word)) if (maybeSingleWordSolution is ValidPuzzleSolution) { println("found a solution in one word: ${boxedWords.word}") possibleValidSolutions.add(maybeSingleWordSolution) } checker.reset() } possibleNextWords.forEach { nextWord -> val wordList = listOf(boxedWords.word, nextWord.word) val slnResult = checker.checkSolution(wordList) when (slnResult) { is ValidPuzzleSolution -> { println("found solution with ${wordList.stringify()}") possibleValidSolutions.add(slnResult) } is IncompletePuzzleSolution -> { if (bestAlternateSolution == null || slnResult.remainingLetters.size < bestAlternateSolution!!.remainingLetters.size) { bestAlternateSolution = slnResult } } else -> {} } checker.reset() } if (possibleValidSolutions.isNotEmpty()) { return@withContext possibleValidSolutions } else if (bestAlternateSolution != null) { return@withContext setOf(bestAlternateSolution!!) } else { return@withContext setOf() } } private fun findPossibleWords(): List<BoxedWords> { val partitionedWords = dictionary.words.chunked(dictionary.words.size / threadCount) val result = mutableSetOf<BoxedWords>() val deferredResults = mutableListOf<Deferred<Set<BoxedWords>>>() runBlocking { partitionedWords.forEach { dictWords -> deferredResults.add(async { findPossibleWordsPartitioned(dictWords) }) } deferredResults.forEach { result.addAll(it.await()) } } val sortedResult = result.sorted() println("filtered the possible words down to ${sortedResult.size} from ${dictionary.words.size} dictionary words") return sortedResult } private suspend fun findPossibleWordsPartitioned(dictionaryWordsSection: List<String>): Set<BoxedWords> = withContext(solverContext) { val result = mutableSetOf<BoxedWords>() if (dictionaryWordsSection.isEmpty()) { return@withContext result } val checker = LetterBoxedSolutionChecker(puzzle, dictionary) dictionaryWordsSection.forEach { dWord -> when (val wordResult = checker.checkWord(dWord)) { is ValidWord -> { result.add(BoxedWords(dWord, wordResult.remainingLetters)) } is InvalidWord -> { // do nothing } } checker.reset() } println( "finished checking from words \"${dictionaryWordsSection.first()}\" " + "to \"${dictionaryWordsSection.last()}\", found ${result.size} valid words" ) return@withContext result } }
0
Kotlin
0
0
32f65f18067d686bb79cf84bdbb30bc880319124
6,578
LetterBoxedPuzzleSolver
Apache License 2.0
tests/aockt/y2021/Y2021D02Test.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2021 import io.github.jadarma.aockt.test.AdventDay import io.github.jadarma.aockt.test.AdventSpec @AdventDay(2021, 2, "Dive!") class Y2021D02Test : AdventSpec<Y2021D02>({ val exampleInput = """ forward 5 down 5 forward 8 up 3 down 8 forward 2 """.trimIndent() partOne { exampleInput shouldOutput 150 } partTwo { exampleInput shouldOutput 900 } })
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
430
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/io/github/trustedshops_public/spring_boot_starter_keycloak_path_based_resolver/configuration/holder.kt
trustedshops-public
524,078,409
false
{"Kotlin": 22803}
package io.github.trustedshops_public.spring_boot_starter_keycloak_path_based_resolver.configuration import org.keycloak.adapters.KeycloakDeployment import java.lang.IllegalArgumentException class MatcherConfiguration( private val parent: KeycloakPathContextConfigurationHolder, private val antPatterns: Array<out String> ) { /** * Configure keycloak deployment for the given antPatterns * * @see org.keycloak.adapters.KeycloakDeployment */ fun useKeycloakDeployment(keycloakDeployment: KeycloakDeployment): KeycloakPathContextConfigurationHolder { antPatterns .associateWith { keycloakDeployment } .forEach { (pattern, deployment) -> if (parent.mapping.containsKey(pattern)) { throw IllegalArgumentException("pattern '${pattern}' can not be assigned twice") } parent.mapping[pattern] = deployment } parent.mapping.putAll(antPatterns.associateWith { keycloakDeployment }) return parent } } /** * Configuration allowing to map given ant patterns to keycloak deployments */ class KeycloakPathContextConfigurationHolder { /** * Mapping, sorted by the longest string being the first in the map, so iteration always uses the most specific * matcher first */ internal val mapping = sortedMapOf<String, KeycloakDeployment>(compareBy<String> { -it.length }.thenBy { it }) /** * Configure context for given ant path matcher * * For more information check AntPathMatcher * @see org.springframework.util.AntPathMatcher */ fun antMatchers(vararg antPatterns: String): MatcherConfiguration = MatcherConfiguration(this, antPatterns) }
2
Kotlin
0
0
451885d836f596ae1423b78d9a7a873552b42e18
1,752
spring-boot-starter-keycloak-path-based-resolver
MIT License
src/test/kotlin/com/cillu/mediator/queries/domain/TestQuery2.kt
thecillu
520,490,197
false
{"Kotlin": 69256}
package com.cillu.mediator.queries.domain import com.cillu.mediator.queries.Query import java.util.* class TestQuery2(idEvent: UUID): Query(idEvent)
5
Kotlin
0
0
bd852463d1af35fb92be7fa853dfb7a7c85a66c8
153
mediatork
MIT License
src/main/kotlin/dev/arbjerg/lavalink/client/FunctionalLoadResultHandler.kt
lavalink-devs
642,292,256
false
{"Kotlin": 110289, "Java": 26629, "HTML": 414}
package dev.arbjerg.lavalink.client import dev.arbjerg.lavalink.client.protocol.LoadFailed import dev.arbjerg.lavalink.client.protocol.PlaylistLoaded import dev.arbjerg.lavalink.client.protocol.SearchResult import dev.arbjerg.lavalink.client.protocol.TrackLoaded import java.util.function.Consumer /** * Helper class for creating an [AbstractAudioLoadResultHandler] using only methods that can be passed as lambdas. * * @param trackLoadedConsumer gets called when a track has loaded * @param playlistLoadedConsumer gets called when a playlist has loaded * @param searchResultConsumer gets called when a search result has loaded * @param noMatchesHandler gets called when there are no matches for your input * @param loadFailedConsumer gets called in case of a load failure */ class FunctionalLoadResultHandler @JvmOverloads constructor( private val trackLoadedConsumer: Consumer<TrackLoaded>?, private val playlistLoadedConsumer: Consumer<PlaylistLoaded>? = null, private val searchResultConsumer: Consumer<SearchResult>? = null, private val noMatchesHandler: Runnable? = null, private val loadFailedConsumer: Consumer<LoadFailed>? = null, ) : AbstractAudioLoadResultHandler() { override fun ontrackLoaded(result: TrackLoaded) { trackLoadedConsumer?.accept(result) } override fun onPlaylistLoaded(result: PlaylistLoaded) { playlistLoadedConsumer?.accept(result) } override fun onSearchResultLoaded(result: SearchResult) { searchResultConsumer?.accept(result) } override fun noMatches() { noMatchesHandler?.run() } override fun loadFailed(result: LoadFailed) { loadFailedConsumer?.accept(result) } }
3
Kotlin
5
10
0bf628dc10499cef11fca1508f02ac5447aeb3f7
1,714
lavalink-client
MIT License
dispatcher/src/main/kotlin/pl/droidsonroids/testing/mockwebserver/Fixture.kt
willowtreeapps
412,033,826
true
{"Kotlin": 39922}
package pl.droidsonroids.testing.mockwebserver internal class Fixture { var statusCode = 0 internal set var body: String? = null internal set var headers: List<String> = emptyList() internal set internal fun hasJsonBody() = body?.isPossibleJson() ?: false }
0
Kotlin
0
0
f4544107368be2acd1e446c31759e6f92576e94e
301
mockwebserver-path-dispatcher
MIT License
livekit-android-sdk/src/main/java/io/livekit/android/webrtc/PeerConnectionExt.kt
Sahibjadatalib
434,121,768
true
{"Kotlin": 309477}
package io.livekit.android.webrtc import org.webrtc.PeerConnection /** * Completed state is a valid state for a connected connection, so this should be used * when checking for a connected state */ internal fun PeerConnection.isConnected(): Boolean { return when (iceConnectionState()) { PeerConnection.IceConnectionState.CONNECTED, PeerConnection.IceConnectionState.COMPLETED -> true else -> false } }
0
null
0
1
6c20b7c9224c7abffbb30fc399c8b4bd94fcd1f6
439
client-sdk-android
Apache License 2.0
data/slack-jackson-dto/src/main/kotlin/com/kreait/slack/api/contract/jackson/group/channels/SetTopic.kt
wudmer
214,514,160
true
{"Kotlin": 1205090, "Shell": 935}
package com.kreait.slack.api.contract.jackson.group.channels import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonSubTypes import com.fasterxml.jackson.annotation.JsonTypeInfo import com.kreait.slack.api.contract.jackson.common.types.Channel import com.kreait.slack.api.contract.jackson.util.JacksonDataClass @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "ok", visible = true) @JsonSubTypes( JsonSubTypes.Type(value = SuccessfulChannelsSetTopicResponse::class, name = "true"), JsonSubTypes.Type(value = ErrorChannelsSetTopicResponse::class, name = "false") ) @JacksonDataClass sealed class ChannelsSetTopicResponse constructor(@JsonProperty("ok") open val ok: Boolean) /** * Success-response of this request. * * @property ok will be true * @property channel the channel object with the changed topic */ @JacksonDataClass data class SuccessfulChannelsSetTopicResponse constructor(override val ok: Boolean, @JsonProperty("channel") val channel: Channel) : ChannelsSetTopicResponse(ok) { companion object } /** * Failure-response of this request * * @property ok will be false * @property error contains the error description */ @JacksonDataClass data class ErrorChannelsSetTopicResponse constructor(override val ok: Boolean, @JsonProperty("error") val error: String, @JsonProperty("detail") val detail: String) : ChannelsSetTopicResponse(ok) { companion object } /** * Sets the topic for a channel. * * @property channelId Channel to set the topic of * @property topic the topic you want to set */ @JacksonDataClass data class ChannelsSetTopicRequest constructor(@JsonProperty("channel") val channelId: String, @JsonProperty("topic") val topic: String) { companion object }
0
Kotlin
0
0
a46b9fcf8317d576133a4b1b4e64b89f6b3b1ca2
2,054
slack-spring-boot-starter
MIT License
core/src/main/java/me/syahdilla/putra/sholeh/story/core/CoreComponent.kt
adi-itgg
607,399,179
false
null
package me.syahdilla.putra.sholeh.story.core import android.content.Context import org.koin.core.annotation.ComponentScan import org.koin.core.annotation.Module import org.koin.core.component.KoinComponent import org.koin.core.component.inject @Module @ComponentScan("me.syahdilla.putra.sholeh") class CoreComponent: KoinComponent { val context: Context by inject() }
0
Kotlin
0
0
80ab31ed8387d71ea9493ca371f770209b2e7ec0
373
StoryAppDicoding
MIT License
scrimage-webp/src/test/kotlin/com/sksamuel/scrimage/webp/Gif2WebpTest.kt
sksamuel
10,459,209
false
{"Java": 441354, "Kotlin": 119638, "Scala": 60675}
package com.sksamuel.scrimage.webp import com.sksamuel.scrimage.nio.AnimatedGifReader import com.sksamuel.scrimage.nio.ImageSource import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe import java.io.File class Gif2WebpTest : FunSpec() { init { test("gif2webp writer") { AnimatedGifReader.read(ImageSource.of(File("src/test/resources/animated.gif"))) .bytes(Gif2WebpWriter.DEFAULT) shouldBe javaClass.getResourceAsStream("/animated.webp").readBytes() } } }
2
Java
137
997
2ca50e7e56fc491911e476b37cdde271f2f494fe
534
scrimage
Apache License 2.0
src/test/kotlin/no/nav/tilleggsstonader/sak/vilkår/vilkårperiode/VilkårperiodeExtensions.kt
navikt
685,490,225
false
{"Kotlin": 1224644, "HTML": 33935, "Gherkin": 11561, "Shell": 924, "Dockerfile": 164}
package no.nav.tilleggsstonader.sak.vilkår.vilkårperiode import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.domain.DelvilkårAktivitet import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.domain.DelvilkårMålgruppe import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.domain.DelvilkårVilkårperiode import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.domain.Vilkårperiode import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.dto.DelvilkårAktivitetDto import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.dto.DelvilkårMålgruppeDto import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.dto.VilkårperiodeDto import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.dto.VurderingDto import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.evaluering.ResultatEvaluering object VilkårperiodeExtensions { val Vilkårperiode.medlemskap: DelvilkårVilkårperiode.Vurdering get() = (this.delvilkår as DelvilkårMålgruppe).medlemskap val Vilkårperiode.lønnet: DelvilkårVilkårperiode.Vurdering get() = (this.delvilkår as DelvilkårAktivitet).lønnet val Vilkårperiode.mottarSykepenger: DelvilkårVilkårperiode.Vurdering get() = (this.delvilkår as DelvilkårAktivitet).mottarSykepenger val VilkårperiodeDto.medlemskap: VurderingDto? get() = (this.delvilkår as DelvilkårMålgruppeDto).medlemskap val VilkårperiodeDto.lønnet: VurderingDto? get() = (this.delvilkår as DelvilkårAktivitetDto).lønnet val VilkårperiodeDto.mottarSykepenger: VurderingDto? get() = (this.delvilkår as DelvilkårAktivitetDto).mottarSykepenger val ResultatEvaluering.medlemskap: DelvilkårVilkårperiode.Vurdering get() = (this.delvilkår as DelvilkårMålgruppe).medlemskap val ResultatEvaluering.lønnet: DelvilkårVilkårperiode.Vurdering get() = (this.delvilkår as DelvilkårAktivitet).lønnet val ResultatEvaluering.mottarSykepenger: DelvilkårVilkårperiode.Vurdering get() = (this.delvilkår as DelvilkårAktivitet).mottarSykepenger }
1
Kotlin
0
0
aa2388c76e5fa553c26b51f6266185715c783a75
2,090
tilleggsstonader-sak
MIT License
src/Day01.kt
kenyee
573,186,108
false
{"Kotlin": 57550}
fun main() { // ktlint-disable filename fun getTopCalories(input: List<String>): List<Int> { var elfCal = 0 val calorieSubtotals = mutableListOf<Int>() for (line in input) { if (line.isEmpty()) { calorieSubtotals.add(elfCal) elfCal = 0 } else { elfCal += line.toInt() } } // check last elf if (elfCal > 0) { calorieSubtotals.add(elfCal) } return calorieSubtotals.sortedDescending() } fun part1(input: List<String>): Int { val topCalories = getTopCalories(input) return topCalories.first() } fun part2(input: List<String>): Int { val topCalories = getTopCalories(input) return topCalories.take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") println("test result most calories is: ${part1(testInput)}") check(part1(testInput) == 24000) println("test result 3 max calories total is: ${part2(testInput)}") check(part2(testInput) == 45000) val input = readInput("Day01_input") println("Input data max calories is: ${part1(input)}") println("Input data 3 max calories total is: ${part2(input)}") }
0
Kotlin
0
0
814f08b314ae0cbf8e5ae842a8ba82ca2171809d
1,324
KotlinAdventOfCode2022
Apache License 2.0
RoomUdemy/app/src/main/java/ec/com/paul/roomudemy/db/entity/Professor.kt
PaulMarcelo
255,495,694
false
null
package ec.com.paul.roomudemy.db.entity import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey import ec.com.paul.roomudemy.constants.Constants /** * Created by <NAME> on 27/3/2019. * <NAME> */ @Entity(tableName = Constants.NAME_TABLE_PROFESSOR) class Professor { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id = 0 @ColumnInfo(name = "name") var name = "" @ColumnInfo(name = "email") var email = "" }
0
Kotlin
0
0
5c363e7e5837eaec8c43c1edf6eafa69ab84725d
550
Android
Apache License 2.0
app/src/main/java/com/ablec/myarchitecture/logic/rx/RxViewModel.kt
AbelChange
420,311,870
false
{"Kotlin": 210810, "Java": 26553, "CMake": 1695, "C++": 990, "AIDL": 931}
package com.ablec.myarchitecture.logic.rx import android.app.Application import androidx.lifecycle.AndroidViewModel open class RxViewModel (app: Application) : AndroidViewModel(app) { }
0
Kotlin
0
1
8157307ad46829db7565225a1c820ad7fe3f4a6d
195
MyArchiteture
Apache License 2.0
app/src/main/kotlin/com/flxrs/dankchat/data/api/ffz/dto/FFZEmoteSetDto.kt
SunRed
280,093,579
true
{"Kotlin": 793639}
package com.flxrs.dankchat.data.api.ffz.dto import androidx.annotation.Keep import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Keep @Serializable data class FFZEmoteSetDto(@SerialName(value = "emoticons") val emotes: List<FFZEmoteDto>)
0
Kotlin
0
0
7873e57a86a9ff5df99e19aaf954cf9afaef265d
269
DankChat
MIT License
core_library_common/src/iosMain/kotlin/net/apptronic/core/ios/anim/animations/BaseAnimations.kt
apptronicnet
264,405,837
false
null
package net.apptronic.core.ios.anim.animations import net.apptronic.core.ios.anim.ViewAnimationDefinition import net.apptronic.core.ios.anim.ViewTransformation import platform.UIKit.UIView import platform.UIKit.UIViewAnimationCurve import platform.UIKit.alpha import platform.UIKit.animateWithDuration object ViewAnimation_Empty : ViewAnimationDefinition() { override fun createTransformation(): ViewTransformation { return object : ViewTransformation() { override fun animate(target: UIView, container: UIView, duration: Double) { UIView.animateWithDuration(duration, animations = {}, completion = this::completed) } override fun cancel(target: UIView, container: UIView) { // do nothing } } } } object ViewAnimation_FadeIn : BasicViewAnimationDefinition() { override fun createBasicViewTransformation(): BasicViewTransformation { return object : BasicViewTransformation() { override fun animate(target: UIView, container: UIView, duration: Double) { target.prepareAnimation { alpha = 0.0 } startAnimation(duration) { target.alpha = 1.0 } } override fun cancel(target: UIView, container: UIView) { target.alpha = 1.0 } } } } object ViewAnimation_FadeOut : BasicViewAnimationDefinition() { override fun createBasicViewTransformation(): BasicViewTransformation { return object : BasicViewTransformation() { override fun animate(target: UIView, container: UIView, duration: Double) { target.prepareAnimation { alpha = 1.0 } startAnimation(duration) { target.alpha = 0.0 } } override fun cancel(target: UIView, container: UIView) { target.alpha = 1.0 } } } } class ViewAnimation_FromTop( val amount: Float = 1f, animationCurve: UIViewAnimationCurve = UIViewAnimationCurve.UIViewAnimationCurveLinear ) : BasicViewAnimationDefinition(animationCurve) { override fun createBasicViewTransformation(): BasicViewTransformation { return object : BasicViewTransformation() { override fun animate(target: UIView, container: UIView, duration: Double) { target.prepareAnimation { translateToParent(target, container, y = -amount) } startAnimation(duration) { translateToParent(target, container, y = 0f) } } override fun cancel(target: UIView, container: UIView) { translateToParent(target, container, y = 0f) } } } } class ViewAnimation_ToTop( val amount: Float = 1f, animationCurve: UIViewAnimationCurve = UIViewAnimationCurve.UIViewAnimationCurveLinear ) : BasicViewAnimationDefinition(animationCurve) { override fun createBasicViewTransformation(): BasicViewTransformation { return object : BasicViewTransformation() { override fun animate(target: UIView, container: UIView, duration: Double) { target.prepareAnimation { translateToParent(target, container, y = 0f) } startAnimation(duration) { translateToParent(target, container, y = -amount) } } override fun cancel(target: UIView, container: UIView) { translateToParent(target, container, y = 0f) } } } } class ViewAnimation_FromBottom( val amount: Float = 1f, animationCurve: UIViewAnimationCurve = UIViewAnimationCurve.UIViewAnimationCurveLinear ) : BasicViewAnimationDefinition(animationCurve) { override fun createBasicViewTransformation(): BasicViewTransformation { return object : BasicViewTransformation() { override fun animate(target: UIView, container: UIView, duration: Double) { target.prepareAnimation { translateToParent(target, container, y = amount) } startAnimation(duration) { translateToParent(target, container, y = 0f) } } override fun cancel(target: UIView, container: UIView) { translateToParent(target, container, y = 0f) } } } } class ViewAnimation_ToBottom( val amount: Float = 1f, animationCurve: UIViewAnimationCurve = UIViewAnimationCurve.UIViewAnimationCurveLinear ) : BasicViewAnimationDefinition(animationCurve) { override fun createBasicViewTransformation(): BasicViewTransformation { return object : BasicViewTransformation() { override fun animate(target: UIView, container: UIView, duration: Double) { target.prepareAnimation { translateToParent(target, container, y = 0f) } startAnimation(duration) { translateToParent(target, container, y = amount) } } override fun cancel(target: UIView, container: UIView) { translateToParent(target, container, y = 0f) } } } } class ViewAnimation_FromLeft( val amount: Float = 1f, animationCurve: UIViewAnimationCurve = UIViewAnimationCurve.UIViewAnimationCurveLinear ) : BasicViewAnimationDefinition(animationCurve) { override fun createBasicViewTransformation(): BasicViewTransformation { return object : BasicViewTransformation() { override fun animate(target: UIView, container: UIView, duration: Double) { target.prepareAnimation { translateToParent(target, container, x = -amount) } startAnimation(duration) { translateToParent(target, container, x = 0f) } } override fun cancel(target: UIView, container: UIView) { translateToParent(target, container, x = 0f) } } } } class ViewAnimation_ToLeft( val amount: Float = 1f, animationCurve: UIViewAnimationCurve = UIViewAnimationCurve.UIViewAnimationCurveLinear ) : BasicViewAnimationDefinition(animationCurve) { override fun createBasicViewTransformation(): BasicViewTransformation { return object : BasicViewTransformation() { override fun animate(target: UIView, container: UIView, duration: Double) { target.prepareAnimation { translateToParent(target, container, x = 0f) } startAnimation(duration) { translateToParent(target, container, x = -amount) } } override fun cancel(target: UIView, container: UIView) { translateToParent(target, container, x = 0f) } } } } class ViewAnimation_FromRight( val amount: Float = 1f, animationCurve: UIViewAnimationCurve = UIViewAnimationCurve.UIViewAnimationCurveLinear ) : BasicViewAnimationDefinition(animationCurve) { override fun createBasicViewTransformation(): BasicViewTransformation { return object : BasicViewTransformation() { override fun animate(target: UIView, container: UIView, duration: Double) { target.prepareAnimation { translateToParent(target, container, x = amount) } startAnimation(duration) { translateToParent(target, container, x = 0f) } } override fun cancel(target: UIView, container: UIView) { translateToParent(target, container, x = 0f) } } } } class ViewAnimation_ToRight( val amount: Float = 1f, animationCurve: UIViewAnimationCurve = UIViewAnimationCurve.UIViewAnimationCurveLinear ) : BasicViewAnimationDefinition(animationCurve) { override fun createBasicViewTransformation(): BasicViewTransformation { return object : BasicViewTransformation() { override fun animate(target: UIView, container: UIView, duration: Double) { target.prepareAnimation { translateToParent(target, container, x = 0f) } startAnimation(duration) { translateToParent(target, container, x = amount) } } override fun cancel(target: UIView, container: UIView) { translateToParent(target, container, x = 0f) } } } }
2
Kotlin
0
6
5320427ddc9dd2393f01e75564dab126fdeaac72
8,949
core
MIT License
mobius-migration/src/test/java/org/simple/mobius/migration/EventsOnlyTest.kt
simpledotorg
132,515,649
false
{"Kotlin": 5970450, "Shell": 1660, "HTML": 545}
package org.simple.mobius.migration import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import org.junit.Test import org.simple.mobius.migration.fix.EveInit import org.simple.mobius.migration.fix.EveModel import org.simple.mobius.migration.fix.EveUpdate import org.simple.mobius.migration.fix.defaultModel import org.simple.mobius.migration.fix.eveEffectHandler class EventsOnlyTest { @Test fun `it can run a state machine that's driven without external events`() { // given val modelUpdatesSubject = PublishSubject.create<EveModel>() val testObserver = modelUpdatesSubject.test() val fixture = MobiusTestFixture( Observable.empty(), defaultModel, EveInit(), EveUpdate(), eveEffectHandler(), modelUpdatesSubject::onNext ).also { it.start() } // then testObserver .assertNoErrors() .assertValues('a', 'b', 'c') .assertNotTerminated() fixture.dispose() } }
4
Kotlin
73
223
58d14c702db2b27b9dc6c1298c337225f854be6d
1,003
simple-android
MIT License
compiler/testData/diagnostics/testsWithStdLib/annotations/kClass/kClassInAnnotationsOutVariance.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
import kotlin.reflect.KClass open class A class B1 : A() class B2 : A() annotation class Ann1(val arg: KClass<out A>) @Ann1(A::class) class MyClass1 @Ann1(<!TYPE_MISMATCH!>Any::class<!>) class MyClass1a @Ann1(B1::class) class MyClass2 annotation class Ann2(val arg: KClass<out B1>) @Ann2(<!TYPE_MISMATCH!>A::class<!>) class MyClass3 @Ann2(B1::class) class MyClass4 @Ann2(<!TYPE_MISMATCH!>B2::class<!>) class MyClass5
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
426
kotlin
Apache License 2.0
data_shared/src/main/java/com/pimenta/bestv/data/local/database/MediaDb.kt
marcuspimenta
132,016,354
false
null
/* * Copyright (C) 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 com.pimenta.bestv.data.local.database import androidx.room.Database import androidx.room.RoomDatabase import com.pimenta.bestv.data.local.dao.MovieDao import com.pimenta.bestv.data.local.dao.TvShowDao import com.pimenta.bestv.model.data.local.MovieDbModel import com.pimenta.bestv.model.data.local.TvShowDbModel /** * Created by marcus on 05-03-2018. */ @Database( entities = [ MovieDbModel::class, TvShowDbModel::class ], version = 1, exportSchema = false ) abstract class MediaDb : RoomDatabase() { abstract fun movieDao(): MovieDao abstract fun tvShowDao(): TvShowDao }
5
Kotlin
20
54
63b92f876dd7d4571d3824e723e67c1872d25cd3
1,220
BESTV
Apache License 2.0
app/src/main/java/io/github/tubb/fcrash/sample/MainActivity.kt
TUBB
133,892,109
false
{"Kotlin": 9309}
package io.github.tubb.fcrash.sample import android.annotation.SuppressLint import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.os.Message import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private val handler = @SuppressLint("HandlerLeak") object : Handler() { override fun handleMessage(msg: Message?) { throw RuntimeException("Crashed by me!") } } private var bgmFriendlyCrash: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val app: App = application as App swt_app.setOnCheckedChangeListener { _, isChecked -> app.changeAppFriendly(isChecked) } swt_bgm.setOnCheckedChangeListener { _, isChecked -> bgmFriendlyCrash = isChecked } btn_crash.setOnClickListener { Toast.makeText(this, "App will crash after 5s", Toast.LENGTH_SHORT).show() handler.sendEmptyMessageDelayed(0, 5000) } btn_crash_bg.setOnClickListener { Toast.makeText(this, "Background service will crash after 5s", Toast.LENGTH_SHORT).show() val bgmIntent: Intent = Intent(this, ProcessService::class.java) bgmIntent.putExtra("bgmFriendlyCrash", bgmFriendlyCrash) startService(bgmIntent) } } }
0
Kotlin
0
2
14779b6e9530a0f20f6d78ca6d668ee55f7529d1
1,562
FriendlyCrash
Apache License 2.0
MDC-111/kotlin/shipping/app/src/main/java/com/google/codelabs/mdc/kotlin/shipping/ShippingInfoActivity.kt
RamyAmanuelSamwel
206,103,873
false
null
package com.google.codelabs.mdc.kotlin.shipping import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.google.android.material.textfield.TextInputLayout import kotlinx.android.synthetic.main.shipping_info_activity.* class ShippingInfoActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.shipping_info_activity) val rootView = findViewById<View>(android.R.id.content) val textInputLayouts = Utils.findViewsWithType( rootView, TextInputLayout::class.java) save_button.setOnClickListener { var noErrors = true for (textInputLayout in textInputLayouts) { val editTextString = textInputLayout.editText!!.text.toString() if (editTextString.isEmpty()) { textInputLayout.error = resources.getString(R.string.error_string) noErrors = false } else { textInputLayout.error = null } } if (noErrors) { // All fields are valid! } } } }
0
Kotlin
0
0
b40e0ad26a3bedf7e12c3273f53b1b73fd67701d
1,247
Codelab-Kotlin
Apache License 2.0
app/src/main/java/com/strings/airqualityvisualizer/data/remote/ConnectionState.kt
MohitMandalia
446,240,820
false
{"Kotlin": 19401}
package com.strings.airqualityvisualizer.data.remote sealed class ConnectionState(val message : String? =null){ class Connected(message: String) : ConnectionState(message) class CannotConnect(message: String) : ConnectionState(message) class Error(message: String) : ConnectionState(message) }
0
Kotlin
0
4
e5f01f377f1f9b426f15330a0fe6657f502a3e6e
306
AirQualityVisualizer
Apache License 2.0
src/main/kotlin/br/com/zupacademy/ratkovski/pix/registra/entity/ChavePix.kt
Ratkovski
395,480,677
true
{"Kotlin": 104442, "Smarty": 2172, "Dockerfile": 164}
package br.com.zupacademy.ratkovski.pix.registra.entity import br.com.zupacademy.ratkovski.pix.grpcenum.TipoChave import br.com.zupacademy.ratkovski.pix.grpcenum.TipoConta import br.com.zupacademy.ratkovski.pix.registra.ContaAssociada import java.time.LocalDateTime import java.util.* import javax.persistence.* import javax.validation.Valid import javax.validation.constraints.NotBlank import javax.validation.constraints.NotNull import javax.validation.constraints.Size @Entity //@Introspected @Table(uniqueConstraints = [UniqueConstraint(name = "uk_chave_pix",columnNames =["chave"])]) class ChavePix ( @field:NotNull @Column(name="cliente_id", length = 16, nullable = false) val clienteId:UUID, @field:NotNull @Enumerated(EnumType.STRING) @Column(nullable = false) val tipo: TipoChave, @field:NotBlank @field:Size(max = 77) @Column(unique =true,length = 77,nullable = false) var chave:String, @field:NotNull @Enumerated(EnumType.STRING) @Column(nullable = false) val tipoConta: TipoConta, @field:Valid @Embedded val conta: ContaAssociada ) { @Id @GeneratedValue @Column(length = 16) var pixId: UUID? = null @Column(nullable = false) val criadaEm: LocalDateTime = LocalDateTime.now() //quando for registrar no bcb e for chave aleatoria o outro sistema vai gerar fun chaveAleatoria(): Boolean { return tipo == TipoChave.RANDOM } fun atualiza(chave: String): Boolean { if (chaveAleatoria()) { this.chave = chave return true } return false } override fun toString(): String { return "ChavePix(clienteId=$clienteId, tipo=$tipo, chave='$chave', tipoConta=$tipoConta, conta=$conta, pixId=$pixId, criadaEm=$criadaEm)" } /** * Verifica se esta chave pertence a este cliente */ fun pertenceAo(clienteId: UUID) = this.clienteId.equals(clienteId) }
0
Kotlin
0
0
c4123d9e88247192717061e47fcb1ed6c55b2d9b
1,970
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
voip24h-sdk/src/main/java/com/voip24h/sdk/call/utils/SipConfiguration.kt
handeskXYZ
482,784,508
false
{"Kotlin": 66643}
package com.voip24h.sdk.call.utils import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo import android.telephony.TelephonyManager class SipConfiguration private constructor(builder: Builder) { var ext: String = "" var password: String = "" var domain: String = "" var transport: TransportType = TransportType.Tcp var isKeepAlive: Boolean = true var isIpv6Enable: Boolean = true var mediaEncryption: MediaEncryption = MediaEncryption.None init { this.ext = builder.ext this.password = <PASSWORD> this.domain = builder.domain this.transport = builder.transport this.isKeepAlive = builder.isKeepAlive this.isIpv6Enable = builder.isIpv6Enable this.mediaEncryption = builder.mediaEncryption } class Builder constructor( val ext: String, val password: <PASSWORD>, val domain: String ) { var transport: TransportType = TransportType.Tcp var isKeepAlive: Boolean = true var isIpv6Enable: Boolean = true var mediaEncryption: MediaEncryption = MediaEncryption.None fun transport(transportType: TransportType): Builder { this.transport = transportType return this } fun isKeepAlive(isEnable: Boolean): Builder { this.isKeepAlive = isEnable return this } fun isIpv6Enable(isEnable: Boolean): Builder { this.isIpv6Enable = isEnable return this } fun setMediaEncryption(mediaEncryption: MediaEncryption): Builder { this.mediaEncryption = mediaEncryption return this } fun create(): SipConfiguration { return SipConfiguration(this) } } }
0
Kotlin
0
0
fde921771a7bdd59e70626d41cfb45ed307983ac
1,833
Android-SDK
Apache License 2.0
app/src/main/java/com/workbook/liuwb/workbook/actions/jetpack/databind/Demo.kt
bobo-lwenb
224,773,966
false
null
package com.workbook.liuwb.workbook.actions.jetpack.databind import androidx.databinding.BaseObservable import androidx.databinding.Bindable import com.workbook.liuwb.workbook.BR class Demo(name: String, age: Int) : BaseObservable() { @get:Bindable var name: String = name set(name) { field = name notifyPropertyChanged(BR.name) } @get:Bindable var age: Int = age set(age) { field = age notifyPropertyChanged(BR.age) } }
0
Kotlin
0
0
9057c0ed87d0241a7704c7dfb9e285a378c2224e
520
WorkBook
Apache License 2.0
conclave-cloud-auction/backend/build.gradle.kts
R3Conclave
351,032,160
false
null
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { id("org.springframework.boot") version "2.5.12" id("io.spring.dependency-management") version "1.0.11.RELEASE" kotlin("jvm") version "1.6.10" kotlin("plugin.spring") version "1.6.10" } group = "com.r3" version = "0.0.1-SNAPSHOT" java.sourceCompatibility = JavaVersion.VERSION_11 repositories { //maven(url = "/home/rhopkins/src/conclave-sdk/build/sdk/repo") maven(url = "/home/rhopkins/src/ConclaveCloud/conclave-cloud-sdk-java/conclave-cloud-sdk/build/repo") mavenCentral() } dependencies { implementation("org.springframework.boot:spring-boot-starter-web") implementation("com.fasterxml.jackson.module:jackson-module-kotlin") implementation("org.jetbrains.kotlin:kotlin-reflect") implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") testImplementation("org.springframework.boot:spring-boot-starter-test") } tasks.withType<KotlinCompile> { kotlinOptions { freeCompilerArgs = listOf("-Xjsr305=strict") jvmTarget = "11" } } tasks.withType<Test> { useJUnitPlatform() }
2
Kotlin
10
11
88b54dcff8b16226b33f46a7710139e2f17be231
1,063
conclave-samples
Apache License 2.0
idea/testData/intentions/convertSnakeCaseTestFunctionToSpaced/snake.kt
android
263,405,600
true
null
// CONFIGURE_LIBRARY: JUnit@lib/junit-4.12.jar import org.junit.Test class A { @Test fun <caret>test_two_plus_two_equals_four() {} } fun test() { A().test_two_plus_two_equals_four() }
15
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
193
kotlin
Apache License 2.0
fuzzer/fuzzing_output/crashing_tests/verified/kClassInAnnotation.kt-1495394469.kt
ItsLastDay
102,885,402
false
null
import kotlin.reflect.KClass @Retention(AnnotationRetention.RUNTIME) annotation class Ann(val arg: KClass<*>) class OK @Ann(OK::class) class MyClass fun test(): String { val arg = (MyClass)?::class.java.getAnnotation((Ann)?::class.java).arg.java return arg.Ann() }
0
Kotlin
0
6
bb80db8b1383a6c7f186bea95c53faff4c0e0281
265
KotlinFuzzer
MIT License
app/src/main/java/com/comjeong/nomadworker/data/repository/place/PlaceDetailRepositoryImpl.kt
HUFSummer-Hackathon
512,365,622
false
{"Kotlin": 281486}
package com.comjeong.nomadworker.data.repository.place import com.comjeong.nomadworker.data.datasource.source.place.PlaceDetailDataSource import com.comjeong.nomadworker.data.mapper.PlaceMapper import com.comjeong.nomadworker.data.model.place.PlaceScrapRequestData import com.comjeong.nomadworker.data.model.place.UpdatePlaceRateRequestData import com.comjeong.nomadworker.domain.model.place.PlaceDetailResult import com.comjeong.nomadworker.domain.model.place.PlaceScrapResult import com.comjeong.nomadworker.domain.model.place.UpdatePlaceRateResult import com.comjeong.nomadworker.domain.repository.place.PlaceDetailRepository class PlaceDetailRepositoryImpl(private val dataSource: PlaceDetailDataSource) : PlaceDetailRepository { override suspend fun getPlaceDetailById(placeId: Long): PlaceDetailResult { return PlaceMapper.mapToPlaceDetailResult(dataSource.getPlaceDetailById(placeId)) } override suspend fun updatePlaceRate(body: UpdatePlaceRateRequestData): UpdatePlaceRateResult { return PlaceMapper.mapToUpdatePlaceRateResult(dataSource.updatePlaceRate(body)) } override suspend fun postPlaceScrap(body: PlaceScrapRequestData): PlaceScrapResult { return PlaceMapper.mapToPlaceScrapResult(dataSource.postPlaceScrap(body)) } }
2
Kotlin
0
0
5857dbe020888785367e0e4596a7b342aa1ec4a7
1,286
NomadWorker-Android
MIT License
core/sfc-core/src/main/kotlin/com/amazonaws/sfc/transformations/Sqrt.kt
aws-samples
700,380,828
false
{"Kotlin": 2245850, "Python": 6111, "Dockerfile": 4679, "TypeScript": 4547, "JavaScript": 1171}
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 package com.amazonaws.sfc.transformations import com.amazonaws.sfc.config.ConfigurationClass import com.google.gson.JsonObject @ConfigurationClass @TransformerOperator(["Sqrt"]) class Sqrt : TransformationImpl<Nothing>() { @TransformerMethod fun apply(target: Number?): Number? { val result = when (target) { null -> null is Float -> kotlin.math.sqrt(target) else -> kotlin.math.sqrt(target.toDouble()) } return if (result == null || result.toDouble().isNaN()) null else result } companion object { fun fromJson(o: JsonObject): TransformationOperator = TransformationOperatorNoOperand.fromJson<Sqrt>(o) fun create() = Sqrt() } }
5
Kotlin
2
15
fd38dbb80bf6be06c00261d9992351cc8a103a63
836
shopfloor-connectivity
MIT No Attribution
src/main/kotlin/no/nav/hjelpemidler/delbestilling/internal.kt
navikt
638,489,446
false
{"Kotlin": 116506, "Dockerfile": 224}
package no.nav.hjelpemidler.delbestilling import io.ktor.http.HttpStatusCode import io.ktor.server.application.call import io.ktor.server.response.respondText import io.ktor.server.routing.Route import io.ktor.server.routing.get import org.apache.kafka.clients.consumer.KafkaConsumer fun Route.internal() { get("/isalive") { call.respondText("ALIVE", status = HttpStatusCode.OK) } get("/isready") { call.respondText("READY", status = HttpStatusCode.OK) } }
1
Kotlin
0
0
325a2c9f94bded795e2aefa3ae04121daf53cc01
492
hm-delbestilling-api
MIT License
sdk/src/jsMain/kotlin/gitfox/util/JsAntilog.kt
dector
341,706,824
false
null
package gitfox.util import com.github.aakira.napier.Antilog import com.github.aakira.napier.Napier internal class JsAntilog : Antilog() { override fun performLog(priority: Napier.Level, tag: String?, throwable: Throwable?, message: String?) { val logTag = "GitFox" val fullMessage = if (message != null) { if (throwable != null) "$message\n${throwable.message}" else message } else throwable?.message ?: return when (priority) { Napier.Level.VERBOSE -> console.log("VERBOSE $logTag : $fullMessage") Napier.Level.DEBUG -> console.log("DEBUG $logTag : $fullMessage") Napier.Level.INFO -> console.info("INFO $logTag : $fullMessage") Napier.Level.WARNING -> console.warn("WARNING $logTag : $fullMessage") Napier.Level.ERROR -> console.error("ERROR $logTag : $fullMessage") Napier.Level.ASSERT -> console.error("ASSERT $logTag : $fullMessage") } } }
0
Kotlin
0
1
7258eb2bc4ca9fcd1ebf3029217d80d6fd2de4b9
992
gitfox-mirror
Apache License 2.0
src/main/kotlin/org/dif/model/Keys.kt
andkononykhin
412,794,577
true
{"Kotlin": 52393}
package org.dif.model data class PublicKey<T : PublicKeyType>( val encodingType: EncodingType, val encodedValue: String, val type: T ) typealias PublicKeyAgreement = PublicKey<PublicKeyTypeAgreement> typealias PublicKeyAuthentication = PublicKey<PublicKeyTypeAuthentication>
0
null
0
0
0a785d8c19db814f6946d9545597cb057a8abccf
289
peer-did-jvm
Apache License 2.0
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/kotlin/org/jetbrains/kotlin/gradle/GradleDaemonMemoryIT.kt
android
263,405,600
true
null
/* * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle import org.junit.Test import kotlin.test.assertTrue class GradleDaemonMemoryIT : BaseGradleIT() { // For corresponding documentation, see https://docs.gradle.org/current/userguide/gradle_daemon.html // Setting user.variant to different value implies a new daemon process will be created. // In order to stop daemon process, special exit task is used ( System.exit(0) ). @Test fun testGradleDaemonMemory() { val project = Project("gradleDaemonMemory") val VARIANT_CONSTANT = "ForTest" val userVariantArg = "-Duser.variant=$VARIANT_CONSTANT" val MEMORY_MAX_GROWTH_LIMIT_KB = 5000 val BUILD_COUNT = 10 val reportMemoryUsage = "-Dkotlin.gradle.test.report.memory.usage=true" val options = BaseGradleIT.BuildOptions(withDaemon = true) fun exitTestDaemon() { project.build(userVariantArg, reportMemoryUsage, "exit", options = options) { assertFailed() assertContains("The daemon has exited normally or was terminated in response to a user interrupt.") } } fun buildAndGetMemoryAfterBuild(): Int { var reportedMemory: Int? = null project.build(userVariantArg, reportMemoryUsage, "clean", "assemble", options = options) { assertSuccessful() val matches = "\\[KOTLIN\\]\\[PERF\\] Used memory after build: (\\d+) kb \\(difference since build start: ([+-]?\\d+) kb\\)" .toRegex().find(output) assertTasksExecuted(":compileKotlin") assert(matches != null && matches.groups.size == 3) { "Used memory after build is not reported by plugin" } reportedMemory = matches!!.groupValues[1].toInt() } return reportedMemory!! } exitTestDaemon() try { val usedMemory = (1..BUILD_COUNT).map { buildAndGetMemoryAfterBuild() } // ensure that the maximum of the used memory established after several first builds doesn't raise significantly in the subsequent builds val establishedMaximum = usedMemory.take(5).max()!! val totalMaximum = usedMemory.max()!! val maxGrowth = totalMaximum - establishedMaximum assertTrue( maxGrowth <= MEMORY_MAX_GROWTH_LIMIT_KB, "Maximum used memory over series of builds growth $maxGrowth (from $establishedMaximum to $totalMaximum) kb > $MEMORY_MAX_GROWTH_LIMIT_KB kb" ) // testing that nothing remains locked by daemon, see KT-9440 project.build(userVariantArg, "clean", options = BaseGradleIT.BuildOptions(withDaemon = true)) { assertSuccessful() } } finally { exitTestDaemon() } } }
15
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
3,075
kotlin
Apache License 2.0
account/src/main/kotlin/com/mzr/sm/security/WebSecurityConfig.kt
muzuro
494,824,933
false
{"Kotlin": 32243}
package com.mzr.sm.security import com.mzr.sm.security.service.ServiceAuthenticationProvider import com.mzr.sm.security.service.ServiceTokenAuthenticationFilter import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.config.BeanIds import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.core.userdetails.User import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter import org.springframework.security.provisioning.InMemoryUserDetailsManager import org.springframework.security.web.authentication.www.BasicAuthenticationFilter @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) class WebSecurityConfig( private val passwordEncoder: PasswordEncoder, private val serviceAuthenticationProvider: ServiceAuthenticationProvider, ) : WebSecurityConfigurerAdapter() { @Bean(name = [BeanIds.AUTHENTICATION_MANAGER]) override fun authenticationManagerBean(): AuthenticationManager { return super.authenticationManagerBean() } override fun configure(builder: AuthenticationManagerBuilder) { builder.authenticationProvider(serviceAuthenticationProvider) } override fun configure(http: HttpSecurity) { http .addFilterAfter( ServiceTokenAuthenticationFilter(serviceAuthenticationProvider), BasicAuthenticationFilter::class.java) .cors() .and() .csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests{ configurer -> configurer .antMatchers( "/error", "/login" ) .permitAll() .anyRequest() .authenticated() } .oauth2ResourceServer { obj: OAuth2ResourceServerConfigurer<HttpSecurity?> -> obj .jwt() .jwtAuthenticationConverter(jwtAuthenticationConverter()) } } private fun jwtAuthenticationConverter(): JwtAuthenticationConverter? { // create a custom JWT converter to map the "authorities" from the token as granted authorities val jwtGrantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter() jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("authorities") jwtGrantedAuthoritiesConverter.setAuthorityPrefix("") val jwtAuthenticationConverter = JwtAuthenticationConverter() jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter) return jwtAuthenticationConverter } @Bean override fun userDetailsService(): UserDetailsService { val user1 = User .withUsername("<EMAIL>") .authorities("email.update") .passwordEncoder { rawPassword: String? -> passwordEncoder.encode(rawPassword) } .password("<PASSWORD>") .build() val userDetailsManager = InMemoryUserDetailsManager() userDetailsManager.createUser(user1) return userDetailsManager } }
0
Kotlin
0
0
36daef8d0d395b8e2391c4428175c2758fc055ca
4,291
security-kafka-events
Apache License 2.0
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/plugin/KotlinPluginLifecycleStageRestriction.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.plugin import org.jetbrains.kotlin.gradle.plugin.KotlinPluginLifecycle.IllegalLifecycleException import kotlin.coroutines.* /** * Will ensure that the given [block] cannot leave the specified allowed stages [allowed] * e.g. * * ```kotlin * project.launchInStage(Stage.BeforeFinaliseDsl) { * withRestrictedStages(Stage.upTo(Stage.FinaliseDsl)) { * await(Stage.FinaliseDsl) // <- OK, since still in allowed stages * await(Stage.AfterFinaliseDsl) // <- fails, since not in allowed stages! * } * } * ``` */ internal suspend fun <T> withRestrictedStages(allowed: Set<KotlinPluginLifecycle.Stage>, block: suspend () -> T): T { val newCoroutineContext = coroutineContext + KotlinPluginLifecycleStageRestriction(currentKotlinPluginLifecycle(), allowed) return suspendCoroutine { continuation -> val newContinuation = object : Continuation<T> { override val context: CoroutineContext get() = newCoroutineContext override fun resumeWith(result: Result<T>) { continuation.resumeWith(result) } } block.startCoroutine(newContinuation) } } private class KotlinPluginLifecycleStageRestriction( private val lifecycle: KotlinPluginLifecycle, private val allowedStages: Set<KotlinPluginLifecycle.Stage>, ) : CoroutineContext.Element, ContinuationInterceptor { override val key: CoroutineContext.Key<*> = ContinuationInterceptor override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> = object : Continuation<T> { override val context: CoroutineContext get() = continuation.context override fun resumeWith(result: Result<T>) = when { result.isFailure -> continuation.resumeWith(result) lifecycle.stage !in allowedStages -> continuation.resumeWithException( IllegalLifecycleException( "Required stage in '$allowedStages', but lifecycle switched to '${lifecycle.stage}'" ) ) else -> continuation.resumeWith(result) } } init { if (lifecycle.stage !in allowedStages) { throw IllegalLifecycleException("Required stage in '${allowedStages}' but lifecycle is currently in '${lifecycle.stage}'") } } }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
2,590
kotlin
Apache License 2.0
idea/testData/quickfix/increaseVisibility/exposedParameterTypePublic.kt
android
263,405,600
true
null
// "Make 'Nested' public" "true" // ACTION: Make 'Nested' internal class Outer { private class Nested } class Generic<T> internal fun foo(<caret>arg: Generic<Outer.Nested>) {}
15
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
182
kotlin
Apache License 2.0
src/main/kotlin/tester/TreeTestingProcessReporter.kt
i-am-arunkumar
393,908,591
true
{"Kotlin": 100873}
package tester import com.intellij.execution.process.ProcessHandler import com.intellij.execution.process.ProcessOutputTypes import com.intellij.execution.testframework.sm.ServiceMessageBuilder import com.intellij.execution.testframework.sm.ServiceMessageBuilder.* import common.errors.Err import common.errors.presentableString import tester.judge.Verdict import tester.judge.Verdict.Companion.presentableString import tester.tree.ResultNode import tester.tree.TestNode import tester.tree.TreeTestingProcess /** * Class that abstracts formatting and sending output to the console and the TestRunner UI */ class TreeTestingProcessReporter(private val processHandler: ProcessHandler) : TreeTestingProcess.Listener { override fun leafStart(node: TestNode.Leaf) { testStarted(node.name).apply() testStdOut(node.name).addAttribute( "out", "${"___".repeat(5)}[ ${node.name} ]${"___".repeat(5)}\n" ).apply() } override fun leafFinish(node: ResultNode.Leaf) { val nodeName = node.sourceNode.name if (node.output.isNotEmpty()) testStdOut(nodeName) .addAttribute("out", node.output.let { if (it.endsWith('\n')) it else it + '\n' }) .apply() if (node.error.isNotEmpty()) testStdErr(nodeName) .addAttribute("out", node.error) .addAttribute("message", node.verdict.presentableString()) .apply() val verdictString = node.verdict.presentableString() when (node.verdict) { Verdict.CORRECT_ANSWER -> testStdOut(nodeName).addAttribute("out", "\n" + verdictString + "\n\n").apply() else -> { if (node.verdictError.isNotEmpty()) testStdErr(nodeName) .addAttribute("out", node.verdictError) .apply() testFailed(nodeName).addAttribute("message", verdictString + "\n").apply() } } testFinished(nodeName) .addAttribute("duration", node.executionTime.toString()) .apply() } override fun groupStart(node: TestNode.Group) { testSuiteStarted(node.name).apply() } override fun groupFinish(node: ResultNode.Group) { testSuiteFinished(node.sourceNode.name).apply() } override fun testingProcessStartErrored(error: Err) { testsStarted() processHandler.notifyTextAvailable( error.presentableString() + "\n", ProcessOutputTypes.STDERR ) processHandler.notifyTextAvailable(error.stackTraceToString(), ProcessOutputTypes.STDERR) } override fun testingProcessError(message: String) { processHandler.notifyTextAvailable(message + "\n", ProcessOutputTypes.STDERR) } private fun ServiceMessageBuilder.apply() { processHandler.notifyTextAvailable( this.toString() + "\n", ProcessOutputTypes.STDOUT ) } }
0
null
0
0
4f72acfdb83c7917faa397818bd198b67fd3d6d8
3,054
AutoCp
MIT License
compiler/testData/codegen/box/nonLocalReturns/localReturnInsideProperty.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
interface ClassData fun f() = object : ClassData { val someInt: Int get() { return 5 } } fun box(): String{ f() return "OK" }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
167
kotlin
Apache License 2.0
kt/godot-library/src/main/kotlin/godot/gen/godot/RichTextEffect.kt
utopia-rise
289,462,532
false
{"Kotlin": 1464908, "GDScript": 492843, "C++": 484675, "C#": 10278, "C": 8523, "Shell": 8429, "Java": 2136, "CMake": 939, "Python": 75}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT", "RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate") package godot import godot.`annotation`.GodotBaseType import godot.core.TypeManager import godot.util.VoidPtr import kotlin.Boolean import kotlin.Int import kotlin.NotImplementedError import kotlin.Suppress /** * A custom effect for a [godot.RichTextLabel]. * * Tutorials: * [https://github.com/Eoin-ONeill-Yokai/Godot-Rich-Text-Effect-Test-Project](https://github.com/Eoin-ONeill-Yokai/Godot-Rich-Text-Effect-Test-Project) * * A custom effect for a [godot.RichTextLabel]. * * **Note:** For a [godot.RichTextEffect] to be usable, a BBCode tag must be defined as a member variable called `bbcode` in the script. * * [codeblocks] * * [gdscript skip-lint] * * # The RichTextEffect will be usable like this: `[example]Some text[/example]` * * var bbcode = "example" * * [/gdscript] * * [csharp skip-lint] * * // The RichTextEffect will be usable like this: `[example]Some text[/example]` * * string bbcode = "example"; * * [/csharp] * * [/codeblocks] * * **Note:** As soon as a [godot.RichTextLabel] contains at least one [godot.RichTextEffect], it will continuously process the effect unless the project is paused. This may impact battery life negatively. */ @GodotBaseType public open class RichTextEffect : Resource() { public override fun new(scriptIndex: Int): Boolean { callConstructor(ENGINECLASS_RICHTEXTEFFECT, scriptIndex) return true } /** * Override this method to modify properties in [charFx]. The method must return `true` if the character could be transformed successfully. If the method returns `false`, it will skip transformation to avoid displaying broken text. */ public open fun _processCustomFx(charFx: CharFXTransform): Boolean { throw NotImplementedError("_process_custom_fx is not implemented for RichTextEffect") } public companion object internal object MethodBindings { public val _processCustomFxPtr: VoidPtr = TypeManager.getMethodBindPtr("RichTextEffect", "_process_custom_fx") } }
61
Kotlin
33
445
1dfa11d5c43fc9f85de2260b8e88f4911afddcb9
2,394
godot-kotlin-jvm
MIT License
data/src/main/kotlin/data/RootModule.kt
stoyicker
292,305,403
true
{"Java": 646382, "Kotlin": 423127, "Shell": 885}
package data import android.content.Context import androidx.room.Room import androidx.room.RoomDatabase import dagger.Module import dagger.Provides import data.database.AppDatabase import javax.inject.Singleton @Module internal class RootModule(private val context: Context) { @Provides @Singleton fun context() = context @Provides @Singleton fun database(context: Context): AppDatabase = Room.databaseBuilder( context, AppDatabase::class.java, "AppDatabase") // AUTOMATIC (the default) transforms into WRITE_AHEAD_LOGGING, which seems to give problems // with incorrectly understanding database locks .setJournalMode(RoomDatabase.JournalMode.TRUNCATE) .fallbackToDestructiveMigration() .allowMainThreadQueries() .build() }
0
Java
2
0
fecfefd7a64dc8c9397343850b9de4d52117b5c3
793
dinger-unpublished
MIT License
app/src/main/java/io/horizontalsystems/bankwallet/entities/ConfiguredToken.kt
Helge-Albert
651,814,837
false
null
package io.horizontalsystems.bankwallet.entities import android.os.Parcelable import io.horizontalsystems.bankwallet.core.protocolType import io.horizontalsystems.marketkit.models.BlockchainType import io.horizontalsystems.marketkit.models.Token import kotlinx.parcelize.Parcelize import java.util.* @Parcelize data class ConfiguredToken( val token: Token, val coinSettings: CoinSettings = CoinSettings() ): Parcelable { override fun hashCode(): Int { return Objects.hash(token, coinSettings) } override fun equals(other: Any?): Boolean { if (this === other) return true return other is ConfiguredToken && other.token == token && other.coinSettings == coinSettings } val badge get() = when (token.blockchainType) { BlockchainType.Bitcoin, BlockchainType.Litecoin, -> coinSettings.derivation?.value?.uppercase() BlockchainType.BitcoinCash -> coinSettings.bitcoinCashCoinType?.value?.uppercase() else -> token.protocolType?.uppercase() } }
0
Kotlin
0
1
229170247c81772b27828d5a4d796d2d970f644d
1,103
wallet-android
MIT License
app/src/main/java/com/yoavst/quickapps/music/AbstractRemoteControlService.kt
yoavst
22,375,409
false
null
package com.yoavst.quickapps.music import android.content.Intent import android.graphics.Bitmap import android.os.Binder import android.os.IBinder import android.service.notification.NotificationListenerService import android.service.notification.StatusBarNotification /** * Base class for the remote control service. */ public abstract class AbstractRemoteControlService : NotificationListenerService() { private val mBinder = RCBinder() protected var callback: Callback? = null public inner class RCBinder : Binder() { public fun getService(): AbstractRemoteControlService { return this@AbstractRemoteControlService } } override fun onUnbind(intent: Intent): Boolean { stopSelf() return false } override fun onBind(intent: Intent): IBinder { if (intent.getAction().startsWith("com.yoavst.quickmusic.BIND_RC_CONTROL")) { return mBinder } else { return super.onBind(intent) } } /** * Return the intent of the current client. */ abstract fun getCurrentClientIntent(): Intent? /** * Enables the remote controller */ abstract fun setRemoteControllerEnabled(): Boolean /** * Disables the remote controller */ abstract fun setRemoteControllerDisabled() /** * Tells the client to go the next song */ abstract fun sendNextKey() /** * Tells the client to pause the song */ abstract fun sendPauseKey() /** * Tells the client to resume the song */ abstract fun sendPlayKey() /** * Tells the client to go back to the previous song. */ abstract fun sendPreviousKey() /** * Returns true if playing. * @return True if playing */ abstract fun isPlaying(): Boolean /** * Returns position and duration. * @return Position and duration */ abstract fun getPosition(): Int /** * We do not use notification listening, so it is ignored */ override fun onNotificationPosted(notification: StatusBarNotification) { } /** * We do not use notification listening, so it is ignored */ override fun onNotificationRemoved(notification: StatusBarNotification) { } /** * Disable the remote controller on destroy of the service */ override fun onDestroy() { setRemoteControllerDisabled() } protected fun millisToSeconds(value: Long): Int { if (value < 0) return -1 else return value.toInt() / 1000 } public interface Callback { public fun onMediaMetadataChanged(artist: String, title: String, duration: Int, albumArt: Bitmap?) public fun onPlaybackStateChanged(state: Int) public fun onClientChange(clearing: Boolean) } public open fun setListener(callback: Callback?) { this.callback = callback } companion object { protected val BITMAP_HEIGHT: Int = 1100 protected val BITMAP_WIDTH: Int = 1100 } }
1
Kotlin
23
34
8b7fe52844a0bcc29c6288044322fe04e890c028
3,056
quickapps
Creative Commons Attribution 3.0 Unported
fuzzer/fuzzing_output/crashing_tests/verified/reifiedSafeAsFunKSmall.kt1601346338.kt
ItsLastDay
102,885,402
false
null
fun fn0(): Unit { } fun fn1(x: Any): Unit { } inline fun <reified T> Unit.reifiedSafeAsReturnsNonNull(x: (Any)?, operation: String): Unit { val y = try { (x as? T) }catch(e: Throwable) { throw AssertionError("$operation: should not throw exceptions, got $e") } if (y == null)({throw AssertionError("$operation: should return non-null, got null")}) } inline fun <reified T> reifiedSafeAsReturnsNull(fn0: (Any)?, operation: String): Unit { val y = try { (x as? T) }catch(e: Throwable) { throw AssertionError("$operation: should not throw exceptions, got $e") } if (y != null)({throw AssertionError("$operation: should return null, got $y")}) } fun box(): String { val f0 = (((::fn0)!!)!! as Any) val f1 = (::fn1 as Any) reifiedSafeAsReturnsNonNull<Function0<*>>(f0, "f0 as Function0<*>") reifiedSafeAsReturnsNull<Function1<*, *>>(f0, "f0 as Function1<*, *>") reifiedSafeAsReturnsNull<Function0<*>>(f1, "f1 as Function0<*>") reifiedSafeAsReturnsNonNull<Function1<*, *>>(f1, "f1 as Function1<*, *>") reifiedSafeAsReturnsNull<Function0<*>>(null, "null as Function0<*>") reifiedSafeAsReturnsNull<Function1<*, *>>(null, "null as Function1<*, *>") return "OK" }
0
Kotlin
0
6
bb80db8b1383a6c7f186bea95c53faff4c0e0281
1,155
KotlinFuzzer
MIT License
sample/shared_code/src/iOSMain/kotlin/com/freeletics/flowredux/sample/NsQueueDispatcher.kt
ychescale9
217,978,193
true
{"Kotlin": 82153, "Shell": 919}
package com.freeletics.flowredux.sample import platform.darwin.dispatch_async import platform.darwin.dispatch_get_main_queue import platform.darwin.dispatch_after import platform.darwin.DISPATCH_TIME_NOW import platform.darwin.dispatch_time import platform.darwin.dispatch_queue_t import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.Delay import kotlinx.coroutines.DisposableHandle import kotlinx.coroutines.InternalCoroutinesApi import kotlinx.coroutines.Runnable @UseExperimental(InternalCoroutinesApi::class) val applicationNsQueueDispatcher: CoroutineDispatcher = NsQueueDispatcher(dispatch_get_main_queue()) @InternalCoroutinesApi internal class NsQueueDispatcher(private val dispatchQueue: dispatch_queue_t) : CoroutineDispatcher(), Delay { override fun dispatch(context: CoroutineContext, block: Runnable) { dispatch_async(dispatchQueue) { block.run() } } @InternalCoroutinesApi override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timeMillis * 1_000_000), dispatchQueue) { try { with(continuation) { resumeUndispatched(Unit) } } catch (err: Throwable) { throw err } } } @InternalCoroutinesApi override fun invokeOnTimeout(timeMillis: Long, block: Runnable, context: CoroutineContext): DisposableHandle { val handle = object : DisposableHandle { var disposed = false private set override fun dispose() { disposed = true } } dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timeMillis * 1_000_000), dispatchQueue) { try { if (!handle.disposed) { block.run() } } catch (err: Throwable) { throw err } } return handle } }
10
Kotlin
0
0
1ae6213f86ddd40f05358f95e0e0ce678245d1cc
2,134
FlowRedux
Apache License 2.0
adapters/s7/src/main/kotlin/com/amazonaws/sfc/s7/CustomDriverBase.kt
aws-samples
700,380,828
false
{"Kotlin": 2245850, "Python": 6111, "Dockerfile": 4679, "TypeScript": 4547, "JavaScript": 1171}
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 package com.amazonaws.sfc.s7 import org.apache.plc4x.java.api.PlcConnection import org.apache.plc4x.java.api.exceptions.PlcConnectionException import org.apache.plc4x.java.spi.configuration.ConfigurationFactory import org.apache.plc4x.java.spi.connection.DefaultNettyPlcConnection import org.apache.plc4x.java.spi.connection.GeneratedDriverBase import org.apache.plc4x.java.spi.generation.Message import org.apache.plc4x.java.transport.tcp.TcpTransport import java.lang.Boolean.parseBoolean import java.util.regex.Pattern // Extends PLC4J class to overload the getConnection method. For loading of classes PLC4J requires // all jars to be in the class path loaded by the Thread classloader, where SFC uses a pure config // approach loading the configured classes using the URLClassLoader. internal abstract class CustomDriverBase<B : Message?> : GeneratedDriverBase<B>() { override fun getConnection(connectionString: String?): PlcConnection { val matcher = URI_PATTERN.matcher(connectionString.toString()) if (!matcher.matches()) { throw PlcConnectionException( "Connection string doesn't match the format '{protocol-code}:({transport-code})?//{transport-address}(?{parameter-string)?'") } val protocolCode = matcher.group("protocolCode") val transportConfig = matcher.group("transportConfig") val paramString = matcher.group("paramString") if (protocolCode != getProtocolCode()) { throw PlcConnectionException("This driver is not suited to handle this connection string") } val configuration = ConfigurationFactory().createConfiguration(configurationType, paramString) ?: throw PlcConnectionException("Unsupported configuration") // As the S7 protocol always uses TCP create it statically val transport = TcpTransport() ConfigurationFactory.configure(configuration, transport) // Create communication channel for the driver val channelFactory = transport.createChannelFactory(transportConfig) ?: throw PlcConnectionException("Unable to get channel factory from url $transportConfig") ConfigurationFactory.configure(configuration, channelFactory) initializePipeline(channelFactory) val awaitSetupComplete = if (System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_SETUP_COMPLETE) != null) parseBoolean(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_SETUP_COMPLETE)) else awaitSetupComplete() val awaitDisconnectComplete = if (System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCONNECT_COMPLETE) != null) parseBoolean(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCONNECT_COMPLETE)) else awaitDisconnectComplete() val awaitDiscoverComplete = if (System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCOVER_COMPLETE) != null) parseBoolean(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCOVER_COMPLETE)) else awaitDiscoverComplete() return DefaultNettyPlcConnection( canRead(), canWrite(), canSubscribe(), fieldHandler, valueHandler, configuration, channelFactory, awaitSetupComplete, awaitDisconnectComplete, awaitDiscoverComplete, getStackConfigurer(transport), optimizer) } companion object { private val URI_PATTERN = Pattern.compile( "^(?<protocolCode>[a-z0-9\\-]*)(:(?<transportCode>[a-z0-9]*))?://(?<transportConfig>[^?]*)(\\?(?<paramString>.*))?") } }
5
Kotlin
2
15
fd38dbb80bf6be06c00261d9992351cc8a103a63
3,721
shopfloor-connectivity
MIT No Attribution
composeApp/src/commonMain/kotlin/com/vproject/paldex/presentation/component/PalStatItem.kt
viethua99
753,486,244
false
{"Kotlin": 86136, "Ruby": 2154, "Swift": 660}
package com.vproject.paldex.presentation.component import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.height import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.vproject.paldex.model.Stats import com.vproject.paldex.presentation.component.theme.Green300 import com.vproject.paldex.presentation.component.theme.Yellow400 import kotlin.math.roundToInt @Composable internal fun PalStatItem( modifier: Modifier = Modifier, statName: String, statValue: Long ) { val animationProgress = remember { Animatable( initialValue = 0f, ) } LaunchedEffect(Unit) { animationProgress.animateTo( targetValue = 1f, animationSpec = tween( durationMillis = 8 * statValue.toInt() / 40, easing = LinearEasing ) ) } Row ( verticalAlignment = Alignment.CenterVertically, modifier = modifier ) { Text( text = statName, color = MaterialTheme.colorScheme.onBackground.copy(.8f), style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(.3f) ) Text( text = "${(statValue * animationProgress.value).roundToInt()}", color = MaterialTheme.colorScheme.onBackground, style = MaterialTheme.typography.bodyLarge.copy( fontWeight = FontWeight.Bold ), modifier = Modifier.weight(.2f) ) val progress = statValue.toFloat() / 200.toFloat() val animatedProgress = progress * animationProgress.value val progressColor = if (progress >= .5f) Green300 else Yellow400 val progressTrackColor = MaterialTheme.colorScheme.outline.copy(.2f) Box( modifier = Modifier .weight(.5f) .height(10.dp) .drawBehind { drawRoundRect( color = progressTrackColor, topLeft = Offset.Zero, size = size, cornerRadius = CornerRadius(size.height, size.height), ) drawRoundRect( color = progressColor, topLeft = Offset.Zero, size = Size(width = size.width * animatedProgress, height = size.height), cornerRadius = CornerRadius(size.height, size.height), ) } ) } }
0
Kotlin
0
2
d12b6fc43ef85b58df1b3cb366c0b3c84e0093be
3,277
Paldex
Apache License 2.0
application/app/src/main/java/com/seljabali/appcompattheming/ui/landingpage/LandingPageItems.kt
seljabali
260,080,043
false
null
package com.seljabali.appcompattheming.ui.landingpage import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.seljabali.appcompattheming.R enum class LandingPageItems(@StringRes override val titleStringId: Int, @DrawableRes override val iconId: Int = R.drawable.ic_launcher_background) : LandingItem { WIDGETS(R.string.widgets, R.drawable.ic_widgets), DESIGN(R.string.design, R.drawable.ic_paint) }
0
Kotlin
0
2
2e86f3155e07a608441acc58a0aa633c32bab755
470
android-appcompat-theming
Creative Commons Zero v1.0 Universal
app/src/main/java/com/nivekaa/icepurpykt/domain/listener/OnProductSelectedListener.kt
nivekalara237
394,590,651
false
null
package com.nivekaa.icepurpykt.domain.listener import com.nivekaa.icepurpykt.domain.model.ProductVM interface OnProductSelectedListener { fun productSelected(product: ProductVM?) }
0
Kotlin
0
0
aaddfaf3e4299ece7eb5921073a319006c03df52
186
ice-purpy4kt
Apache License 2.0
app/src/main/java/org/tensorflow/demo/Styles.kt
fornewid
198,774,014
true
{"Kotlin": 26615}
package org.tensorflow.demo object Styles { @JvmStatic val thumbnails = listOf( R.drawable.style0, R.drawable.style1, R.drawable.style2, R.drawable.style3, R.drawable.style4, R.drawable.style5, R.drawable.style6, R.drawable.style7, R.drawable.style8, R.drawable.style9, R.drawable.style10, R.drawable.style11, R.drawable.style12, R.drawable.style13, R.drawable.style14, R.drawable.style15, R.drawable.style16, R.drawable.style17, R.drawable.style18, R.drawable.style19, R.drawable.style20, R.drawable.style21, R.drawable.style22, R.drawable.style23, R.drawable.style24, R.drawable.style25 ) @JvmStatic val count = thumbnails.size }
0
Kotlin
1
1
4b78a9fe743b8f0c61cb845857fceb6671a9e9c5
863
tensorflow-style-transfer-android
Apache License 2.0
simplecloud-launcher/src/main/kotlin/eu/thesimplecloud/launcher/logging/AnsiColorHelper.kt
theSimpleCloud
270,085,977
false
{"Kotlin": 2004142, "Java": 4872, "Shell": 1302, "Batchfile": 156}
/* * MIT License * * Copyright (C) 2020-2022 The SimpleCloud authors * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package eu.thesimplecloud.launcher.logging import org.fusesource.jansi.Ansi /** * Created by IntelliJ IDEA. * User: Philipp.Eistrach * Date: 05.09.2019 * Time: 17:38 */ enum class AnsiColorHelper(val ansiName: String, val index: Char, val ansiCode: String) { RESET("reset", 'r', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.DEFAULT).boldOff().toString()), WHITE("white", 'f', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).bold().toString()), BLACK("black", '0', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).bold().toString()), RED("red", 'c', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).bold().toString()), YELLOW("yellow", 'e', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).bold().toString()), BLUE("blue", '9', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).bold().toString()), GREEN("green", 'a', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).bold().toString()), PURPLE("purple", '5', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).boldOff().toString()), ORANGE("orange", '6', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).boldOff().toString()), GRAY("gray", '7', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).boldOff().toString()), DARK_RED("dark_red", '4', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).boldOff().toString()), DARK_GRAY("dark_gray", '8', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).boldOff().toString()), DARK_BLUE("dark_blue", '1', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).boldOff().toString()), DARK_GREEN("dark_green", '2', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).boldOff().toString()), LIGHT_BLUE("light_blue", 'b', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).bold().toString()), CYAN("cyan", '3', Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).boldOff().toString()); companion object { fun toColoredString(msg: String): String { var text = msg for (consoleColour in values()) { text = text.replace('§'.toString() + "" + consoleColour.index, consoleColour.ansiCode) text = text.replace('&'.toString() + "" + consoleColour.index, consoleColour.ansiCode) } return text } } }
11
Kotlin
47
101
d8ad6e6f627b1ad80034dfb9c97393dd47905825
3,504
SimpleCloud
MIT License
txt-editor/src/main/controller/IEditorController.kt
FabioFischer
96,144,253
false
{"Kotlin": 36342}
package main.controller import javafx.scene.control.Tab import main.model.Editor interface IEditorController { fun get(tab: Tab) : Editor? fun getAll() : List<Editor>? fun getAllTabs() : List<Tab>? fun add(editor: Editor) fun delete(editor: Editor) fun rename(editor: Editor?, name: String) }
0
Kotlin
0
4
97e7376e9471120132eb16332f61b73b16537996
318
code-it
MIT License
presentation/src/main/java/com/bayarsahintekin/matchscores/MainActivity.kt
bayarsahintekin0
651,000,613
false
{"Kotlin": 254022, "Ruby": 1708}
package com.bayarsahintekin.matchscores import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Surface import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import com.bayarsahintekin.matchscores.ui.components.MainScreenView import com.bayarsahintekin.matchscores.ui.theme.MSTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { private val viewModel: MainViewModel by viewModels() @SuppressLint("SuspiciousIndentation") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MSTheme { // A surface container using the 'background' color from the theme Surface(modifier = Modifier.fillMaxSize(), color = Color.White) { MainScreenView() } } } } }
0
Kotlin
0
2
7aeef154ace50b206ec6600f55260ae5188b806a
1,131
MatchScores
Open LDAP Public License v2.2.1
app/src/main/java/ru/mobile/lukslol/util/view/ContextExtensions.kt
silverxcoins
260,674,124
false
{"Kotlin": 73778}
package ru.mobile.lukslol.util.view
0
Kotlin
0
1
bdedaf16c62777f413e56d0d3a0b1336d1966d98
38
LukS-LoL-Tracker
Apache License 2.0
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/DualScreenSettings.kt
Konyaco
574,321,009
false
{"Kotlin": 11029508, "Java": 256912}
package com.konyaco.fluent.icons.filled import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Filled.DualScreenSettings: ImageVector get() { if (_dualScreenSettings != null) { return _dualScreenSettings!! } _dualScreenSettings = fluentIcon(name = "Filled.DualScreenSettings") { fluentPath { moveTo(13.27f, 2.98f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -1.44f, 2.5f) lineToRelative(-0.58f, 0.14f) arcToRelative(5.73f, 5.73f, 0.0f, false, false, 0.0f, 1.8f) lineToRelative(0.54f, 0.13f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 1.45f, 2.51f) lineToRelative(-0.18f, 0.64f) curveToRelative(0.44f, 0.38f, 0.94f, 0.7f, 1.48f, 0.92f) lineToRelative(0.5f, -0.52f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.9f, 0.0f) lineToRelative(0.5f, 0.52f) arcToRelative(5.28f, 5.28f, 0.0f, false, false, 1.48f, -0.9f) lineToRelative(-0.2f, -0.7f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 1.44f, -2.5f) lineToRelative(0.59f, -0.14f) arcToRelative(5.73f, 5.73f, 0.0f, false, false, -0.01f, -1.8f) lineToRelative(-0.54f, -0.13f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -1.45f, -2.51f) lineToRelative(0.19f, -0.63f) curveToRelative(-0.44f, -0.39f, -0.94f, -0.7f, -1.49f, -0.93f) lineToRelative(-0.5f, 0.52f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.9f, 0.0f) lineToRelative(-0.5f, -0.52f) curveToRelative(-0.53f, 0.22f, -1.03f, 0.53f, -1.47f, 0.91f) lineToRelative(0.2f, 0.69f) close() moveTo(16.5f, 8.0f) curveToRelative(-0.8f, 0.0f, -1.45f, -0.67f, -1.45f, -1.5f) reflectiveCurveTo(15.7f, 5.0f, 16.5f, 5.0f) curveToRelative(0.8f, 0.0f, 1.45f, 0.67f, 1.45f, 1.5f) reflectiveCurveTo(17.3f, 8.0f, 16.5f, 8.0f) close() moveTo(16.5f, 13.0f) arcTo(6.5f, 6.5f, 0.0f, false, false, 22.0f, 9.96f) verticalLineToRelative(10.29f) curveToRelative(0.0f, 0.97f, -0.78f, 1.75f, -1.75f, 1.75f) lineTo(13.0f, 22.0f) curveToRelative(-0.09f, 0.0f, -0.17f, 0.0f, -0.26f, -0.02f) lineTo(12.74f, 11.81f) arcTo(6.47f, 6.47f, 0.0f, false, false, 16.5f, 13.0f) close() moveTo(16.24f, 17.5f) horizontalLineToRelative(-1.6f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, 1.5f) lineTo(16.34f, 19.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, -1.5f) horizontalLineToRelative(-0.1f) close() moveTo(10.0f, 6.5f) lineTo(10.0f, 6.0f) lineTo(3.75f, 6.0f) curveTo(2.78f, 6.0f, 2.0f, 6.78f, 2.0f, 7.75f) verticalLineToRelative(12.5f) curveTo(2.0f, 21.2f, 2.78f, 22.0f, 3.75f, 22.0f) lineTo(11.0f, 22.0f) curveToRelative(0.08f, 0.0f, 0.16f, 0.0f, 0.25f, -0.02f) lineTo(11.25f, 10.33f) arcTo(6.47f, 6.47f, 0.0f, false, true, 10.0f, 6.5f) close() moveTo(9.24f, 17.5f) horizontalLineToRelative(0.1f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, 1.5f) lineTo(7.65f, 19.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, -1.5f) horizontalLineToRelative(1.6f) close() } } return _dualScreenSettings!! } private var _dualScreenSettings: ImageVector? = null
4
Kotlin
4
155
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
4,143
compose-fluent-ui
Apache License 2.0
app/src/main/java/com/apps/quixom/arshaps/MainActivity.kt
Fenscode
149,290,389
false
null
package com.apps.quixom.arshaps import android.graphics.Point import android.net.Uri import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.view.View import com.apps.quixom.arshaps.utility.PointerDrawable import com.google.ar.core.* import com.google.ar.sceneform.FrameTime import com.google.ar.sceneform.Scene import com.google.ar.sceneform.ux.ArFragment import kotlinx.android.synthetic.main.activity_main.* import android.widget.ImageView import android.widget.LinearLayout import android.support.v7.app.AlertDialog import com.google.ar.core.HitResult import com.google.ar.sceneform.rendering.ModelRenderable import com.google.ar.core.Anchor import com.google.ar.sceneform.AnchorNode import com.google.ar.sceneform.ux.TransformableNode import com.google.ar.sceneform.rendering.Renderable class MainActivity : AppCompatActivity(), Scene.OnUpdateListener { var fragment: ArFragment? = null val pointerDrawable: PointerDrawable = PointerDrawable() var isTracking: Boolean = false var isHitting: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) fragment = supportFragmentManager.findFragmentById(R.id.sceneform_fragment) as ArFragment fragment!!.arSceneView.scene.addOnUpdateListener(this) initializeGallery() fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } } override fun onUpdate(frameTime: FrameTime?) { fragment?.onUpdate(frameTime) onViewUpdate() } private fun onViewUpdate(): Unit { val trackingChanged = upTracking() val contentView = findViewById<View>(android.R.id.content) if (trackingChanged) { if (isTracking) { contentView.overlay.add(pointerDrawable) } else { contentView.overlay.remove(pointerDrawable) } contentView.invalidate() } if (isTracking) { val hitTestChanged = updateHitTest() if (hitTestChanged) { pointerDrawable.setEnabled(isHitting) contentView.invalidate() } } } private fun upTracking(): Boolean { val frame: Frame = fragment?.arSceneView!!.arFrame val wasTracking = isTracking isTracking = true && frame.camera.trackingState == TrackingState.TRACKING return isTracking != wasTracking } private fun updateHitTest(): Boolean { val frame: Frame = fragment?.arSceneView!!.arFrame val pt: Point = getScreenCenter() val hitsList: ArrayList<HitResult> = ArrayList() val wasHitting = isHitting isHitting = false if (true) { hitsList.addAll(frame.hitTest(pt.x.toFloat(), pt.y.toFloat())) for (hit in hitsList) { val trackable = hit.trackable if (trackable is Plane && trackable.isPoseInPolygon(hit.hitPose)) { isHitting = true break } } } return wasHitting != isHitting } private fun getScreenCenter(): Point { val vw: View = findViewById<View>(android.R.id.content) return Point(vw.width.div(2), vw.height.div(2)) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } private fun initializeGallery() { val gallery = findViewById<LinearLayout>(R.id.gallery_layout) val andy = ImageView(this) andy.setImageResource(R.drawable.droid_thumb) andy.contentDescription = "andy" andy.setOnClickListener { view -> addObject(Uri.parse("andy.sfb")) } gallery.addView(andy) val cabin = ImageView(this) cabin.setImageResource(R.drawable.cabin_thumb) cabin.contentDescription = "cabin" cabin.setOnClickListener { view -> addObject(Uri.parse("Cabin.sfb")) } gallery.addView(cabin) val house = ImageView(this) house.setImageResource(R.drawable.house_thumb) house.contentDescription = "house" house.setOnClickListener { view -> addObject(Uri.parse("House.sfb")) } gallery.addView(house) val igloo = ImageView(this) igloo.setImageResource(R.drawable.igloo_thumb) igloo.contentDescription = "igloo" igloo.setOnClickListener { view -> addObject(Uri.parse("igloo.sfb")) } gallery.addView(igloo) } private fun addObject(model: Uri) { val frame = fragment!!.arSceneView.arFrame val pt = getScreenCenter() val hits: List<HitResult> if (frame != null) { hits = frame.hitTest(pt.x.toFloat(), pt.y.toFloat()) for (hit in hits) { val trackable = hit.trackable if (trackable is Plane && trackable.isPoseInPolygon(hit.hitPose)) { placeObject(fragment!!, hit.createAnchor(), model) break } } } } private fun placeObject(fragment: ArFragment, anchor: Anchor, model: Uri) { val renderableFuture = ModelRenderable.builder() .setSource(fragment.context, model) .build() .thenAccept { renderable -> addNodeToScene(fragment, anchor, renderable) } .exceptionally { throwable -> val builder = AlertDialog.Builder(this) builder.setMessage(throwable.message) .setTitle("Codelab error!") val dialog = builder.create() dialog.show() null } } private fun addNodeToScene(fragment: ArFragment, anchor: Anchor, renderable: Renderable) { val anchorNode = AnchorNode(anchor) val node = TransformableNode(fragment.transformationSystem) node.renderable = renderable node.setParent(anchorNode) fragment.arSceneView.scene.addChild(anchorNode) node.select() } }
0
Kotlin
0
2
a1df7afa54c383edddca946956cb45a673db4044
6,929
AR_Stickers
Apache License 2.0
compiler/testData/diagnostics/tests/inference/reportingImprovements/kt42620.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// SKIP_TXT class Foo fun main1() = when { else -> <!NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER, TYPE_MISMATCH!>Foo::plus<!> } fun main2() = if (true) <!NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>Foo::<!UNRESOLVED_REFERENCE!>minus<!><!> else <!NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>Foo::<!UNRESOLVED_REFERENCE!>times<!><!> fun main3() = if (true) { Foo::<!UNRESOLVED_REFERENCE!>minus<!> } else { Foo::<!UNRESOLVED_REFERENCE!>times<!> } fun main4() = try { Foo::<!UNRESOLVED_REFERENCE!>minus<!> } finally { Foo::<!UNRESOLVED_REFERENCE!>times<!> } fun main5() = <!NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>Foo::<!UNRESOLVED_REFERENCE!>minus<!><!> ?: <!NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>Foo::<!UNRESOLVED_REFERENCE!>times<!><!>
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
754
kotlin
Apache License 2.0
TripKitAndroid/src/main/java/com/skedgo/tripkit/a2brouting/SingleRouteService.kt
skedgo
38,415,407
false
{"Java": 815763, "Kotlin": 434506}
package com.skedgo.tripkit.a2brouting import com.skedgo.tripkit.common.model.Query import com.skedgo.tripkit.TransportModeFilter import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import com.skedgo.tripkit.routing.TripGroup /** * A decorator of [RouteService] that performs only one routing request. * For example, if we ask it to route from A to B, and while that request * is still progress and later we ask it to route from C to B, * then the request A-to-B will be cancelled. * Cancellation is invoked asynchronously. That means the execution * of the request C-to-D doesn't have to wait for * the cancellation of the request A-to-B to be done to get started. */ class SingleRouteService(private val routeService: RouteService) : RouteService { /* toSerialized() to be thread-safe. */ private val cancellationSignal = PublishSubject.create<Any>().toSerialized() override fun routeAsync(query: Query, transportModeFilter: TransportModeFilter): Observable<List<TripGroup>> { cancellationSignal.onNext(Any()) return routeService.routeAsync(query, transportModeFilter) .takeUntil(cancellationSignal) } }
2
Java
3
4
2b5604f11975cc84c24b83ebb6fde9e34815a8ae
1,215
tripkit-android
Apache License 2.0
imageviewer/src/main/java/com/stfalcon/imageviewer/StfalconImageViewer.kt
Goooler
350,295,171
true
{"Kotlin": 62353}
/* * Copyright 2018 stfalcon.com * * 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.stfalcon.imageviewer import android.content.Context import android.view.View import android.widget.ImageView import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.DimenRes import androidx.annotation.IntRange import androidx.annotation.Px import androidx.core.content.ContextCompat import com.stfalcon.imageviewer.listeners.OnDismissListener import com.stfalcon.imageviewer.listeners.OnImageChangeListener import com.stfalcon.imageviewer.loader.ImageLoader import com.stfalcon.imageviewer.viewer.builder.BuilderData import com.stfalcon.imageviewer.viewer.dialog.ImageViewerDialog import kotlin.math.roundToInt @Suppress("MemberVisibilityCanBePrivate", "unused") class StfalconImageViewer<T> private constructor( context: Context, private val builderData: BuilderData<T> ) { private val dialog = ImageViewerDialog(context, builderData) /** * Displays the built viewer if passed list of images is not empty * * @param animate whether the passed transition view should be animated on open. Useful for screen rotation handling. */ @JvmOverloads fun show(animate: Boolean = true) { if (builderData.images.isNotEmpty()) { dialog.show(animate) } } /** * Closes the viewer with suitable close animation */ fun close() { dialog.close() } /** * Dismisses the dialog with no animation */ fun dismiss() { dialog.dismiss() } /** * Updates an existing images list if a new list is not empty, otherwise closes the viewer */ fun updateImages(images: Array<T>) { updateImages(images.toList()) } /** * Updates an existing images list if a new list is not empty, otherwise closes the viewer */ fun updateImages(images: List<T>) { if (images.isNotEmpty()) { dialog.updateImages(images) } else { dialog.close() } } fun currentPosition(): Int { return dialog.getCurrentPosition() } fun setCurrentPosition(@IntRange(from = 0) position: Int): Int { return dialog.setCurrentPosition(position) } /** * Updates transition image view. * Useful for a case when image position has changed and you want to update the transition animation target. */ fun updateTransitionImage(imageView: ImageView?) { dialog.updateTransitionImage(imageView) } /** * Builder class for [StfalconImageViewer] */ class Builder<T>(private val context: Context, images: List<T>, imageLoader: ImageLoader<T>) { private val data: BuilderData<T> = BuilderData(images, imageLoader) constructor(context: Context, images: Array<T>, imageLoader: ImageLoader<T>) : this( context, images.toList(), imageLoader ) /** * Sets a position to start viewer from. * * @return This Builder object to allow calls chaining */ fun withStartPosition(@IntRange(from = 0) position: Int): Builder<T> = apply { data.startPosition = position } /** * Sets a background color value for the viewer * * @return This Builder object to allow calls chaining */ fun withBackgroundColor(@ColorInt color: Int): Builder<T> = apply { data.backgroundColor = color } /** * Sets a background color resource for the viewer * * @return This Builder object to allow calls chaining */ fun withBackgroundColorResource(@ColorRes color: Int): Builder<T> = withBackgroundColor(ContextCompat.getColor(context, color)) /** * Sets custom overlay view to be shown over the viewer. * Commonly used for image description or counter displaying. * * @return This Builder object to allow calls chaining */ fun withOverlayView(view: View?): Builder<T> = apply { data.overlayView = view } /** * Sets space between the images using dimension. * * @return This Builder object to allow calls chaining */ fun withImagesMargin(@DimenRes dimen: Int): Builder<T> = apply { data.imageMarginPixels = context.resources.getDimension(dimen).roundToInt() } /** * Sets space between the images in pixels. * * @return This Builder object to allow calls chaining */ fun withImageMarginPixels(@Px marginPixels: Int): Builder<T> = apply { data.imageMarginPixels = marginPixels } /** * Sets overall padding for zooming and scrolling area using dimension. * * @return This Builder object to allow calls chaining */ fun withContainerPadding(@DimenRes padding: Int): Builder<T> { @Px val paddingPx = context.resources.getDimension(padding).roundToInt() return withContainerPaddingPixels(paddingPx, paddingPx, paddingPx, paddingPx) } /** * Sets `start`, `top`, `end` and `bottom` padding for zooming and scrolling area using dimension. * * @return This Builder object to allow calls chaining */ fun withContainerPadding( @DimenRes start: Int, @DimenRes top: Int, @DimenRes end: Int, @DimenRes bottom: Int ): Builder<T> = withContainerPaddingPixels( context.resources.getDimension(start).roundToInt(), context.resources.getDimension(top).roundToInt(), context.resources.getDimension(end).roundToInt(), context.resources.getDimension(bottom).roundToInt() ) /** * Sets overall padding for zooming and scrolling area in pixels. * * @return This Builder object to allow calls chaining */ fun withContainerPaddingPixels(@Px padding: Int): Builder<T> = apply { data.containerPaddingPixels = intArrayOf(padding, padding, padding, padding) } /** * Sets `start`, `top`, `end` and `bottom` padding for zooming and scrolling area in pixels. * * @return This Builder object to allow calls chaining */ fun withContainerPaddingPixels( @Px start: Int, @Px top: Int, @Px end: Int, @Px bottom: Int ): Builder<T> = apply { data.containerPaddingPixels = intArrayOf(start, top, end, bottom) } /** * Sets status bar visibility. True by default. * * @return This Builder object to allow calls chaining */ fun withHiddenStatusBar(value: Boolean): Builder<T> = apply { data.shouldStatusBarHide = value } /** * Enables or disables zooming. True by default. * * @return This Builder object to allow calls chaining */ fun allowZooming(value: Boolean): Builder<T> = apply { data.isZoomingAllowed = value } /** * Enables or disables the "Swipe to Dismiss" gesture. True by default. * * @return This Builder object to allow calls chaining */ fun allowSwipeToDismiss(value: Boolean): Builder<T> = apply { data.isSwipeToDismissAllowed = value } /** * Sets a target [ImageView] to be part of transition when opening or closing the viewer/ * * @return This Builder object to allow calls chaining */ fun withTransitionFrom(imageView: ImageView?): Builder<T> = apply { data.transitionView = imageView } /** * Sets [OnImageChangeListener] for the viewer. * * @return This Builder object to allow calls chaining */ fun withImageChangeListener(imageChangeListener: OnImageChangeListener?): Builder<T> = apply { data.imageChangeListener = imageChangeListener } /** * Sets [OnDismissListener] for viewer. * * @return This Builder object to allow calls chaining */ fun withDismissListener(onDismissListener: OnDismissListener?): Builder<T> = apply { data.onDismissListener = onDismissListener } /** * Creates a [StfalconImageViewer] with the arguments supplied to this builder. It does not * show the dialog. This allows the user to do any extra processing * before displaying the dialog. Use [.show] if you don't have any other processing * to do and want this to be created and displayed. */ fun build(): StfalconImageViewer<T> = StfalconImageViewer(context, data) /** * Creates the [StfalconImageViewer] with the arguments supplied to this builder and * shows the dialog. * * @param animate whether the passed transition view should be animated on open. Useful for screen rotation handling. */ @JvmOverloads fun show(animate: Boolean = true): StfalconImageViewer<T> = build().also { it.show(animate) } } }
1
Kotlin
1
1
0446ed892d519cb848673bcbe1b585df298e08d3
9,949
StfalconImageViewer
Apache License 2.0
js/js.translator/testData/box/char/charConversions.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// EXPECTED_REACHABLE_NODES: 1285 package foo fun box(): String { assertEquals('A', 'A'.toChar(), "toChar") assertEquals(65, 'A'.toInt(), "toInt") assertEquals(65.toShort(), 'A'.toShort(), "toShort") assertEquals(65.toByte(), 'A'.toByte(), "toByte") assertEquals(65.0, 'A'.toDouble(), "toDouble") assertEquals(65.0f, 'A'.toFloat(), "toFloat") assertEquals(65L, 'A'.toLong(), "toLong") return "OK" }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
433
kotlin
Apache License 2.0
kt/godot-library/src/main/kotlin/godot/gen/godot/LinkButton.kt
utopia-rise
289,462,532
false
{"Kotlin": 1464908, "GDScript": 492843, "C++": 484675, "C#": 10278, "C": 8523, "Shell": 8429, "Java": 2136, "CMake": 939, "Python": 75}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT", "RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate") package godot import godot.`annotation`.GodotBaseType import godot.core.TypeManager import godot.core.VariantArray import godot.core.VariantType.ARRAY import godot.core.VariantType.LONG import godot.core.VariantType.NIL import godot.core.VariantType.STRING import godot.core.memory.TransferContext import godot.util.VoidPtr import kotlin.Any import kotlin.Boolean import kotlin.Int import kotlin.Long import kotlin.String import kotlin.Suppress /** * A button that represents a link. * * A button that represents a link. This type of button is primarily used for interactions that cause a context change (like linking to a web page). * * See also [godot.BaseButton] which contains common properties and methods associated with this node. */ @GodotBaseType public open class LinkButton : BaseButton() { /** * The button's text that will be displayed inside the button's area. */ public var text: String get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getTextPtr, STRING) return (TransferContext.readReturnValue(STRING, false) as String) } set(`value`) { TransferContext.writeArguments(STRING to value) TransferContext.callMethod(rawPtr, MethodBindings.setTextPtr, NIL) } /** * The underline mode to use for the text. See [enum LinkButton.UnderlineMode] for the available modes. */ public var underline: UnderlineMode get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getUnderlineModePtr, LONG) return LinkButton.UnderlineMode.from(TransferContext.readReturnValue(LONG) as Long) } set(`value`) { TransferContext.writeArguments(LONG to value.id) TransferContext.callMethod(rawPtr, MethodBindings.setUnderlineModePtr, NIL) } /** * The [URI](https://en.wikipedia.org/wiki/Uniform_Resource_Identifier) for this [godot.LinkButton]. If set to a valid URI, pressing the button opens the URI using the operating system's default program for the protocol (via [godot.OS.shellOpen]). HTTP and HTTPS URLs open the default web browser. * * **Examples:** * * [codeblocks] * * [gdscript] * * uri = "https://godotengine.org" # Opens the URL in the default web browser. * * uri = "C:\SomeFolder" # Opens the file explorer at the given path. * * uri = "C:\SomeImage.png" # Opens the given image in the default viewing app. * * [/gdscript] * * [csharp] * * Uri = "https://godotengine.org"; // Opens the URL in the default web browser. * * Uri = "C:\SomeFolder"; // Opens the file explorer at the given path. * * Uri = "C:\SomeImage.png"; // Opens the given image in the default viewing app. * * [/csharp] * * [/codeblocks] */ public var uri: String get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getUriPtr, STRING) return (TransferContext.readReturnValue(STRING, false) as String) } set(`value`) { TransferContext.writeArguments(STRING to value) TransferContext.callMethod(rawPtr, MethodBindings.setUriPtr, NIL) } /** * Base text writing direction. */ public var textDirection: Control.TextDirection get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getTextDirectionPtr, LONG) return Control.TextDirection.from(TransferContext.readReturnValue(LONG) as Long) } set(`value`) { TransferContext.writeArguments(LONG to value.id) TransferContext.callMethod(rawPtr, MethodBindings.setTextDirectionPtr, NIL) } /** * Language code used for line-breaking and text shaping algorithms, if left empty current locale is used instead. */ public var language: String get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getLanguagePtr, STRING) return (TransferContext.readReturnValue(STRING, false) as String) } set(`value`) { TransferContext.writeArguments(STRING to value) TransferContext.callMethod(rawPtr, MethodBindings.setLanguagePtr, NIL) } /** * Set BiDi algorithm override for the structured text. */ public var structuredTextBidiOverride: TextServer.StructuredTextParser get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getStructuredTextBidiOverridePtr, LONG) return TextServer.StructuredTextParser.from(TransferContext.readReturnValue(LONG) as Long) } set(`value`) { TransferContext.writeArguments(LONG to value.id) TransferContext.callMethod(rawPtr, MethodBindings.setStructuredTextBidiOverridePtr, NIL) } /** * Set additional options for BiDi override. */ public var structuredTextBidiOverrideOptions: VariantArray<Any?> get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getStructuredTextBidiOverrideOptionsPtr, ARRAY) return (TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>) } set(`value`) { TransferContext.writeArguments(ARRAY to value) TransferContext.callMethod(rawPtr, MethodBindings.setStructuredTextBidiOverrideOptionsPtr, NIL) } public override fun new(scriptIndex: Int): Boolean { callConstructor(ENGINECLASS_LINKBUTTON, scriptIndex) return true } public enum class UnderlineMode( id: Long, ) { /** * The LinkButton will always show an underline at the bottom of its text. */ UNDERLINE_MODE_ALWAYS(0), /** * The LinkButton will show an underline at the bottom of its text when the mouse cursor is over it. */ UNDERLINE_MODE_ON_HOVER(1), /** * The LinkButton will never show an underline at the bottom of its text. */ UNDERLINE_MODE_NEVER(2), ; public val id: Long init { this.id = id } public companion object { public fun from(`value`: Long) = entries.single { it.id == `value` } } } public companion object internal object MethodBindings { public val setTextPtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "set_text") public val getTextPtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "get_text") public val setTextDirectionPtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "set_text_direction") public val getTextDirectionPtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "get_text_direction") public val setLanguagePtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "set_language") public val getLanguagePtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "get_language") public val setUriPtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "set_uri") public val getUriPtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "get_uri") public val setUnderlineModePtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "set_underline_mode") public val getUnderlineModePtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "get_underline_mode") public val setStructuredTextBidiOverridePtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "set_structured_text_bidi_override") public val getStructuredTextBidiOverridePtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "get_structured_text_bidi_override") public val setStructuredTextBidiOverrideOptionsPtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "set_structured_text_bidi_override_options") public val getStructuredTextBidiOverrideOptionsPtr: VoidPtr = TypeManager.getMethodBindPtr("LinkButton", "get_structured_text_bidi_override_options") } }
61
Kotlin
33
445
1dfa11d5c43fc9f85de2260b8e88f4911afddcb9
8,247
godot-kotlin-jvm
MIT License
src/main/kotlin/fr/jcgay/gradle/notifier/extension/NotifierConfiguration.kt
jcgay
34,996,280
false
null
package fr.jcgay.gradle.notifier.extension import java.util.Properties interface NotifierConfiguration { fun asProperties(): Properties }
14
Kotlin
1
18
9c59a26f58be9d76f42f83ac7f164471dc6af4b7
146
gradle-notifier
MIT License
src/main/kotlin/br/com/zupacademy/ratkovski/pix/carrega/GrpcExtensions.kt
Ratkovski
395,480,677
true
{"Kotlin": 104442, "Smarty": 2172, "Dockerfile": 164}
package br.com.zupacademy.ratkovski.pix.carrega import br.com.zupacademy.ratkovski.DetailsKeyPixRequest import br.com.zupacademy.ratkovski.DetailsKeyPixRequest.FiltroCase.* import javax.validation.ConstraintViolationException import javax.validation.Validator fun DetailsKeyPixRequest.toModel(validator: Validator):Filtro{ val filtro = when(filtroCase!!) { PIXID -> pixId.let { Filtro.PorPixId(clienteId = it.clienteId, pixId = it.pixId) } CHAVE -> Filtro.PorChave(chave) FILTRO_NOT_SET -> Filtro.Invalido() } val violations = validator.validate(filtro) if (violations.isNotEmpty()) { throw ConstraintViolationException(violations); } return filtro }
0
Kotlin
0
0
c4123d9e88247192717061e47fcb1ed6c55b2d9b
731
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/tests/CloseableGroup.kt
tecc
471,897,398
true
{"Kotlin": 5244117, "Python": 948, "JavaScript": 775, "HTML": 88, "Mustache": 77}
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.tests.utils.tests import java.io.* class CloseableGroup : Closeable { private val resources = mutableListOf<Closeable>() fun use(resource: Closeable) { resources.add(resource) } override fun close() { resources.forEach { it.close() } } }
7
Kotlin
1
1
4ccd943f96a483c5ea2cf50c0873e457c8af3e66
429
ktor
Apache License 2.0
compiler/tests-spec/testData/codegen/box/linked/overload-resolution/building-the-overload-candidate-set-ocs/operator-call/p-1/pos/2.9.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// WITH_STDLIB /* * KOTLIN CODEGEN BOX SPEC TEST (POSITIVE) * * SPEC VERSION: 0.1-488 * MAIN LINK: overload-resolution, building-the-overload-candidate-set-ocs, operator-call -> paragraph 1 -> sentence 2 * PRIMARY LINKS: overload-resolution, choosing-the-most-specific-candidate-from-the-overload-candidate-set, algorithm-of-msc-selection -> paragraph 3 -> sentence 3 * SECONDARY LINKS: statements, assignments, operator-assignments -> paragraph 2 -> sentence 1 * statements, assignments, operator-assignments -> paragraph 2 -> sentence 2 * statements, assignments, operator-assignments -> paragraph 2 -> sentence 3 * NUMBER: 9 * DESCRIPTION: nullable receiver and inline operator function */ fun cc() : C = C() fun box(): String { val a: A? = A(B()) a?.b += ::cc if (f3 && !f1 && !f2 && !f4) { f3 = false a?.b.plusAssign(::cc) if (f3 && !f1 && !f2 && !f4) return "OK" } return "NOK" } class A(val b: B) var f1 = false var f2 = false var f3 = false var f4 = false class B { inline operator fun plusAssign(c: ()->C) { f1 = true print("1") } inline operator fun plus(c: ()->C): C { f2 = true print("2") return c() } } @JvmName("aa") inline operator fun B?.plusAssign(c: ()->C) { f3 = true print("3") } @JvmName("bb") inline operator fun B?.plusAssign(c: ()->Any) { f4 = true print("4") } class C
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
1,444
kotlin
Apache License 2.0
analysis/analysis-api/testData/components/symbolInfoProvider/annotationApplicableTargets/nonAnnotationClass.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
class A() @<caret>A object Foo
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
31
kotlin
Apache License 2.0
compiler/testData/diagnostics/tests/dataFlowInfoTraversal/IfThenElse.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
fun bar(x: Int): Int = x + 1 fun foo() { val x: Int? = null bar(if (x == null) 0 else <!DEBUG_INFO_SMARTCAST!>x<!>) if (x == null) { bar(<!DEBUG_INFO_CONSTANT, TYPE_MISMATCH!>x<!>) return } else { bar(<!DEBUG_INFO_SMARTCAST!>x<!>) } bar(<!DEBUG_INFO_SMARTCAST!>x<!>) val y: Int? = null if (y is Int) { bar(<!DEBUG_INFO_SMARTCAST!>y<!>) } else { bar(<!TYPE_MISMATCH!>y<!>) return } bar(<!DEBUG_INFO_SMARTCAST!>y<!>) val z: Int? = null if (z != null) bar(<!DEBUG_INFO_SMARTCAST!>z<!>) bar(<!TYPE_MISMATCH!>z<!>) bar(z!!) if (<!SENSELESS_COMPARISON!>z != null<!>) bar(z<!UNNECESSARY_NOT_NULL_ASSERTION!>!!<!>) }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
726
kotlin
Apache License 2.0
app/src/main/java/org/kimp/mustep/utils/service/MediaPoolService.kt
KonstantIMP
501,167,167
false
{"Kotlin": 102716}
package org.kimp.mustep.utils.service import android.app.Service import android.content.Intent import android.net.Uri import android.os.Binder import android.os.IBinder import com.google.android.exoplayer2.ExoPlayer import com.google.android.exoplayer2.MediaItem import java.lang.Float.min import kotlin.math.roundToLong class MediaPoolService : Service() { private lateinit var player: ExoPlayer private val binder = MediaPoolBinder() override fun onCreate() { super.onCreate() player = ExoPlayer.Builder(this).build() } override fun onBind(intent: Intent): IBinder = binder override fun onDestroy() { super.onDestroy() player.release() } inner class MediaPoolBinder : Binder() { fun getService(): MediaPoolService = this@MediaPoolService } fun isPlaying(): Boolean = player.isPlaying fun setSource(uri: Uri) { player.addMediaItem(MediaItem.fromUri(uri)) player.prepare() } fun getProgress(): Float { return min(100.0f, player.currentPosition * 100.0f / player.contentDuration) } fun seekToProgress(progress: Float) { player.seekTo( (player.contentDuration * progress / 100.0f).roundToLong() ) } fun playOrResume() { player.play() } fun pause() { player.pause() } fun stopPlaying() { player.stop() player.clearMediaItems() } }
0
Kotlin
1
0
4ce18c7a9512dcab3955365b3a109f7529fe1875
1,454
muStepKotlin
MIT License
scabbard-gradle-plugin/src/main/kotlin/dev/arunkumar/scabbard/gradle/projectmeta/ProjectMeta.kt
ZacSweers
231,048,146
true
{"Kotlin": 70124, "Java": 935}
package dev.arunkumar.scabbard.gradle.projectmeta import org.gradle.api.Project private const val KOTLIN_ANDROID = "kotlin-android" const val ANNOTATION_PROCESSOR = "annotationProcessor" internal val Project.hasJavaAnnotationProcessorConfig get() = configurations.findByName( ANNOTATION_PROCESSOR ) != null internal val Project.hasKotlinAndroidPlugin get() = plugins.findPlugin(KOTLIN_ANDROID) != null internal val Project.hasKotlinPlugin get() = plugins.findPlugin("kotlin") != null internal val Project.isKotlinProject get() = hasKotlinAndroidPlugin || hasKotlinPlugin
0
null
0
0
170d1dcf7778ebc1ec010d27582c5ae8ed064fd9
584
scabbard
Apache License 2.0
compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Sequence.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// WITH_STDLIB fun test(s: Sequence<Int>) { val <!UNUSED_VARIABLE!>foo<!> = s.<!USELESS_CALL_ON_NOT_NULL!>orEmpty()<!> }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
126
kotlin
Apache License 2.0
integration-tests/gradle/projects/it-wasm-basic/settings.gradle.kts
Mu-L
406,989,990
true
{"Kotlin": 3712559, "CSS": 63401, "JavaScript": 33594, "TypeScript": 13611, "HTML": 6976, "FreeMarker": 4120, "Java": 3923, "SCSS": 2794, "Shell": 970}
/* * Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ apply(from = "../template.settings.gradle.kts") rootProject.name = "it-wasm-js-wasi-basic"
1
Kotlin
0
0
a1c3b89871a3a4f90d6441db356685d48a84ab63
202
dokka
Apache License 2.0
epli-backend/src/main/kotlin/ru/epli/features/register/RegisterRouting.kt
Uliana2303
544,899,725
false
{"Kotlin": 136839}
package ru.epli.features.register import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import ru.epli.cache.TokenCache import ru.epli.cache.inMemoryCache import ru.epli.utils.isValidEmail import java.util.* fun Application.configureRegisterRouting() { routing { post("/register") { val registerController = RegisterController(call) registerController.registerNewUser() } } }
0
Kotlin
1
0
ac10c539bfd1127339b68af95a7c09ffbcdf1685
530
summer-practice
MIT License
src/main/java/org/ethtrader/ticker/DataReader.kt
jaycarey
69,341,866
false
null
package org.ethtrader.ticker import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.module.kotlin.registerKotlinModule import org.glassfish.jersey.client.ClientProperties import java.math.BigDecimal import java.security.SecureRandom import java.security.cert.X509Certificate import javax.net.ssl.SSLContext import javax.net.ssl.X509TrustManager import javax.ws.rs.client.ClientBuilder class DataReader(providers: Map<String, ProviderConf>) { private val client = ClientBuilder.newBuilder() .property(ClientProperties.CONNECT_TIMEOUT, 10000) .property(ClientProperties.READ_TIMEOUT, 10000) .sslContext(sslContext()) private val objectMapper = ObjectMapper() .registerKotlinModule() private val providerFunctions = providers.map { provider -> var cache = mapOf<String, JsonNode>() provider.key to { values: List<String> -> try { val url = provider.value.url.format(*values.toTypedArray()) var rootNode = cache[url] if (rootNode == null) { rootNode = readObject(url) cache += url to rootNode } if (provider.value.filter != null) { rootNode = rootNode.find { it.at(provider.value.filter).asText() == values.last() } } if (rootNode is ArrayNode && rootNode.size() == 1) { rootNode = rootNode.first() } println("JSON Response form provider [${provider.key}], $values: $rootNode") println("Reading fields: ${provider.value.fields}") rootNode?.parseFields(provider.value.fields) } catch (e: Throwable) { println("Unexpected exception: " + e.printStackTrace()) mapOf<String, BigDecimal>() } } }.toMap() fun read(dataPoints: Map<String, List<String>>): Map<String, Map<String, BigDecimal?>?> { val data = dataPoints.map { val function = providerFunctions.get(it.value.first()) it.key to if (function == null) null else function(it.value.drop(1)) }.toMap() println("Data points retrieved:\n - ${data.map { it }.joinToString("\n - ")}") return data } private fun JsonNode.parseFields(fields: Map<String, String>): Map<String, BigDecimal?> = fields.map { it.key to try { val text = at(it.value).asText() if (text.isNullOrEmpty()) BigDecimal.ZERO else BigDecimal(text) } catch (t: Throwable) { null } }.toMap() private fun readObject(url: String): JsonNode { return retry(times = 10) { Thread.sleep(300) val urlAndQuery = url.split("?") var target = client.build().target(urlAndQuery[0]) target = urlAndQuery.getOrNull(1)?.split(",")?.map { it.split("=") }?.fold(target) { t, k -> t.queryParam(k[0], k[1]) } ?: target println("Fetching from URL: $target") val request = target.request() val response = request.get() val json = response.readEntity(String::class.java) objectMapper.readTree(json) } } private fun sslContext(): SSLContext? { val sslContext = SSLContext.getInstance("SSL") sslContext.init(null, arrayOf(object : X509TrustManager { override fun checkClientTrusted(p0: Array<out X509Certificate>?, p1: String?) = Unit override fun checkServerTrusted(p0: Array<out X509Certificate>?, p1: String?) = Unit override fun getAcceptedIssuers(): Array<out X509Certificate>? = null }), SecureRandom()) return sslContext } } fun <T> retry(times: Int, total: Int = times, action: () -> T): T = try { Thread.sleep(total.toLong() - times) action() } catch (e: Throwable) { if (times > 0) retry(times - 1, total, action) else throw e }
0
Kotlin
3
3
6a4883fa9eed62af2eaa481069406ad52d1f6ad7
4,229
ethtrader-ticker
Apache License 2.0
bootstrap-icons-compose/src/main/java/com/wiryadev/bootstrapiconscompose/bootstrapicons/normal/FileText.kt
wiryadev
380,639,096
false
{"Kotlin": 4825599}
package com.wiryadev.bootstrapiconscompose.bootstrapicons.normal import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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 com.wiryadev.bootstrapiconscompose.bootstrapicons.NormalGroup public val NormalGroup.FileText: ImageVector get() { if (_fileText != null) { return _fileText!! } _fileText = Builder(name = "FileText", defaultWidth = 16.0.dp, defaultHeight = 16.0.dp, viewportWidth = 16.0f, viewportHeight = 16.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(5.0f, 4.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, 1.0f) horizontalLineToRelative(6.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, -1.0f) lineTo(5.0f, 4.0f) close() moveTo(4.5f, 6.5f) arcTo(0.5f, 0.5f, 0.0f, false, true, 5.0f, 6.0f) horizontalLineToRelative(6.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.0f, 1.0f) lineTo(5.0f, 7.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, true, -0.5f, -0.5f) close() moveTo(5.0f, 8.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, 1.0f) horizontalLineToRelative(6.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, -1.0f) lineTo(5.0f, 8.0f) close() moveTo(5.0f, 10.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, 1.0f) horizontalLineToRelative(3.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, -1.0f) lineTo(5.0f, 10.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(2.0f, 2.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f) horizontalLineToRelative(8.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f) verticalLineToRelative(12.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, 2.0f) lineTo(4.0f, 16.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, -2.0f) lineTo(2.0f, 2.0f) close() moveTo(12.0f, 1.0f) lineTo(4.0f, 1.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.0f, 1.0f) verticalLineToRelative(12.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, 1.0f) horizontalLineToRelative(8.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, -1.0f) lineTo(13.0f, 2.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.0f, -1.0f) close() } } .build() return _fileText!! } private var _fileText: ImageVector? = null
0
Kotlin
0
2
1c199d953dc96b261aab16ac230dc7f01fb14a53
3,918
bootstrap-icons-compose
MIT License