code
stringlengths
6
1.04M
language
stringclasses
1 value
AST_depth
int64
-1
40
alphanumeric_fraction
float64
0
0.97
max_line_length
int64
0
1k
avg_line_length
float64
0
171
num_lines
int64
0
4.25k
source
stringclasses
1 value
package motocitizen.ui.rows.message import android.content.Context import android.graphics.Color import android.view.Gravity import android.view.View import android.widget.FrameLayout import android.widget.LinearLayout import motocitizen.content.message.Message import motocitizen.main.R import motocitizen.utils.name import motocitizen.utils.timeString import org.jetbrains.anko.matchParent import org.jetbrains.anko.textView import org.jetbrains.anko.wrapContent //todo smell abstract class MessageRow(context: Context, val message: Message, val type: Type) : FrameLayout(context) { enum class Type { FIRST, MIDDLE, LAST, ONE } //todo WTF!? abstract val ONE: Int abstract val FIRST: Int private val MIDDLE = R.drawable.message_row_middle private val LAST = R.drawable.message_row_last override fun onAttachedToWindow() { super.onAttachedToWindow() setBackground() joinRowsByOwner() textView(message.owner.name()) { layoutParams = LayoutParams(matchParent, wrapContent) visibility = if (type == Type.FIRST || type == Type.ONE) View.VISIBLE else View.INVISIBLE setTextColor(Color.parseColor(if (message.isOwner) "#00ffff" else "#ffff00")) } textView(String.format("%s%s \u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0", if (type == Type.MIDDLE || type == Type.LAST) "" else "\n", message.text)) { layoutParams = LayoutParams(wrapContent, matchParent) maxLines = 10 } textView(message.time.timeString()) { layoutParams = LayoutParams(matchParent, wrapContent) gravity = Gravity.END or Gravity.BOTTOM setTextColor(Color.parseColor(if (message.isOwner) "#21272b" else "#21272b")) //todo 0xff21272b.toInt() } } private fun setBackground() = setBackgroundResource( when (type) { Type.MIDDLE -> MIDDLE Type.FIRST -> FIRST Type.LAST -> LAST Type.ONE -> ONE }) private fun joinRowsByOwner() { if (type != Type.MIDDLE && type != Type.LAST) return val lp = LinearLayout.LayoutParams(matchParent, wrapContent) lp.topMargin = 0 layoutParams = lp } }
kotlin
22
0.658568
176
36.193548
62
starcoderdata
<reponame>andrzej-nov/Tangler package com.andrzejn.tangler import aurelienribon.tweenengine.Tween import aurelienribon.tweenengine.TweenManager import com.andrzejn.tangler.helper.* import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch import com.badlogic.gdx.graphics.g2d.Sprite /** * Holds all application-wide objects. * Singleton objects cause a lot of issues on Android because of its memory allocation/release strategy, * so everything should be passed in the Context object on each app object creation or method call * where it is needed. */ class Context( /** * Reference to the Main game object. Needed to switch game screens on different points of execution. */ val game: Main ) { /** * The batch for drawing all screen contents. */ lateinit var batch: PolygonSpriteBatch /** * The batch for drawing tile sprites. It is simpler to have two separate batches than to remember when to switch * the camera on single batch */ lateinit var tileBatch: PolygonSpriteBatch /** * Atlas object that loads and provides sprite textures, fonts etc. */ val a: Atlas = Atlas() /** * Drawing helper objects (cameras, ShapeDrawers etc.) */ val drw: Draw = Draw(this) /** * Helper object for some fade-out animations */ val fader: Fader = Fader(this) /** * Helper object for the game saving/loading */ val sav: SaveGame = SaveGame(this) /** * Helper object to track and display the score */ val score: Score = Score(this) /** * Game settings access (settings are stored using GDX system Preferences class) */ val gs: GameSettings = GameSettings() /** * The main object that handles all animations */ val tweenManager: TweenManager = TweenManager() init { // Need to specify which objects' properties will be used for animations Tween.registerAccessor(Sprite::class.java, SpriteAccessor()) Tween.registerAccessor(Fader::class.java, FaderAccessor()) Tween.registerAccessor(Score::class.java, ScoreAccessor()) } /** * Not clearly documented but working method to check whether some transition animations are in progress * (and ignore user input until animations complete, for example) */ fun tweenAnimationRunning(): Boolean { return tweenManager.objects.isNotEmpty() } /** * Many times we'll need to fit a sprite into arbitrary rectangle, retaining proportions */ fun fitToRect(s: Sprite, wBound: Float, hBound: Float) { var width = wBound var height = wBound * s.regionHeight / s.regionWidth if (height > hBound) { height = hBound width = hBound * s.regionWidth / s.regionHeight } s.setSize(width, height) } /** * (Re)create OpenGL drawing batches. Called only on application startup or unpause */ fun initBatches() { if (this::batch.isInitialized) // Check if the lateinit property has been initialised already batch.dispose() batch = PolygonSpriteBatch() if (this::tileBatch.isInitialized) tileBatch.dispose() tileBatch = PolygonSpriteBatch() drw.initBatch(batch) drw.initTileBatch(tileBatch) } /** * Shortened accessor to the screen viewportWidth */ val viewportWidth: Float get() = drw.screen.worldWidth /** * Shortened accessor to the screen viewportHeight */ val viewportHeight: Float get() = drw.screen.worldHeight /** * Cleanup */ fun dispose() { if (this::batch.isInitialized) batch.dispose() if (this::tileBatch.isInitialized) tileBatch.dispose() score.dispose() } }
kotlin
14
0.651254
117
28.453846
130
starcoderdata
package com.example interface ImageStorage { fun putImage(image: ByteArray): Int fun getImage(id: Int): ByteArray? fun getLink(path: String?): String? fun deleteImage(id: Int) }
kotlin
8
0.690355
39
17
11
starcoderdata
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.decompiler.common import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.FileViewProvider import com.intellij.psi.PsiManager import com.intellij.psi.compiled.ClassFileDecompilers import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.decompiler.KotlinDecompiledFileViewProvider import org.jetbrains.kotlin.idea.decompiler.KtDecompiledFile import org.jetbrains.kotlin.idea.decompiler.textBuilder.DecompiledText import org.jetbrains.kotlin.idea.decompiler.textBuilder.buildDecompiledText import org.jetbrains.kotlin.idea.decompiler.textBuilder.defaultDecompilerRendererOptions import org.jetbrains.kotlin.metadata.ProtoBuf import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion import org.jetbrains.kotlin.metadata.deserialization.NameResolverImpl import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.serialization.SerializerExtensionProtocol import org.jetbrains.kotlin.serialization.deserialization.ClassDeserializer import org.jetbrains.kotlin.serialization.deserialization.FlexibleTypeDeserializer import org.jetbrains.kotlin.serialization.deserialization.getClassId import org.jetbrains.kotlin.utils.addIfNotNull import java.io.IOException abstract class KotlinMetadataDecompiler<out V : BinaryVersion>( private val fileType: FileType, private val serializerProtocol: () -> SerializerExtensionProtocol, private val flexibleTypeDeserializer: FlexibleTypeDeserializer, private val expectedBinaryVersion: () -> V, private val invalidBinaryVersion: () -> V, stubVersion: Int ) : ClassFileDecompilers.Full() { private val metadataStubBuilder: KotlinMetadataStubBuilder = KotlinMetadataStubBuilder(stubVersion, fileType, serializerProtocol, ::readFileSafely) private val renderer: DescriptorRenderer by lazy { DescriptorRenderer.withOptions { defaultDecompilerRendererOptions() } } abstract fun readFile(bytes: ByteArray, file: VirtualFile): FileWithMetadata? override fun accepts(file: VirtualFile) = file.fileType == fileType override fun getStubBuilder() = metadataStubBuilder override fun createFileViewProvider(file: VirtualFile, manager: PsiManager, physical: Boolean): FileViewProvider { return KotlinDecompiledFileViewProvider(manager, file, physical) { provider -> if (readFileSafely(provider.virtualFile) == null) { null } else { KtDecompiledFile(provider, this::buildDecompiledText) } } } private fun readFileSafely(file: VirtualFile, content: ByteArray? = null): FileWithMetadata? { if (!file.isValid) return null return try { readFile(content ?: file.contentsToByteArray(false), file) } catch (e: IOException) { // This is needed because sometimes we're given VirtualFile instances that point to non-existent .jar entries. // Such files are valid (isValid() returns true), but an attempt to read their contents results in a FileNotFoundException. // Note that although calling "refresh()" instead of catching an exception would seem more correct here, // it's not always allowed and also is likely to degrade performance null } } private fun buildDecompiledText(virtualFile: VirtualFile): DecompiledText { if (virtualFile.fileType != fileType) { error("Unexpected file type ${virtualFile.fileType}") } val file = readFileSafely(virtualFile) return when (file) { null -> { createIncompatibleAbiVersionDecompiledText(expectedBinaryVersion(), invalidBinaryVersion()) } is FileWithMetadata.Incompatible -> { createIncompatibleAbiVersionDecompiledText(expectedBinaryVersion(), file.version) } is FileWithMetadata.Compatible -> { val packageFqName = file.packageFqName val resolver = KotlinMetadataDeserializerForDecompiler( packageFqName, file.proto, file.nameResolver, file.version, serializerProtocol(), flexibleTypeDeserializer ) val declarations = arrayListOf<DeclarationDescriptor>() declarations.addAll(resolver.resolveDeclarationsInFacade(packageFqName)) for (classProto in file.classesToDecompile) { val classId = file.nameResolver.getClassId(classProto.fqName) declarations.addIfNotNull(resolver.resolveTopLevelClass(classId)) } buildDecompiledText(packageFqName, declarations, renderer) } } } } sealed class FileWithMetadata { class Incompatible(val version: BinaryVersion) : FileWithMetadata() open class Compatible( val proto: ProtoBuf.PackageFragment, val version: BinaryVersion, serializerProtocol: SerializerExtensionProtocol ) : FileWithMetadata() { val nameResolver = NameResolverImpl(proto.strings, proto.qualifiedNames) val packageFqName = FqName(nameResolver.getPackageFqName(proto.`package`.getExtension(serializerProtocol.packageFqName))) open val classesToDecompile: List<ProtoBuf.Class> = proto.class_List.filter { proto -> val classId = nameResolver.getClassId(proto.fqName) !classId.isNestedClass && classId !in ClassDeserializer.BLACK_LIST } } }
kotlin
22
0.721975
135
45.176471
136
starcoderdata
<filename>app/src/main/java/com/example/androiddevchallenge/data/MockData.kt<gh_stars>1-10 /* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.data import com.example.androiddevchallenge.R import com.example.androiddevchallenge.model.Pet import com.example.androiddevchallenge.model.PetType import com.example.androiddevchallenge.model.Sex val pets = listOf( Pet( name = "Mitka", resource = R.drawable.mitka, type = PetType.Cat, sex = Sex.Male, ageYears = 8..8, description = "Labai draugiškas katinas rainys, mirė šeimininkas. 11 m. Micka.", url = "https://tautmilesgloba.lt/gyvunai/mitka/", ), Pet( name = "Fredis", resource = R.drawable.fredis, type = PetType.Dog, sex = Sex.Male, ageYears = 1..3, description = """ ❤️ Ieškome namų Šalčininkų Fredžiui ❤️ Fredis mums atvežtas iš Šalčininkų. Žmonės jį rado išsigandusį su patinusiu pilvu. Atrodė, kaip auglys ar išvarža, bet laimė, nieko baisaus – tik uždegimas. Šiuo metu atlikta kastracija. Labai ieškom mylinčių šeimininkų Fredžiui ❤️ Žmogus, kurį šis šuo pamilsta bus visas gyvenimas! Tačiau, kaip ir daugelis gyvūnų turi minusų, šiam ponui nepatinka, kai nepažįstami lenda glostyti – smalsauja, seka iš paskos, stebi, bet nedrįsk kišti nagų, nes įkąsiu. +370 650 71786 Tautmilė (prieglaudos sodyboje prie Medininkų) """.trimIndent(), url = "https://tautmilesgloba.lt/gyvunai/fredis-2/", ), Pet( name = "Geraldas", resource = R.drawable.geraldas, type = PetType.Dog, sex = Sex.Male, ageYears = 1..3, description = """ RASTAS lapkričio 22 d. Kairėnuose, be čipo, laukia savo šeimininkų prieglaudoj. +37067151274 Olga, Vilnius """.trimIndent(), url = "https://tautmilesgloba.lt/gyvunai/naujokas-3/", ), Pet( name = "Laila", resource = R.drawable.laila, type = PetType.Dog, sex = Sex.Female, ageYears = 1..3, description = """ ❤️ Ieškome namų Lailaaaaai ❤️ Nepražiopsokit nepaprastai įspūdingos meškutės. Jauna, aktyvi, be galo meili. Gražuolė, linksmuolė, stipruolė lalaila vardu Laila😊 Ji laukia savo Žmogaus Rasų g. 39, Vilniuje. Išgelbėta nuo gyvenimo prie būdos Laila – tokio švelnaus ir meilaus būdo, kad tiesiog neįtikėtina, kad ji vis dar prieglaudoje. Nors ir didelė, tvirto sudėjimo, tačiau savo meilė gali pavergti kiekvieną širdį. Ši dama puikiai išmokyta vaikščioti su pavadėliu, nepuola kitų kitų šunų, visą savo dėmesį skirs tik jums. Šuo yra tas vienintelis pasaulyje, kuris tave myli labiau nei save – <NAME>. +370 671 51274 Olga, Vilnius ———————————————————– Gyveno pas moterį, kuri negalėjo ja tinkamai pasirūpinti, prie būdos. Jos likimu vis rūpinosi kita geraširdė moteris – nupirko naują būdą, nuvežė pas veterinarus, veždavo maisto, o galiausiai sulaukė vietos prieglaudoje ir atgabeno ją mums. Labai pozityvi, aktyvi ir draugiška kalytė. """.trimIndent(), url = "https://tautmilesgloba.lt/gyvunai/laila/", ), Pet( name = "Lentvarietis", resource = R.drawable.lentvarietis, type = PetType.Dog, sex = Sex.Male, ageYears = 4..8, description = """ Lentvarietis vis dar laukia savo nuolatinių namų, prieglaudėleje. 🏡 Jam apie 4-8 metus, mėgsta pasivaikščiojimus gamtoje, tačiau, kaip ir visiems pagyvenusiems gyvūnams patinka tingiai gulėti savo minkštame guoliuke 💤. Su kitais šunimis sutaria gerai, pasivaikščiojimo metu netempia, prisitaiko prie jūsų ėjimo greičio. Kaip bebūtų keista – skanukai jo visiškai nedomina, bet tai nėra bėda, nes jis labai paklusnus. Taigi, nepraleisk progos suteikti šiam nuostabiam senučiukui šiltus ir jaukius namus. 🐾 Protingas šuo gali mus daug ko išmokyti. Kantrybės. Rūpestingumo. Bičiulystės. Ir meilės. (Pem Braun) """.trimIndent(), url = "https://tautmilesgloba.lt/gyvunai/lentvarietis/", ), Pet( name = "Džordžas", resource = R.drawable.dzordzas, type = PetType.Dog, sex = Sex.Male, ageYears = 1..3, description = "Džordžas Holivudas <3", url = "https://tautmilesgloba.lt/gyvunai/dzordzas-sodyboj/", ), ).let { it + it + it }
kotlin
15
0.661252
504
48.134615
104
starcoderdata
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package openxr.templates import org.lwjgl.generator.* import openxr.* val FB_keyboard_tracking = "FBKeyboardTracking".nativeClassXR("FB_keyboard_tracking", type = "instance", postfix = "FB") { documentation = """ The $templateName extension. """ IntConstant( "The extension specification version.", "FB_keyboard_tracking_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "FB_KEYBOARD_TRACKING_EXTENSION_NAME".."XR_FB_keyboard_tracking" ) EnumConstant( "XR_MAX_KEYBOARD_TRACKING_NAME_SIZE_FB", "MAX_KEYBOARD_TRACKING_NAME_SIZE_FB".."128" ) EnumConstant( "Extends {@code XrStructureType}.", "TYPE_KEYBOARD_SPACE_CREATE_INFO_FB".."1000116009", "TYPE_KEYBOARD_TRACKING_QUERY_FB".."1000116004", "TYPE_SYSTEM_KEYBOARD_TRACKING_PROPERTIES_FB".."1000116002" ) EnumConstant( "XrKeyboardTrackingFlagBitsFB", "KEYBOARD_TRACKING_EXISTS_BIT_FB".enum(0x00000001), "KEYBOARD_TRACKING_LOCAL_BIT_FB".enum(0x00000002), "KEYBOARD_TRACKING_REMOTE_BIT_FB".enum(0x00000004), "KEYBOARD_TRACKING_CONNECTED_BIT_FB".enum(0x00000008) ) EnumConstant( "XrKeyboardTrackingQueryFlagBitsFB", "KEYBOARD_TRACKING_QUERY_LOCAL_BIT_FB".enum(0x00000002), "KEYBOARD_TRACKING_QUERY_REMOTE_BIT_FB".enum(0x00000004) ) XrResult( "QuerySystemTrackedKeyboardFB", """ Queries the system keyboard. <h5>C Specification</h5> The #QuerySystemTrackedKeyboardFB() function is defined as: <pre><code> ￿XrResult xrQuerySystemTrackedKeyboardFB( ￿ XrSession session, ￿ const XrKeyboardTrackingQueryFB* queryInfo, ￿ XrKeyboardTrackingDescriptionFB* keyboard);</code></pre> <h5>Description</h5> The #QuerySystemTrackedKeyboardFB() function populates an ##XrKeyboardTrackingDescriptionFB structure with enough information to describe a keyboard that the system can locate. <h5>Valid Usage (Implicit)</h5> <ul> <li>The {@link FBKeyboardTracking XR_FB_keyboard_tracking} extension <b>must</b> be enabled prior to calling #QuerySystemTrackedKeyboardFB()</li> <li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li> <li>{@code queryInfo} <b>must</b> be a pointer to a valid ##XrKeyboardTrackingQueryFB structure</li> <li>{@code keyboard} <b>must</b> be a pointer to an ##XrKeyboardTrackingDescriptionFB structure</li> </ul> <h5>Return Codes</h5> <dl> <dt>On success, this command returns</dt> <dd><ul> <li>#SUCCESS</li> <li>#SESSION_LOSS_PENDING</li> </ul></dd> <dt>On failure, this command returns</dt> <dd><ul> <li>#ERROR_FUNCTION_UNSUPPORTED</li> <li>#ERROR_VALIDATION_FAILURE</li> <li>#ERROR_RUNTIME_FAILURE</li> <li>#ERROR_HANDLE_INVALID</li> <li>#ERROR_INSTANCE_LOST</li> <li>#ERROR_SESSION_LOST</li> <li>#ERROR_FEATURE_UNSUPPORTED</li> </ul></dd> </dl> <h5>See Also</h5> ##XrKeyboardTrackingDescriptionFB, ##XrKeyboardTrackingQueryFB """, XrSession("session", "the session that will be associated with a keyboard space."), XrKeyboardTrackingQueryFB.const.p("queryInfo", "the ##XrKeyboardTrackingQueryFB that describes the type of keyboard to return. queryInfo must have either #KEYBOARD_TRACKING_QUERY_LOCAL_BIT_FB or #KEYBOARD_TRACKING_QUERY_REMOTE_BIT_FB set."), XrKeyboardTrackingDescriptionFB.p("keyboard", "the ##XrKeyboardTrackingDescriptionFB output structure.") ) XrResult( "CreateKeyboardSpaceFB", """ Create a foveation profile. <h5>C Specification</h5> The #CreateKeyboardSpaceFB() function is defined as: <pre><code> ￿XrResult xrCreateKeyboardSpaceFB( ￿ XrSession session, ￿ const XrKeyboardSpaceCreateInfoFB* createInfo, ￿ XrSpace* keyboardSpace);</code></pre> <h5>Description</h5> The #CreateKeyboardSpaceFB() function returns an {@code XrSpace} that can be used to locate a physical keyboard in space. The origin of the created {@code XrSpace} is located in the center of the bounding box in the x and z axes, and at the top of the y axis (meaning the keyboard is located entirely in negative y). <h5>Valid Usage (Implicit)</h5> <ul> <li>The {@link FBKeyboardTracking XR_FB_keyboard_tracking} extension <b>must</b> be enabled prior to calling #CreateKeyboardSpaceFB()</li> <li>{@code session} <b>must</b> be a valid {@code XrSession} handle</li> <li>{@code createInfo} <b>must</b> be a pointer to a valid ##XrKeyboardSpaceCreateInfoFB structure</li> <li>{@code keyboardSpace} <b>must</b> be a pointer to an {@code XrSpace} handle</li> </ul> <h5>Return Codes</h5> <dl> <dt>On success, this command returns</dt> <dd><ul> <li>#SUCCESS</li> <li>#SESSION_LOSS_PENDING</li> </ul></dd> <dt>On failure, this command returns</dt> <dd><ul> <li>#ERROR_FUNCTION_UNSUPPORTED</li> <li>#ERROR_VALIDATION_FAILURE</li> <li>#ERROR_RUNTIME_FAILURE</li> <li>#ERROR_HANDLE_INVALID</li> <li>#ERROR_INSTANCE_LOST</li> <li>#ERROR_SESSION_LOST</li> <li>#ERROR_OUT_OF_MEMORY</li> <li>#ERROR_LIMIT_REACHED</li> <li>#ERROR_FEATURE_UNSUPPORTED</li> </ul></dd> </dl> <h5>See Also</h5> ##XrKeyboardSpaceCreateInfoFB """, XrSession("session", "the session that will be associated with the returned keyboard space."), XrKeyboardSpaceCreateInfoFB.const.p("createInfo", "the ##XrKeyboardSpaceCreateInfoFB that describes the type of keyboard to track."), Check(1)..XrSpace.p("keyboardSpace", "the {@code XrSpace} output structure.") ) }
kotlin
16
0.604048
324
37.821429
168
starcoderdata
package pro.glideim.ui.group import pro.glideim.sdk.api.group.GroupMemberBean import pro.glideim.sdk.api.user.UserInfoBean data class GroupMemberViewData( val memberInfo: GroupMemberBean, val userInfo: UserInfoBean )
kotlin
5
0.809735
48
24.222222
9
starcoderdata
<filename>platform/platform-impl/src/com/intellij/diagnostic/hprof/analysis/HProfAnalysis.kt /* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.analysis import com.google.common.base.Stopwatch import com.intellij.diagnostic.hprof.classstore.HProfMetadata import com.intellij.diagnostic.hprof.histogram.Histogram import com.intellij.diagnostic.hprof.navigator.ObjectNavigator import com.intellij.diagnostic.hprof.parser.HProfEventBasedParser import com.intellij.diagnostic.hprof.util.FileBackedIntList import com.intellij.diagnostic.hprof.util.FileBackedUByteList import com.intellij.diagnostic.hprof.util.HeapReportUtils.sectionHeader import com.intellij.diagnostic.hprof.util.HeapReportUtils.toShortStringAsCount import com.intellij.diagnostic.hprof.util.PartialProgressIndicator import com.intellij.diagnostic.hprof.visitors.RemapIDsVisitor import com.intellij.openapi.progress.ProgressIndicator import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.TestOnly import java.nio.channels.FileChannel import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption class HProfAnalysis(private val hprofFileChannel: FileChannel, private val tempFilenameSupplier: TempFilenameSupplier) { interface TempFilenameSupplier { fun getTempFilePath(type: String): Path } private data class TempFile( val type: String, val path: Path, val channel: FileChannel ) private val tempFiles = mutableListOf<TempFile>() private var includeMetaInfo = true @TestOnly fun setIncludeMetaInfo(value: Boolean) { includeMetaInfo = value } private fun openTempEmptyFileChannel(@NonNls type: String): FileChannel { val tempPath = tempFilenameSupplier.getTempFilePath(type) val tempChannel = FileChannel.open(tempPath, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.DELETE_ON_CLOSE) tempFiles.add(TempFile(type, tempPath, tempChannel)) return tempChannel } fun analyze(progress: ProgressIndicator): String { val result = StringBuilder() val totalStopwatch = Stopwatch.createStarted() val prepareFilesStopwatch = Stopwatch.createStarted() val analysisStopwatch = Stopwatch.createUnstarted() progress.text = "Analyze Heap" progress.text2 = "Open heap file" progress.fraction = 0.0 val parser = HProfEventBasedParser(hprofFileChannel) try { progress.text2 = "Create class definition map" progress.fraction = 0.0 val hprofMetadata = HProfMetadata.create(parser) progress.text2 = "Create class histogram" progress.fraction = 0.1 val histogram = Histogram.create(parser, hprofMetadata.classStore) val nominatedClasses = ClassNomination(histogram, 5).nominateClasses() progress.text2 = "Create id mapping file" progress.fraction = 0.2 // Currently, there is a maximum count of supported instances. Produce simplified report // (histogram only), if the count exceeds maximum. if (!isSupported(histogram.instanceCount)) { result.appendln(histogram.prepareReport("All", 50)) return result.toString() } val idMappingChannel = openTempEmptyFileChannel("id-mapping") val remapIDsVisitor = RemapIDsVisitor.createFileBased( idMappingChannel, histogram.instanceCount) parser.accept(remapIDsVisitor, "id mapping") parser.setIdRemappingFunction(remapIDsVisitor.getRemappingFunction()) hprofMetadata.remapIds(remapIDsVisitor.getRemappingFunction()) progress.text2 = "Create object graph files" progress.fraction = 0.3 val navigator = ObjectNavigator.createOnAuxiliaryFiles( parser, openTempEmptyFileChannel("auxOffset"), openTempEmptyFileChannel("aux"), hprofMetadata, histogram.instanceCount ) prepareFilesStopwatch.stop() val parentList = FileBackedIntList.createEmpty(openTempEmptyFileChannel("parents"), navigator.instanceCount + 1) val sizesList = FileBackedIntList.createEmpty(openTempEmptyFileChannel("sizes"), navigator.instanceCount + 1) val visitedList = FileBackedIntList.createEmpty(openTempEmptyFileChannel("visited"), navigator.instanceCount + 1) val refIndexList = FileBackedUByteList.createEmpty(openTempEmptyFileChannel("refIndex"), navigator.instanceCount + 1) analysisStopwatch.start() val nominatedClassNames = nominatedClasses.map { it.classDefinition.name } val analysisConfig = AnalysisConfig(perClassOptions = AnalysisConfig.PerClassOptions(classNames = nominatedClassNames), metaInfoOptions = AnalysisConfig.MetaInfoOptions(include = includeMetaInfo)) val analysisContext = AnalysisContext( navigator, analysisConfig, parentList, sizesList, visitedList, refIndexList, histogram ) val analysisReport = AnalyzeGraph(analysisContext).analyze(PartialProgressIndicator(progress, 0.4, 0.4)) result.appendln(analysisReport) analysisStopwatch.stop() if (includeMetaInfo) { result.appendln(sectionHeader("Analysis information")) result.appendln("Prepare files duration: $prepareFilesStopwatch") result.appendln("Analysis duration: $analysisStopwatch") result.appendln("TOTAL DURATION: $totalStopwatch") result.appendln("Temp files:") result.appendln(" heapdump = ${toShortStringAsCount(hprofFileChannel.size())}") tempFiles.forEach { temp -> val channel = temp.channel if (channel.isOpen) { result.appendln(" ${temp.type} = ${toShortStringAsCount(channel.size())}") } } } } finally { parser.close() closeAndDeleteTemporaryFiles() } return result.toString() } private fun isSupported(instanceCount: Long): Boolean { // Limitation due to FileBackedHashMap in RemapIDsVisitor. Many other components // assume instanceCount <= Int.MAX_VALUE. return RemapIDsVisitor.isSupported(instanceCount) && instanceCount <= Int.MAX_VALUE } private fun closeAndDeleteTemporaryFiles() { tempFiles.forEach { tempFile -> try { tempFile.channel.close() } catch (ignored: Throwable) { } try { tempFile.path.let { Files.deleteIfExists(it) } } catch (ignored: Throwable) { } } tempFiles.clear() } }
kotlin
32
0.708594
125
35.77
200
starcoderdata
package foo expect class <!AMBIGUOUS_ACTUALS("Class 'A'", "bottom.kt, middle.kt")!>A<!>
kotlin
6
0.681818
75
28.666667
3
starcoderdata
<filename>PermissionsDispatcher-master/processor/src/main/kotlin/permissions/dispatcher/processor/exception/MixPermissionTypeException.kt package permissions.dispatcher.processor.exception import permissions.dispatcher.processor.util.simpleString import javax.lang.model.element.ExecutableElement public class MixPermissionTypeException(e: ExecutableElement, permissionName: String) : RuntimeException("Method '${e.simpleString()}()' defines '$permissionName' with other permissions at the same time.") { }
kotlin
12
0.846457
207
62.625
8
starcoderdata
<gh_stars>1-10 package ru.aleshi.letsplaycities.ui.global import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import ru.aleshi.letsplaycities.ui.FetchState import ru.quandastudio.lpsclient.core.LpsRepository import javax.inject.Inject class FriendGameRequestViewModel @Inject constructor(private val lpsRepository: LpsRepository) : ViewModel() { private val mState: MutableLiveData<FetchState> = MutableLiveData() val state: LiveData<FetchState> get() = mState fun onDecline(userId: Int) { viewModelScope.launch(Dispatchers.IO) { mState.postValue(FetchState.LoadingState) try { lpsRepository.declineGameRequestResult(userId) } catch (e: Exception) { mState.postValue(FetchState.ErrorState(e)) } mState.postValue(FetchState.FinishState) } } }
kotlin
22
0.724432
96
30.088235
34
starcoderdata
<gh_stars>1-10 // KJS_WITH_FULL_RUNTIME // WITH_RUNTIME const val MaxUI = UInt.MAX_VALUE const val MinUI = UInt.MIN_VALUE const val MaxUL = ULong.MAX_VALUE const val MinUL = ULong.MIN_VALUE val M = MaxUI.toULong() val N = Int.MAX_VALUE.toUInt() fun testSimpleUIntLoop() { var s = 0 for (i in 6u downTo 1u) { s = s*10 + i.toInt() } if (s != 654321) throw AssertionError("$s") } fun testEmptyUIntLoop() { var s = 0 for (i in 1u downTo 6u) { s = s*10 + i.toInt() } if (s != 0) throw AssertionError("$s") } fun testSimpleULongLoop() { var s = 0 for (i in 6UL downTo 1UL) { s = s*10 + i.toInt() } if (s != 654321) throw AssertionError("$s") } fun testEmptyULongLoop() { var s = 0 for (i in 1UL downTo 6UL) { s = s*10 + i.toInt() } if (s != 0) throw AssertionError("$s") } fun testULongLoop() { var s = 0 for (i in M+6UL downTo M+1UL) { s = s*10 + (i-M).toInt() } if (s != 654321) throw AssertionError("$s") } fun testEmptyULongLoop2() { var s = 0 for (i in M+1UL downTo M+6UL) { s = s*10 + (i-M).toInt() } if (s != 0) throw AssertionError("$s") } fun testMaxUIdownToMinUI() { val xs = ArrayList<UInt>() for (i in MinUI downTo MaxUI) { xs.add(i) if (xs.size > 23) break } if (xs.size > 0) { throw AssertionError("Wrong elements for MaxUI..MinUI: $xs") } } fun testMaxULdownToMinUL() { val xs = ArrayList<ULong>() for (i in MinUL downTo MaxUL) { xs.add(i) if (xs.size > 23) break } if (xs.size > 0) { throw AssertionError("Wrong elements for MaxUI..MinUI: $xs") } } fun testWrappingULongLoop() { val MA = M - 1UL val MB = M + 1UL val xs = ArrayList<ULong>() for (i in MB downTo MA) { xs.add(i) if (xs.size > 3) break } if (xs != listOf(MB, M, MA)) throw AssertionError("$xs") } fun testWrappingUIntLoop() { val NA = N - 1u val NB = N + 1u val xs = ArrayList<UInt>() for (i in NB downTo NA) { xs.add(i) if (xs.size > 3) break } if (xs != listOf(NB, N, NA)) throw AssertionError("$xs") } fun box(): String { testSimpleUIntLoop() testEmptyUIntLoop() testSimpleULongLoop() testEmptyULongLoop() testULongLoop() testEmptyULongLoop2() testMaxUIdownToMinUI() testMaxULdownToMinUL() testWrappingULongLoop() testWrappingUIntLoop() return "OK" }
kotlin
13
0.563251
68
20
119
starcoderdata
package com.khoben.autotitle.model /** * Playback event for syncing components depending on current playback state * * @property playState current [PlaybackState] * @property currentPosition current position of playback */ data class PlaybackEvent(val playState: PlaybackState, val currentPosition: Long = 0L)
kotlin
5
0.793651
86
34.111111
9
starcoderdata
// IGNORE_BACKEND_FIR: JVM_IR open class A { open val a = "OK" } class B : A() { override val a = "FAIL" fun foo() = "CRUSH" } class C { fun A?.complex(): String { if (this is B) return foo() else if (this != null) return a else return "???" } fun bar() = A().complex() } fun box() = C().bar()
kotlin
12
0.49422
39
15.47619
21
starcoderdata
<reponame>dayanruben/androidx /* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.splashscreen.test import android.app.Instrumentation import android.content.ComponentName import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import androidx.test.core.app.ApplicationProvider import androidx.test.filters.LargeTest import androidx.test.platform.app.InstrumentationRegistry import androidx.test.screenshot.matchers.MSSIMMatcher import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until import org.hamcrest.core.IsNull.notNullValue import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertThat import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import java.io.File import java.io.FileOutputStream import java.io.IOException import java.util.concurrent.TimeUnit import kotlin.reflect.KClass private const val SPLASH_SCREEN_STYLE_ICON = 1 private const val KEY_SPLASH_SCREEN_STYLE: String = "android.activity.splashScreenStyle" private const val BASIC_SAMPLE_PACKAGE: String = "androidx.core.splashscreen.test" private const val LAUNCH_TIMEOUT: Long = 5000 @LargeTest @RunWith(Parameterized::class) public class SplashscreenTest( public val name: String, public val activityClass: KClass<out SplashScreenTestControllerHolder> ) { private lateinit var device: UiDevice public companion object { @Parameterized.Parameters(name = "{0}") @JvmStatic public fun data(): Iterable<Array<Any>> { return listOf( arrayOf("Platform", SplashScreenTestActivity::class), arrayOf("AppCompat", SplashScreenAppCompatTestActivity::class) ) } } @Before public fun setUp() { device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) } @Test public fun compatAttributePopulated() { val activity = startActivityWithSplashScreen() assertEquals(1234, activity.duration) assertEquals(R.color.bg_launcher, activity.splashscreenBackgroundId) val expectedTheme = if (activity.isCompatActivity) R.style.Theme_Test_AppCompat else R.style.Theme_Test assertEquals(expectedTheme, activity.finalAppTheme) assertEquals(R.drawable.android, activity.splashscreenIconId) } @Test public fun exitAnimationListenerCalled() { val activity = startActivityWithSplashScreen { // Clear out any previous instances it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) it.putExtra(EXTRA_ANIMATION_LISTENER, true) } assertTrue(activity.exitAnimationListenerLatch.await(2, TimeUnit.SECONDS)) } @Test public fun splashScreenWaited() { val activity = startActivityWithSplashScreen { // Clear out any previous instances it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) it.putExtra(EXTRA_SPLASHSCREEN_WAIT, true) } assertTrue( "Waiting condition was never checked", activity.waitedLatch.await(2, TimeUnit.SECONDS) ) assertFalse( "Activity should not have been drawn", activity.hasDrawn ) activity.waitBarrier.set(false) assertTrue( "Activity was never drawn", activity.drawnLatch.await(2, TimeUnit.SECONDS) ) } @Test public fun exitAnimationListenerCalledAfterWait() { val activity = startActivityWithSplashScreen { // Clear out any previous instances it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) it.putExtra(EXTRA_SPLASHSCREEN_WAIT, true) it.putExtra(EXTRA_ANIMATION_LISTENER, true) } activity.waitBarrier.set(false) assertTrue( "Activity was never drawn", activity.drawnLatch.await(2, TimeUnit.SECONDS) ) assertTrue(activity.exitAnimationListenerLatch.await(2, TimeUnit.SECONDS)) } @Test public fun splashscreenViewScreenshotComparison() { val activity = startActivityWithSplashScreen { // Clear out any previous instances it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) it.putExtra(EXTRA_SPLASHSCREEN_WAIT, true) it.putExtra(EXTRA_ANIMATION_LISTENER, true) it.putExtra(EXTRA_SPLASHSCREEN_VIEW_SCREENSHOT, true) } assertTrue(activity.waitedLatch.await(2, TimeUnit.SECONDS)) activity.waitBarrier.set(false) activity.exitAnimationListenerLatch.await(2, TimeUnit.SECONDS) compareBitmaps(activity.splashScreenScreenshot!!, activity.splashScreenViewScreenShot!!) } private fun compareBitmaps( beforeScreenshot: Bitmap, afterScreenshot: Bitmap ) { val beforeBuffer = IntArray(beforeScreenshot.width * beforeScreenshot.height) beforeScreenshot.getPixels( beforeBuffer, 0, beforeScreenshot.width, 0, 0, beforeScreenshot.width, beforeScreenshot.height ) val afterBuffer = IntArray(afterScreenshot.width * afterScreenshot.height) afterScreenshot.getPixels( afterBuffer, 0, afterScreenshot.width, 0, 0, afterScreenshot.width, afterScreenshot.height ) val matcher = MSSIMMatcher(0.90).compareBitmaps( beforeBuffer, afterBuffer, afterScreenshot.width, afterScreenshot.height ) if (!matcher.matches) { val bundle = Bundle() val diff = matcher.diff?.writeToDevice("diff.png") bundle.putString("splashscreen_diff", diff?.absolutePath) bundle.putString( "splashscreen_before", beforeScreenshot.writeToDevice("before.png").absolutePath ) bundle.putString( "splashscreen_after", afterScreenshot.writeToDevice("after.png").absolutePath ) val path = diff?.parentFile?.path InstrumentationRegistry.getInstrumentation().sendStatus(2, bundle) fail( "SplashScreenView and SplashScreen don't match\n${matcher.comparisonStatistics}" + "\nResult saved at $path" ) } } private fun Bitmap.writeToDevice(name: String): File { return writeToDevice( { compress(Bitmap.CompressFormat.PNG, 0 /*ignored for png*/, it) }, name ) } private fun writeToDevice( writeAction: (FileOutputStream) -> Unit, name: String ): File { val deviceOutputDirectory = File( InstrumentationRegistry.getInstrumentation().context.externalCacheDir, "splashscreen_test" ) if (!deviceOutputDirectory.exists() && !deviceOutputDirectory.mkdir()) { throw IOException("Could not create folder.") } val file = File(deviceOutputDirectory, name) try { FileOutputStream(file).use { writeAction(it) } } catch (e: Exception) { throw IOException( "Could not write file to storage (path: ${file.absolutePath}). " + " Stacktrace: " + e.stackTrace ) } return file } private fun startActivityWithSplashScreen( intentModifier: ((Intent) -> Unit)? = null ): SplashScreenTestController { // Start from the home screen device.pressHome() // Wait for launcher val launcherPackage: String = device.launcherPackageName assertThat(launcherPackage, notNullValue()) device.wait( Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT ) // Launch the app val context = ApplicationProvider.getApplicationContext<Context>() val baseIntent = context.packageManager.getLaunchIntentForPackage( BASIC_SAMPLE_PACKAGE ) val intent = Intent(baseIntent).apply { component = ComponentName(BASIC_SAMPLE_PACKAGE, activityClass.qualifiedName!!) intentModifier?.invoke(this) } val monitor = object : Instrumentation.ActivityMonitor( activityClass.qualifiedName!!, Instrumentation.ActivityResult(0, Intent()), false ) { override fun onStartActivity(intent: Intent?): Instrumentation.ActivityResult? { return if (intent?.component?.packageName == BASIC_SAMPLE_PACKAGE) { Instrumentation.ActivityResult(0, Intent()) } else { null } } } InstrumentationRegistry.getInstrumentation().addMonitor(monitor) context.startActivity( intent, // Force the splash screen to be shown with an icon Bundle().apply { putInt(KEY_SPLASH_SCREEN_STYLE, SPLASH_SCREEN_STYLE_ICON) } ) assertTrue( device.wait( Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT ) ) val splashScreenTestActivity = monitor.waitForActivityWithTimeout(LAUNCH_TIMEOUT) as SplashScreenTestControllerHolder? if (splashScreenTestActivity == null) { fail( activityClass.simpleName!! + " was not launched after " + "$LAUNCH_TIMEOUT ms" ) } return splashScreenTestActivity!!.controller } }
kotlin
24
0.648605
99
35.083045
289
starcoderdata
<gh_stars>1-10 package net.dontdrinkandroot.wicket.model import org.apache.wicket.model.IModel import java.text.SimpleDateFormat import java.util.* class SimpleDateFormatModel : AbstractChainedModel<Date, String> { // TODO: Maybe refactor this into an IComponentAssignedModel in order to use the locale of the attached component. private val simpleDateFormat: SimpleDateFormat constructor(parent: IModel<Date>, pattern: String) : super(parent) { simpleDateFormat = SimpleDateFormat(pattern) } constructor(parent: IModel<Date>, pattern: String, locale: Locale) : super(parent) { simpleDateFormat = SimpleDateFormat(pattern, locale) } override fun getValue(parentValue: Date?) = simpleDateFormat.format(parentValue) }
kotlin
22
0.756863
118
33.818182
22
starcoderdata
package pl.sienczykm.templbn import android.app.Application import pl.sienczykm.templbn.utils.handleNightMode import timber.log.Timber class App : Application() { override fun onCreate() { super.onCreate() handleNightMode() if (BuildConfig.DEBUG) Timber.plant(Timber.DebugTree()) } }
kotlin
15
0.709375
63
19.0625
16
starcoderdata
package cookcook.nexters.com.amoogye.views.tools.add_tools import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import cookcook.nexters.com.amoogye.R class AddUtilCompleteFragment : Fragment() { interface OnAddUtilResultListener { fun onAddUtilResult() } companion object { // 선택 선언 1 (Fragment를 싱글턴으로 사용 시) private var INSTANCE: AddUtilCompleteFragment? = null fun getInstance(): AddUtilCompleteFragment { if (INSTANCE == null) { INSTANCE = AddUtilCompleteFragment() } return INSTANCE!! } fun instanceInit() { INSTANCE = null } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) return inflater.inflate(R.layout.fragment_addutil_3_complete, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) } }
kotlin
15
0.670549
116
26.340909
44
starcoderdata
<gh_stars>1-10 package `fun`.inaction.sample.dialog import `fun`.inaction.dialog.dialogs.* import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.TextView import android.widget.Toast class MainActivity : AppCompatActivity() { /** * 显示对话框的 TextView */ private lateinit var dialogTV: TextView /** * 显示Style的TextView */ private lateinit var styleTV: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) dialogTV = findViewById(R.id.dialogTV) styleTV = findViewById(R.id.styleTV) } /** * 点击 Show 按钮的事件 */ fun onClickShow(v: View) { when (dialogTV.text) { "CommonDialog" -> { val dialog = CommonDialog(this) with(dialog) { setTitle("提示") setContent("确定要退出吗?") onConfirmClickListener = { dialog.dismiss() } onCancelClickListener = { dialog.dismiss() } show() } } "TextListDialog" -> { var style: Int = when (styleTV.text) { "Style_NoTitle" -> TextListDialog.Style_NoTitle "Style_NoTitle_TextCenter" -> TextListDialog.Style_NoTitle_TextCenter else -> TextListDialog.Style_Default } val dialog = TextListDialog(this, style) dialog.setTitle("选择通知栏样式") .setData(listOf("系统样式", "云音乐通知栏", "可以不要右边的对勾"), 1) .setOnItemClickListener { v, position -> toast("你点击了第${position}项") dialog.dismiss() } .show() } "IconTextListDialog" -> { var style: Int = when (styleTV.text) { "Style_NoTitle" -> IconTextListDialog.Style_NoTitle "Style_TitleCenter" -> IconTextListDialog.Style_TitleCenter else -> IconTextListDialog.Style_Default } val dialog = IconTextListDialog(this, style) val data = listOf( Pair(R.drawable.ic_qq, "QQ登录") , Pair(R.drawable.ic_wechat, "微信登录") , Pair(R.drawable.ic_weibo, "微博登录") ) dialog.setTitle("选择登录方式") .setData(data) .setOnItemClickListener { v, position -> toast("你点击了第${position}项") dialog.dismiss() } .show() } "BottomTextListDialog" -> { var style: Int = when (styleTV.text) { "Style_NoCancelButton" -> BottomTextListDialog.Style_NoCancelButton "Style_TextLeft_NoCancelButton" -> BottomTextListDialog.Style_TextLeft_NoCancelButton else -> BottomTextListDialog.Style_Default } val dialog = BottomTextListDialog(this, style) dialog.setData(listOf("拍照", "从相册选择", "我编一个选项")) .setOnItemClickListener { v, position -> toast("你点击了第${position}项") dialog.dismiss() } .setOnCancelClickListener { dialog.dismiss() } .show() } "BottomIconTextListDialog" -> { val style: Int = when (styleTV.text) { "Style_NoTitle" -> BottomIconTextListDialog.Style_NoTitle "Style_TitleCenter" -> BottomIconTextListDialog.Style_TitleCenter else -> BottomIconTextListDialog.Style_Default } val data = listOf( Pair(R.drawable.ic_qq, "QQ登录") , Pair(R.drawable.ic_wechat, "微信登录") , Pair(R.drawable.ic_weibo, "微博登录") ) val dialog = BottomIconTextListDialog(this, style) dialog.setTitle("选择登录方式") .setData(data) .setOnItemClickListener { v, position -> toast("你点击了第${position}项") dialog.dismiss() } .show() } else -> { toast("Bug:${dialogTV.text}") } } } /** * 点击 选择对话框 按钮的回调 */ fun onClickChooseDialog(v: View) { val dialog = TextListDialog(this) dialog.setTitle("选择对话框") val dialogList = listOf( "CommonDialog", "TextListDialog", "IconTextListDialog" , "BottomTextListDialog", "BottomIconTextListDialog" ) dialog.setData(dialogList, dialogList.indexOf(dialogTV.text)) dialog.setOnItemClickListener { v, position -> dialogTV.setText(dialogList[position]) styleTV.setText("null") dialog.dismiss() } dialog.show() } /** * 点击 选择Style 按钮的回调 */ fun onClickChooseStyle(v: View) { // 对话框的 Style 的集合 var styleList: List<String>? = null when (dialogTV.text) { "CommonDialog" -> { styleList = listOf("Style_Default") } "TextListDialog" -> { styleList = listOf("Style_Default", "Style_NoTitle", "Style_NoTitle_TextCenter") } "IconTextListDialog" -> { styleList = listOf("Style_Default", "Style_NoTitle", "Style_TitleCenter") } "BottomTextListDialog" -> { styleList = listOf("Style_Default", "Style_NoCancelButton", "Style_TextLeft_NoCancelButton") } "BottomIconTextListDialog" -> { styleList = listOf("Style_Default", "Style_NoTitle", "Style_TitleCenter") } } // 如果对话框没有可选的 Style if (styleList == null) { val dialog = CommonDialog(this) with(dialog) { setTitle("提示") setContent("这个对话框没有可选Style") onCancelClickListener = { dialog.dismiss() } onConfirmClickListener = { dialog.dismiss() } } return } // 显示可选的Style val dialog = TextListDialog(this) dialog.setTitle("选择Style") dialog.setData(styleList) dialog.setOnItemClickListener { v, position -> styleTV.setText(styleList[position]) dialog.dismiss() } dialog.show() } /** * 显示Toast */ fun toast(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() } }
kotlin
25
0.48465
105
31.721461
219
starcoderdata
/* * Copyright 2018. nekocode (<EMAIL>) * * 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 cn.nekocode.gradle.depan import cn.nekocode.gradle.depan.bytecode.DepanClassVisitor import com.android.SdkConstants import com.android.build.api.transform.QualifiedContent import com.android.build.api.transform.Transform import com.android.build.api.transform.TransformInvocation import com.android.build.gradle.internal.pipeline.TransformManager import com.android.build.gradle.internal.pipeline.TransformTask import com.android.utils.FileUtils import org.gradle.api.Project import org.objectweb.asm.ClassReader import java.io.IOException import java.io.InputStream import java.io.UncheckedIOException import java.util.zip.ZipEntry import java.util.zip.ZipInputStream /** * @author nekocode (<EMAIL>) */ class DepanTransform(private val project: Project) : Transform() { override fun getName() = "depan" override fun getInputTypes(): Set<QualifiedContent.ContentType> = TransformManager.CONTENT_CLASS override fun getScopes(): MutableSet<in QualifiedContent.Scope> = TransformManager.EMPTY_SCOPES override fun getReferencedScopes(): MutableSet<in QualifiedContent.Scope> = TransformManager.SCOPE_FULL_PROJECT override fun isIncremental() = false override fun transform(invocation: TransformInvocation) { val ext = (invocation.context as TransformTask).extensions val config = ext.getByType(DepanConfig::class.java) if (!config.enabled) { return } val graphBuilder = ext.getByType(GraphBuilder::class.java) invocation.referencedInputs.forEach { input -> input.directoryInputs.forEach { directoryInput -> for (file in FileUtils.getAllFiles(directoryInput.file)) { if (!file.name.endsWith(SdkConstants.DOT_CLASS)) { continue } file.inputStream().use { transform(it, graphBuilder) } } } input.jarInputs.forEach { jarInput -> jarInput.file.inputStream().use { jis -> ZipInputStream(jis).use { zis -> var entry: ZipEntry? = zis.nextEntry while (entry != null) { if (!entry.isDirectory && entry.name.endsWith(SdkConstants.DOT_CLASS)) { transform(zis, graphBuilder) } entry = zis.nextEntry } } } } } } private fun transform(ins: InputStream, graphBuilder: GraphBuilder) { val visitor = DepanClassVisitor(graphBuilder) try { val cr = ClassReader(ins) cr.accept(visitor, 0) } catch (e: IOException) { throw UncheckedIOException(e) } } }
kotlin
38
0.630133
115
34.32
100
starcoderdata
<filename>domain/src/main/java/com/jacekpietras/zoo/domain/interactor/GetShortestPathFromUserUseCase.kt package com.jacekpietras.zoo.domain.interactor import com.jacekpietras.core.PointD import com.jacekpietras.zoo.domain.business.GraphAnalyzer import kotlinx.coroutines.flow.firstOrNull class GetShortestPathFromUserUseCase( private val getUserPositionUseCase: GetUserPositionUseCase, private val initializeGraphAnalyzerIfNeededUseCase: InitializeGraphAnalyzerIfNeededUseCase, ) { suspend fun run(point: PointD): List<PointD> { initializeGraphAnalyzerIfNeededUseCase.run() return GraphAnalyzer.getShortestPath( startPoint = getUserPositionUseCase.run().firstOrNull(), endPoint = point, ) } }
kotlin
16
0.783926
103
37
20
starcoderdata
package me.gendal.conclave.eventmanager.common import com.r3.conclave.mail.Curve25519PublicKey import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import java.util.* @Serializable sealed class ClientRequest @Serializable data class SetupComputation( val computation: Computation ) : ClientRequest() @Serializable data class Computation( val computationName: String, val computationType: ComputationType, val parties: List< @Serializable(with = Curve25519PublicKeySerializer::class) Curve25519PublicKey>, val quorum: Int ) { enum class ComputationType { max, min, avg, key, } } @Serializable data class SubmitValue( val computationName: String, val submission: Submission ) : ClientRequest() @Serializable data class Submission( val submissionValue: String, val submissionMessage: String = "" ) @Serializable object ListComputations : ClientRequest() @Serializable data class GetComputationResult( val computationName: String ) : ClientRequest() @Serializable sealed class EnclaveResponse @Serializable enum class ResponseCode { SUCCESS, NOT_AUTHORISED, COMPUTATION_DOES_NOT_EXIST, NO_RESULTS, QUORUM_NOT_REACHED, COMPUTATION_TYPE_DOES_NOT_EXIST, COMPUTATION_ALREADY_EXISTS, COMPUTATION_LOCKED, CHECK_INBOX, } @Serializable data class EnclaveMessageResponse( val message: String, val responseCode: ResponseCode = ResponseCode.SUCCESS ) : EnclaveResponse() @Serializable data class Computations( val computations: List<Computation> = emptyList(), val responseCode: ResponseCode = ResponseCode.SUCCESS ) : EnclaveResponse() @Serializable data class ComputationResult( val result: String, val responseCode: ResponseCode = ResponseCode.SUCCESS ) : EnclaveResponse() @Serializable data class KeyMatcherResult( val computation: Computation, val key: String, val submissions: List<Pair<@Serializable(with = Curve25519PublicKeySerializer::class) Curve25519PublicKey, String>>, val responseCode: ResponseCode ) : EnclaveResponse() @Serializable class SignedData(val bytes: ByteArray, val signature: ByteArray) private object Curve25519PublicKeySerializer : KSerializer<Curve25519PublicKey> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Curve25519PublicKey", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: Curve25519PublicKey) { encoder.encodeString(Base64.getEncoder().encodeToString(value.encoded)) } override fun deserialize(decoder: Decoder): Curve25519PublicKey { return Curve25519PublicKey(Base64.getDecoder().decode(decoder.decodeString())) } }
kotlin
18
0.761062
120
26.241071
112
starcoderdata
package com.xiaocydx.cxrv.itemvisible import android.os.Build import androidx.lifecycle.Lifecycle import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.LayoutManager import androidx.recyclerview.widget.RecyclerView.VERTICAL import androidx.recyclerview.widget.StaggeredGridLayoutManager import androidx.test.core.app.ActivityScenario import com.google.common.truth.Truth.assertThat import com.xiaocydx.cxrv.TestActivity import com.xiaocydx.cxrv.TestAdapter import io.mockk.mockk import io.mockk.verify import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config /** * ItemVisible的单元测试 * * @author xcc * @date 2021/10/18 */ @Config(sdk = [Build.VERSION_CODES.Q]) @RunWith(RobolectricTestRunner::class) class ItemVisibleTest { private lateinit var scenario: ActivityScenario<TestActivity> private val testAdapter: TestAdapter = TestAdapter() private val testItems = (0..99).map { it.toString() } @Before fun setup() { scenario = ActivityScenario .launch(TestActivity::class.java) .moveToState(Lifecycle.State.CREATED) } @Test fun recyclerView_LinearLayoutManager_ItemVisible() { recyclerView_ItemVisible { LinearLayoutManager(context) } } @Test fun recyclerView_GridLayoutManager_ItemVisible() { recyclerView_ItemVisible { GridLayoutManager(context, 3) } } @Test fun recyclerView_StaggeredGridLayoutManager_ItemVisible() { recyclerView_ItemVisible { StaggeredGridLayoutManager(3, VERTICAL) } } private inline fun recyclerView_ItemVisible( crossinline layout: RecyclerView.() -> LayoutManager ) { scenario.onActivity { activity -> activity.recyclerView.apply { layoutManager = layout() testItemVisibleProperty() } }.recreate().onActivity { activity -> activity.recyclerView.apply { layoutManager = layout() testItemVisibleHelper() } }.recreate().onActivity { activity -> activity.recyclerView.apply { layoutManager = layout() testFirstItemVisibleHandler() } }.recreate().onActivity { activity -> activity.recyclerView.apply { layoutManager = layout() testLastItemVisibleHandler() } } } private fun RecyclerView.testItemVisibleProperty() { adapter = testAdapter testAdapter.items = testItems assertThat(isFirstItemVisible).isTrue() assertThat(isFirstItemCompletelyVisible).isTrue() assertThat(isLastItemVisible).isFalse() assertThat(isLastItemCompletelyVisible).isFalse() scrollToPosition(testAdapter.items.lastIndex) assertThat(isFirstItemVisible).isFalse() assertThat(isFirstItemCompletelyVisible).isFalse() assertThat(isLastItemVisible).isTrue() assertThat(isLastItemCompletelyVisible).isTrue() } private fun RecyclerView.testItemVisibleHelper() { val helper = ItemVisibleHelper(this) adapter = testAdapter testAdapter.items = testItems assertThat(helper.isFirstItemVisible).isTrue() assertThat(helper.isFirstItemCompletelyVisible).isTrue() assertThat(helper.isLastItemVisible).isFalse() assertThat(helper.isLastItemCompletelyVisible).isFalse() scrollToPosition(testAdapter.items.lastIndex) assertThat(helper.isFirstItemVisible).isFalse() assertThat(helper.isFirstItemCompletelyVisible).isFalse() assertThat(helper.isLastItemVisible).isTrue() assertThat(helper.isLastItemCompletelyVisible).isTrue() } private fun RecyclerView.testFirstItemVisibleHandler() { val firstItemHandler: () -> Unit = mockk(relaxed = true) val firstItemCompletelyHandler: () -> Unit = mockk(relaxed = true) val firstItemDisposable = doOnFirstItemVisible(once = true, handler = firstItemHandler) val firstItemCompletelyDisposable = doOnFirstItemCompletelyVisible(once = true, handler = firstItemCompletelyHandler) adapter = testAdapter testAdapter.items = testItems verify(exactly = 1) { firstItemHandler.invoke() } verify(exactly = 1) { firstItemCompletelyHandler.invoke() } assertThat(firstItemDisposable.isDisposed).isTrue() assertThat(firstItemCompletelyDisposable.isDisposed).isTrue() } private fun RecyclerView.testLastItemVisibleHandler() { val lastItemHandler: () -> Unit = mockk(relaxed = true) val lastItemCompletelyHandler: () -> Unit = mockk(relaxed = true) val lastItemDisposable = doOnLastItemVisible(once = true, handler = lastItemHandler) val lastItemCompletelyDisposable = doOnLastItemCompletelyVisible(once = true, handler = lastItemCompletelyHandler) adapter = testAdapter testAdapter.items = testItems scrollToPosition(testAdapter.items.lastIndex) verify(exactly = 1) { lastItemHandler.invoke() } verify(exactly = 1) { lastItemCompletelyHandler.invoke() } assertThat(lastItemDisposable.isDisposed).isTrue() assertThat(lastItemCompletelyDisposable.isDisposed).isTrue() } }
kotlin
32
0.689381
97
35.934641
153
starcoderdata
<filename>subscribing-sdk/src/main/java/com/ably/tracking/subscriber/CoreSubscriber.kt<gh_stars>1-10 package com.ably.tracking.subscriber import com.ably.tracking.ConnectionException import com.ably.tracking.LocationUpdate import com.ably.tracking.Resolution import com.ably.tracking.TrackableState import com.ably.tracking.common.Ably import com.ably.tracking.common.ClientTypes import com.ably.tracking.common.ConnectionState import com.ably.tracking.common.ConnectionStateChange import com.ably.tracking.common.PresenceAction import com.ably.tracking.common.PresenceData import com.ably.tracking.common.createSingleThreadDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch internal interface CoreSubscriber { fun enqueue(event: AdhocEvent) fun request(request: Request<*>) val enhancedLocations: SharedFlow<LocationUpdate> val rawLocations: SharedFlow<LocationUpdate> val trackableStates: StateFlow<TrackableState> val resolutions: SharedFlow<Resolution> } internal fun createCoreSubscriber( ably: Ably, initialResolution: Resolution? = null, trackableId: String, ): CoreSubscriber { return DefaultCoreSubscriber(ably, initialResolution, trackableId) } /** * This is a private static single thread dispatcher that will be used for all the [Subscriber] instances. */ private val singleThreadDispatcher = createSingleThreadDispatcher() private class DefaultCoreSubscriber( private val ably: Ably, private val initialResolution: Resolution?, private val trackableId: String, ) : CoreSubscriber { private val scope = CoroutineScope(singleThreadDispatcher + SupervisorJob()) private val sendEventChannel: SendChannel<Event> private val _trackableStates: MutableStateFlow<TrackableState> = MutableStateFlow(TrackableState.Offline()) private val _enhancedLocations: MutableSharedFlow<LocationUpdate> = MutableSharedFlow(replay = 1) private val _rawLocations: MutableSharedFlow<LocationUpdate> = MutableSharedFlow(replay = 1) private val _resolutions: MutableSharedFlow<Resolution> = MutableSharedFlow(replay = 1) override val enhancedLocations: SharedFlow<LocationUpdate> get() = _enhancedLocations.asSharedFlow() override val rawLocations: SharedFlow<LocationUpdate> get() = _rawLocations.asSharedFlow() override val trackableStates: StateFlow<TrackableState> get() = _trackableStates.asStateFlow() override val resolutions: SharedFlow<Resolution> get() = _resolutions.asSharedFlow() init { val channel = Channel<Event>() sendEventChannel = channel scope.launch { coroutineScope { sequenceEventsQueue(channel) } } ably.subscribeForAblyStateChange { enqueue(AblyConnectionStateChangeEvent(it)) } } override fun enqueue(event: AdhocEvent) { scope.launch { sendEventChannel.send(event) } } override fun request(request: Request<*>) { scope.launch { sendEventChannel.send(request) } } private fun CoroutineScope.sequenceEventsQueue(receiveEventChannel: ReceiveChannel<Event>) { launch { val properties = Properties() // processing for (event in receiveEventChannel) { // handle events after the subscriber is stopped if (properties.isStopped) { if (event is Request<*>) { // when the event is a request then call its handler when (event) { is StopEvent -> event.handler(Result.success(Unit)) else -> event.handler(Result.failure(SubscriberStoppedException())) } continue } else if (event is AdhocEvent) { // when the event is an adhoc event then just ignore it continue } } when (event) { is StartEvent -> { updateTrackableState(properties) ably.connect(trackableId, properties.presenceData, useRewind = true, willSubscribe = true) { if (it.isSuccess) { request(ConnectionCreatedEvent(event.handler)) } else { event.handler(it) } } } is ConnectionCreatedEvent -> { ably.subscribeForPresenceMessages( trackableId = trackableId, listener = { enqueue(PresenceMessageEvent(it)) }, callback = { subscribeResult -> if (subscribeResult.isSuccess) { request(ConnectionReadyEvent(event.handler)) } else { ably.disconnect(trackableId, properties.presenceData) { event.handler(subscribeResult) } } } ) } is ConnectionReadyEvent -> { subscribeForChannelState() subscribeForEnhancedEvents() subscribeForRawEvents() subscribeForResolutionEvents() event.handler(Result.success(Unit)) } is PresenceMessageEvent -> { when (event.presenceMessage.action) { PresenceAction.PRESENT_OR_ENTER -> { if (event.presenceMessage.data.type == ClientTypes.PUBLISHER) { properties.isPublisherOnline = true updateTrackableState(properties) } } PresenceAction.LEAVE_OR_ABSENT -> { if (event.presenceMessage.data.type == ClientTypes.PUBLISHER) { properties.isPublisherOnline = false updateTrackableState(properties) } } else -> Unit } } is ChangeResolutionEvent -> { properties.presenceData = properties.presenceData.copy(resolution = event.resolution) ably.updatePresenceData(trackableId, properties.presenceData) { event.handler(it) } } is StopEvent -> { try { ably.close(properties.presenceData) properties.isStopped = true notifyAssetIsOffline() event.handler(Result.success(Unit)) } catch (exception: ConnectionException) { event.handler(Result.failure(exception)) } } is AblyConnectionStateChangeEvent -> { properties.lastConnectionStateChange = event.connectionStateChange updateTrackableState(properties) } is ChannelConnectionStateChangeEvent -> { properties.lastChannelConnectionStateChange = event.connectionStateChange updateTrackableState(properties) } } } } } private fun updateTrackableState(properties: Properties) { val newTrackableState = when (properties.lastConnectionStateChange.state) { ConnectionState.ONLINE -> { when (properties.lastChannelConnectionStateChange.state) { ConnectionState.ONLINE -> if (properties.isPublisherOnline) TrackableState.Online else TrackableState.Offline() ConnectionState.OFFLINE -> TrackableState.Offline() ConnectionState.FAILED -> TrackableState.Failed(properties.lastChannelConnectionStateChange.errorInformation!!) // are we sure error information will always be present? } } ConnectionState.OFFLINE -> TrackableState.Offline() ConnectionState.FAILED -> TrackableState.Failed(properties.lastConnectionStateChange.errorInformation!!) // are we sure error information will always be present? } if (newTrackableState != properties.trackableState) { properties.trackableState = newTrackableState scope.launch { _trackableStates.emit(newTrackableState) } } } private fun subscribeForChannelState() { ably.subscribeForChannelStateChange(trackableId) { enqueue(ChannelConnectionStateChangeEvent(it)) } } private fun subscribeForEnhancedEvents() { ably.subscribeForEnhancedEvents(trackableId) { scope.launch { _enhancedLocations.emit(it) } } } private fun subscribeForRawEvents() { ably.subscribeForRawEvents(trackableId) { scope.launch { _rawLocations.emit(it) } } } private fun subscribeForResolutionEvents() { ably.subscribeForResolutionEvents(trackableId) { scope.launch { _resolutions.emit(it) } } } private fun notifyAssetIsOffline() { scope.launch { _trackableStates.emit(TrackableState.Offline()) } } private inner class Properties( var isStopped: Boolean = false, var isPublisherOnline: Boolean = false, var trackableState: TrackableState = TrackableState.Offline(), var lastConnectionStateChange: ConnectionStateChange = ConnectionStateChange( ConnectionState.OFFLINE, null ), var lastChannelConnectionStateChange: ConnectionStateChange = ConnectionStateChange( ConnectionState.OFFLINE, null ), var presenceData: PresenceData = PresenceData(ClientTypes.SUBSCRIBER, initialResolution) ) }
kotlin
37
0.590075
188
42.65873
252
starcoderdata
package com.eugeneek.injector import java.util.* import kotlin.reflect.KClass abstract class Scope { private val instances = mutableMapOf<KClass<*>, MutableMap<String, Any>>() private var parentScope: Scope? = null internal val childScopes = HashSet<String>() internal val isRoot: Boolean get() = parentScope == null abstract fun init() inline fun <reified T: Any> bind(instance: T, name: String? = T::class.qualifiedName) { bind(T::class, instance, name) } @JvmOverloads fun <T: Any> bind(type: KClass<*>, instance: T, name: String? = type.qualifiedName) { requireNotNull(name) { "You must provide not null name to bind instance of this class" } val namedInstances = instances[type] ?: mutableMapOf() namedInstances[name] = instance instances[type] = namedInstances } internal fun setParentScope(parentScope: Scope) { this.parentScope = parentScope } internal fun addChildScopeName(childScopeName: String) { childScopes.add(childScopeName) } @Suppress("UNCHECKED_CAST") internal fun <T> getInstance(type: KClass<*>, name: String): T? = instances[type]?.get(name) as? T ?: parentScope?.getInstance(type, name) }
kotlin
12
0.666137
96
29.707317
41
starcoderdata
<filename>tunaui/src/main/java/com/tunasoftware/tunaui/creditcard/NewCardDialogFragment.kt package com.tunasoftware.tunaui.creditcard import android.graphics.drawable.Drawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.DrawableCompat import com.tunasoftware.tunaui.R class NewCardDialogFragment : NewCardFragment() { companion object { fun newInstance() = NewCardDialogFragment() } override fun onStart() { super.onStart() resources.getBoolean(R.bool.tuna_new_card_dialog_fragment_window_is_floating).let { if (it) { val width = resources.getDimension(R.dimen.tuna_select_payment_method_layout_width) val height = resources.getDimension(R.dimen.tuna_select_payment_method_layout_height) dialog?.window?.setLayout(width.toInt(), height.toInt()) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(STYLE_NORMAL, R.style.Theme_TunaUI_DialogFragment) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val view = super.onCreateView(inflater, container, savedInstanceState) arguments?.let { NewCardDialogFragmentArgs.fromBundle(it) }?.let { showCpfField = it.shouldShowCpf } return view } override fun getNavigationIconDrawable(): Drawable? { val icon = ContextCompat.getDrawable(requireContext(), R.drawable.tuna_ic_close) if (icon != null) { DrawableCompat.setTint(icon, ContextCompat.getColor(requireContext(), R.color.tunaui_primary_dark_color)) } return ContextCompat.getDrawable(requireContext(), R.drawable.tuna_ic_close) } override fun getCurrentFocus(): View? { return dialog?.currentFocus } }
kotlin
22
0.691824
117
34.655172
58
starcoderdata
<filename>app/src/main/java/com/drawable/learning/ClipDrawableFragment.kt package com.drawable.learning import android.graphics.drawable.ClipDrawable import android.view.Gravity import android.widget.SeekBar import androidx.core.content.ContextCompat import com.drawable.learning.databinding.FragmentClipDrawableBinding class ClipDrawableFragment : BaseFragment<FragmentClipDrawableBinding>() { private val clipDrawable by lazy { ContextCompat.getDrawable(context!!, R.drawable.clip_drawable) } private val manualClipDrawable by lazy { ClipDrawable( ContextCompat.getDrawable(context!!, R.drawable.nick), Gravity.CENTER, ClipDrawable.VERTICAL ) } override fun initView() { binding.clipDrawableInclude.apply { tv1.setText(R.string.clip_drawable) tv1.background = clipDrawable tv2.setText(R.string.clip_drawable) tv2.background = manualClipDrawable } //level 默认级别为 0,即完全裁剪,使图像不可见。当级别为 10,000 时,图像不会裁剪,而是完全可见。 binding.seekBar.apply { //init level clipDrawable?.level = progress manualClipDrawable.level = progress //add listener setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged( seekBar: SeekBar?, progress: Int, fromUser: Boolean ) { clipDrawable?.level = progress manualClipDrawable.level = progress } override fun onStartTrackingTouch(seekBar: SeekBar?) { } override fun onStopTrackingTouch(seekBar: SeekBar?) { } }) } } }
kotlin
23
0.611292
81
29.716667
60
starcoderdata
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.font.testutils import androidx.compose.ui.text.ExperimentalTextApi import androidx.compose.ui.text.font.AndroidFontLoader import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontSynthesis import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.TypefaceRequest import androidx.compose.ui.text.font.TypefaceRequestCache import androidx.compose.ui.text.font.TypefaceResult import androidx.compose.ui.text.font.TypefaceResult.Immutable import com.google.common.truth.Truth.assertThat /** * Cheat to validate cache behavior in FontFamilyResolver * * Throws if cache contains [TypefaceResult.Async] * * @return null if cache miss, otherwise result if [TypefaceResult.Immutable] */ @OptIn(ExperimentalTextApi::class) internal fun TypefaceRequestCache.getImmutableResultFor( fontFamily: FontFamily, fontWeight: FontWeight = FontWeight.Normal, fontStyle: FontStyle = FontStyle.Normal, fontSynthesis: FontSynthesis = FontSynthesis.All, fontLoader: AndroidFontLoader ): Any? { val result = get( TypefaceRequest( fontFamily = fontFamily, fontWeight = fontWeight, fontStyle = fontStyle, fontSynthesis = fontSynthesis, resourceLoaderCacheKey = fontLoader.cacheKey ) ) if (result == null) { return result } assertThat(result).isInstanceOf(Immutable::class.java) return result.value }
kotlin
15
0.75
77
35.066667
60
starcoderdata
<gh_stars>1-10 package codeforces.ozon2020 fun main() { val (n, m) = readInts() val a = readInts().sorted() if (n > m) return println(0) var ans = 1L for (i in a.indices) { for (j in 0 until i) { ans = ans * (a[i] - a[j]) % m } } println(ans) } private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
kotlin
17
0.600496
57
20.210526
19
starcoderdata
<reponame>Soyle-Productions/soyle-stories package com.soyle.stories.scene.setting.list import com.soyle.stories.common.ViewBuilder import javafx.event.EventTarget import javafx.scene.Node import javafx.scene.image.ImageView import tornadofx.imageview import tornadofx.opcr class SceneSettingInviteImage private constructor() { companion object { @ViewBuilder fun EventTarget.sceneSettingInviteImage() { with(SceneSettingInviteImage()) { render() } } } private fun EventTarget.render(): Node { return imageview("com/soyle/stories/scene/Symbols-design.png") { isPreserveRatio = true isSmooth = true fitHeight = 260.0 } } }
kotlin
16
0.689986
72
25.071429
28
starcoderdata
<reponame>JetBrains/projector-markdown-plugin /* * MIT License * * Copyright (c) 2019-2020 JetBrains s.r.o. * * 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 org.jetbrains.projector.plugins.markdown.lang.index import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.stubs.StringStubIndexExtension import com.intellij.psi.stubs.StubIndex import com.intellij.psi.stubs.StubIndexKey import com.intellij.util.CommonProcessors import org.jetbrains.projector.plugins.markdown.lang.psi.impl.MarkdownHeaderImpl class MarkdownHeadersIndex : StringStubIndexExtension<MarkdownHeaderImpl>() { override fun getKey(): StubIndexKey<String, MarkdownHeaderImpl> = KEY companion object { val KEY: StubIndexKey<String, MarkdownHeaderImpl> = StubIndexKey.createIndexKey<String, MarkdownHeaderImpl>("markdown.header") fun collectFileHeaders(suggestHeaderRef: String, project: Project, psiFile: PsiFile?): Collection<PsiElement> { val list = mutableListOf<PsiElement>() StubIndex.getInstance().processElements( MarkdownHeadersIndex.KEY, suggestHeaderRef, project, psiFile?.let { GlobalSearchScope.fileScope(it) }, MarkdownHeaderImpl::class.java, CommonProcessors.CollectProcessor(list) ) return list } } }
kotlin
21
0.774074
130
44
54
starcoderdata
<reponame>geoHeil/streaming-reference import com.github.geoheil.streamingreference.Libraries description = "Reusable, tested bulding blocks" dependencies{ api(Libraries.pureConfig) api(Libraries.pureConfigEnumeratum) }
kotlin
12
0.819383
54
27.5
8
starcoderdata
package com.fsck.k9.notification interface NotificationResourceProvider { val iconWarning: Int val iconMarkAsRead: Int val iconDelete: Int val iconReply: Int val iconNewMail: Int val iconSendingMail: Int val iconCheckingMail: Int val wearIconMarkAsRead: Int val wearIconDelete: Int val wearIconArchive: Int val wearIconReplyAll: Int val wearIconMarkAsSpam: Int val pushChannelName: String val pushChannelDescription: String val messagesChannelName: String val messagesChannelDescription: String val miscellaneousChannelName: String val miscellaneousChannelDescription: String fun authenticationErrorTitle(): String fun authenticationErrorBody(accountName: String): String fun certificateErrorTitle(accountName: String): String fun certificateErrorBody(): String fun newMailTitle(): String fun newMailUnreadMessageCount(unreadMessageCount: Int, accountName: String): String fun newMessagesTitle(newMessagesCount: Int): String fun additionalMessages(overflowMessagesCount: Int, accountName: String): String fun previewEncrypted(): String fun noSubject(): String fun recipientDisplayName(recipientDisplayName: String): String fun noSender(): String fun sendFailedTitle(): String fun sendingMailTitle(): String fun sendingMailBody(accountName: String): String fun checkingMailTicker(accountName: String, folderName: String): String fun checkingMailTitle(): String fun checkingMailSeparator(): String fun actionMarkAsRead(): String fun actionMarkAllAsRead(): String fun actionDelete(): String fun actionDeleteAll(): String fun actionReply(): String fun actionArchive(): String fun actionArchiveAll(): String fun actionMarkAsSpam(): String }
kotlin
7
0.752198
87
32.090909
55
starcoderdata
<filename>app/src/main/java/com/anafthdev/imdbmovie/data/MovieType.kt package com.anafthdev.imdbmovie.data /** * MOST_POPULAR_MOVIE | BOX_OFFICE_MOVIE | TOP_250_MOVIE | MOVIE_INFORMATION */ enum class MovieType { MOST_POPULAR_MOVIE, BOX_OFFICE_MOVIE, TOP_250_MOVIE, MOVIE_INFORMATION }
kotlin
10
0.744966
82
23.916667
12
starcoderdata
<filename>plugin/src/test/kotlin/nl/tudelft/hyperion/plugin/settings/HyperionSettingsConfigurableTest.kt<gh_stars>1-10 package nl.tudelft.hyperion.plugin.settings import com.intellij.openapi.project.Project import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.runs import io.mockk.unmockkAll import io.mockk.verify import nl.tudelft.hyperion.plugin.settings.ui.HyperionSettingsForm import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test /** * Test class that tests/verifies all methods from [HyperionSettingsConfigurable]. */ class HyperionSettingsConfigurableTest { private val mockProject: Project = mockk() private val mockSettingsForm: HyperionSettingsForm = mockk() private lateinit var configurable: HyperionSettingsConfigurable @BeforeEach fun setup() { configurable = HyperionSettingsConfigurable(mockProject).apply { settingsPane = mockSettingsForm } } @AfterEach fun cleanup() { unmockkAll() } @Test fun `Test getId`() { assertEquals("hyperion.settings", configurable.id) } @Test fun `Test getDisplayName`() { assertEquals("Hyperion", configurable.displayName) } @Test fun `Test createComponent`() { every { mockSettingsForm.root } returns null configurable.createComponent() verify(exactly = 1) { mockSettingsForm.root } } @Test fun `Test reset`() { every { mockSettingsForm.reset() } just runs configurable.reset() verify(exactly = 1) { mockSettingsForm.reset() } } @Test fun `Test isModified`() { every { mockSettingsForm.isModified } returns false configurable.isModified() verify(exactly = 1) { mockSettingsForm.isModified } } @Test fun `Test apply`() { every { mockSettingsForm.apply() } just runs configurable.apply() verify(exactly = 1) { mockSettingsForm.apply() } } }
kotlin
15
0.694338
118
24.728395
81
starcoderdata
<reponame>MarvinSchramm/slack-broker-spring-boot-starter<filename>client/slack-spring-api-client/src/main/kotlin/io/hndrs/slack/api/spring/group/oauth/SpringOauthAccessMethod.kt package io.hndrs.slack.api.spring.group.oauth import io.hndrs.slack.api.contract.jackson.group.oauth.AccessResponse import io.hndrs.slack.api.contract.jackson.group.oauth.ErrorAccessResponse import io.hndrs.slack.api.contract.jackson.group.oauth.SuccessfullAccessResponse import io.hndrs.slack.api.group.ApiCallResult import io.hndrs.slack.api.group.oauth.OauthAccessMethod import io.hndrs.slack.api.group.oauth.OauthMethodGroup import io.hndrs.slack.api.spring.group.RestTemplateFactory import io.hndrs.slack.api.spring.group.SlackRequestBuilder import org.springframework.web.client.RestTemplate /** * Spring based implementation of [OauthMethodGroup.access] */ @Suppress("UNCHECKED_CAST") class SpringOauthAccessMethod(private val restTemplate: RestTemplate = io.hndrs.slack.api.spring.group.RestTemplateFactory.slackTemplate()) : io.hndrs.slack.api.group.oauth.OauthAccessMethod() { override fun request(): io.hndrs.slack.api.group.ApiCallResult<SuccessfullAccessResponse, ErrorAccessResponse> { val response = SlackRequestBuilder<AccessResponse>(restTemplate = restTemplate) .toMethod("oauth.v2.access") .returnAsType(AccessResponse::class.java) .postUrlEncoded( mapOf( Pair("client_id", params.clientId), Pair("client_secret", params.client_secret), Pair("code", params.code) ) ) return when (response.body!!) { is SuccessfullAccessResponse -> { val responseEntity = response.body as SuccessfullAccessResponse this.onSuccess?.invoke(responseEntity) io.hndrs.slack.api.group.ApiCallResult(success = responseEntity) } is ErrorAccessResponse -> { val responseEntity = response.body as ErrorAccessResponse this.onFailure?.invoke(responseEntity) io.hndrs.slack.api.group.ApiCallResult(failure = responseEntity) } } } }
kotlin
21
0.703371
177
46.340426
47
starcoderdata
<gh_stars>10-100 package cafe.adriel.androidcoroutinescopes import android.os.Bundle import android.util.Log import androidx.lifecycle.ViewModelProviders import cafe.adriel.androidcoroutinescopes.appcompat.CoroutineScopedActivity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class MainActivity : CoroutineScopedActivity() { companion object { private val TAG: String = MainActivity::class.java.simpleName } private lateinit var viewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java) } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) // Activity Coroutine launch { Log.d(TAG, "MAIN THREAD") withContext(Dispatchers.Default){ Log.d(TAG, "OTHER THREAD") } } // ViewModel Coroutine viewModel.doSomethingAsync() } }
kotlin
20
0.708621
78
27.292683
41
starcoderdata
package com.testerum.scanner.step_lib_scanner.model.cache_marshalling import com.testerum.common_fast_serialization.FastMarshaller import com.testerum.common_fast_serialization.read_write.FastInput import com.testerum.common_fast_serialization.read_write.FastOutput import com.testerum.common_fast_serialization.read_write.extensions.readList import com.testerum.common_fast_serialization.read_write.extensions.requireExactVersion import com.testerum.common_fast_serialization.read_write.extensions.writeList import com.testerum.common_fast_serialization.read_write.extensions.writeVersion import com.testerum.scanner.step_lib_scanner.model.ExtensionsScanResult object ExtensionsScanResultMarshaller : FastMarshaller<ExtensionsScanResult> { private const val CURRENT_VERSION = 1 override fun serialize(prefix: String, data: ExtensionsScanResult, output: FastOutput) { output.writeVersion(prefix, CURRENT_VERSION) output.writeList("$prefix.steps", data.steps, BasicStepDefMarshaller) output.writeList("$prefix.hooks", data.hooks, HookDefMarshaller) output.writeList("$prefix.settingDefinitions", data.settingDefinitions, SettingDefinitionMarshaller) } override fun parse(prefix: String, input: FastInput): ExtensionsScanResult { input.requireExactVersion(prefix, CURRENT_VERSION) val steps = input.readList("$prefix.steps", BasicStepDefMarshaller) val hooks = input.readList("$prefix.hooks", HookDefMarshaller) val settingDefinitions = input.readList("$prefix.settingDefinitions", SettingDefinitionMarshaller) return ExtensionsScanResult(steps, hooks, settingDefinitions) } }
kotlin
12
0.795346
108
48.294118
34
starcoderdata
package featurea.cameraView import android.content.Context import android.net.Uri import android.view.SurfaceView import com.pedro.vlc.VlcListener import org.videolan.libvlc.IVLCVout import org.videolan.libvlc.LibVLC import org.videolan.libvlc.Media import org.videolan.libvlc.MediaPlayer import java.util.* internal class VlcVideoLibrary : MediaPlayer.EventListener { private val vlcListener: VlcListener private val surfaceView: SurfaceView private var vlc: LibVLC // https://stackoverflow.com/a/42670642/909169 lateinit var mediaPlayer: MediaPlayer constructor(context: Context, vlcListener: VlcListener, surfaceView: SurfaceView) { this.vlcListener = vlcListener this.surfaceView = surfaceView this.vlc = LibVLC(context, ArrayList()) } fun play(url: String?) { if (::mediaPlayer.isInitialized && !mediaPlayer.isReleased) { if (!mediaPlayer.isPlaying) mediaPlayer.play() } else { setMedia(Media(vlc, Uri.parse(url))) } } fun stop() { mediaPlayer.scale = 0f mediaPlayer.pause() mediaPlayer.stop() mediaPlayer.setVideoTrackEnabled(false) mediaPlayer.vlcVout.detachViews() mediaPlayer.vlcVout.setWindowSize(0, 0) mediaPlayer.media = null mediaPlayer.release() } override fun onEvent(event: MediaPlayer.Event) { when (event.type) { MediaPlayer.Event.Playing -> vlcListener.onComplete() MediaPlayer.Event.EncounteredError -> vlcListener.onError() } } /*internals*/ private fun setMedia(media: Media) { media.setHWDecoderEnabled(true, false) mediaPlayer = MediaPlayer(vlc).apply { this.media = media setEventListener(this@VlcVideoLibrary) setVideoTrackEnabled(true) }.also { val vlcVout: IVLCVout = it.vlcVout vlcVout.setVideoView(surfaceView) val width: Int = surfaceView.width val height: Int = surfaceView.height if (width != 0 && height != 0) { vlcVout.setWindowSize(width, height) } vlcVout.attachViews() it.play() } } }
kotlin
21
0.642952
87
29.808219
73
starcoderdata
package com.solana.rxsolana.actions import com.solana.actions.Action import com.solana.actions.sendSOL import com.solana.core.Account import com.solana.core.PublicKey import io.reactivex.Single import io.reactivex.disposables.Disposables fun Action.sendSOL( account: Account, destination: PublicKey, amount: Long ): Single<String> { return Single.create { emitter -> this.sendSOL(account, destination, amount) { result -> result.onSuccess { emitter.onSuccess(it) }.onFailure { emitter.onError(it) } } Disposables.empty() } }
kotlin
26
0.651017
62
24.56
25
starcoderdata
<gh_stars>10-100 package org.rsmod.plugins.api.model.ui.gameframe import com.google.inject.Scope import dev.misfitlabs.kotlinguice4.KotlinModule class GameframeModule(private val scope: Scope) : KotlinModule() { override fun configure() { bind<GameframeList>().`in`(scope) } }
kotlin
13
0.736486
66
23.666667
12
starcoderdata
/* * Copyright (c) 2022 WallPanel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package xyz.wallpanel.app.ui.fragments import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.navigation.Navigation import xyz.wallpanel.app.R import xyz.wallpanel.app.ui.activities.SettingsActivity import xyz.wallpanel.app.databinding.FragmentAboutBinding import timber.log.Timber class AboutFragment : Fragment() { private lateinit var binding: FragmentAboutBinding private var versionNumber: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentAboutBinding.inflate(inflater, container, false); return binding.root } override fun onDestroyView() { super.onDestroyView() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // Set title bar if((activity as SettingsActivity).supportActionBar != null) { (activity as SettingsActivity).supportActionBar!!.setDisplayHomeAsUpEnabled(true) (activity as SettingsActivity).supportActionBar!!.setDisplayShowHomeEnabled(true) (activity as SettingsActivity).supportActionBar!!.title = (getString(R.string.pref_about_title)) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { view?.let { Navigation.findNavController(it).navigate(R.id.settings_action) } return true } return super.onOptionsItemSelected(item) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) try { val packageInfo = requireActivity().packageManager.getPackageInfo(requireActivity().packageName, 0) versionNumber = " v" + packageInfo.versionName binding.versionName.text = versionNumber } catch (e: PackageManager.NameNotFoundException) { Timber.e(e.message) } binding.sendFeedbackButton.setOnClickListener { feedback() } binding.rateApplicationButton.setOnClickListener { rate() } binding.githubButton.setOnClickListener { showGitHub() } binding.supportButton.setOnClickListener { showSupport() } } private fun rate() { try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + GOOGLE_PLAY_RATING))) } catch (ex: android.content.ActivityNotFoundException) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + GOOGLE_PLAY_RATING))) } } private fun showSupport() { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(SUPPORT_URL))) } private fun showGitHub() { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(GITHUB_URL))) } private fun feedback() { val email = Intent(Intent.ACTION_SENDTO) email.type = "text/email" email.data = Uri.parse("mailto:" + EMAIL_ADDRESS) email.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.mail_to_subject_text) + " " + versionNumber) startActivity(Intent.createChooser(email, getString(R.string.mail_subject_text))) } companion object { const val SUPPORT_URL:String = "https://wallpanel.xyz" const val GOOGLE_PLAY_RATING = "xyz.wallpanel.app" const val GITHUB_URL = "https://github.com/TheTimeWalker/wallpanel-android" const val EMAIL_ADDRESS = "<EMAIL>" fun newInstance(): AboutFragment { return AboutFragment() } } }
kotlin
26
0.694937
134
35.984
125
starcoderdata
<reponame>wwy863399246/WanAndroid<filename>app/src/main/java/com/wwy/android/app/MyGlideModule.kt /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.wwy.android.app import android.annotation.SuppressLint import android.app.ActivityManager import android.content.Context import android.content.Context.ACTIVITY_SERVICE import com.bumptech.glide.Glide import com.bumptech.glide.GlideBuilder import com.bumptech.glide.Registry import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.gifdecoder.GifDecoder import com.bumptech.glide.load.DecodeFormat import com.bumptech.glide.load.DecodeFormat.PREFER_ARGB_8888 import com.bumptech.glide.load.DecodeFormat.PREFER_RGB_565 import com.bumptech.glide.load.resource.gif.GifFrameResourceDecoder import com.bumptech.glide.module.AppGlideModule import com.bumptech.glide.request.RequestOptions import java.io.InputStream /** * Glide module configurations */ @GlideModule class MyGlideModule : AppGlideModule() { @SuppressLint("CheckResult") override fun applyOptions(context: Context, builder: GlideBuilder) { val defaultOptions = RequestOptions() // Prefer higher quality images unless we're on a low RAM device val activityManager = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager val format = if (activityManager.isLowRamDevice) PREFER_RGB_565 else PREFER_ARGB_8888 // Disable hardware bitmaps as they don't play nicely with Palette defaultOptions.swap(format, builder) } //扩展函数 @SuppressLint("CheckResult") fun RequestOptions.swap(format: DecodeFormat, builder: GlideBuilder) { this.format(format) this.disallowHardwareConfig() builder.setDefaultRequestOptions(this) } override fun isManifestParsingEnabled(): Boolean { return false } }
kotlin
12
0.758692
97
35.059701
67
starcoderdata
<reponame>Sathawale27/kotlin fun x(): Boolean { return true } public fun foo(p: String?): Int { // See KT-6283 do { if (p != null) break } while (!x()) // p can be null despite of the break return p.<!INAPPLICABLE_CANDIDATE!>length<!> }
kotlin
10
0.596226
48
23.181818
11
starcoderdata
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.maven.actions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.util.xml.DomElement import com.intellij.util.xml.DomUtil import com.intellij.util.xml.actions.generate.AbstractDomGenerateProvider import com.intellij.util.xml.ui.actions.generate.GenerateDomElementAction import org.jetbrains.idea.maven.dom.MavenDomUtil import org.jetbrains.idea.maven.dom.model.MavenDomDependency import org.jetbrains.idea.maven.dom.model.MavenDomPlugin import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel import org.jetbrains.idea.maven.model.MavenId import org.jetbrains.kotlin.idea.maven.PomFile import org.jetbrains.kotlin.idea.maven.configuration.KotlinMavenConfigurator import org.jetbrains.kotlin.idea.versions.MAVEN_STDLIB_ID import org.jetbrains.kotlin.psi.psiUtil.endOffset class GenerateMavenCompileExecutionAction : PomFileActionBase(KotlinMavenExecutionProvider(PomFile.KotlinGoals.Compile, PomFile.DefaultPhases.Compile)) class GenerateMavenTestCompileExecutionAction : PomFileActionBase(KotlinMavenExecutionProvider(PomFile.KotlinGoals.TestCompile, PomFile.DefaultPhases.TestCompile)) class GenerateMavenPluginAction : PomFileActionBase(KotlinMavenPluginProvider()) private const val DefaultKotlinVersion = "\${kotlin.version}" open class PomFileActionBase(generateProvider: AbstractDomGenerateProvider<*>) : GenerateDomElementAction(generateProvider) { override fun isValidForFile(project: Project, editor: Editor, file: PsiFile): Boolean { return MavenDomUtil.isMavenFile(file) && super.isValidForFile(project, editor, file) } override fun startInWriteAction() = true } private class KotlinMavenPluginProvider : AbstractDomGenerateProvider<MavenDomPlugin>("kotlin-maven-plugin-provider", MavenDomPlugin::class.java) { override fun generate(parent: DomElement?, editor: Editor?): MavenDomPlugin? { if (parent !is MavenDomProjectModel) { return null } val knownVersion = parent.dependencies.dependencies.firstOrNull { it.isKotlinStdlib() }?.version?.rawText val version = when { knownVersion == null -> DefaultKotlinVersion knownVersion.isRangeVersion() -> knownVersion.getRangeClosedEnd() ?: DefaultKotlinVersion else -> knownVersion } val pom = PomFile.forFileOrNull(DomUtil.getFile(parent)) ?: return null return pom.addPlugin(MavenId(KotlinMavenConfigurator.GROUP_ID, KotlinMavenConfigurator.MAVEN_PLUGIN_ID, version)) } override fun getElementToNavigate(t: MavenDomPlugin?) = t?.version override fun getParentDomElement(project: Project?, editor: Editor?, file: PsiFile?): DomElement? { if (project == null || editor == null || file == null) { return null } return DomUtil.getContextElement(editor)?.findProject() } override fun isAvailableForElement(contextElement: DomElement): Boolean { val parent = contextElement.findProject() ?: return false return parent.build.plugins.plugins.none(MavenDomPlugin::isKotlinMavenPlugin) } } private class KotlinMavenExecutionProvider(val goal: String, val phase: String) : AbstractDomGenerateProvider<MavenDomPlugin>("kotlin-maven-execution-provider", MavenDomPlugin::class.java) { override fun generate(parent: DomElement?, editor: Editor?): MavenDomPlugin? { if (parent !is MavenDomPlugin) { return null } val file = PomFile.forFileOrNull(DomUtil.getFile(parent)) ?: return null val execution = file.addExecution(parent, goal, phase, listOf(goal)) if (editor != null) { editor.caretModel.moveToOffset(execution.ensureXmlElementExists().endOffset) } return parent } override fun getElementToNavigate(t: MavenDomPlugin?): DomElement? = null override fun getParentDomElement(project: Project?, editor: Editor?, file: PsiFile?): DomElement? { if (project == null || editor == null || file == null) { return null } return DomUtil.getContextElement(editor)?.findPlugin() } override fun isAvailableForElement(contextElement: DomElement): Boolean { val plugin = contextElement.findPlugin() return plugin != null && plugin.isKotlinMavenPlugin() && plugin.executions.executions.none { it.goals.goals.any { it.value == goal } } } } private fun String.getRangeClosedEnd(): String? = when { startsWith("[") -> substringBefore(',', "").drop(1).trimEnd() endsWith("]") -> substringAfterLast(',', "").dropLast(1).trimStart() else -> null } private fun Char.isRangeStart() = this == '[' || this == '(' private fun Char.isRangeEnd() = this == ']' || this == ')' private fun String.isRangeVersion() = length > 2 && this[0].isRangeStart() && last().isRangeEnd() private fun DomElement.findProject(): MavenDomProjectModel? = this as? MavenDomProjectModel ?: DomUtil.getParentOfType(this, MavenDomProjectModel::class.java, true) private fun DomElement.findPlugin(): MavenDomPlugin? = this as? MavenDomPlugin ?: DomUtil.getParentOfType(this, MavenDomPlugin::class.java, true) private fun MavenDomPlugin.isKotlinMavenPlugin() = groupId.stringValue == KotlinMavenConfigurator.GROUP_ID && artifactId.stringValue == KotlinMavenConfigurator.MAVEN_PLUGIN_ID private fun MavenDomDependency.isKotlinStdlib() = groupId.stringValue == KotlinMavenConfigurator.GROUP_ID && artifactId.stringValue == MAVEN_STDLIB_ID
kotlin
22
0.733291
125
41.155405
148
starcoderdata
<filename>app/src/main/java/com/bitwindow/aacpaginginfinitescrollingwithnetworksample/domain/movielist/MovieListUseCase.kt package com.bitwindow.aacpaginginfinitescrollingwithnetworksample.domain.movielist import android.arch.lifecycle.LiveData import android.arch.paging.PagedList import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.domain.Logger import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.domain.addDays import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.domain.diffDays import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.domain.entity.MoviePoster import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.domain.vo.BoundaryState import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.domain.vo.Direction import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.domain.vo.LoadingStatus import java.util.* import javax.inject.Inject class MovieListUseCase @Inject constructor(private val repository: MovieListRepository, private val log : Logger){ fun getMovies(): LiveData<PagedList<MoviePoster>> { return repository.getMovies() } fun getBoundaryState(): LiveData<BoundaryState<Date>> { return repository.getBoundaryState() } // Check which direction the event happened. If the user has scrolled to the top, the // direction will be TOP and if user has scrolled to the bottom (no more data in database) // then direction will be BOTTOM. If there is no data (usually first time the app start) // then fetch movies for current date fun fetchMore(itemDate: Date, direction: Direction) : LiveData<LoadingStatus> { val fetchDate = when (direction) { Direction.BOTTOM -> itemDate.addDays(-1) Direction.TOP -> itemDate.addDays(+1) else -> itemDate } val dateDiff = fetchDate.diffDays(Date()) return if (dateDiff > 0) { log.d("fetchMore future date %s", fetchDate) //if it's a future date don't fetch movies. If repository is still loading some data // then return loading or success to hide the progress bar. repository.returnLoadingOrSuccess() } else{ log.d("fetchMore starting: %s", fetchDate) // Discard a movie which doesn't have poster path because on our list UI we just // show posters repository.fetchMore(fetchDate){posterPath -> posterPath != null} } } fun refresh(){ repository.refresh() } }
kotlin
16
0.737525
122
45.290909
55
starcoderdata
package org.oppia.android.app.home.recentlyplayed import org.oppia.android.app.model.PromotedStory /** Listener interface for when ongoing story is clicked in the UI. */ interface OngoingStoryClickListener { fun onOngoingStoryClicked(promotedStory: PromotedStory) }
kotlin
7
0.818519
70
32.75
8
starcoderdata
<filename>modules/lwjgl/egl/src/templates/kotlin/egl/templates/KHR_stream.kt /* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package egl.templates import egl.* import org.lwjgl.generator.* val KHR_stream = "KHRStream".nativeClassEGL("KHR_stream", postfix = KHR) { documentation = """ Native bindings to the $registryLink extension. This extension defines a new object, the EGLStream, that can be used to efficiently transfer a sequence of image frames from one API to another. The EGLStream has mechanisms that can help keep audio data synchronized to video data. Each EGLStream is associated with a "producer" that generates image frames and inserts them into the EGLStream. The producer is responsible for inserting each image frame into the EGLStream at the correct time so that the consumer can display the image frame for the appropriate period of time. Each EGLStream is also associated with a "consumer" that retrieves image frames from the EGLStream. The consumer is responsible for noticing that an image frame is available and displaying it (or otherwise consuming it). The consumer is also responsible for indicating the latency when that is possible (the latency is the time that elapses between the time it is retrieved from the EGLStream until the time it is displayed to the user). Some APIs are stream oriented (examples: OpenMAX IL, OpenMAX AL). These APIs may be connected directly to an EGLStream as a producer or consumer. Once a stream oriented producer is "connected" to an EGLStream and "started" it may insert image frames into the EGLStream automatically with no further interaction from the application. Likewise, once a stream oriented consumer is "connected" to an EGLStream and "started" it may retrieve image frames from the EGLStream automatically with no further interaction from the application. Some APIs are rendering oriented and require interaction with the application during the rendering of each frame (examples: OpenGL, OpenGL ES, OpenVG). These APIs will not automatically insert or retrieve image frames into/from the EGLStream. Instead the application must take explicit action to cause a rendering oriented producer to insert an image frame or to cause a rendering oriented consumer to retrieve an image frame. The EGLStream conceptually operates as a mailbox. When the producer has a new image frame it empties the mailbox (discards the old contents) and inserts the new image frame into the mailbox. The consumer retrieves the image frame from the mailbox and examines it. When the consumer is finished examining the image frame it is either placed back in the mailbox (if the mailbox is empty) or discarded (if the mailbox is not empty). Timing is mainly controlled by the producer. The consumer operated with a fixed latency that it indicates to the producer through the EGL_CONSUMER_LATENCY_USEC_KHR attribute. The consumer is expected to notice when a new image frame is available in the EGLStream, retrieve it, and display it to the user in the time indicated by EGL_CONSUMER_LATENCY_USEC_KHR. The producer controls when the image frame will be displayed by inserting it into the stream at time T - EGL_CONSUMER_LATENCY_USEC_KHR where T is the time that the image frame is intended to appear to the user. This extension does not cover the details of how a producer or a consumer works or is "connected" to an EGLStream. Different kinds of producers and consumers work differently and are described in additional extension specifications. """ LongConstant( "", "NO_STREAM_KHR"..0L ) IntConstant( "", "CONSUMER_LATENCY_USEC_KHR"..0x3210, "PRODUCER_FRAME_KHR"..0x3212, "CONSUMER_FRAME_KHR"..0x3213, "STREAM_STATE_KHR"..0x3214, "STREAM_STATE_CREATED_KHR"..0x3215, "STREAM_STATE_CONNECTING_KHR"..0x3216, "STREAM_STATE_EMPTY_KHR"..0x3217, "STREAM_STATE_NEW_FRAME_AVAILABLE_KHR"..0x3218, "STREAM_STATE_OLD_FRAME_AVAILABLE_KHR"..0x3219, "STREAM_STATE_DISCONNECTED_KHR"..0x321A, "BAD_STREAM_KHR"..0x321B, "BAD_STATE_KHR"..0x321C ) EGLStreamKHR( "CreateStreamKHR", "", EGLDisplay("dpy", ""), nullable..noneTerminated..EGLint.const.p("attrib_list", "") ) EGLBoolean( "DestroyStreamKHR", "", EGLDisplay("dpy", ""), EGLStreamKHR("stream", "") ) EGLBoolean( "StreamAttribKHR", "", EGLDisplay("dpy", ""), EGLStreamKHR("stream", ""), EGLenum("attribute", ""), EGLint("value", "") ) EGLBoolean( "QueryStreamKHR", "", EGLDisplay("dpy", ""), EGLStreamKHR("stream", ""), EGLenum("attribute", ""), Check(1)..EGLint.p("value", "") ) EGLBoolean( "QueryStreamu64KHR", "", EGLDisplay("dpy", ""), EGLStreamKHR("stream", ""), EGLenum("attribute", ""), Check(1)..EGLuint64KHR.p("value", "") ) } val KHR_stream_attrib = "KHRStreamAttrib".nativeClassEGL("KHR_stream_attrib", postfix = KHR) { documentation = "See ${KHR_stream.link}." EGLStreamKHR( "CreateStreamAttribKHR", "", EGLDisplay("dpy", ""), nullable..noneTerminated..EGLAttrib.const.p("attrib_list", "") ) EGLBoolean( "SetStreamAttribKHR", "", EGLDisplay("dpy", ""), EGLStreamKHR("stream", ""), EGLenum("attribute", ""), EGLAttrib("value", "") ) EGLBoolean( "QueryStreamAttribKHR", "", EGLDisplay("dpy", ""), EGLStreamKHR("stream", ""), EGLenum("attribute", ""), Check(1)..EGLAttrib.p("value", "") ) EGLBoolean( "StreamConsumerAcquireAttribKHR", "", EGLDisplay("dpy", ""), EGLStreamKHR("stream", ""), nullable..noneTerminated..EGLAttrib.const.p("attrib_list", "") ) EGLBoolean( "StreamConsumerReleaseAttribKHR", "", EGLDisplay("dpy", ""), EGLStreamKHR("stream", ""), nullable..noneTerminated..EGLAttrib.const.p("attrib_list", "") ) }
kotlin
18
0.65834
159
37.831325
166
starcoderdata
<filename>analysis/analysis-api-providers/src/org/jetbrains/kotlin/analysis/providers/KotlinDeclarationProvider.kt /* * Copyright 2010-2021 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.analysis.providers import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.name.CallableId import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* /** * A declaration provider for a given scope. Can be created via [KotlinDeclarationProviderFactory]. * May be called frequently, so for implementations it is better to cache results. */ public abstract class KotlinDeclarationProvider { public abstract fun getClassesByClassId(classId: ClassId): Collection<KtClassOrObject> public abstract fun getTypeAliasesByClassId(classId: ClassId): Collection<KtTypeAlias> public abstract fun getClassNamesInPackage(packageFqName: FqName): Set<Name> public abstract fun getTypeAliasNamesInPackage(packageFqName: FqName): Set<Name> public abstract fun getTopLevelProperties(callableId: CallableId): Collection<KtProperty> public abstract fun getTopLevelFunctions(callableId: CallableId): Collection<KtNamedFunction> public abstract fun getPropertyNamesInPackage(packageFqName: FqName): Set<Name> public abstract fun getFunctionsNamesInPackage(packageFqName: FqName): Set<Name> public abstract fun getFacadeFilesInPackage(packageFqName: FqName): Collection<KtFile> public abstract fun findFilesForFacade(facadeFqName: FqName): Collection<KtFile> } public abstract class KotlinDeclarationProviderFactory { public abstract fun createDeclarationProvider(searchScope: GlobalSearchScope): KotlinDeclarationProvider } public fun Project.createDeclarationProvider(searchScope: GlobalSearchScope): KotlinDeclarationProvider = ServiceManager.getService(this, KotlinDeclarationProviderFactory::class.java) .createDeclarationProvider(searchScope)
kotlin
11
0.82306
115
50.272727
44
starcoderdata
<filename>app/src/test/java/io/github/zeyomir/cv/base/DateFormatterTest.kt package io.github.zeyomir.cv.base import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.time.LocalDate import java.util.* internal class DateFormatterTest { lateinit var sut: DateFormatter @BeforeEach fun setup() { sut = DateFormatter(Locale.US) } @Test fun `formats full year then month with leading zero, with dot as separator`() { val date = LocalDate.of(2020, 8, 1) val formattedDate = sut.formatFullYearAndMonth(date) assertEquals("2020.08", formattedDate) } }
kotlin
19
0.719653
83
25.615385
26
starcoderdata
<reponame>cucbin/a2_hub package io.ioprint.djinnidemo.app import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import io.ioprint.djinnidemo.R import io.ioprint.djinnidemo.base.fragment.AbstractBaseFragment import kotlinx.android.synthetic.main.fragment_home.* /** * @author bill.shen * <p>Date: 1/4/19</p> */ class HomeFragment : AbstractBaseFragment(),IHomeView { private val presenter by lazy { HomePresenter(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_home, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { presenter.load() } override fun showText(content:String) { sampleText.text = content } companion object { private val TAG = "HomeFragment" } }
kotlin
16
0.718427
116
25.135135
37
starcoderdata
package com.enxy.domain.features.common class Event<out T>(private val value: T) { private var isHandled: Boolean = false fun getValueIfNotHandled(): T? = value.takeIf { !isHandled }?.also { isHandled = true } fun getValue(): T = value }
kotlin
13
0.686508
91
30.5
8
starcoderdata
<filename>.teamcity/Gradle_Check/configurations/FunctionalTest.kt package configurations import common.Os import jetbrains.buildServer.configs.kotlin.v2018_2.AbsoluteId import model.CIBuildModel import model.Stage import model.TestCoverage import model.TestType class FunctionalTest(model: CIBuildModel, testCoverage: TestCoverage, subProjects: List<String> = listOf(), stage: Stage, buildTypeName: String = "", extraParameters: String = "") : BaseGradleBuildType(model, stage = stage, init = { uuid = testCoverage.asConfigurationId(model, buildTypeName) id = AbsoluteId(uuid) name = testCoverage.asName() + if (buildTypeName.isEmpty()) "" else " ($buildTypeName)" description = "${testCoverage.asName()} for ${when (subProjects.size) { 0 -> "all projects " 1 -> "project ${if (buildTypeName.isEmpty()) subProjects[0] else buildTypeName}" else -> "projects ${subProjects.joinToString(", ")}" }}" val testTaskName = "${testCoverage.testType.name}Test" val testTasks = if (subProjects.isEmpty()) testTaskName else subProjects.joinToString(" ") { "$it:$testTaskName" } val quickTest = testCoverage.testType == TestType.quick val buildScanTags = listOf("FunctionalTest") val buildScanValues = mapOf( "coverageOs" to testCoverage.os.name, "coverageJvmVendor" to testCoverage.vendor.name, "coverageJvmVersion" to testCoverage.testJvmVersion.name ) applyTestDefaults(model, this, testTasks, notQuick = !quickTest, os = testCoverage.os, extraParameters = ( listOf(""""-PtestJavaHome=%${testCoverage.os}.${testCoverage.testJvmVersion}.${testCoverage.vendor}.64bit%"""") + buildScanTags.map { buildScanTag(it) } + buildScanValues.map { buildScanCustomValue(it.key, it.value) } + extraParameters ).filter { it.isNotBlank() }.joinToString(separator = " "), timeout = testCoverage.testType.timeout) params { param("env.JAVA_HOME", "%${testCoverage.os}.${testCoverage.buildJvmVersion}.openjdk.64bit%") when (testCoverage.os) { Os.linux -> param("env.ANDROID_HOME", "/opt/android/sdk") // Use fewer parallel forks on macOs, since the agents are not very powerful. Os.macos -> param("maxParallelForks", "2") else -> { } } } })
kotlin
31
0.663485
232
46.254902
51
starcoderdata
/* * Copyright 2018-2019 <NAME> <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pemistahl.lingua.internal.util.extension import com.github.pemistahl.lingua.api.LanguageDetector import java.io.FileNotFoundException import java.nio.charset.Charset import java.util.regex.PatternSyntaxException internal fun String.asLineSequenceResource( charset: Charset = Charsets.UTF_8, operation: (Sequence<String>) -> Unit ) { val inputStream = LanguageDetector::class.java.getResourceAsStream(this) ?: throw FileNotFoundException("the file '$this' could not be found") inputStream.bufferedReader(charset).useLines(operation) } internal fun String.containsAnyOf(characters: String): Boolean { for (c in characters) { if (this.contains(c)) return true } return false } internal fun String.asRegex() = try { // Android only supports character classes without Is- prefix Regex("\\p{$this}+") } catch (e: PatternSyntaxException) { Regex("\\p{Is$this}+") }
kotlin
12
0.729677
81
31.978723
47
starcoderdata
<filename>src/main/kotlin/de/tweerlei/plumber/pipeline/ProcessingStepFactory.kt /* * Copyright 2022 <NAME> + <NAME> - http://www.tweerlei.de/ * * 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 de.tweerlei.plumber.pipeline import org.springframework.stereotype.Service @Service class ProcessingStepFactory( private val processingSteps: Map<String, ProcessingStep> ) { companion object { const val BEAN_SUFFIX = "Worker" } fun processingStepFor(stepName: String) = processingSteps["$stepName$BEAN_SUFFIX"] ?: throw IllegalArgumentException("Unknown worker type '$stepName'") fun processingStepDescriptions() = processingSteps .mapKeys { (key, _) -> key.substring(0, key.length - BEAN_SUFFIX.length) } .mapValues { (_, factory) -> factory.description } .toSortedMap() }
kotlin
21
0.71043
117
35.078947
38
starcoderdata
<reponame>DebashisINT/Lavos<gh_stars>0 package com.lavos.features.location.shopdurationapi import com.lavos.app.NetworkConstant import com.lavos.base.BaseResponse import com.lavos.features.location.model.MeetingDurationInputParams import com.lavos.features.location.model.ShopDurationRequest import com.lavos.features.location.model.VisitRemarksResponseModel import io.reactivex.Observable import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.Body import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.POST /** * Created by Pratishruti on 28-11-2017. */ interface ShopDurationApi { @POST("Shopsubmission/ShopVisited") fun submitShopDuration(@Body shopDuration: ShopDurationRequest?): Observable<ShopDurationRequest> @POST("Shopsubmission/MeetingVisited") fun submitMeetingDuration(@Body meetingDuration: MeetingDurationInputParams?): Observable<BaseResponse> @FormUrlEncoded @POST("VisitRemarks/List") fun getRemarksList(@Field("session_token") session_token: String, @Field("user_id") user_id: String): Observable<VisitRemarksResponseModel> /** * Companion object to create the ShopDurationApi */ companion object Factory { fun create(): ShopDurationApi { val retrofit = Retrofit.Builder() .client(NetworkConstant.setTimeOutNoRetry()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(NetworkConstant.BASE_URL) .build() return retrofit.create(ShopDurationApi::class.java) } } }
kotlin
24
0.744824
143
36.25
48
starcoderdata
@file:Suppress("unused") package dev.entao.kan.creator import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.TableLayout import android.widget.TableRow import androidx.fragment.app.Fragment import dev.entao.kan.base.act import dev.entao.kan.ext.needId /** * Created by <EMAIL> on 2018-03-14. */ fun TableLayout.tableRow(block: TableRow.() -> Unit): TableRow { val v = TableRow(this.context).needId() this.addView(v) v.block() return v } fun TableLayout.tableRow(param: ViewGroup.LayoutParams, block: TableRow.() -> Unit): TableRow { val v = TableRow(this.context).needId() this.addView(v, param) v.block() return v } fun TableLayout.tableRow(index: Int, param: ViewGroup.LayoutParams, block: TableRow.() -> Unit): TableRow { val v = TableRow(this.context).needId() this.addView(v, index, param) v.block() return v } //TableLayout fun ViewGroup.table(block: TableLayout.() -> Unit): TableLayout { val v = this.createTable() this.addView(v) v.block() return v } fun ViewGroup.table(param: ViewGroup.LayoutParams, block: TableLayout.() -> Unit): TableLayout { val v = this.createTable() this.addView(v, param) v.block() return v } fun ViewGroup.table(index: Int, param: ViewGroup.LayoutParams, block: TableLayout.() -> Unit): TableLayout { val v = this.createTable() this.addView(v, index, param) v.block() return v } fun View.createTable(): TableLayout { return this.context.createTable() } fun Fragment.createTable(): TableLayout { return this.act.createTable() } fun Context.createTable(): TableLayout { return TableLayout(this).needId() }
kotlin
13
0.729829
108
21.722222
72
starcoderdata
<filename>src/main/kotlin/dev/lunarcoffee/risako/framework/core/commands/CommandContext.kt package dev.lunarcoffee.risako.framework.core.commands import dev.lunarcoffee.risako.framework.core.dispatchers.DispatchableContext import net.dv8tion.jda.api.entities.MessageChannel import net.dv8tion.jda.api.events.message.MessageReceivedEvent interface CommandContext : DispatchableContext, MessageChannel { override val event: MessageReceivedEvent }
kotlin
11
0.855876
90
44.1
10
starcoderdata
package com.sksamuel.kotlintest import io.kotlintest.extensions.TestListener import io.kotlintest.matchers.boolean.shouldBeTrue import io.kotlintest.specs.StringSpec import java.io.Closeable // this is here to test for github issue #294 internal object Resources class AutoCloseTest : StringSpec() { private val resourceA = autoClose(Closeable2) private val resourceB = autoClose(Closeable1) init { "should close resources in reverse order" { // nothing to do here } } } object AutoCloseListener : TestListener { override fun afterProject() { Closeable1.closed.shouldBeTrue() Closeable2.closed.shouldBeTrue() } } object Closeable1 : Closeable { var closed = false override fun close() { closed = true } } object Closeable2 : Closeable { var closed = false override fun close() { assert(Closeable1.closed) closed = true } }
kotlin
12
0.724215
50
18
47
starcoderdata
<reponame>gimlet2/arrow-meta<gh_stars>0 package arrow.meta.plugins.analysis.phases.analysis.solver.ast.kotlin.elements import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.ResolutionContext import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.elements.Expression import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.types.Type import arrow.meta.plugins.analysis.phases.analysis.solver.ast.kotlin.KotlinResolutionContext import arrow.meta.plugins.analysis.phases.analysis.solver.ast.kotlin.ast.model import arrow.meta.plugins.analysis.phases.analysis.solver.ast.kotlin.types.KotlinType import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis import org.jetbrains.kotlin.resolve.calls.callUtil.getType fun interface KotlinExpression : Expression, KotlinElement { override fun impl(): KtExpression override fun type(context: ResolutionContext): Type? = if (context is KotlinResolutionContext) impl().getType(context.bindingContext)?.let { KotlinType(it) } else null override fun lastBlockStatementOrThis(): Expression = impl().lastBlockStatementOrThis().model() }
kotlin
16
0.826745
97
53.045455
22
starcoderdata
package io.github.fomin.oasgen.java.dto.jackson.wstatic import io.github.fomin.oasgen.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import java.io.File internal class ObjectConverterMatcherTest { @Test fun `matches object`() { val objectConverterMatcher = ObjectConverterMatcher("com.example.dto", "com.example.routes") val converterRegistry = ConverterRegistry( CompositeConverterMatcher( listOf( objectConverterMatcher ) ) ) val fragmentRegistry = FragmentRegistry( InMemoryContentLoader( mapOf( "dto.yaml" to "type: object" ) ) ) val jsonSchema = JsonSchema(fragmentRegistry.get(Reference.root("dto.yaml")), null) val converterWriter = objectConverterMatcher.match(converterRegistry, jsonSchema) ?: error("Expected non-null value") assertThrows<Exception> { converterWriter.stringParseExpression("any") } assertThrows<Exception> { converterWriter.stringWriteExpression("any") } } @Test fun `simple dto`() { val stringConverterMatcher = StringConverterMatcher() val objectConverterMatcher = ObjectConverterMatcher( "com.example.simple.dto", "com.example.simple.routes" ) val converterRegistry = ConverterRegistry( CompositeConverterMatcher( listOf( stringConverterMatcher, objectConverterMatcher ) ) ) jsonSchemaTestCase( JavaDtoWriter(converterRegistry), File("build/test-schemas/dto/simple"), "dto.yaml", File("../expected-dto/src/simple/java") ) } @Test fun javadoc() { val stringConverterMatcher = StringConverterMatcher() val objectConverterMatcher = ObjectConverterMatcher( "com.example.javadoc.dto", "com.example.javadoc.routes" ) val converterRegistry = ConverterRegistry( CompositeConverterMatcher( listOf( stringConverterMatcher, objectConverterMatcher ) ) ) jsonSchemaTestCase( JavaDtoWriter(converterRegistry), File("build/test-schemas/dto/documentation"), "dto.yaml", File("../expected-dto/src/javadoc/java") ) } }
kotlin
20
0.570232
100
30.650602
83
starcoderdata
package net.redwarp.app.multitool.compass import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.View import android.view.animation.LinearInterpolator import net.redwarp.app.multitool.R class CompassView : View { var angle: Float = 0f set(value) { field = value % 360f invalidate() } var backgroundAngle: Float = 0f set(value) { field = value % 360f invalidate() } private val angleAnimator: ValueAnimator = ValueAnimator() private val paint = Paint() private val textPaint = Paint() private val northArrowPaint = Paint() private val southArrowPaint = Paint() private val north: Direction by lazy { Direction(context.getString(R.string.direction_north), 0f) } private val east: Direction by lazy { Direction(context.getString(R.string.direction_east), 90f) } private val south: Direction by lazy { Direction(context.getString(R.string.direction_south), 180f) } private val west: Direction by lazy { Direction(context.getString(R.string.direction_west), 270f) } private val arrow = Arrow() constructor(context: Context) : super(context) { commonInit(null) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { commonInit(attrs) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { commonInit(attrs) } @Suppress("unused") constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { commonInit(attrs) } private fun commonInit(attrs: AttributeSet?) { val obtainStyledAttributes = context.obtainStyledAttributes(attrs, intArrayOf(R.attr.colorPrimary, R.attr.colorPrimaryLight)) @SuppressLint("ResourceType") paint.color = obtainStyledAttributes.getColor(1, Color.WHITE) paint.isAntiAlias = true textPaint.color = obtainStyledAttributes.getColor(0, Color.BLACK) textPaint.isAntiAlias = true northArrowPaint.color = Color.RED northArrowPaint.isAntiAlias = true southArrowPaint.color = obtainStyledAttributes.getColor(0, Color.BLACK) southArrowPaint.isAntiAlias = true obtainStyledAttributes.recycle() angleAnimator.addUpdateListener { this.angle = it.animatedValue as Float } angleAnimator.interpolator = LinearInterpolator() } /** * A compass view should be square. */ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, widthMeasureSpec) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { // Update letters val width = w.toFloat() textPaint.textSize = width / 6f north.measureOffsets(textPaint, width) east.measureOffsets(textPaint, width) south.measureOffsets(textPaint, width) west.measureOffsets(textPaint, width) arrow.measure(width) } override fun draw(canvas: Canvas?) { super.draw(canvas) if (canvas != null) { canvas.save() canvas.translate(width / 2f, height / 2f) drawBackgroundCircle(canvas) arrow.draw(canvas) canvas.restore() } } private fun drawBackgroundCircle(canvas: Canvas) { canvas.save() canvas.rotate(backgroundAngle) canvas.drawCircle(0f, 0f, width / 2f, paint) north.draw(canvas, textPaint) east.draw(canvas, textPaint) south.draw(canvas, textPaint) west.draw(canvas, textPaint) canvas.restore() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() if (angleAnimator.isRunning) { angleAnimator.end() } } fun setAngle(angle: Float, animated: Boolean) { if (animated) { angleAnimator.cancel() val (fromAngle, toAngle) = findAngles(this.angle, angle) angleAnimator.setFloatValues(fromAngle, toAngle) angleAnimator.duration = (Math.abs(toAngle - fromAngle) * 4f).toLong() angleAnimator.start() } else { this.angle = angle } } private fun findAngles(angle1: Float, angle2: Float): Pair<Float, Float> { return if (angle1 > angle2) { if (Math.abs(angle2 - angle1) < Math.abs(angle2 + 360f - angle1)) { Pair(angle1, angle2) } else { Pair(angle1, angle2 + 360f) } } else { if (Math.abs(angle2 - angle1) < Math.abs(angle2 - 360f - angle1)) { Pair(angle1, angle2) } else { Pair(angle1, angle2 - 360f) } } } private class Direction(val text: String, val degrees: Float) { var xOffset = 0f var yOffset = 0f fun measureOffsets(paint: Paint, width: Float) { xOffset = -paint.measureText(text) / 2f yOffset = -width * .3f } fun draw(canvas: Canvas, paint: Paint) { canvas.save() canvas.rotate(degrees, 0f, 0f) canvas.drawText(text, xOffset, yOffset, paint) canvas.restore() } } private inner class Arrow { val path = Path() val workRect = RectF() fun measure(width: Float) { path.rewind() path.moveTo(-width / 20f, 0f) path.lineTo(0f, -width * .4f) path.lineTo(width / 20f, 0f) workRect.set(-width / 20f, -width / 20f, width / 20f, width / 20f) path.arcTo(workRect, 0f, 180f, true) path.close() path.fillType = Path.FillType.EVEN_ODD } fun draw(canvas: Canvas) { canvas.save() canvas.rotate(180f + angle) canvas.drawPath(path, southArrowPaint) canvas.rotate(180f) canvas.drawPath(path, northArrowPaint) canvas.restore() canvas.drawCircle(0f, 0f, width / 32f, southArrowPaint) } } }
kotlin
21
0.601519
133
31.099502
201
starcoderdata
<gh_stars>0 package com.sk.android.letswatch.vo data class ApiFailure(val statusCode: Int, val statusMessage: String) : Exception(statusMessage)
kotlin
6
0.806897
96
35.5
4
starcoderdata
<filename>compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/input/pointer/PointerInteropFilterAndroidViewOffsetsTest.kt<gh_stars>0 /* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.input.pointer import android.content.Context import android.view.MotionEvent import android.view.MotionEvent.ACTION_DOWN import android.view.MotionEvent.ACTION_UP import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.ui.Modifier import androidx.compose.ui.platform.AmbientDensity import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.test.TestActivity import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.nhaarman.mockitokotlin2.clearInvocations import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith // Tests that pointer offsets are correct when a pointer is dispatched from Android through // Compose and back into Android and each layer offsets the pointer during dispatch. @MediumTest @RunWith(AndroidJUnit4::class) class PointerInteropFilterAndroidViewOffsetsTest { private lateinit var five: View private val theHitListener: () -> Unit = mock() @get:Rule val rule = createAndroidComposeRule<TestActivity>() @Before fun setup() { rule.activityRule.scenario.onActivity { activity -> // one: Android View that is the touch target, inside // two: Android View with 1x2 padding, inside // three: Compose Box with 2x12 padding, inside // four: Android View with 3x13 padding, inside // five: Android View with 4x14 padding // // With all of the padding, "one" is at 10 x 50 relative to "five" and the tests // dispatch MotionEvents to "five". val one = CustomView(activity).apply { layoutParams = ViewGroup.LayoutParams(1, 1) hitListener = theHitListener } val two = FrameLayout(activity).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) setPadding(1, 11, 0, 0) addView(one) } val four = ComposeView(activity).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) setPadding(3, 13, 0, 0) setContent { with(AmbientDensity.current) { // Box is "three" Box( Modifier.padding(start = (2f / density).dp, top = (12f / density).dp) ) { AndroidView({ two }) } } } } five = FrameLayout(activity).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) setPadding(4, 14, 0, 0) addView(four) } activity.setContentView(five) } } @Test fun uiClick_inside_hits() { uiClick(10, 50, true) } @Test fun uiClick_justOutside_misses() { uiClick(9, 50, false) uiClick(10, 49, false) uiClick(11, 50, false) uiClick(10, 51, false) } // Gets reused to should always clean up state. private fun uiClick(x: Int, y: Int, hits: Boolean) { clearInvocations(theHitListener) rule.activityRule.scenario.onActivity { val down = MotionEvent( 0, ACTION_DOWN, 1, 0, arrayOf(PointerProperties(1)), arrayOf(PointerCoords(x.toFloat(), y.toFloat())), five ) val up = MotionEvent( 10, ACTION_UP, 1, 0, arrayOf(PointerProperties(1)), arrayOf(PointerCoords(x.toFloat(), y.toFloat())), five ) five.dispatchTouchEvent(down) five.dispatchTouchEvent(up) } if (hits) { verify(theHitListener, times(2)).invoke() } else { verify(theHitListener, never()).invoke() } } } private class CustomView(context: Context) : View(context) { lateinit var hitListener: () -> Unit override fun onTouchEvent(event: MotionEvent?): Boolean { hitListener() return true } }
kotlin
39
0.60077
144
32.948864
176
starcoderdata
package com.Atul.bank.api import com.Atul.bank.AtulIssueRequest import com.Atul.bank.AtulMoveRequest import com.Atul.bank.AtulState import net.corda.core.contracts.StateAndRef import net.corda.core.identity.CordaX500Name import net.corda.core.messaging.CordaRPCOps import net.corda.core.messaging.startFlow import net.corda.core.utilities.getOrThrow import java.time.LocalDateTime import javax.ws.rs.* import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response import net.corda.core.utilities.loggerFor import org.slf4j.Logger // API is accessible from /api/bank. All paths specified below are relative to it. @Path("bank") class BankWebApi(private val rpc: CordaRPCOps) { companion object { val logger: Logger = loggerFor<BankWebApi>() } @GET @Path("date") @Produces(MediaType.APPLICATION_JSON) fun getCurrentDate(): Any { return mapOf("date" to LocalDateTime.now().toLocalDate()) } /** * Request asset issuance */ @POST @Path("issue-asset-request") @Consumes(MediaType.APPLICATION_JSON) fun issueAssetRequest(thought: String, issuer: CordaX500Name): Response { return try { val issuerID = rpc.wellKnownPartyFromX500Name(issuer) ?: throw IllegalArgumentException("Could not find the issuer node '${issuer}'.") rpc.startFlow(::AtulIssueRequest, thought, issuerID).returnValue.getOrThrow() logger.info("Issue request completed successfully: $thought") Response.status(Response.Status.CREATED).build() } catch (e: Exception) { logger.error("Issue request failed", e) Response.status(Response.Status.FORBIDDEN).build() } } /** * Request asset move */ @POST @Path("issue-move-request") @Consumes(MediaType.APPLICATION_JSON) fun issueMoveRequest(atul: StateAndRef<AtulState>, newOwner: CordaX500Name): Response { return try { val issuerID = rpc.wellKnownPartyFromX500Name(newOwner) ?: throw IllegalArgumentException("Could not find the new owner node '${newOwner}'.") rpc.startFlow(::AtulMoveRequest, atul, issuerID).returnValue.getOrThrow() logger.info("Movement request completed successfully") Response.status(Response.Status.CREATED).build() } catch (e: Exception) { logger.error("Movement request failed", e) Response.status(Response.Status.FORBIDDEN).build() } } }
kotlin
19
0.689059
153
35.558824
68
starcoderdata
<filename>src/test/kotlin/boti996/lileto/tests/SpecialCharacterTests.kt<gh_stars>0 package boti996.lileto.tests import boti996.lileto.tests.helpers.* import org.jetbrains.spek.api.Spek private val specialCharPlaceholder = SpecialCharacter.VBAR class SpecialCharacterTests : Spek({ val testCases = mutableListOf( singleBracketInPlaintext( BracketWithContent( BracketType.SPECIAL_CHAR, specialCharPlaceholder.literal() ), specialCharPlaceholder.character() ), singleBracketInPlaintext_noClosingMarkerChar( BracketWithContent( BracketType.SPECIAL_CHAR, specialCharPlaceholder.literal() ), specialCharPlaceholder.character() ), singleBracketInPlaintext_trimWhitespaces( BracketWithContent( BracketType.SPECIAL_CHAR, specialCharPlaceholder.literal() ), specialCharPlaceholder.character() ), multipleBracketsInPlaintext( bracketListOf(SpecialCharacter.values().map { specialCharacter -> BracketType.SPECIAL_CHAR to specialCharacter.literal() }), SpecialCharacter.values().map { specialCharacter -> specialCharacter.character() } ), multipleSpecialCharactersInOneBracket(10), multipleSpecialCharactersInOneBracket_notCommaSeparated(10), multipleSpecialCharactersInOneBracket_unicodeChars(10) ) this.evaluateTestcases(testCases, BracketType.SPECIAL_CHAR) }) internal fun multipleSpecialCharactersInOneBracket(count: Int) = _multipleSpecialCharactersInOneBracket( count, listOf("Multiple special characters", "in one bracket.") ) internal fun multipleSpecialCharactersInOneBracket_notCommaSeparated(count: Int) = _multipleSpecialCharactersInOneBracket( count, listOf("Multiple special characters", "with no comma separation."), useCommas = false ) internal fun multipleSpecialCharactersInOneBracket_unicodeChars(count: Int) = _multipleSpecialCharactersInOneBracket( count, listOf("Multiple special characters", "using Unicode character codes"), useUnicode = true ) internal fun _multipleSpecialCharactersInOneBracket(count: Int, description: List<String>, useCommas: Boolean = true, useUnicode: Boolean = false) : testcase { assert(count >= 0) descriptionListSizeAssertion(description, 2) val specialCharacters = SpecialCharacter.values() fun getRandomUnicode() : Char = (Char.MIN_VALUE..Char.MAX_VALUE).random() fun getRandomCharacter() : Any = if (useUnicode) getRandomUnicode() else specialCharacters.random() fun getContentCharacter(char: Any) = if (char is Char) char.toInt().toString() else (char as SpecialCharacter).literal() fun getEvaluatedCharacter(char: Any) = if (char is Char) char.toString() else (char as SpecialCharacter).character() val randomContent = StringBuilder() val evaluatedContent = StringBuilder() randomContent.append("${description[0]} [") evaluatedContent.append("${description[0]} [") randomContent.append(BracketType.SPECIAL_CHAR.open()) for (i in 0 until count) { val character = getRandomCharacter() randomContent.append(getContentCharacter(character)) if (useCommas && i < count - 1) randomContent.append(',') evaluatedContent.append(getEvaluatedCharacter(character)) } randomContent.append(BracketType.SPECIAL_CHAR.close()) randomContent.append("] ${description[1]}") evaluatedContent.append("] ${description[1]}") return buildTestCaseEntry( listOf(randomContent.toString()), evaluatedContent.toString() ) }
kotlin
30
0.656787
136
32.181818
121
starcoderdata
package tech.kzen.launcher.client.wrap import kotlinx.css.* import kotlin.js.Json import kotlin.js.json fun reactStyle(handler: RuleSet): Json { val style = CssBuilder().apply(handler) val reactStyles = json() for (e in style.declarations) { reactStyles[e.key] = e.value.toString() } return reactStyles }
kotlin
13
0.689349
47
17.833333
18
starcoderdata
<reponame>bdudelsack/TeXiFy-IDEA<filename>src/nl/hannahsten/texifyidea/formatting/BibtexSpacingRules.kt package nl.hannahsten.texifyidea.formatting import com.intellij.formatting.Spacing import com.intellij.psi.codeStyle.CodeStyleSettings import nl.hannahsten.texifyidea.BibtexLanguage import nl.hannahsten.texifyidea.psi.BibtexTypes.* fun createBibtexSpacingBuilder(settings: CodeStyleSettings): TexSpacingBuilder { val bibtexCommonSettings = settings.getCommonSettings(BibtexLanguage) return rules(bibtexCommonSettings) { simple { around(ASSIGNMENT).spaces(1) before(SEPARATOR).spaces(0) between(TYPE, OPEN_BRACE).spaces(0) between(TYPE, OPEN_PARENTHESIS).spaces(0) between(OPEN_BRACE, ID).spaces(0) after(OPEN_PARENTHESIS).spaces(1) around(CONCATENATE).spaces(1) between(ENTRY_CONTENT, ENDTRY).spaces(1) } custom { // Only insert a space between two actual words, so when the left word // is not a left brace, and the right word is not a right brace. customRule { _, left, right -> return@customRule if (right.node?.elementType === NORMAL_TEXT_WORD && left.node?.elementType === NORMAL_TEXT_WORD) { if (left.node?.text == "{" || right.node?.text == "}") null else Spacing.createSpacing(1, 1, 0, bibtexCommonSettings.KEEP_LINE_BREAKS, bibtexCommonSettings.KEEP_BLANK_LINES_IN_CODE) } else null } } } }
kotlin
34
0.64795
141
40.736842
38
starcoderdata
<gh_stars>0 package com.permissionx.currencysystem.fragment import com.hankkin.library.mvp.presenter.RxLifePresenter import com.hankkin.library.utils.LogUtils import com.permissionx.currencysystem.http.HttpClientUtils import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers class HomePresenter :RxLifePresenter<HomeContract.IView>(),HomeContract.IPresenter{ override fun invitationList() { getMvpView().showLoading() HttpClientUtils.Builder.getCommonHttp() .invitation() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeTx ({ getMvpView().hideLoading() getMvpView().invitationListResult(it.list) },{ LogUtils.d(it.message) getMvpView().showErrorMsg(it.message!!) getMvpView().hideLoading() }).bindRxLifeEx(RxLife.ON_DESTROY) } }
kotlin
21
0.675127
83
34.214286
28
starcoderdata
package com.retrypay.example import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView import com.google.android.material.button.MaterialButton import com.retrypay.example.util.Coroutines import com.retrypay.rickandmorti.data.network.model.ApiRMResponse import com.retrypay.rickandmorti.data.repository.PersonRepository import com.retrypay.rickandmorti.util.Resource import com.retrypay.rickandmorti.util.ResourceStatus class MainActivity : AppCompatActivity() { lateinit var personRepository: PersonRepository var allPersonsButton: MaterialButton? = null var responseText: TextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) personRepository = PersonRepository() } override fun onStart() { super.onStart() allPersonsButton = findViewById(R.id.allPersonsButton) responseText = findViewById(R.id.responseText) allPersonsButton?.setOnClickListener { onGetAllPersons() } } private fun onGetAllPersons() { personRepository.getAllPersons(null).observe(this) { when(it.status) { ResourceStatus.SUCCESS -> { // Do something with data setResponseText(it.data.toString()) } ResourceStatus.LOADING -> { // Show loading to user } ResourceStatus.ERROR -> { it.message?.let { // Show message to user } } } } } private fun onGetOnePerson(personId: Int) { personRepository.getOnePerson(personId).observe(this) { when(it.status) { ResourceStatus.SUCCESS -> { // Do something with data } ResourceStatus.LOADING -> { // Show loading to user } ResourceStatus.ERROR -> { it.message?.let { // Show message to user } } } } } private fun onGetSomePersons(personIds: List<Int>) { personRepository.getSomePersons(personIds).observe(this) { when(it.status) { ResourceStatus.SUCCESS -> { // Do something with data } ResourceStatus.LOADING -> { // Show loading to user } ResourceStatus.ERROR -> { it.message?.let { // Show message to user } } } } } private fun onFilterPersons( name: String?, status: String?, species: String?, type: String?, gender: String? ) { personRepository.getPersons(name, status, species, type, gender).observe(this) { when(it.status) { ResourceStatus.SUCCESS -> { // Do something with data } ResourceStatus.LOADING -> { // Show loading to user } ResourceStatus.ERROR -> { it.message?.let { // Show message to user } } } } } private fun setResponseText(text: String) { Coroutines.main { responseText?.text = text } } }
kotlin
24
0.514542
88
30.186441
118
starcoderdata
package com.tongweather.android.logic.model /** 封装realtime(当前时间)和daily(未来几天) **/ data class Weather(val realtime: RealtimeResponse.Realtime, val daily: DailyResponse.Daily)
kotlin
5
0.803468
91
56.666667
3
starcoderdata
package com.github.solairerove.jazz.robots.domain.model.action /** * Proles actions enum. */ enum class ProlesAction(private val message: String) : Action { EAT("eat"), DRINK("drink"), WORK("work"), SLEEP("sleep"); override fun possibleValues(): Array<ProlesAction> = values() override fun getMessage() = message }
kotlin
8
0.663793
65
17.315789
19
starcoderdata
package io.golos.golos.repository.model import io.golos.golos.repository.persistence.model.GolosUserAccountInfo import io.golos.golos.utils.GolosError /** * Created by yuri on 09.11.17. */ data class UserAuthResponse(val isKeyValid: Boolean, val postingAuth: Pair<String, String?>? = null, val activeAuth: Pair<String, String?>? = null, val error: GolosError? = null, val accountInfo: GolosUserAccountInfo)
kotlin
10
0.610687
75
36.428571
14
starcoderdata
plugins { java `maven-publish` } group = "com.oskarmc" version = "1.0.0-SNAPSHOT" publishing { publications { create<MavenPublication>("maven") { groupId = project.group as String? artifactId = project.name version = project.version as String? from(components["java"]) } } repositories { maven { val releasesRepoUrl = uri("https://repository.oskarsmc.com/releases") val snapshotsRepoUrl = uri("https://repository.oskarsmc.com/snapshots") url = if (version.toString().endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl credentials { username = System.getenv("MAVEN_USERNAME") password = <PASSWORD>("<PASSWORD>") } } } } java { withJavadocJar() withSourcesJar() } repositories { mavenCentral() } dependencies { testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.1") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.8.1") testRuntimeOnly("net.kyori:adventure-text-serializer-gson:4.9.3") implementation("net.kyori:adventure-api:4.9.3") implementation("net.kyori:adventure-text-serializer-plain:4.9.3") } tasks.getByName<Test>("test") { useJUnitPlatform() }
kotlin
26
0.620455
100
24.403846
52
starcoderdata
package com.jonnycaley.cryptomanager.ui.transactions.crypto import android.content.Context import android.content.Intent import com.jonnycaley.cryptomanager.data.model.DataBase.NotTransaction import com.jonnycaley.cryptomanager.data.model.DataBase.Transaction import com.jonnycaley.cryptomanager.utils.interfaces.ActivityArgs data class CryptoTransactionArgs(val transaction: Transaction? , val notTransactions: NotTransaction?, val backpressToPortfolio : Boolean) : ActivityArgs { override fun intent(activity: Context): Intent = Intent(activity, CryptoTransactionActivity::class.java).apply { putExtra(TRANSACTION_KEY, transaction) putExtra(NOT_TRANSACTION_KEY, notTransactions) putExtra(BACKPRESS_KEY, backpressToPortfolio) } companion object { fun deserializeFrom(intent: Intent): CryptoTransactionArgs { return CryptoTransactionArgs( transaction = intent.getSerializableExtra(TRANSACTION_KEY) as Transaction?, notTransactions = intent.getSerializableExtra(NOT_TRANSACTION_KEY) as NotTransaction?, backpressToPortfolio = intent.getBooleanExtra(BACKPRESS_KEY, false) ) } } } private const val TRANSACTION_KEY = "transaction_key" private const val NOT_TRANSACTION_KEY = "not_transaction_key" private const val BACKPRESS_KEY = "backpress_key"
kotlin
18
0.75
155
45.3
30
starcoderdata
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.sqldelight import co.touchlab.stately.collections.SharedSet import co.touchlab.stately.concurrency.QuickLock import co.touchlab.stately.concurrency.withLock import com.squareup.sqldelight.db.SqlDatabase import com.squareup.sqldelight.db.SqlPreparedStatement import com.squareup.sqldelight.db.SqlPreparedStatement.Type.SELECT import com.squareup.sqldelight.db.SqlCursor import com.squareup.sqldelight.db.use import com.squareup.sqldelight.internal.QueryList fun <RowType : Any> Query( queries: QueryList, database: SqlDatabase, query: String, mapper: (SqlCursor) -> RowType ): Query<RowType> { return SimpleQuery(queries, database, query, mapper) } private class SimpleQuery<out RowType : Any>( queries: QueryList, private val database: SqlDatabase, private val query: String, mapper: (SqlCursor) -> RowType ) : Query<RowType>(queries, mapper) { override fun createStatement(): SqlPreparedStatement { return database.getConnection().prepareStatement(query, SELECT, 0) } } /** * A listenable, typed query generated by SQLDelight. * * @param RowType the type that this query can map it's result set to. */ abstract class Query<out RowType : Any>( private val queries: QueryList, private val mapper: (SqlCursor) -> RowType ) { private val listenerLock = QuickLock() private val listeners = SharedSet<Listener>() private val statement by lazy(::createStatement) protected abstract fun createStatement(): SqlPreparedStatement /** * Notify listeners that their current result set is staled. * * Called internally by SQLDelight when it detects a possible staling of the result set. Emits * some false positives but never misses a true positive. */ fun notifyDataChanged() { listenerLock.withLock { listeners.forEach(Listener::queryResultsChanged) } } /** * Register a listener to be notified of future changes in the result set. */ fun addListener(listener: Listener) { listenerLock.withLock { if (listeners.isEmpty()) queries.addQuery(this) listeners.add(listener) } } fun removeListener(listener: Listener) { listenerLock.withLock { listeners.remove(listener) if (listeners.isEmpty()) queries.removeQuery(this) } } /** * Execute [statement] as a query. */ fun execute() = statement.executeQuery() /** * Execute [statement] and return the result set as a list of [RowType]. */ fun executeAsList(): List<RowType> { val result = mutableListOf<RowType>() execute().use { while (it.next()) result.add(mapper(it)) } return result } /** * Execute [statement] and return the only row of the result set as a non null [RowType]. * * @throws NullPointerException if when executed this query has no rows in its result set. * @throws IllegalStateException if when executed this query has multiple rows in its result set. */ fun executeAsOne(): RowType { return executeAsOneOrNull() ?: throw NullPointerException("ResultSet returned null for $statement") } /** * Execute [statement] and return the first row of the result set as a non null [RowType] or null * if the result set has no rows. * * @throws IllegalStateException if when executed this query has multiple rows in its result set. */ fun executeAsOneOrNull(): RowType? { execute().use { if (!it.next()) return null val item = mapper(it) if (it.next()) { throw IllegalStateException("ResultSet returned more than 1 row for $statement") } return item } } interface Listener { fun queryResultsChanged() } }
kotlin
21
0.711002
99
29.669065
139
starcoderdata
<filename>app/src/main/java/com/project/smartlog/ui/EditLogEntryFragment.kt<gh_stars>0 package com.project.smartlog.ui import android.app.Activity import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import com.project.smartlog.repository.entity.LogEntry import com.project.smartlog.viewmodel.MainActivityViewModel import io.reactivex.Completable import io.reactivex.CompletableObserver import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.fragment_add_log_entry.* /** * Created by arvin-2009 on Feb 2019. */ class EditLogEntryFragment : AddLogEntryFragment() { var logEntry: LogEntry? = null var year = 0 var month = 0 var day = 0 var hour = 0 var minute = 0 var viewModel : MainActivityViewModel ? = null var pos = -1 override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val logId = arguments?.getLong("logId") pos = arguments?.getInt("pos")!! viewModel = ViewModelProviders.of(requireActivity())[MainActivityViewModel::class.java] toolbar_title.text = "Edit Log" var createdTime = 0L viewModel!!.onGetLogDetails().observe(this, Observer { logEntry = it title_editText.setText(it!!.title) description_editText.setText(it.description) logbook_title.text = "Log Book : ".plus(logEntry!!.logBookTitle) createdTime = it.createdTime val timeTemp = it.dateTime.split(" ") dateButton.text = timeTemp[0] timeButton.text = timeTemp[1] viewModel!!.getDateTime(it.createdTime).observe(this, Observer { year = it!![0].toInt() month = it[1].toInt() day = it[2].toInt() hour = it[3].toInt() minute = it[4].toInt() }) }) viewModel!!.getLogDetails(logId!!) toolbar.setNavigationOnClickListener { activity!!.onBackPressed() } dateButton.setOnClickListener { val datePicker = DatePickerFragment() datePicker.setTargetFragment(this, 1001) val bundle = Bundle() bundle.putString("date", dateButton.getText().toString()) datePicker.arguments = bundle datePicker.show(fragmentManager, "date") } timeButton.setOnClickListener { val fromTimePicker = TimePickerFragment() fromTimePicker.setTargetFragment(this, 1002) val bundle = Bundle() val list = timeButton.text.split(":") bundle.putInt("hour", list[0].toInt()) bundle.putInt("minute", list[1].toInt()) fromTimePicker.arguments = bundle fromTimePicker.show(fragmentManager, "time") } submit_button.setOnClickListener { val title = title_editText.text.toString() val desc = description_editText.text.toString() if (title_editText.length() > 0) { progress_bar.visibility = View.VISIBLE title_textLayout.error = "" logEntry!!.title = title logEntry!!.description = desc viewModel!!.getDate(year, month, day, hour, minute).observe(this, Observer { logEntry!!.createdTime = it as Long Completable.fromAction { viewModel!!.updateLogDetails(logEntry!!) }.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(object : CompletableObserver { override fun onComplete() { progress_bar.visibility = View.GONE Toast.makeText(context, "Updated successfully", Toast.LENGTH_SHORT).show() val intent = Intent() intent.putExtra("isUpdated", true) intent.putExtra("pos", pos) intent.putExtra("logEntry", logEntry) targetFragment!!.onActivityResult(1111, Activity.RESULT_OK, intent) activity!!.onBackPressed() } override fun onSubscribe(d: Disposable) { } override fun onError(e: Throwable) { Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show() } }) }) } else { title_textLayout.error = "Please enter title" } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { when (requestCode) { 1001 -> { year = data!!.getIntExtra("year", 2000) month = data.getIntExtra("month", 2000) day = data.getIntExtra("day", 2000) dateButton.text = year.toString().plus("-").plus(month + 1 ).plus("-").plus(day) } 1002 -> { hour = data!!.getIntExtra("hour", 1) minute = data.getIntExtra("minute", 0) timeButton.text = hour.toString().plus(":").plus(minute).plus(":").plus("0") } } } } }
kotlin
40
0.552869
106
34.379518
166
starcoderdata
package com.redissi.trakt.internal import com.redissi.trakt.enums.ReleaseType import com.squareup.moshi.FromJson import com.squareup.moshi.ToJson internal class ReleaseTypeAdapter { @ToJson fun toJson(releaseType: ReleaseType): String { return releaseType.toString() } @FromJson fun fromJson(releaseType: String): ReleaseType? { return ReleaseType.fromValue(releaseType) } }
kotlin
11
0.735084
53
21.105263
19
starcoderdata
<filename>plugins/stats-collector/src/com/intellij/completion/sorting/MLSorter.kt // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.completion.sorting import com.intellij.codeInsight.completion.CompletionFinalSorter import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementDecorator import com.intellij.codeInsight.lookup.LookupElementPresentation import com.intellij.codeInsight.lookup.LookupManager import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.completion.settings.CompletionStatsCollectorSettings import com.intellij.lang.Language import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.Pair import com.intellij.openapi.util.registry.Registry import com.intellij.psi.util.PsiUtilCore import com.intellij.stats.completion.CompletionUtil import com.intellij.stats.completion.RelevanceUtil import com.intellij.stats.completion.prefixLength import com.intellij.stats.experiment.EmulatedExperiment import com.intellij.stats.experiment.WebServiceStatus import com.intellij.stats.personalization.UserFactorsManager import com.jetbrains.completion.feature.impl.FeatureUtils import java.util.* @Suppress("DEPRECATION") class MLSorterFactory : CompletionFinalSorter.Factory { override fun newSorter() = MLSorter() } class MLSorter : CompletionFinalSorter() { private val webServiceStatus = WebServiceStatus.getInstance() private val cachedScore: MutableMap<LookupElement, ItemRankInfo> = IdentityHashMap() override fun getRelevanceObjects(items: MutableIterable<LookupElement>): Map<LookupElement, List<Pair<String, Any>>> { if (cachedScore.isEmpty()) { return items.associate { it to listOf(Pair.create(FeatureUtils.ML_RANK, FeatureUtils.NONE as Any)) } } if (hasUnknownFeatures(items)) { return items.associate { it to listOf(Pair.create(FeatureUtils.ML_RANK, FeatureUtils.UNDEFINED as Any)) } } if (!isCacheValid(items)) { return items.associate { it to listOf(Pair.create(FeatureUtils.ML_RANK, FeatureUtils.INVALID_CACHE as Any)) } } return items.associate { val result = mutableListOf<Pair<String, Any>>() val cached = cachedScore[it] if (cached != null) { result.add(Pair.create(FeatureUtils.ML_RANK, cached.mlRank)) result.add(Pair.create(FeatureUtils.BEFORE_ORDER, cached.positionBefore)) } it to result } } private fun isCacheValid(items: Iterable<LookupElement>): Boolean { return items.map { cachedScore[it]?.prefixLength }.toSet().size == 1 } private fun hasUnknownFeatures(items: Iterable<LookupElement>) = items.any { val score = cachedScore[it] score?.mlRank == null } override fun sort(items: MutableIterable<LookupElement>, parameters: CompletionParameters): Iterable<LookupElement> { val languageRanker = RankingSupport.getRanker(parameters.language()) if (languageRanker == null || !shouldSortByMlRank()) return items val lookup = LookupManager.getActiveLookup(parameters.editor) as? LookupImpl ?: return items val startTime = System.currentTimeMillis() val sorted = sortByMLRanking(languageRanker, parameters, items, lookup) ?: return items val timeSpent = System.currentTimeMillis() - startTime if (ApplicationManager.getApplication().isDispatchThread) { val totalTime = timeSpent + (lookup.getUserData(CompletionUtil.ML_SORTING_CONTRIBUTION_KEY) ?: 0) lookup.putUserData(CompletionUtil.ML_SORTING_CONTRIBUTION_KEY, totalTime) } return sorted } private fun shouldSortByMlRank(): Boolean { val application = ApplicationManager.getApplication() if (application.isUnitTestMode) return false val settings = CompletionStatsCollectorSettings.getInstance() if (application.isEAP && webServiceStatus.isExperimentOnCurrentIDE() && settings.isCompletionLogsSendAllowed) { return EmulatedExperiment.shouldRank(webServiceStatus.experimentVersion()) } return settings.isRankingEnabled } /** * Null means we encountered unknown features and are unable to sort them */ private fun sortByMLRanking(ranker: RankingSupport.LanguageRanker, parameters: CompletionParameters, items: MutableIterable<LookupElement>, lookup: LookupImpl): Iterable<LookupElement>? { val relevanceObjects = lookup.getRelevanceObjects(items, false) val prefixLength = lookup.prefixLength() val userFactors = lookup.getUserData(UserFactorsManager.USER_FACTORS_KEY) ?: emptyMap() val positionsBefore = mutableMapOf<LookupElement, Int>() return items .mapIndexed { position, lookupElement -> positionsBefore[lookupElement] = position val relevance = buildRelevanceMap(lookupElement, relevanceObjects[lookupElement], lookup.prefixLength(), position, parameters) ?: return null val rank: Double = calculateElementRank(ranker, lookupElement, position, relevance, userFactors, prefixLength) ?: return null lookupElement to rank } .sortedByDescending { it.second } .map { it.first } .addDiagnosticsIfNeeded(positionsBefore) } private fun buildRelevanceMap(lookupElement: LookupElement, relevanceObjects: List<Pair<String, Any?>>?, prefixLength: Int, position: Int, parameters: CompletionParameters): Map<String, Any>? { if (relevanceObjects == null) return null val relevanceMap = RelevanceUtil.asRelevanceMap(relevanceObjects) relevanceMap["position"] = position relevanceMap["query_length"] = prefixLength relevanceMap["result_length"] = lookupElement.lookupString.length relevanceMap["auto_popup"] = parameters.isAutoPopup relevanceMap["completion_type"] = parameters.completionType.toString() relevanceMap["invocation_count"] = parameters.invocationCount return relevanceMap } private fun Iterable<LookupElement>.addDiagnosticsIfNeeded(positionsBefore: Map<LookupElement, Int>): Iterable<LookupElement> { if (Registry.`is`("completion.stats.show.ml.ranking.diff")) { return this.mapIndexed { position, element -> MyMovedLookupElement(element, positionsBefore.getValue(element), position) } } return this } private fun getCachedRankInfo(element: LookupElement, prefixLength: Int, position: Int): ItemRankInfo? { val cached = cachedScore[element] if (cached != null && prefixLength == cached.prefixLength && cached.positionBefore == position) { return cached } return null } private fun calculateElementRank(ranker: RankingSupport.LanguageRanker, element: LookupElement, position: Int, relevance: Map<String, Any>, userFactors: Map<String, Any?>, prefixLength: Int): Double? { val cachedWeight = getCachedRankInfo(element, prefixLength, position) if (cachedWeight != null) { return cachedWeight.mlRank } val unknownFactors = ranker.unknownFeatures(relevance.keys) val mlRank: Double? = if (unknownFactors.isEmpty()) ranker.rank(relevance, userFactors) else null val info = ItemRankInfo(position, mlRank, prefixLength) cachedScore[element] = info return info.mlRank } } private class MyMovedLookupElement(delegate: LookupElement, private val before: Int, private val after: Int) : LookupElementDecorator<LookupElement>(delegate) { override fun renderElement(presentation: LookupElementPresentation) { super.renderElement(presentation) val diff = after - before val diffText = if (diff < 0) diff.toString() else "+$diff" val oldText = presentation.itemText presentation.itemText = "$oldText (${diffText})" } } private data class ItemRankInfo(val positionBefore: Int, val mlRank: Double?, val prefixLength: Int) fun CompletionParameters.language(): Language? { val offset = editor.caretModel.offset return PsiUtilCore.getLanguageAtOffset(originalFile, offset) }
kotlin
27
0.716702
140
42.22335
197
starcoderdata
<filename>presentation/src/main/java/com/noxel/colorstudio/model/CategoryModel.kt package com.noxel.colorstudio.model import com.squareup.moshi.Json data class CategoryModel ( @Json(name="id") var id: Int? = null, @Json(name="image") var image: String? = null, @Json(name="title") var title: String? = null )
kotlin
10
0.693452
81
27.083333
12
starcoderdata
package com.imtae.githubcontributions.repository import com.imtae.githubcontributions.domain.Contribution import com.imtae.githubcontributions.domain.Contributions import com.imtae.githubcontributions.domain.Range import com.imtae.githubcontributions.domain.Year import com.imtae.githubcontributions.key.Type import org.jsoup.Jsoup import org.springframework.stereotype.Component import java.lang.Exception import java.text.SimpleDateFormat import java.util.* @Component class ContributionParsingRepositoryImpl : ContributionParsingRepository { private val _yearList = arrayListOf<Year>() private val _contributionsList = arrayListOf<Contributions>() override fun getContributions(user: String): Contribution { val yearList = getContributionYears(user) _yearList.clear() _contributionsList.clear() return getContributionData(yearList) } override fun getContribution(user: String, date: String): Any = getContributionData(user, date) override fun getTodayContribution(user: String): Any = getContributionData(user) private fun getContributionYears(user: String): ArrayList<String> { val doc = Jsoup.connect("https://github.com/$user") .userAgent("Mozilla") .timeout(10000) .ignoreHttpErrors(true) .get() val years = doc.select(".js-year-link") val yearLinkList = arrayListOf<String>() years.forEach{ yearLinkList.add(it.attr("href").trim()) } return yearLinkList } private fun getContributionData(yearLinkList : ArrayList<String>): Contribution { for (yearLink in yearLinkList) { val doc = Jsoup.connect("https://github.com$yearLink").ignoreHttpErrors(true).get() val contributionText = doc.select(".js-yearly-contributions h2").text() .replace("[ ]".toRegex(), "") .split("[a-z|A-Z]".toRegex()) println(contributionText) println(doc.select(".js-yearly-contributions h2").text()) val year = contributionText[contributionText.lastIndex].ifBlank { SimpleDateFormat("yyyy").format(Calendar.getInstance().time) } // 2020, 2019 ... val total = Integer.parseInt(contributionText[0].replace(",", "")) // 550, 140 ... val contributions = doc.select("rect.ContributionCalendar-day") val contributionList = arrayListOf<Contributions>() for (contribution in contributions.indices) { val fill = checkFillColor(contributions[contribution].attr("data-level").toString()) val dataCount = contributions[contribution].attr("data-count") val dataDate = contributions[contribution].attr("data-date") if (!dataCount.isNullOrEmpty()) contributionList.add(Contributions(dataDate, Integer.parseInt(dataCount), fill)) } _yearList.add(Year(year, total, Range(contributionList[0].date!!, contributionList[contributionList.size -1].date!!))) for (contribution in contributionList) _contributionsList.add(contribution) } return Contribution(_yearList, _contributionsList) } private val checkDateValid = { date: String, type: Type -> when { date.matches("^\\d{4}\\-(0[1-9]|1[012])\\-(0[1-9]|[12][0-9]|3[01])\$".toRegex()) && type == Type.DATE -> true date.matches("^\\d{4}".toRegex()) && type == Type.YEAR -> true else -> false } } private fun getContributionData(user: String, date: String? = null): Any { val currentYear = SimpleDateFormat("yyyy").format(Calendar.getInstance().time) val todayDate = SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().time) println(date) val yearPath: String = try { date?.slice(0..3).toString() } catch (e: Exception) { currentYear } val connection = when { date == null || checkDateValid(date, Type.DATE) -> Jsoup.connect("https://github.com/$user?tab=overview&from=$yearPath-01-01&to=$yearPath-12-31") checkDateValid(date, Type.YEAR) -> Jsoup.connect("https://github.com/$user?tab=overview&from=$date-01-01&to=$date-12-31") else -> return Contributions() } val doc = connection .userAgent("Mozilla") .timeout(10000) .ignoreHttpErrors(true) .get() val contributions = doc.select("rect.ContributionCalendar-day") val contributionList = arrayListOf<Contributions>() for (contribution in contributions.indices) { val fill = checkFillColor(contributions[contribution].attr("data-level")) val dataCount = contributions[contribution].attr("data-count") val dataDate = contributions[contribution].attr("data-date") if (contributions[contribution].attr("data-date") == date ?: todayDate) { return Contributions(dataDate, Integer.parseInt(dataCount), fill) } else if (!dataCount.isNullOrEmpty()) contributionList.add(Contributions(dataDate, Integer.parseInt(dataCount), fill)) } return if (contributionList.size > 0) contributionList else Contributions() } private fun checkFillColor(fill: String?): String? { return when (fill) { "var(--color-calendar-graph-day-bg)", "0" -> "#e6e8ed" "var(--color-calendar-graph-day-L1-bg)", "1" -> "#8ce797" "var(--color-calendar-graph-day-L2-bg)", "2" -> "#38bc50" "var(--color-calendar-graph-day-L3-bg)", "3" -> "#2c933d" "var(--color-calendar-graph-day-L4-bg)", "4" -> "#1d5d2b" "var(--color-calendar-halloween-graph-day-l1-bg)" -> "#ffee4a" "var(--color-calendar-halloween-graph-day-l2-bg)" -> "#ffc501" "var(--color-calendar-halloween-graph-day-l3-bg)" -> "#fe9600" "var(--color-calendar-halloween-graph-day-l4-bg)" -> "#03001c" else -> fill } } // 추가 예정 private fun changeFillColor(color: String?): String? { return null } }
kotlin
28
0.611477
165
37.896341
164
starcoderdata
<reponame>ligee/kotlin-scripting-proto<gh_stars>0 package org.jetbrains.kotlin.script.examples.jvm.simple.test import org.jetbrains.kotlin.script.examples.jvm.simple.main import org.junit.Test class SimpleTest { @Test fun test1() { main() } @Test fun test2() { main("hello.kts") } }
kotlin
10
0.665644
60
17.166667
18
starcoderdata
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.tooling.serialization import com.intellij.openapi.externalSystem.model.project.dependencies.* import io.github.classgraph.ClassGraph import io.github.classgraph.ClassInfo import org.assertj.core.api.Assertions.assertThat import org.gradle.api.artifacts.Dependency import org.gradle.util.GradleVersion import org.jeasy.random.EasyRandom import org.jeasy.random.EasyRandomParameters import org.jeasy.random.FieldPredicates.* import org.jeasy.random.ObjectCreationException import org.jeasy.random.api.ObjectFactory import org.jeasy.random.api.Randomizer import org.jeasy.random.api.RandomizerContext import org.jeasy.random.util.CollectionUtils import org.jeasy.random.util.ReflectionUtils import org.jetbrains.plugins.gradle.model.DefaultExternalProject import org.jetbrains.plugins.gradle.model.DefaultExternalProjectDependency import org.jetbrains.plugins.gradle.model.DefaultGradleExtensions import org.jetbrains.plugins.gradle.model.ExternalTask import org.jetbrains.plugins.gradle.model.tests.DefaultExternalTestsModel import org.jetbrains.plugins.gradle.tooling.internal.AnnotationProcessingModelImpl import org.jetbrains.plugins.gradle.tooling.internal.BuildScriptClasspathModelImpl import org.jetbrains.plugins.gradle.tooling.internal.RepositoriesModelImpl import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.* import org.jetbrains.plugins.gradle.tooling.util.GradleVersionComparator import org.junit.Before import org.junit.Test import org.objenesis.Objenesis import org.objenesis.ObjenesisStd import java.io.File import java.io.IOException import java.util.* import java.util.function.Consumer import kotlin.random.Random /** * @author Vladislav.Soroka */ class ToolingSerializerTest { private lateinit var myRandom: EasyRandom private lateinit var myRandomParameters: EasyRandomParameters @Before fun setUp() { myRandomParameters = EasyRandomParameters() .seed(Random.nextLong()) .collectionSizeRange(Random.nextInt(0, 2), 3) .objectPoolSize(5) .objectFactory(MyObjectFactory()) .overrideDefaultInitialization(true) .scanClasspathForConcreteTypes(true) myRandom = EasyRandom(myRandomParameters) myRandomParameters .randomize(File::class.java) { File(myRandom.nextObject(String::class.java)) } } @Test @Throws(Exception::class) fun `external project serialization test`() { myRandomParameters .randomize( named("externalSystemId").and(ofType(String::class.java)).and(inClass(DefaultExternalProject::class.java)), Randomizer { "GRADLE" } ) .randomize( named("configurationName").and(ofType(String::class.java)).and(inClass(DefaultExternalProjectDependency::class.java)), Randomizer { Dependency.DEFAULT_CONFIGURATION } ) doTest(DefaultExternalProject::class.java, Consumer { fixMapsKeys(it) }) } @Test @Throws(Exception::class) fun `build script classpath serialization test`() { doTest(BuildScriptClasspathModelImpl::class.java) } @Test @Throws(Exception::class) fun `external test model serialization test`() { doTest(DefaultExternalTestsModel::class.java) } @Test @Throws(Exception::class) fun `gradle extensions serialization test`() { // tasks are not serialized, it's assumed to be populated from ExternalProject model at BaseGradleProjectResolverExtension.populateModuleExtraModels myRandomParameters.excludeField(named("tasks").and(ofType(ArrayList::class.java)).and(inClass(DefaultGradleExtensions::class.java))) doTest(DefaultGradleExtensions::class.java) } @Test @Throws(Exception::class) fun `repositories model serialization test`() { doTest(RepositoriesModelImpl::class.java) } @Test @Throws(Exception::class) fun `IDEA project serialization test`() { // do not assert GradleVersion.buildTime and GradleVersion.commitId properties of GradleVersionComparator.myVersion field val gradleVersion = GradleVersion.version(GradleVersion.current().version) myRandomParameters .randomize( ofType(GradleVersionComparator::class.java).and(inClass(InternalIdeaContentRoot::class.java)), Randomizer { GradleVersionComparator(gradleVersion) } ) .randomize( ofType(InternalProjectIdentifier::class.java), Randomizer { InternalProjectIdentifier(InternalBuildIdentifier(File("")), "") } ) .excludeField(named("parent").and(ofType(InternalIdeaProject::class.java)).and(inClass(InternalIdeaModule::class.java))) .excludeField(named("parent").and(ofType(InternalGradleProject::class.java)).and(inClass(InternalGradleProject::class.java))) .excludeField(named("gradleProject").and(inClass(InternalGradleTask::class.java))) val serializer = ToolingSerializer() doTest(InternalIdeaProject::class.java, Consumer { ideaProject -> val buildIdentifier = InternalBuildIdentifier(myRandom.nextObject(File::class.java)) ideaProject.children.forEach { ideaModule -> ideaModule.parent = ideaProject ideaModule.dependencies .filter { it?.scope?.scope == null } .forEach { it.scope = InternalIdeaDependencyScope.getInstance("Compile") } val seenProjects = Collections.newSetFromMap(IdentityHashMap<InternalGradleProject, Boolean>()) fixGradleProjects(null, ideaModule.gradleProject, seenProjects, buildIdentifier) } }, serializer) } @Test @Throws(Exception::class) fun `annotation processing model serialization test`() { doTest(AnnotationProcessingModelImpl::class.java) } @Test @Throws(Exception::class) fun `project dependencies serialization test`() { doTest(ProjectDependenciesImpl::class.java) val projectDependencies = ProjectDependenciesImpl() val mainCompileDependencies = DependencyScopeNode(1, "compileClasspath", "project : (compileClasspath)", "") val mainRuntimeDependencies = DependencyScopeNode(1, "runtimeClasspath", "project : (runtimeClasspath)", "") val mainDependency = ArtifactDependencyNodeImpl(2, "dep", "dep", "1.0") val mainNestedDependency = ArtifactDependencyNodeImpl(3, "nestedDep", "nestedDep", "1.1") mainDependency.dependencies.add(mainNestedDependency) mainRuntimeDependencies.dependencies.add(mainDependency) mainRuntimeDependencies.dependencies.add(ReferenceNode(3)) val mainComponentDependencies = ComponentDependenciesImpl("main", mainCompileDependencies, mainRuntimeDependencies) projectDependencies.add(mainComponentDependencies) val testCompileDependencies = DependencyScopeNode(1, "testCompileClasspath", "project : (testCompileClasspath)", "") val testRuntimeDependencies = DependencyScopeNode(1, "testRuntimeClasspath", "project : (testRuntimeClasspath)", "") val testDependency = ArtifactDependencyNodeImpl(2, "dep", "dep", "1.0") val testNestedDependency = ArtifactDependencyNodeImpl(3, "nestedDep", "nestedDep", "1.0") testDependency.dependencies.add(testNestedDependency) testRuntimeDependencies.dependencies.add(testDependency) testRuntimeDependencies.dependencies.add(ReferenceNode(3)) val testComponentDependencies = ComponentDependenciesImpl("test", testCompileDependencies, testRuntimeDependencies) projectDependencies.add(testComponentDependencies) val bytes = ToolingSerializer().write(projectDependencies) val deserializedObject = ToolingSerializer().read(bytes, ProjectDependenciesImpl::class.java) val deserializedMainNestedDependency = deserializedObject!!.componentsDependencies[0].runtimeDependenciesGraph.dependencies[0].dependencies[0] assertThat(deserializedMainNestedDependency).isEqualToComparingFieldByField(mainNestedDependency) val deserializedTestNestedDependency = deserializedObject.componentsDependencies[1].runtimeDependenciesGraph.dependencies[0].dependencies[0] assertThat(deserializedTestNestedDependency).isEqualToComparingFieldByField(testNestedDependency) } @Throws(IOException::class) private fun <T> doTest(modelClazz: Class<T>) { doTest(modelClazz, null) } @Throws(IOException::class) private fun <T> doTest(modelClazz: Class<T>, generatedObjectPatcher: Consumer<T>?) { doTest(modelClazz, generatedObjectPatcher, ToolingSerializer()) } @Throws(IOException::class) private fun <T> doTest(modelClazz: Class<T>, generatedObjectPatcher: Consumer<T>?, serializer: ToolingSerializer) { val generatedObject = myRandom.nextObject(modelClazz) generatedObjectPatcher?.accept(generatedObject) val bytes = serializer.write(generatedObject as Any) val deserializedObject = serializer.read(bytes, modelClazz) assertThat(deserializedObject).usingRecursiveComparison().isEqualTo(generatedObject) } companion object { private fun fixGradleProjects(parentGradleProject: InternalGradleProject?, gradleProject: InternalGradleProject, seenProjects: MutableSet<InternalGradleProject>, buildIdentifier: InternalBuildIdentifier) { if (!seenProjects.add(gradleProject)) return gradleProject.projectIdentifier = InternalProjectIdentifier(buildIdentifier, ":" + gradleProject.name) gradleProject.tasks.forEach { it.setGradleProject(gradleProject) if (it.path == null) { it.path = "" } } // workaround StackOverflowError for the test assertion if (parentGradleProject == null) { gradleProject.setChildren(gradleProject.children.take(2)) gradleProject.children.forEach { fixGradleProjects(gradleProject, it, seenProjects, buildIdentifier) } } else { gradleProject.parent = parentGradleProject gradleProject.setChildren(emptyList()) } } private fun fixChildProjectsMapsKeys(externalProject: DefaultExternalProject, processed: MutableSet<DefaultExternalProject>) { if (!processed.add(externalProject)) return val sourceSets = externalProject.sourceSets for (setsKey in sourceSets.keys.toList()) { val sourceSet = sourceSets.remove(setsKey) sourceSets[sourceSet!!.name] = sourceSet } @Suppress("UNCHECKED_CAST") val tasks = externalProject.tasks as HashMap<String, ExternalTask> for (key in tasks.keys.toList()) { val task = tasks.remove(key) as ExternalTask tasks[task.name] = task } @Suppress("UNCHECKED_CAST") val projectMap = externalProject.childProjects as TreeMap<String, DefaultExternalProject> for (key in projectMap.keys.toList()) { val childProject = projectMap.remove(key) projectMap[childProject!!.name] = childProject fixChildProjectsMapsKeys(childProject, processed) } } private fun fixMapsKeys(externalProject: DefaultExternalProject) { fixChildProjectsMapsKeys(externalProject, Collections.newSetFromMap(IdentityHashMap())) } private class MyObjectFactory : ObjectFactory { private val objenesis: Objenesis = ObjenesisStd() override fun <T> createInstance(type: Class<T>, context: RandomizerContext?): T { return if (context!!.parameters.isScanClasspathForConcreteTypes && ReflectionUtils.isAbstract(type)) { val randomConcreteSubType = CollectionUtils.randomElementOf(searchForPublicConcreteSubTypesOf(type)) if (randomConcreteSubType == null) { throw InstantiationError("Unable to find a matching concrete subtype of type: $type in the classpath") } else { createNewInstance(randomConcreteSubType) as T } } else { try { createNewInstance(type) } catch (e: Error) { throw ObjectCreationException("Unable to create an instance of type: $type", e) } } } private fun <T> searchForPublicConcreteSubTypesOf(type: Class<T>): List<Class<*>>? { ClassGraph() .enableClassInfo() .ignoreParentClassLoaders() .acceptPackages( "org.jetbrains.plugins.gradle.*", "com.intellij.openapi.externalSystem.model.*" ) .scan() .use { val subTypes = if (type.isInterface) it.getClassesImplementing(type.name) else it.getSubclasses(type.name) return subTypes.filter { subType: ClassInfo -> subType.isPublic && !subType.isAbstract }.loadClasses(true) } } private fun <T> createNewInstance(type: Class<T>): T { return try { val noArgConstructor = type.getDeclaredConstructor() if (!noArgConstructor.isAccessible) { noArgConstructor.isAccessible = true } noArgConstructor.newInstance() } catch (exception: java.lang.Exception) { objenesis.newInstance(type) } } } } }
kotlin
33
0.730091
152
42.009804
306
starcoderdata
<gh_stars>0 /* * <!-- * ~ Copyright (c) 2017. ThanksMister LLC * ~ * ~ Licensed under the Apache License, Version 2.0 (the "License"); * ~ you may not use this file except in compliance with the License. * ~ You may obtain a copy of the License at * ~ * ~ http://www.apache.org/licenses/LICENSE-2.0 * ~ * ~ Unless required by applicable law or agreed to in writing, software distributed * ~ under the License is distributed on an "AS IS" BASIS, * ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * ~ See the License for the specific language governing permissions and * ~ limitations under the License. * --> */ package com.thanksmister.iot.mqtt.alarmpanel.utils import android.support.annotation.StringDef import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy import java.util.ArrayList /** * Just a utility class to work with the specific settings of the Home Assistant * MQTT Manual Alarm Control Panel https://home-assistant.io/components/alarm_control_panel.manual_mqtt/. */ class AlarmUtils { annotation class AlarmStates annotation class AlarmCommands companion object { const val MODE_ARM_HOME = "mode_arm_home" const val MODE_ARM_HOME_PENDING = "mode_arm_home_pending" const val MODE_ARM_PENDING = "mode_arm_pending" const val MODE_ARM_AWAY = "mode_arm_away" const val MODE_ARM_AWAY_PENDING = "mode_arm_away_pending" const val MODE_DISARM = "mode_disarm" const val MODE_TRIGGERED = "mode_triggered" const val MODE_TRIGGERED_PENDING = "mode_triggered_pending" const val MODE_AWAY_TRIGGERED_PENDING = "mode_triggered_away_pending" const val MODE_HOME_TRIGGERED_PENDING = "mode_triggered_home_pending" const val PORT = 1883 const val ALARM_TYPE = "ALARM" const val COMMAND_ARM_HOME = "ARM_HOME" const val COMMAND_ARM_AWAY = "ARM_AWAY" const val COMMAND_DISARM = "DISARM" const val ALARM_COMMAND_TOPIC = "home/alarm/set" const val ALARM_STATE_TOPIC = "home/alarm" const val STATE_DISARM = "disarmed" const val STATE_ARM_AWAY = "armed_away" const val STATE_ARM_HOME = "armed_home" const val STATE_PENDING = "pending" const val STATE_TRIGGERED = "triggered" const val STATE_ERROR = "error" const val PENDING_TIME = 60 const val PENDING_HOME_TIME = 60 const val PENDING_AWAY_TIME = 60 const val DELAY_TIME = 30 const val DELAY_HOME_TIME = 30 const val DELAY_AWAY_TIME = 30 const val DISABLE_TIME = 30 private val supportedCommands = ArrayList<String>() private val supportedStates = ArrayList<String>() init { supportedCommands.add(COMMAND_ARM_HOME) supportedCommands.add(COMMAND_ARM_AWAY) supportedCommands.add(COMMAND_DISARM) } init { supportedStates.add(STATE_DISARM) supportedStates.add(STATE_ARM_AWAY) supportedStates.add(STATE_ARM_HOME) supportedStates.add(STATE_PENDING) supportedStates.add(STATE_TRIGGERED) } /** * Topic is of type command topic * @param command * @return */ @AlarmCommands fun hasSupportedCommands(command: String): Boolean { return supportedCommands.contains(command) } /** * Topic is of type state topic * @param state * @return */ @AlarmStates fun hasSupportedStates(state: String): Boolean { return supportedStates.contains(state) } } }
kotlin
13
0.635928
105
32.212389
113
starcoderdata
package cash.z.ecc.android.sdk.ext.android import android.annotation.SuppressLint import android.os.Handler import android.os.Looper import androidx.paging.Config import androidx.paging.DataSource import androidx.paging.PagedList import cash.z.ecc.android.sdk.ext.Twig import cash.z.ecc.android.sdk.ext.twig import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExecutorCoroutineDispatcher import kotlinx.coroutines.MainCoroutineDispatcher import kotlinx.coroutines.flow.Flow import java.util.concurrent.Executor /* Adapted from LivePagedListBuilder */ class FlowPagedListBuilder<Key, Value>( private val dataSourceFactory: DataSource.Factory<Key, Value>, private val config: PagedList.Config, private var initialLoadKey: Key? = null, private var boundaryCallback: PagedList.BoundaryCallback<*>? = null, private val notifyContext: CoroutineDispatcher = Dispatchers.Main, private val fetchContext: CoroutineDispatcher = Dispatchers.IO ) { /** * Creates a FlowPagedListBuilder with required parameters. * * @param dataSourceFactory DataSource factory providing DataSource generations. * @param config Paging configuration. */ constructor(dataSourceFactory: DataSource.Factory<Key, Value>, pageSize: Int) : this( dataSourceFactory, Config(pageSize) ) /** * Constructs the `Flow<PagedList>`. * * No work (such as loading) is done immediately, the creation of the first PagedList is * deferred until the Flow is collected. * * @return The Flow of PagedLists */ @SuppressLint("RestrictedApi") fun build(): Flow<List<Value>> { return object : ComputableFlow<List<Value>>(fetchContext) { private lateinit var dataSource: DataSource<Key, Value> private lateinit var list: PagedList<Value> private val callback = DataSource.InvalidatedCallback { invalidate() } override fun compute(): PagedList<Value> { Twig.sprout("computing") var initializeKey = initialLoadKey if (::list.isInitialized) { twig("list is initialized") initializeKey = list.lastKey as Key } do { if (::dataSource.isInitialized) { dataSource.removeInvalidatedCallback(callback) } dataSource = dataSourceFactory.create().apply { twig("adding an invalidated callback") addInvalidatedCallback(callback) } list = PagedList.Builder(dataSource, config) .setNotifyExecutor(notifyContext.toExecutor()) .setFetchExecutor(fetchContext.toExecutor()) .setBoundaryCallback(boundaryCallback) .setInitialKey(initializeKey) .build() } while (list.isDetached) return list.also { Twig.clip("computing") } } }.flow } private fun CoroutineDispatcher.toExecutor(): Executor { return when (this) { is ExecutorCoroutineDispatcher -> executor is MainCoroutineDispatcher -> MainThreadExecutor() else -> throw IllegalStateException("Unable to create executor based on dispatcher: $this") } } class MainThreadExecutor : Executor { private val handler = Handler(Looper.getMainLooper()) override fun execute(runnable: Runnable) { handler.post(runnable) } } }
kotlin
32
0.631818
103
36.4
100
starcoderdata
package uk.co.jakelee.databindingexperiments.vogella import android.app.Activity import android.os.Bundle import android.widget.Toast import androidx.databinding.DataBindingUtil import uk.co.jakelee.databindingexperiments.R import uk.co.jakelee.databindingexperiments.databinding.VogellaTempActivityBinding class TemperatureActivity : Activity(), TemperatureActivityContract.View { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding: VogellaTempActivityBinding = DataBindingUtil.setContentView(this, R.layout.vogella_temp_activity) val temperatureActivityPresenter = TemperatureActivityPresenter(this, applicationContext) val temperatureData = TemperatureData("Hamburg", "10", "") binding.temp = temperatureData binding.presenter = temperatureActivityPresenter } override fun showData(temperatureData: TemperatureData) { val celsius = temperatureData.getCelsius() Toast.makeText(this, celsius, Toast.LENGTH_SHORT).show() } }
kotlin
14
0.779037
118
38.259259
27
starcoderdata
<reponame>learn-notes/AndroidProgramming package com.joh.myapplication import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class QuizActivity : AppCompatActivity() { private val TAG = "QuizActivity" private val KEY_INDEX = "index" private lateinit var mQuestionTextView: TextView private val mQuestionBank = listOf( Question(R.string.question_australia, true), Question(R.string.question_oceans, true), Question(R.string.question_mideast, false), Question(R.string.question_africa, false), Question(R.string.question_americas, true), Question(R.string.question_asia, true) ) private var mCurrentIndex = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_quiz) Log.e(TAG, "onCreate()") val s = this.intent.getStringExtra("TAG") Toast.makeText(this, s, Toast.LENGTH_SHORT).show() if (savedInstanceState != null) { mCurrentIndex = savedInstanceState.getInt(KEY_INDEX,0) } this.mQuestionTextView = findViewById(R.id.question_text_view) mQuestionTextView.setText(mQuestionBank[mCurrentIndex].textResId) // 确认 findViewById<Button>(R.id.true_button).setOnClickListener { checkAnswer(true) } // 否认 findViewById<Button>(R.id.false_button).setOnClickListener { // val toast = Toast.makeText(this, R.string.incorrect_toast, Toast.LENGTH_SHORT) //原始用法 // toast.setGravity(Gravity.TOP, 0, 50) // toast.show() // with作用域用法 // with(toast) { // this.setGravity(Gravity.TOP, 0, 50) // this.show() // } // let作用域用法 // toast.let { // it.setGravity(Gravity.TOP, 0, 50) // it.show() // } checkAnswer(false) } // 下一题 findViewById<Button>(R.id.next_button).setOnClickListener { updateQuestion() } } /** * 更新问题内容 */ private fun updateQuestion() { mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.size mQuestionTextView.setText(mQuestionBank[mCurrentIndex].textResId) } /** * 选择验证 */ private fun checkAnswer(userPressedTrue: Boolean) { val answerIsTrue = mQuestionBank[mCurrentIndex].answerTrue val messageResId = if (userPressedTrue == answerIsTrue) { updateQuestion() R.string.correct_toast } else R.string.incorrect_toast Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt(KEY_INDEX, mCurrentIndex) } override fun onStart() { super.onStart() Log.e(TAG, "onStart()") } override fun onResume() { super.onResume() Log.e(TAG, "onResume()") } override fun onPause() { super.onPause() Log.e(TAG, "onPause()") } override fun onStop() { super.onStop() Log.e(TAG, "onStop()") } override fun onDestroy() { super.onDestroy() Log.e(TAG, "onDestroy()") } }
kotlin
16
0.597721
104
27.536585
123
starcoderdata
<filename>movehub/build.gradle.kts plugins { java } group = "com.github.renegrob" version = "1.0-SNAPSHOT" repositories { mavenCentral() flatDir { dirs("/usr/lib/x86_64-linux-gnu/../lib/java/") } } dependencies { implementation("intel-iot-devkit:tinyb:0.5.1") implementation("com.google.guava:guava:31.0.1-jre") implementation("org.apache.logging.log4j:log4j-core:2.17.1") testImplementation("org.assertj:assertj-core:3.21.0") testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.2") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine") } tasks.getByName<Test>("test") { useJUnitPlatform() }
kotlin
15
0.691958
67
23.444444
27
starcoderdata
package com.meksconway.areyouexpert.ui.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.meksconway.areyouexpert.R import com.meksconway.areyouexpert.data.service.local.entity.NotificationEntity class NotificationAdapter : RecyclerView.Adapter<NotificationAdapter.NotificationViewHolder>() { private val notificationData = arrayListOf<NotificationEntity>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotificationViewHolder { val view: View = LayoutInflater.from(parent.context) .inflate(R.layout.item_notification, parent, false) return NotificationViewHolder(view) } override fun getItemId(position: Int): Long { return notificationData[position].nofiticationId.toLong() } override fun getItemCount() = notificationData.size override fun onBindViewHolder(holder: NotificationViewHolder, position: Int) { holder.bind(notificationData[position]) } fun setItems(list: List<NotificationEntity>) { notificationData.clear() notificationData.addAll(list) notifyDataSetChanged() } class NotificationViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { lateinit var model: NotificationEntity private val notificationTitle = itemView.findViewById<TextView>(R.id.txtNotificationTitle) private val notificationMessage = itemView.findViewById<TextView>(R.id.txtNotificationMessage) fun bind(model: NotificationEntity) { this.model = model notificationTitle?.text = model.notificationTitle notificationMessage?.text = model.notificationMessage } } }
kotlin
15
0.746689
102
37.574468
47
starcoderdata
<gh_stars>0 package no.nav.personbruker.dittnav.brukernotifikasjonbestiller.statusoppdatering import no.nav.brukernotifikasjon.schemas.builders.domain.Eventtype import no.nav.brukernotifikasjon.schemas.builders.util.ValidationUtil.* import no.nav.brukernotifikasjon.schemas.input.StatusoppdateringInput import no.nav.brukernotifikasjon.schemas.input.NokkelInput import no.nav.brukernotifikasjon.schemas.internal.StatusoppdateringIntern import no.nav.brukernotifikasjon.schemas.internal.NokkelIntern import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.common.createULID import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.common.CurrentTimeHelper.nowInEpochMillis import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.common.validation.validatePrefererteKanaler import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.nokkel.NokkelInputTransformer object StatusoppdateringInputTransformer { fun toInternal(nokkelExternal: NokkelInput, statusoppdateringExternal: StatusoppdateringInput): Pair<NokkelIntern, StatusoppdateringIntern> { return NokkelInputTransformer.toNokkelInternal(nokkelExternal) to toStatusoppdateringInternal(statusoppdateringExternal) } private fun toStatusoppdateringInternal(externalStatusoppdatering: StatusoppdateringInput): StatusoppdateringIntern { return StatusoppdateringIntern.newBuilder() .setTidspunkt(externalStatusoppdatering.getTidspunkt()) .setBehandlet(nowInEpochMillis()) .setLink(validateLinkAndConvertToString(validateLinkAndConvertToURL(externalStatusoppdatering.getLink()), "link", MAX_LENGTH_LINK, isLinkRequired(Eventtype.STATUSOPPDATERING))) .setSikkerhetsnivaa(validateSikkerhetsnivaa(externalStatusoppdatering.getSikkerhetsnivaa())) .setStatusGlobal(validateStatusGlobal(externalStatusoppdatering.getStatusGlobal())) .setStatusIntern(externalStatusoppdatering.getStatusIntern()?.let { status -> validateMaxLength(status, "statusIntern", MAX_LENGTH_STATUSINTERN)}) .setSakstema(validateNonNullFieldMaxLength(externalStatusoppdatering.getSakstema(), "sakstema", MAX_LENGTH_SAKSTEMA)) .build() } }
kotlin
32
0.828054
188
65.969697
33
starcoderdata
<filename>BurgerJoint/app/src/main/java/com/zg/burgerjoint/data/model/impls/MockBurgerModelImpl.kt package com.zg.burgerjoint.data.model.impls import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.zg.burgerjoint.data.model.BurgerModel import com.zg.burgerjoint.data.vos.BurgerVO import com.zg.burgerjoint.dummy.getDummyBurgers object MockBurgerModelImpl : BurgerModel { var burgersInOrder: MutableList<BurgerVO> = arrayListOf() var burgersInOrderLiveData = MutableLiveData<List<BurgerVO>>() override fun getAllBurgers(): LiveData<List<BurgerVO>> { val liveData = MutableLiveData<List<BurgerVO>>() liveData.postValue(getDummyBurgers()) return liveData } override fun findBurgerById(burgerId: Int): LiveData<BurgerVO> { val liveData = MutableLiveData<BurgerVO>() liveData.postValue(getDummyBurgers().first { it.burgerId == burgerId }) return liveData } override fun getBurgersInCart(): LiveData<List<BurgerVO>> { burgersInOrderLiveData.postValue(burgersInOrder) return burgersInOrderLiveData } override fun removeItemFromCart(burger: BurgerVO) { burgersInOrder.remove(burger) burgersInOrderLiveData.postValue(burgersInOrder) } override fun addItemToCart(burger: BurgerVO) { burgersInOrder.add(burger) burgersInOrderLiveData.postValue(burgersInOrder) } }
kotlin
18
0.743911
98
34.073171
41
starcoderdata
<reponame>damoasda/ZimLX /* * This file is part of Lawnchair Launcher. * * Lawnchair Launcher is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Lawnchair Launcher is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Lawnchair Launcher. If not, see <https://www.gnu.org/licenses/>. */ package org.zimmob.zimlx.gestures import android.content.Context import android.graphics.PointF import android.text.TextUtils import android.util.Log import android.view.MotionEvent import com.android.launcher3.util.TouchController import org.json.JSONException import org.json.JSONObject import org.zimmob.zimlx.ZimLauncher import org.zimmob.zimlx.gestures.gestures.* import org.zimmob.zimlx.gestures.handlers.* import org.zimmob.zimlx.zimPrefs class GestureController(val launcher: ZimLauncher) : TouchController { private val prefs = launcher.zimPrefs private val blankGestureHandler = BlankGestureHandler(launcher, null) private val doubleTapGesture by lazy { DoubleTapGesture(this) } private val pressHomeGesture by lazy { PressHomeGesture(this) } private val pressBackGesture by lazy { PressBackGesture(this) } private val longPressGesture by lazy { LongPressGesture(this) } val hasBackGesture get() = pressBackGesture.handler !is BlankGestureHandler val verticalSwipeGesture by lazy { VerticalSwipeGesture(this) } //val navSwipeUpGesture by lazy { NavSwipeUpGesture(this) } var touchDownPoint = PointF() private var swipeUpOverride: Pair<GestureHandler, Long>? = null override fun onControllerInterceptTouchEvent(ev: MotionEvent): Boolean { return false } override fun onControllerTouchEvent(ev: MotionEvent): Boolean { return false } fun onBlankAreaTouch(ev: MotionEvent): Boolean { return doubleTapGesture.isEnabled && doubleTapGesture.onTouchEvent(ev) } fun onLongPress() { longPressGesture.isEnabled && longPressGesture.onEvent() } fun onPressHome() { pressHomeGesture.isEnabled && pressHomeGesture.onEvent() } fun onPressBack() { pressBackGesture.isEnabled && pressBackGesture.onEvent() } fun setSwipeUpOverride(handler: GestureHandler, downTime: Long) { if (swipeUpOverride?.second != downTime) { swipeUpOverride = Pair(handler, downTime) } } fun getSwipeUpOverride(downTime: Long): GestureHandler? { swipeUpOverride?.let { if (it.second == downTime) { return it.first } else { swipeUpOverride = null } } return null } fun createHandlerPref(key: String, defaultValue: GestureHandler = blankGestureHandler) = prefs.StringBasedPref( key, defaultValue, prefs.doNothing, ::createGestureHandler, GestureHandler::toString, GestureHandler::onDestroy) private fun createGestureHandler(jsonString: String) = createGestureHandler(launcher, jsonString, blankGestureHandler) companion object { private const val TAG = "GestureController" private val LEGACY_SLEEP_HANDLERS = listOf( "org.zimmob.zimlx.gestures.handlers.SleepGestureHandlerDeviceAdmin", "org.zimmob.zimlx.gestures.handlers.SleepGestureHandlerAccessibility", "org.zimmob.zimlx.gestures.handlers.SleepGestureHandlerRoot") fun createGestureHandler(context: Context, jsonString: String?, fallback: GestureHandler): GestureHandler { if (!TextUtils.isEmpty(jsonString)) { val config: JSONObject? = try { JSONObject(jsonString) } catch (e: JSONException) { null } var className = config?.getString("class") ?: jsonString if (className in LEGACY_SLEEP_HANDLERS) { className = SleepGestureHandler::class.java.name } val configValue = if (config?.has("config") == true) config.getJSONObject("config") else null // Log.d(TAG, "creating handler $className with config ${configValue?.toString(2)}") try { val handler = Class.forName(className!!).getConstructor(Context::class.java, JSONObject::class.java) .newInstance(context, configValue) as GestureHandler if (handler.isAvailable) return handler } catch (t: Throwable) { Log.e(TAG, "can't create gesture handler", t) } } return fallback } fun getClassName(jsonString: String): String { val config: JSONObject? = try { JSONObject(jsonString) } catch (e: JSONException) { null } val className = config?.getString("class") ?: jsonString return if (className in LEGACY_SLEEP_HANDLERS) { SleepGestureHandler::class.java.name } else { className } } fun getGestureHandlers(context: Context, isSwipeUp: Boolean, hasBlank: Boolean) = mutableListOf( //SwitchAppsGestureHandler(context, null), //BlankGestureHandler(context, null), -> Added in apply block SleepGestureHandler(context, null), SleepGestureHandlerTimeout(context, null), OpenDrawerGestureHandler(context, null), OpenWidgetsGestureHandler(context, null), OpenSettingsGestureHandler(context, null), OpenOverviewGestureHandler(context, null), StartGlobalSearchGestureHandler(context, null), StartAppSearchGestureHandler(context, null), NotificationsOpenGestureHandler(context, null), OpenOverlayGestureHandler(context, null), StartAssistantGestureHandler(context, null), StartVoiceSearchGestureHandler(context, null), StartAppGestureHandler(context, null) //OpenRecentsGestureHandler(context, null), //LaunchMostRecentTaskGestureHandler(context, null) ).apply { if (hasBlank) { add(1, BlankGestureHandler(context, null)) } }.filter { it.isAvailableForSwipeUp(isSwipeUp) } } }
kotlin
25
0.645002
124
40.029762
168
starcoderdata
package kotlinAsJavaPlugin import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest import org.jetbrains.dokka.links.Callable import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.links.TypeConstructor import org.junit.jupiter.api.Test import kotlin.test.assertEquals class JvmNameTest : BaseAbstractTest() { val configuration = dokkaConfiguration { sourceSets { sourceSet { sourceRoots = listOf("src/") classpath += jvmStdlibPath!! } } } @Test fun `should change name for class containing top level function`() { testInline( """ |/src/main/kotlin/kotlinAsJavaPlugin/sample.kt |@file:JvmName("CustomJvmName") |package kotlinAsJavaPlugin |fun sample(): String = "" """.trimMargin(), configuration, ) { documentablesTransformationStage = { module -> val expectedClassLikeDri = DRI( packageName = "kotlinAsJavaPlugin", classNames = "CustomJvmName", ) val classLike = module.packages.flatMap { it.classlikes }.first() assertEquals(expectedClassLikeDri, classLike.dri) assertEquals("CustomJvmName", classLike.name) } } } @Test fun `should change name for top level function`() { testInline( """ |/src/main/kotlin/kotlinAsJavaPlugin/sample.kt |@file:JvmName("CustomJvmName") |package kotlinAsJavaPlugin |@JvmName("jvmSample") |fun sample(): String = "" """.trimMargin(), configuration, ) { documentablesTransformationStage = { module -> val expectedFunctionDri = DRI( packageName = "kotlinAsJavaPlugin", classNames = "CustomJvmName", callable = Callable( "jvmSample", receiver = null, params = emptyList() ) ) val function = module.packages.flatMap { it.classlikes }.flatMap { it.functions }.first() assertEquals(expectedFunctionDri, function.dri) assertEquals("jvmSample", function.name) } } } @Test fun `should change name of a setter for top level property`() { testInline( """ |/src/main/kotlin/kotlinAsJavaPlugin/sample.kt |@file:JvmName("CustomJvmName") |package kotlinAsJavaPlugin |@get:JvmName("xd") |@set:JvmName("asd") |var property: String | get() = "" | set(value) {} """.trimMargin(), configuration, ) { documentablesTransformationStage = { module -> val expectedSetterDri = DRI( packageName = "kotlinAsJavaPlugin", classNames = "CustomJvmName", callable = Callable( "asd", receiver = null, //Todo this is bad, this should be a type in java, look at the bytecode params = listOf(TypeConstructor("kotlin.String", emptyList())) ) ) val function = module.packages.flatMap { it.classlikes }.flatMap { it.functions }.first { it.name == "asd"} assertEquals(expectedSetterDri, function.dri) assertEquals("asd", function.name) } } } @Test fun `should change name of a getter for top level property`() { testInline( """ |/src/main/kotlin/kotlinAsJavaPlugin/sample.kt |@file:JvmName("CustomJvmName") |package kotlinAsJavaPlugin |@get:JvmName("xd") |@set:JvmName("asd") |var property: String | get() = "" | set(value) {} """.trimMargin(), configuration, ) { documentablesTransformationStage = { module -> val expectedGetterDri = DRI( packageName = "kotlinAsJavaPlugin", classNames = "CustomJvmName", callable = Callable( "xd", receiver = null, params = emptyList() ) ) val function = module.packages.flatMap { it.classlikes }.flatMap { it.functions }.first { it.name == "xd"} assertEquals(expectedGetterDri, function.dri) assertEquals("xd", function.name) } } } @Test fun `should leave the name as default if annotation is not provided`() { testInline( """ |/src/main/kotlin/kotlinAsJavaPlugin/sample.kt |package kotlinAsJavaPlugin |fun sample(): String = "" """.trimMargin(), configuration, ) { documentablesTransformationStage = { module -> val expectedClassLikeDri = DRI( packageName = "kotlinAsJavaPlugin", classNames = "SampleKt", ) val classLike = module.packages.flatMap { it.classlikes }.first() assertEquals(expectedClassLikeDri, classLike.dri) assertEquals("SampleKt", classLike.name) } } } }
kotlin
34
0.505464
123
34.917722
158
starcoderdata
<reponame>rekybongso/jyro-github-app package com.rekyb.jyro.data.repository import com.rekyb.jyro.data.local.FavouritesDao import com.rekyb.jyro.data.local.FavouritesEntity import com.rekyb.jyro.domain.model.UserDetailsModel import com.rekyb.jyro.domain.repository.FavouritesRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import javax.inject.Inject class FavouritesRepositoryImpl @Inject constructor( private val favouritesDao: FavouritesDao, ) : FavouritesRepository { override fun getFavouritesList(): Flow<List<UserDetailsModel>> { return favouritesDao.getFavouritesList() .map { data -> data.map { it.toModel() } } .distinctUntilChanged() .flowOn(Dispatchers.IO) } override suspend fun checkUserOnFavList(userName: String): Boolean { return favouritesDao.check(userName) } override suspend fun addUserToFavList(user: UserDetailsModel) { return favouritesDao.add(FavouritesEntity.toEntityFrom(user)) } override suspend fun removeUserFromFavList(user: UserDetailsModel) { return favouritesDao.remove(FavouritesEntity.toEntityFrom(user)) } override suspend fun clearFavList() { return favouritesDao.deleteAll() } }
kotlin
24
0.72585
72
31.666667
45
starcoderdata
<filename>core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt package net.corda.core.transactions import net.corda.core.CordaInternal import net.corda.core.DeleteForDJVM import net.corda.core.KeepForDJVM import net.corda.core.contracts.* import net.corda.core.contracts.ComponentGroupEnum.COMMANDS_GROUP import net.corda.core.contracts.ComponentGroupEnum.OUTPUTS_GROUP import net.corda.core.crypto.* import net.corda.core.identity.Party import net.corda.core.internal.Emoji import net.corda.core.internal.SerializedStateAndRef import net.corda.core.internal.createComponentGroups import net.corda.core.node.NetworkParameters import net.corda.core.node.ServiceHub import net.corda.core.node.ServicesForResolution import net.corda.core.node.services.AttachmentId import net.corda.core.serialization.CordaSerializable import net.corda.core.serialization.SerializedBytes import net.corda.core.serialization.serialize import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.lazyMapped import java.security.PublicKey import java.security.SignatureException import java.util.function.Predicate /** * A transaction ready for serialisation, without any signatures attached. A WireTransaction is usually wrapped * by a [SignedTransaction] that carries the signatures over this payload. * The identity of the transaction is the Merkle tree root of its components (see [MerkleTree]). * * For privacy purposes, each part of a transaction should be accompanied by a nonce. * To avoid storing a random number (nonce) per component, an initial [privacySalt] is the sole value utilised, * so that all component nonces are deterministically computed. * * A few notes about backwards compatibility: * A wire transaction can be backwards compatible, in the sense that if an old client receives a [componentGroups] with * more elements than expected, it will normally deserialise the required objects and omit any checks in the optional * new fields. Moreover, because the Merkle tree is constructed from the received list of [ComponentGroup], which internally * deals with bytes, any client can compute the Merkle tree and on the same time relay a [WireTransaction] object even * if she is unable to read some of the "optional" component types. We stress that practically, a new type of * [WireTransaction] should only be considered compatible if and only if the following rules apply: * <p><ul> * <li>Component-type ordering is fixed (eg. inputs, then outputs, then commands etc, see [ComponentGroupEnum] for the actual ordering). * <li>Removing a component-type that existed in older wire transaction types is not allowed, because it will affect the Merkle tree structure. * <li>Changing the order of existing component types is also not allowed, for the same reason. * <li>New component types must be added at the end of the list of [ComponentGroup] and update the [ComponentGroupEnum] with the new type. After a component is added, its ordinal must never change. * <li>A new component type should always be an "optional value", in the sense that lack of its visibility does not change the transaction and contract logic and details. An example of "optional" components could be a transaction summary or some statistics. * </ul></p> */ @CordaSerializable @KeepForDJVM class WireTransaction(componentGroups: List<ComponentGroup>, val privacySalt: PrivacySalt) : TraversableTransaction(componentGroups) { @DeleteForDJVM constructor(componentGroups: List<ComponentGroup>) : this(componentGroups, PrivacySalt()) @Deprecated("Required only in some unit-tests and for backwards compatibility purposes.", ReplaceWith("WireTransaction(val componentGroups: List<ComponentGroup>, override val privacySalt: PrivacySalt)"), DeprecationLevel.WARNING) @DeleteForDJVM @JvmOverloads constructor( inputs: List<StateRef>, attachments: List<SecureHash>, outputs: List<TransactionState<ContractState>>, commands: List<Command<*>>, notary: Party?, timeWindow: TimeWindow?, privacySalt: PrivacySalt = PrivacySalt() ) : this(createComponentGroups(inputs, outputs, commands, attachments, notary, timeWindow, emptyList()), privacySalt) init { check(componentGroups.all { it.components.isNotEmpty() }) { "Empty component groups are not allowed" } check(componentGroups.map { it.groupIndex }.toSet().size == componentGroups.size) { "Duplicated component groups detected" } checkBaseInvariants() check(inputs.isNotEmpty() || outputs.isNotEmpty()) { "A transaction must contain at least one input or output state" } check(commands.isNotEmpty()) { "A transaction must contain at least one command" } if (timeWindow != null) check(notary != null) { "Transactions with time-windows must be notarised" } } /** The transaction id is represented by the root hash of Merkle tree over the transaction components. */ override val id: SecureHash get() = merkleTree.hash /** Public keys that need to be fulfilled by signatures in order for the transaction to be valid. */ val requiredSigningKeys: Set<PublicKey> get() { val commandKeys = commands.flatMap { it.signers }.toSet() // TODO: prevent notary field from being set if there are no inputs and no time-window. return if (notary != null && (inputs.isNotEmpty() || references.isNotEmpty() || timeWindow != null)) { commandKeys + notary.owningKey } else { commandKeys } } /** * Looks up identities and attachments from storage to generate a [LedgerTransaction]. A transaction is expected to * have been fully resolved using the resolution flow by this point. * * @throws AttachmentResolutionException if a required attachment was not found in storage. * @throws TransactionResolutionException if an input points to a transaction not found in storage. */ @Throws(AttachmentResolutionException::class, TransactionResolutionException::class) @DeleteForDJVM fun toLedgerTransaction(services: ServicesForResolution): LedgerTransaction { return toLedgerTransactionInternal( resolveIdentity = { services.identityService.partyFromKey(it) }, resolveAttachment = { services.attachments.openAttachment(it) }, resolveStateRefAsSerialized = { resolveStateRefBinaryComponent(it, services) }, networkParameters = services.networkParameters ) } /** * Looks up identities, attachments and dependent input states using the provided lookup functions in order to * construct a [LedgerTransaction]. Note that identity lookup failure does *not* cause an exception to be thrown. * * @throws AttachmentResolutionException if a required attachment was not found using [resolveAttachment]. * @throws TransactionResolutionException if an input was not found not using [resolveStateRef]. */ @Deprecated("Use toLedgerTransaction(ServicesForTransaction) instead") @Throws(AttachmentResolutionException::class, TransactionResolutionException::class) fun toLedgerTransaction( resolveIdentity: (PublicKey) -> Party?, resolveAttachment: (SecureHash) -> Attachment?, resolveStateRef: (StateRef) -> TransactionState<*>?, @Suppress("UNUSED_PARAMETER") resolveContractAttachment: (TransactionState<ContractState>) -> AttachmentId? ): LedgerTransaction { // This reverts to serializing the resolved transaction state. return toLedgerTransactionInternal(resolveIdentity, resolveAttachment, { stateRef -> resolveStateRef(stateRef)?.serialize() }, null) } private fun toLedgerTransactionInternal( resolveIdentity: (PublicKey) -> Party?, resolveAttachment: (SecureHash) -> Attachment?, resolveStateRefAsSerialized: (StateRef) -> SerializedBytes<TransactionState<ContractState>>?, networkParameters: NetworkParameters? ): LedgerTransaction { // Look up public keys to authenticated identities. val authenticatedCommands = commands.lazyMapped { cmd, _ -> val parties = cmd.signers.mapNotNull { pk -> resolveIdentity(pk) } CommandWithParties(cmd.signers, parties, cmd.value) } val serializedResolvedInputs = inputs.map { ref -> SerializedStateAndRef(resolveStateRefAsSerialized(ref) ?: throw TransactionResolutionException(ref.txhash), ref) } val resolvedInputs = serializedResolvedInputs.lazyMapped { star, _ -> star.toStateAndRef() } val serializedResolvedReferences = references.map { ref -> SerializedStateAndRef(resolveStateRefAsSerialized(ref) ?: throw TransactionResolutionException(ref.txhash), ref) } val resolvedReferences = serializedResolvedReferences.lazyMapped { star, _ -> star.toStateAndRef() } val resolvedAttachments = attachments.lazyMapped { att, _ -> resolveAttachment(att) ?: throw AttachmentResolutionException(att) } val ltx = LedgerTransaction.create( resolvedInputs, outputs, authenticatedCommands, resolvedAttachments, id, notary, timeWindow, privacySalt, networkParameters, resolvedReferences, componentGroups, serializedResolvedInputs, serializedResolvedReferences ) checkTransactionSize(ltx, networkParameters?.maxTransactionSize ?: DEFAULT_MAX_TX_SIZE, serializedResolvedInputs, serializedResolvedReferences) return ltx } /** * Deterministic function that checks if the transaction is below the maximum allowed size. * It uses the binary representation of transactions. */ private fun checkTransactionSize(ltx: LedgerTransaction, maxTransactionSize: Int, resolvedSerializedInputs: List<SerializedStateAndRef>, resolvedSerializedReferences: List<SerializedStateAndRef>) { var remainingTransactionSize = maxTransactionSize fun minus(size: Int) { require(remainingTransactionSize > size) { "Transaction exceeded network's maximum transaction size limit : $maxTransactionSize bytes." } remainingTransactionSize -= size } // This calculates a value that is slightly lower than the actual re-serialized version. But it is stable and does not depend on the classloader. fun componentGroupSize(componentGroup: ComponentGroupEnum): Int { return this.componentGroups.firstOrNull { it.groupIndex == componentGroup.ordinal }?.let { cg -> cg.components.sumBy { it.size } + 4 } ?: 0 } // Check attachments size first as they are most likely to go over the limit. With ContractAttachment instances // it's likely that the same underlying Attachment CorDapp will occur more than once so we dedup on the attachment id. ltx.attachments.distinctBy { it.id }.forEach { minus(it.size) } minus(resolvedSerializedInputs.sumBy { it.serializedState.size }) minus(resolvedSerializedReferences.sumBy { it.serializedState.size }) // For Commands and outputs we can use the component groups as they are already serialized. minus(componentGroupSize(COMMANDS_GROUP)) minus(componentGroupSize(OUTPUTS_GROUP)) } /** * Build filtered transaction using provided filtering functions. */ fun buildFilteredTransaction(filtering: Predicate<Any>): FilteredTransaction = FilteredTransaction.buildFilteredTransaction(this, filtering) /** * Builds whole Merkle tree for a transaction. * Briefly, each component group has its own sub Merkle tree and all of the roots of these trees are used as leaves * in a top level Merkle tree. * Note that ordering of elements inside a [ComponentGroup] matters when computing the Merkle root. * On the other hand, insertion group ordering does not affect the top level Merkle tree construction, as it is * actually an ordered Merkle tree, where its leaves are ordered based on the group ordinal in [ComponentGroupEnum]. * If any of the groups is an empty list or a null object, then [SecureHash.allOnesHash] is used as its hash. * Also, [privacySalt] is not a Merkle tree leaf, because it is already "inherently" included via the component nonces. */ val merkleTree: MerkleTree by lazy { MerkleTree.getMerkleTree(groupHashes) } /** * The leaves (group hashes) of the top level Merkle tree. * If a group's Merkle root is allOnesHash, it is a flag that denotes this group is empty (if list) or null (if single object) * in the wire transaction. */ internal val groupHashes: List<SecureHash> by lazy { val listOfLeaves = mutableListOf<SecureHash>() // Even if empty and not used, we should at least send oneHashes for each known // or received but unknown (thus, bigger than known ordinal) component groups. for (i in 0..componentGroups.map { it.groupIndex }.max()!!) { val root = groupsMerkleRoots[i] ?: SecureHash.allOnesHash listOfLeaves.add(root) } listOfLeaves } /** * Calculate the hashes of the existing component groups, that are used to build the transaction's Merkle tree. * Each group has its own sub Merkle tree and the hash of the root of this sub tree works as a leaf of the top * level Merkle tree. The root of the latter is the transaction identifier. * * The tree structure is helpful for preserving privacy, please * see the user-guide section "Transaction tear-offs" to learn more about this topic. */ internal val groupsMerkleRoots: Map<Int, SecureHash> by lazy { availableComponentHashes.map { Pair(it.key, MerkleTree.getMerkleTree(it.value).hash) }.toMap() } /** * Calculate nonces for every transaction component, including new fields (due to backwards compatibility support) we cannot process. * Nonce are computed in the following way: * nonce1 = H(salt || path_for_1st_component) * nonce2 = H(salt || path_for_2nd_component) * etc. * Thus, all of the nonces are "independent" in the sense that knowing one or some of them, you can learn * nothing about the rest. */ internal val availableComponentNonces: Map<Int, List<SecureHash>> by lazy { componentGroups.map { Pair(it.groupIndex, it.components.mapIndexed { internalIndex, internalIt -> componentHash(internalIt, privacySalt, it.groupIndex, internalIndex) }) }.toMap() } /** * Calculate hashes for every transaction component. These will be used to build the full Merkle tree. * The root of the tree is the transaction identifier. The tree structure is helpful for privacy, please * see the user-guide section "Transaction tear-offs" to learn more about this topic. */ internal val availableComponentHashes: Map<Int, List<SecureHash>> by lazy { componentGroups.map { Pair(it.groupIndex, it.components.mapIndexed { internalIndex, internalIt -> componentHash(availableComponentNonces[it.groupIndex]!![internalIndex], internalIt) }) }.toMap() } /** * Checks that the given signature matches one of the commands and that it is a correct signature over the tx. * * @throws SignatureException if the signature didn't match the transaction contents. * @throws IllegalArgumentException if the signature key doesn't appear in any command. */ fun checkSignature(sig: TransactionSignature) { require(commands.any { it.signers.any { sig.by in it.keys } }) { "Signature key doesn't match any command" } sig.verify(id) } companion object { private const val DEFAULT_MAX_TX_SIZE = 10485760 @CordaInternal @Deprecated("Do not use, this is internal API") fun createComponentGroups(inputs: List<StateRef>, outputs: List<TransactionState<ContractState>>, commands: List<Command<*>>, attachments: List<SecureHash>, notary: Party?, timeWindow: TimeWindow?): List<ComponentGroup> { return createComponentGroups(inputs, outputs, commands, attachments, notary, timeWindow, emptyList()) } /** * This is the main logic that knows how to retrieve the binary representation of [StateRef]s. * * For [ContractUpgradeWireTransaction] or [NotaryChangeWireTransaction] it knows how to recreate the output state in the correct classloader independent of the node's classpath. */ @CordaInternal internal fun resolveStateRefBinaryComponent(stateRef: StateRef, services: ServicesForResolution): SerializedBytes<TransactionState<ContractState>>? { return if (services is ServiceHub) { val coreTransaction = services.validatedTransactions.getTransaction(stateRef.txhash)?.coreTransaction ?: throw TransactionResolutionException(stateRef.txhash) when (coreTransaction) { is WireTransaction -> coreTransaction.componentGroups.firstOrNull { it.groupIndex == ComponentGroupEnum.OUTPUTS_GROUP.ordinal }?.components?.get(stateRef.index) as SerializedBytes<TransactionState<ContractState>>? is ContractUpgradeWireTransaction -> coreTransaction.resolveOutputComponent(services, stateRef) is NotaryChangeWireTransaction -> coreTransaction.resolveOutputComponent(services, stateRef) else -> throw UnsupportedOperationException("Attempting to resolve input ${stateRef.index} of a ${coreTransaction.javaClass} transaction. This is not supported.") } } else { // For backwards compatibility revert to using the node classloader. services.loadState(stateRef).serialize() } } } @DeleteForDJVM override fun toString(): String { val buf = StringBuilder() buf.appendln("Transaction:") for (reference in references) { val emoji = Emoji.rightArrow buf.appendln("${emoji}REFS: $reference") } for (input in inputs) { val emoji = Emoji.rightArrow buf.appendln("${emoji}INPUT: $input") } for ((data) in outputs) { val emoji = Emoji.leftArrow buf.appendln("${emoji}OUTPUT: $data") } for (command in commands) { val emoji = Emoji.diamond buf.appendln("${emoji}COMMAND: $command") } for (attachment in attachments) { val emoji = Emoji.paperclip buf.appendln("${emoji}ATTACHMENT: $attachment") } return buf.toString() } override fun equals(other: Any?): Boolean { if (other is WireTransaction) { return (this.id == other.id) } return false } override fun hashCode(): Int = id.hashCode() } /** * A ComponentGroup is used to store the full list of transaction components of the same type in serialised form. * Practically, a group per component type of a transaction is required; thus, there will be a group for input states, * a group for all attachments (if there are any) etc. */ @CordaSerializable open class ComponentGroup(open val groupIndex: Int, open val components: List<OpaqueBytes>)
kotlin
36
0.692994
257
53.075881
369
starcoderdata
<gh_stars>1-10 /* Copyright 2017-2021 <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 batect.docker.build.buildkit.services import batect.testutils.createForEachTest import batect.testutils.equalTo import batect.testutils.runForEachTest import com.natpryce.hamkrest.assertion.assertThat import io.grpc.health.v1.HealthCheckRequest import io.grpc.health.v1.HealthCheckResponse import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object HealthServiceSpec : Spek({ describe("a gRPC health service") { val service by createForEachTest { HealthService() } describe("checking the health of the server") { val response by runForEachTest { service.Check(HealthCheckRequest()) } it("returns that the server is OK") { assertThat(response, equalTo(HealthCheckResponse(HealthCheckResponse.ServingStatus.SERVING))) } } } })
kotlin
38
0.741497
109
34.853659
41
starcoderdata
<filename>src/main/kotlin/com/wutsi/flutter/sdui/AppBar.kt<gh_stars>1-10 package com.wutsi.flutter.sdui import com.wutsi.flutter.sdui.enums.WidgetType.AppBar class AppBar( val title: String? = null, val elevation: Double? = null, val backgroundColor: String? = null, val foregroundColor: String? = null, val leading: WidgetAware? = null, val actions: List<WidgetAware>? = null, val automaticallyImplyLeading: Boolean? = null, val bottom: TabBar? = null, ) : WidgetAware { override fun toWidget() = Widget( type = AppBar, attributes = mapOf( "title" to title, "elevation" to elevation, "backgroundColor" to backgroundColor, "foregroundColor" to foregroundColor, "automaticallyImplyLeading" to automaticallyImplyLeading, "actions" to actions?.map { it.toWidget() }, "leading" to leading?.toWidget(), "bottom" to bottom?.toWidget(), ), ) }
kotlin
22
0.633634
72
33.448276
29
starcoderdata
<filename>compiler/parser/src/commonMain/kotlin/ParseTree.kt<gh_stars>1-10 package org.plank.syntax.parser import org.antlr.v4.kotlinruntime.ParserRuleContext import org.antlr.v4.kotlinruntime.tree.TerminalNode import pw.binom.collection.LinkedList sealed interface ParseTreeElement { override fun toString(): String fun multilineString(ident: String = ""): String } class ParseTreeLeaf(val text: String) : ParseTreeElement { override fun toString(): String = "T[$text]" override fun multilineString(ident: String): String = ident + "T[$text]\n" } class ParseTreeNode(val name: String) : ParseTreeElement { val children = LinkedList<ParseTreeElement>() fun child(element: ParseTreeElement): ParseTreeNode { children.add(element) return this } override fun toString(): String = "Node($name) $children" override fun multilineString(ident: String): String = buildString { append(ident) append(name) append("\n") children.forEach { element -> append(element.multilineString("$ident ")) } } } fun ParserRuleContext.toParseTree(): ParseTreeNode { val nodeName = this::class.simpleName?.removeSuffix("Context") ?: error("Unknown name for parse context: $this") val tree = ParseTreeNode(nodeName) children.orEmpty().forEach { element -> when (element) { is ParserRuleContext -> tree.child(element.toParseTree()) is TerminalNode -> tree.child(ParseTreeLeaf(element.text)) } } return tree }
kotlin
24
0.721622
76
28.019608
51
starcoderdata
// Original bug: KT-36816 interface Parent<T> class Foo<T>(x: T?): Parent<T> {} class Bar<T>(x: T): Parent<T> {} fun <T> select(vararg x: T) = x[0] fun <T> main(x: T) { val y = select(Foo(x), Bar(x)) // y is Parent<out T> in NI, Parent<T> in OI }
kotlin
13
0.572549
79
20.25
12
starcoderdata
/** * Copyright (c) 2018-2019 Dr. <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 org.drx.evoleq.dsl import org.junit.Test class ConfigurationsTest { @Test fun testIt() { val configurations = Configurations() class Ex(val x: Int, val y: String) class ExConfig(var x : Int? = null, var y: String? = null) : Configuration<Ex> { override fun configure(): Ex { return Ex(x!!, y!!) } } class Impl1 class Impl2 class Impl3 configurations.register<Impl1,ExConfig>(ExConfig(1,"1")) configurations.register<Impl2,ExConfig>(ExConfig(2,"2")) configurations.register<Impl3,ExConfig>(ExConfig()) val c1 = (configurations.get<Impl1>() as ExConfig).configure() assert (c1.x == 1 && c1.y == "1") val c2 = (configurations.get<Impl2>() as ExConfig).configure() assert (c2.x == 2 && c2.y == "2") val cc3 = (configurations.get<Impl3>() as ExConfig) cc3.x = 3 cc3.y = "3" val c3 = cc3.configure() class Impl4 configurations.register<Impl4, ExConfig>(setupConfiguration<Ex,ExConfig> { x = 3 } as ExConfig) } }
kotlin
18
0.625862
103
30.654545
55
starcoderdata