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
<reponame>GRAM-DSM/Color-Android package com.gram.color_android.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.gram.color_android.data.model.sign.RegisterRequest import com.gram.color_android.data.repository.sign.SignRepositoryImpl import com.gram.color_android.network.set.RegisterSet import kotlinx.coroutines.launch import retrofit2.Response class RegisterViewModel : ViewModel() { private val signRepository = SignRepositoryImpl() private val _registerLiveData: MutableLiveData<RegisterSet> = MutableLiveData() val registerLiveData: LiveData<RegisterSet> = _registerLiveData fun nameCheck(nickname: String) { val path = HashMap<String, String>() path["nickname"] = nickname viewModelScope.launch { val response = signRepository.nameCheck(path) if (response.isSuccessful) { nameCheckSuccess(response) } else { _registerLiveData.postValue(RegisterSet.NAME_FAIL) } } } fun sendEmail(email: String) { val body = HashMap<String, String>() body["email"] = email viewModelScope.launch { val response = signRepository.sendEmail(body) if (response.isSuccessful) { sendEmailSuccess(response) } else { _registerLiveData.postValue(RegisterSet.SEND_FAIL) } } } fun emailCertify(email: String, code: String) { viewModelScope.launch { val response = signRepository.emailCertify(email, code) if (response.isSuccessful) { emailCertifySuccess(response) } else { _registerLiveData.postValue(RegisterSet.EMAIL_FAIL) } } } fun register(registerRequest: RegisterRequest) { viewModelScope.launch { val response = signRepository.register(registerRequest) if (response.isSuccessful) { registerSuccess(response) } else { _registerLiveData.postValue(RegisterSet.REGISTER_FAIL) } } } private fun nameCheckSuccess(response: Response<Void>) { if (response.code() == 200) { _registerLiveData.postValue(RegisterSet.NAME_SUCCESS) } else { _registerLiveData.postValue(RegisterSet.NAME_FAIL) } } private fun sendEmailSuccess(response: Response<Void>) { if (response.code() == 200) { _registerLiveData.postValue(RegisterSet.SEND_SUCCESS) } else { _registerLiveData.postValue(RegisterSet.SEND_FAIL) } } private fun emailCertifySuccess(response: Response<Void>) { if (response.code() == 200) { _registerLiveData.postValue(RegisterSet.EMAIL_SUCCESS) } else { _registerLiveData.postValue(RegisterSet.EMAIL_FAIL) } } private fun registerSuccess(response: Response<Void>) { if (response.code() == 201) { _registerLiveData.postValue(RegisterSet.REGISTER_SUCCESS) } else { _registerLiveData.postValue(RegisterSet.REGISTER_FAIL) } } }
kotlin
20
0.631785
83
32.505051
99
starcoderdata
<reponame>Marc-JB/TextToSpeechKt buildscript { repositories { google() gradlePluginPortal() mavenCentral() // TODO: Remove manual R8 declaration when AGP 7.1 releases: https://issuetracker.google.com/issues/206855609 maven(url = "https://storage.googleapis.com/r8-releases/raw") } dependencies { // TODO: Remove manual R8 declaration when AGP 7.1 releases: https://issuetracker.google.com/issues/206855609 classpath("com.android.tools:r8:3.1.42") classpath("com.android.tools.build:gradle:7.0.4") classpath(kotlin("gradle-plugin", "1.6.10")) classpath("org.jetbrains.dokka:dokka-gradle-plugin:1.6.0") } }
kotlin
19
0.660969
117
38
18
starcoderdata
<filename>subprojects/docs/src/samples/userguide/artifacts/uploading/kotlin/build.gradle.kts plugins { java } // tag::archive-artifact[] val myJar = task<Jar>("myJar") artifacts { add("archives", myJar) } // end::archive-artifact[] // tag::file-artifact[] val someFile = file("$buildDir/somefile.txt") artifacts { add("archives", someFile) } // end::file-artifact[] // tag::customized-file-artifact[] val myTask = task<MyTaskType>("myTask") { destFile = file("$buildDir/somefile.txt") } artifacts { add("archives", myTask.destFile!!) { name = "my-artifact" type = "text" builtBy(myTask) } } // end::customized-file-artifact[] // tag::map-file-artifact[] val generate = task<MyTaskType>("generate") { destFile = file("$buildDir/somefile.txt") } artifacts { add("archives", mapOf("file" to generate.destFile, "name" to "my-artifact", "type" to "text", "builtBy" to generate)) } // end::map-file-artifact[] open class MyTaskType : DefaultTask() { var destFile: File? = null } // tag::uploading[] repositories { flatDir { name = "fileRepo" dirs("repo") } } tasks.getByName<Upload>("uploadArchives") { repositories { add(project.repositories["fileRepo"]) ivy { credentials { username = "username" password = "pw" } url = uri("http://repo.mycompany.com") } } } // end::uploading[]
kotlin
24
0.600135
109
19.816901
71
starcoderdata
<reponame>sleticalboy/Daily-Work package com.sleticalboy.learning.components import android.net.Uri import android.text.TextUtils import android.util.Log import android.view.View import android.widget.EditText import android.widget.TextView import com.sleticalboy.learning.R import com.sleticalboy.learning.base.BaseActivity import com.sleticalboy.learning.databinding.ActivityProviderBinding class ProviderPractise : BaseActivity() { private var mResult: TextView? = null override fun layout(): View { // R.layout.activity_provider return ActivityProviderBinding.inflate(layoutInflater).root } override fun initView() { mResult = findViewById(R.id.queryResult) val table = findViewById<EditText>(R.id.etTable) findViewById<View>(R.id.btnQuery).setOnClickListener { doQuery(table.text.toString().trim { it <= ' ' }) } } private fun doQuery(table: String) { require(!TextUtils.isEmpty(table)) { "table is null." } val projection = arrayOf("mac_address") val cursor = contentResolver.query(Uri.parse("$BASE_URI/$table"), projection, null, null, null) if (cursor != null) { if (cursor.moveToFirst()) { val mac = cursor.getString(cursor.getColumnIndex(projection[0])) mResult!!.text = mac } try { cursor.close() } catch (t: Throwable) { Log.d(TAG, "doQuery() error with: $table", t) } } } companion object { private const val TAG = "MainActivity" private const val BASE_URI = "com.sleticalboy.dailywork.store" } }
kotlin
23
0.635246
80
31.245283
53
starcoderdata
import com.android.build.api.dsl.ApplicationExtension import com.android.build.api.artifact.Artifacts import com.android.build.api.artifact.ArtifactType import com.android.build.api.variant.VariantOutputConfiguration.OutputType import com.android.build.gradle.AppPlugin import org.gradle.api.Plugin import org.gradle.api.Project class CustomPlugin: Plugin<Project> { override fun apply(project: Project) { project.plugins.withType(AppPlugin::class.java) { // NOTE: BaseAppModuleExtension is internal. This will be replaced by a public // interface val extension = project.extensions.getByName("android") as ApplicationExtension<*,*,*,*,*> extension.configure(project) } } } fun ApplicationExtension<*,*,*,*,*>.configure(project: Project) { // Note: Everything in there is incubating. // onVariantProperties registers an action that configures variant properties during // variant computation (which happens during afterEvaluate) onVariantProperties { // applies to all variants. This excludes test components (unit test and androidTest) } // use filter to apply onVariantProperties to a subset of the variants onVariantProperties.withBuildType("release") { // Because app module can have multiple output when using mutli-APK, versionCode/Name // are only available on the variant output. // Here gather the output when we are in single mode (ie no multi-apk) val mainOutput = this.outputs.single { it.outputType == OutputType.SINGLE } // create version Code generating task val versionCodeTask = project.tasks.register("computeVersionCodeFor${name}", VersionCodeTask::class.java) { it.outputFile.set(project.layout.buildDirectory.file("versionCode.txt")) } // wire version code from the task output // map will create a lazy Provider that // 1. runs just before the consumer(s), ensuring that the producer (VersionCodeTask) has run // and therefore the file is created. // 2. contains task dependency information so that the consumer(s) run after the producer. mainOutput.versionCode.set(versionCodeTask.map { it.outputFile.get().asFile.readText().toInt() }) // same for version Name val versionNameTask = project.tasks.register("computeVersionNameFor${name}", VersionNameTask::class.java) { it.outputFile.set(project.layout.buildDirectory.file("versionName.txt")) } mainOutput.versionName.set(versionNameTask.map { it.outputFile.get().asFile.readText() }) // finally add the verifier task that will check that the merged manifest // does contain the version code and version name from the tasks added // above. project.tasks.register("verifierFor${name}", VerifyManifestTask::class.java) { it.apkFolder.set(artifacts.get(ArtifactType.APK)) it.builtArtifactsLoader.set(artifacts.getBuiltArtifactsLoader()) } } }
kotlin
27
0.701863
115
48.354839
62
starcoderdata
<filename>src/main/kotlin/com/amaljoyc/demo/camel/config/JsonConfig.kt package com.amaljoyc.demo.camel.config import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.KotlinModule import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Primary @Configuration class JsonConfig { @Bean @Primary fun objectMapper(): ObjectMapper { val objectMapper = ObjectMapper() objectMapper.registerModule(KotlinModule()) return objectMapper } }
kotlin
13
0.790164
70
29.55
20
starcoderdata
package org.danilopianini import java.lang.IllegalStateException /** * Utility methods collection, to be exposed to settings.gradle.kts. */ object VersionAliases { /** * The aliases of refreshversions-aliases. */ val additionalAliases: String = Thread .currentThread() .contextClassLoader .getResource("org/danilopianini/version-aliases") ?.readText() ?: throw IllegalStateException("Unable to find the version aliases") /** * A single-element list with just the aliases of refreshversions-aliases. * Shortcut to simply inject these aliases and nothing else. */ val justAdditionalAliases: List<String> = listOf(additionalAliases) }
kotlin
13
0.692629
78
27.76
25
starcoderdata
<gh_stars>1-10 // 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 git4idea.branch import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.ContainerUtil @Service internal class GitCompareBranchesFilesManager(private val project: Project) : Disposable { private val sessionId = System.currentTimeMillis().toString() private val openedFiles = ContainerUtil.createWeakValueMap<GitCompareBranchesVirtualFileSystem.Path, GitCompareBranchesFile>() fun openFile(compareBranchesUi: GitCompareBranchesUi, focus: Boolean) { val file = openedFiles.getOrPut(createPath(sessionId, compareBranchesUi), { GitCompareBranchesFile(sessionId, compareBranchesUi) }) FileEditorManager.getInstance(project).openFile(file, focus) } fun findFile(path: GitCompareBranchesVirtualFileSystem.Path): VirtualFile? = openedFiles[path] override fun dispose() { openedFiles.clear() } companion object { @JvmStatic fun getInstance(project: Project) = project.service<GitCompareBranchesFilesManager>() @JvmStatic internal fun createPath(sessionId: String, compareBranchesUi: GitCompareBranchesUi): GitCompareBranchesVirtualFileSystem.Path { return GitCompareBranchesVirtualFileSystem.Path(sessionId, compareBranchesUi.project.locationHash, compareBranchesUi.rangeFilter.ranges, compareBranchesUi.rootFilter?.roots) } } }
kotlin
17
0.758924
140
42.380952
42
starcoderdata
<reponame>timyates/advent-of-kotlin-2021 package com.bloidonia.advent.day10 import com.bloidonia.advent.readList import kotlin.collections.ArrayDeque fun opener(ch: Char) = when (ch) { ')' -> '(' ']' -> '[' '}' -> '{' else -> '<' } private fun corruptScore(ch: Char) = when (ch) { ')' -> 3 ']' -> 57 '}' -> 1197 else -> 25137 } private fun completionScore(ch: Char) = when (ch) { '(' -> 1L '[' -> 2L '{' -> 3L else -> 4L } data class Score(val corrupt: Int, val autoComplete: Long) fun String.score(): Score { val expected = ArrayDeque<Char>(this.length) for (ch in this) { when (ch) { '{', '(', '[', '<' -> expected.addFirst(ch) else -> { if (expected.removeFirst() != opener(ch)) { return Score(corruptScore(ch), 0) } } } } return Score(0, expected.fold(0L) { acc: Long, c: Char -> acc * 5 + completionScore(c) }) } // Only works as the input list is an odd length fun List<Long>.median() = this.sorted()[this.size / 2] fun main() { println(readList("/day10input.txt") { it.score() }.sumOf { it.corrupt }) println(readList("/day10input.txt") { it.score().autoComplete }.filter { it > 0 }.median()) }
kotlin
23
0.540856
95
24.215686
51
starcoderdata
<reponame>ironbatshashank/open-event-android package org.fossasia.openevent.general.ticket import java.io.Serializable /** * A wrapper class around a list of Ticket Ids and Quantities. * This class allows for passing this data between frgments in a typesafe manner. * * @param value The list of ids and quantities */ data class TicketIdAndQtyWrapper(val value: List<Pair<Int, Int>>) : Serializable
kotlin
11
0.777778
81
32.75
12
starcoderdata
<gh_stars>1-10 // 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.github.pullrequest.ui.toolwindow import com.intellij.ide.plugins.newui.VerticalLayout import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.application.invokeLater import com.intellij.openapi.roots.ui.componentsList.components.ScrollablePanel import com.intellij.openapi.util.Key import com.intellij.openapi.vcs.ui.FontUtil import com.intellij.ui.* import com.intellij.ui.components.JBList import com.intellij.util.ui.JBUI import com.intellij.util.ui.ListUiUtil import com.intellij.util.ui.UI import com.intellij.util.ui.UIUtil import com.intellij.vcs.log.VcsUser import com.intellij.vcs.log.impl.HashImpl import com.intellij.vcs.log.impl.VcsUserImpl import com.intellij.vcs.log.ui.details.commit.CommitDetailsPanel import com.intellij.vcs.log.ui.details.commit.getCommitDetailsBackground import com.intellij.vcs.log.ui.frame.CommitPresentationUtil import org.jetbrains.plugins.github.api.data.GHCommit import org.jetbrains.plugins.github.api.data.GHGitActor import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.ui.changes.GHPRCommitsListCellRenderer import org.jetbrains.plugins.github.ui.util.HtmlEditorPane import org.jetbrains.plugins.github.ui.util.SingleValueModel import org.jetbrains.plugins.github.util.GithubUIUtil import java.awt.Rectangle import javax.swing.JComponent import javax.swing.JList import javax.swing.ListSelectionModel import javax.swing.ScrollPaneConstants internal object GHPRCommitsBrowserComponent { val COMMITS_LIST_KEY = Key.create<JList<GHCommit>>("COMMITS_LIST") fun create(commitsModel: SingleValueModel<List<GHCommit>>, onCommitSelected: (GHCommit?) -> Unit): JComponent { val commitsListModel = CollectionListModel(commitsModel.value) val actionManager = ActionManager.getInstance() val commitsList = JBList(commitsListModel).apply { selectionMode = ListSelectionModel.SINGLE_SELECTION val renderer = GHPRCommitsListCellRenderer() cellRenderer = renderer UIUtil.putClientProperty(this, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, listOf(renderer.panel)) emptyText.text = GithubBundle.message("pull.request.does.not.contain.commits") }.also { ScrollingUtil.installActions(it) ListUiUtil.Selection.installSelectionOnFocus(it) ListUiUtil.Selection.installSelectionOnRightClick(it) PopupHandler.installSelectionListPopup(it, DefaultActionGroup(actionManager.getAction("Github.PullRequest.Changes.Reload")), ActionPlaces.UNKNOWN, actionManager) ListSpeedSearch(it) { commit -> commit.messageHeadlineHTML } } commitsModel.addValueChangedListener { val currentList = commitsListModel.toList() val newList = commitsModel.value if (currentList != newList) { val selectedCommit = commitsList.selectedValue commitsListModel.replaceAll(newList) commitsList.setSelectedValue(selectedCommit, true) } } val commitDetailsModel = SingleValueModel<GHCommit?>(null) val commitDetailsComponent = createCommitDetailsComponent(commitDetailsModel) commitsList.addListSelectionListener { e -> if (e.valueIsAdjusting) return@addListSelectionListener onCommitSelected(commitsList.selectedValue) } val commitsScrollPane = ScrollPaneFactory.createScrollPane(commitsList, true).apply { isOpaque = false viewport.isOpaque = false horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER } val commitsBrowser = OnePixelSplitter(true, "Github.PullRequest.Commits.Browser", 0.7f).apply { firstComponent = commitsScrollPane secondComponent = commitDetailsComponent UIUtil.putClientProperty(this, COMMITS_LIST_KEY, commitsList) } commitsList.addListSelectionListener { e -> if (e.valueIsAdjusting) return@addListSelectionListener val index = commitsList.selectedIndex commitDetailsModel.value = if (index != -1) commitsListModel.getElementAt(index) else null commitsBrowser.validate() commitsBrowser.repaint() if (index != -1) ScrollingUtil.ensureRangeIsVisible(commitsList, index, index) } return commitsBrowser } private fun createCommitDetailsComponent(model: SingleValueModel<GHCommit?>): JComponent { val messagePane = HtmlEditorPane().apply { font = FontUtil.getCommitMessageFont() } //TODO: show avatar val hashAndAuthorPane = HtmlEditorPane().apply { font = FontUtil.getCommitMetadataFont() } val commitDetailsPanel = ScrollablePanel(VerticalLayout(UI.scale(CommitDetailsPanel.INTERNAL_BORDER))).apply { border = JBUI.Borders.empty(CommitDetailsPanel.EXTERNAL_BORDER, CommitDetailsPanel.SIDE_BORDER) background = getCommitDetailsBackground() add(messagePane, VerticalLayout.FILL_HORIZONTAL) add(hashAndAuthorPane, VerticalLayout.FILL_HORIZONTAL) } val commitDetailsScrollPane = ScrollPaneFactory.createScrollPane(commitDetailsPanel, true).apply { isVisible = false isOpaque = false viewport.isOpaque = false horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER } model.addAndInvokeValueChangedListener { val commit = model.value if (commit == null) { messagePane.setBody("") hashAndAuthorPane.setBody("") commitDetailsScrollPane.isVisible = false } else { val subject = "<b>${commit.messageHeadlineHTML}</b>" val body = commit.messageBodyHTML val fullMessage = if (body.isNotEmpty()) "$subject<br><br>$body" else subject messagePane.setBody(fullMessage) hashAndAuthorPane.setBody(getHashAndAuthorText(commit.oid, commit.author, commit.committer)) commitDetailsScrollPane.isVisible = true commitDetailsPanel.scrollRectToVisible(Rectangle(0, 0, 0, 0)) invokeLater { // JDK bug - need to force height recalculation (see JBR-2256) messagePane.setSize(messagePane.width, Int.MAX_VALUE / 2) hashAndAuthorPane.setSize(hashAndAuthorPane.width, Int.MAX_VALUE / 2) } } } return commitDetailsScrollPane } private fun getHashAndAuthorText(hash: String, author: GHGitActor?, committer: GHGitActor?): String { val authorUser = createUser(author) val authorTime = author?.date?.time ?: 0L val committerUser = createUser(committer) val committerTime = committer?.date?.time ?: 0L return CommitPresentationUtil.formatCommitHashAndAuthor(HashImpl.build(hash), authorUser, authorTime, committerUser, committerTime) } private val unknownUser = VcsUserImpl("unknown user", "") private fun createUser(actor: GHGitActor?): VcsUser { val name = actor?.name val email = actor?.email return if (name != null && email != null) { VcsUserImpl(name, email) } else unknownUser } }
kotlin
26
0.747286
140
40.352273
176
starcoderdata
/** * BreadWallet * * Created by <NAME> <<EMAIL>> on 9/25/19. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.xwallet.tools.animation import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.app.Activity import android.content.Context import android.view.MotionEvent import android.view.View import android.view.animation.OvershootInterpolator import com.bluelinelabs.conductor.Router @Suppress("MagicNumber") class SlideDetector(private val root: View) : View.OnTouchListener { constructor(router: Router, root: View) : this(root) { this.router = router } constructor(context: Context, root: View) : this(root) { this.context = context } private var router: Router? = null private var context: Context? = null private var origY: Float = 0f private var dY: Float = 0f override fun onTouch(v: View, event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> { origY = root.y dY = root.y - event.rawY } MotionEvent.ACTION_MOVE -> if (event.rawY + dY > origY) root.animate() .y(event.rawY + dY) .setDuration(0) .start() MotionEvent.ACTION_UP -> if (root.y > origY + root.height / 5) { root.animate() .y((root.height * 2).toFloat()) .setDuration(200) .setInterpolator(OvershootInterpolator(0.5f)) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) removeCurrentView() } }) .start() } else { root.animate() .y(origY) .setDuration(100) .setInterpolator(OvershootInterpolator(0.5f)) .start() } else -> return false } return true } private fun removeCurrentView() { router?.popCurrentController() (context as? Activity)?.fragmentManager?.popBackStack() } }
kotlin
30
0.616623
80
36.141304
92
starcoderdata
<reponame>codequest-eu/devstarter-android-mvi package com.example.appName import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment class EntryPointFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = null override fun onStart() { super.onStart() (requireActivity() as MainActivity) .navController .navigate( EntryPointFragmentDirections.actionEntryPointFragmentToUserNavGraph() ) } }
kotlin
17
0.687776
85
24.148148
27
starcoderdata
<reponame>Soedirman-Machine-Learning/Plant-disease package com.tflite.DeteksipenyakittanamanMn import android.annotation.SuppressLint import android.content.Intent import android.content.pm.ActivityInfo import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import android.os.Build import android.os.Bundle import android.os.SystemClock import android.provider.MediaStore import android.widget.Toast import androidx.annotation.RequiresApi import androidx.appcompat.app.ActionBar import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_import_gallery.* import java.io.IOException class DeteksiDariGaleri : AppCompatActivity() { private lateinit var mClassifier: KlasifikasiDariGaleri private lateinit var mBitmap: Bitmap private val mGalleryRequestCode = 2 private val mInputSize = 64 private val mModelPath = "DeteksiPenyakitTanamanMoNet.tflite" private val mLabelPath = "label.txt" private val mSamplePath = "yellow.JPG" private var lastProcessingTimeMs: Long = 0 @SuppressLint("SetTextI18n") @RequiresApi(Build.VERSION_CODES.O) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (supportActionBar != null) { (supportActionBar as ActionBar).title = "Pendeteksi Penyakit Tanaman" } requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT setContentView(R.layout.activity_import_gallery) mClassifier = KlasifikasiDariGaleri(assets, mModelPath, mLabelPath, mInputSize) resources.assets.open(mSamplePath).use { mBitmap = BitmapFactory.decodeStream(it) mBitmap = Bitmap.createScaledBitmap(mBitmap, mInputSize, mInputSize, true) mPhotoImageView.setImageBitmap(mBitmap) } mGalleryButton.setOnClickListener { val callGalleryIntent = Intent(Intent.ACTION_PICK) callGalleryIntent.type = "image/*" startActivityForResult(callGalleryIntent, mGalleryRequestCode) } mDetectButton.setOnClickListener { val startTime = SystemClock.uptimeMillis()//menghitung waktu awal val results = mClassifier.recognizeImage(mBitmap).firstOrNull() mResultTextView.text= results?.title+"\n Probabilitas: "+results?.percent+"%" lastProcessingTimeMs = SystemClock.uptimeMillis() - startTime//menghitung lamanya proses val waktu = lastProcessingTimeMs.toString()//konversi ke string delaytime.text = "$waktu ms " } } @SuppressLint("MissingSuperCall", "SetTextI18n") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if(requestCode == mGalleryRequestCode) { if (data != null) { val uri = data.data try { mBitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, uri) } catch (e: IOException) { e.printStackTrace() } println("Selesai!") mBitmap = scaleImage(mBitmap) mPhotoImageView.setImageBitmap(mBitmap) } } else { Toast.makeText(this, "Unrecognized request code", Toast.LENGTH_LONG).show() } } fun scaleImage(bitmap: Bitmap?): Bitmap { val orignalWidth = bitmap!!.width val originalHeight = bitmap.height val scaleWidth = mInputSize.toFloat() / orignalWidth val scaleHeight = mInputSize.toFloat() / originalHeight val matrix = Matrix() matrix.postScale(scaleWidth, scaleHeight) return Bitmap.createBitmap(bitmap, 0, 0, orignalWidth, originalHeight, matrix, true) } }
kotlin
21
0.669223
100
36.382353
102
starcoderdata
package com.airbnb.mvrx.hellodagger import io.reactivex.Observable import java.util.concurrent.TimeUnit import javax.inject.Inject class HelloRepository @Inject constructor() { fun sayHello(): Observable<String> { return Observable .just("Hello, world!") .delay(2, TimeUnit.SECONDS) } }
kotlin
13
0.693009
45
22.571429
14
starcoderdata
package ca.logaritm.dezel.modules.graphic import android.graphics.Bitmap import android.util.LruCache /** * @class ImageLiveCache * @since 0.1.0 * @hidden */ open class ImageLiveCache(val size: Int) { //-------------------------------------------------------------------------- // Properties //-------------------------------------------------------------------------- /** * @property cache * @since 0.1.0 * @hidden */ private val cache: LruCache<String, Bitmap> = LruCache(size) //-------------------------------------------------------------------------- // Methods //-------------------------------------------------------------------------- /** * Stores the bitmap in memory. * @method set * @since 0.1.0 */ public fun set(uri: String, bitmap: Bitmap) { if (this.cache.get(uri) == null) { this.cache.put(uri, bitmap) } } /** * Retrieves the bitmap from memory. * @method get * @since 0.1.0 */ public fun get(uri: String): Bitmap? { return this.cache.get(uri) } /** * Indicates whether a memory cache exists. * @method has * @since 0.1.0 */ public fun has(uri: String): Boolean { return this.cache.get(uri) != null } }
kotlin
13
0.46689
77
20.321429
56
starcoderdata
<reponame>bubenheimer/androidx /* * Copyright 2019 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 import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.graphics.takeOrElse 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.intl.LocaleList import androidx.compose.ui.text.style.BaselineShift import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextDirection import androidx.compose.ui.text.style.TextGeometricTransform import androidx.compose.ui.text.style.TextIndent import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.isUnspecified import androidx.compose.ui.unit.sp /** The default font size if none is specified. */ private val DefaultFontSize = 14.sp private val DefaultLetterSpacing = 0.sp private val DefaultBackgroundColor = Color.Transparent // TODO(nona): Introduce TextUnit.Original for representing "do not change the original result". // Need to distinguish from Inherit. private val DefaultLineHeight = TextUnit.Unspecified private val DefaultColor = Color.Black /** * Styling configuration for a `Text`. * * @sample androidx.compose.ui.text.samples.TextStyleSample * * @param color The text color. * @param fontSize The size of glyphs to use when painting the text. This * may be [TextUnit.Unspecified] for inheriting from another [TextStyle]. * @param fontWeight The typeface thickness to use when painting the text (e.g., bold). * @param fontStyle The typeface variant to use when drawing the letters (e.g., italic). * @param fontSynthesis Whether to synthesize font weight and/or style when the requested weight or * style cannot be found in the provided custom font family. * @param fontFamily The font family to be used when rendering the text. * @param fontFeatureSettings The advanced typography settings provided by font. The format is the * same as the CSS font-feature-settings attribute: * https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop * @param letterSpacing The amount of space to add between each letter. * @param baselineShift The amount by which the text is shifted up from the current baseline. * @param textGeometricTransform The geometric transformation applied the text. * @param localeList The locale list used to select region-specific glyphs. * @param background The background color for the text. * @param textDecoration The decorations to paint on the text (e.g., an underline). * @param shadow The shadow effect applied on the text. * @param textAlign The alignment of the text within the lines of the paragraph. * @param textDirection The algorithm to be used to resolve the final text and paragraph * direction: Left To Right or Right To Left. If no value is provided the system will use the * [LayoutDirection] as the primary signal. * @param textIndent The indentation of the paragraph. * @param lineHeight Line height for the [Paragraph] in [TextUnit] unit, e.g. SP or EM. * * @see AnnotatedString * @see SpanStyle * @see ParagraphStyle */ @Immutable class TextStyle( val color: Color = Color.Unspecified, val fontSize: TextUnit = TextUnit.Unspecified, val fontWeight: FontWeight? = null, val fontStyle: FontStyle? = null, val fontSynthesis: FontSynthesis? = null, val fontFamily: FontFamily? = null, val fontFeatureSettings: String? = null, val letterSpacing: TextUnit = TextUnit.Unspecified, val baselineShift: BaselineShift? = null, val textGeometricTransform: TextGeometricTransform? = null, val localeList: LocaleList? = null, val background: Color = Color.Unspecified, val textDecoration: TextDecoration? = null, val shadow: Shadow? = null, val textAlign: TextAlign? = null, val textDirection: TextDirection? = null, val lineHeight: TextUnit = TextUnit.Unspecified, val textIndent: TextIndent? = null ) { internal constructor(spanStyle: SpanStyle, paragraphStyle: ParagraphStyle) : this ( color = spanStyle.color, fontSize = spanStyle.fontSize, fontWeight = spanStyle.fontWeight, fontStyle = spanStyle.fontStyle, fontSynthesis = spanStyle.fontSynthesis, fontFamily = spanStyle.fontFamily, fontFeatureSettings = spanStyle.fontFeatureSettings, letterSpacing = spanStyle.letterSpacing, baselineShift = spanStyle.baselineShift, textGeometricTransform = spanStyle.textGeometricTransform, localeList = spanStyle.localeList, background = spanStyle.background, textDecoration = spanStyle.textDecoration, shadow = spanStyle.shadow, textAlign = paragraphStyle.textAlign, textDirection = paragraphStyle.textDirection, lineHeight = paragraphStyle.lineHeight, textIndent = paragraphStyle.textIndent ) init { if (!lineHeight.isUnspecified) { // Since we are checking if it's negative, no need to convert Sp into Px at this point. check(lineHeight.value >= 0f) { "lineHeight can't be negative (${lineHeight.value})" } } } @Stable fun toSpanStyle(): SpanStyle = SpanStyle( color = color, fontSize = fontSize, fontWeight = fontWeight, fontStyle = fontStyle, fontSynthesis = fontSynthesis, fontFamily = fontFamily, fontFeatureSettings = fontFeatureSettings, letterSpacing = letterSpacing, baselineShift = baselineShift, textGeometricTransform = textGeometricTransform, localeList = localeList, background = background, textDecoration = textDecoration, shadow = shadow ) @Stable fun toParagraphStyle(): ParagraphStyle = ParagraphStyle( textAlign = textAlign, textDirection = textDirection, lineHeight = lineHeight, textIndent = textIndent ) /** * Returns a new text style that is a combination of this style and the given [other] style. * * [other] text style's null or inherit properties are replaced with the non-null properties of * this text style. Another way to think of it is that the "missing" properties of the [other] * style are _filled_ by the properties of this style. * * If the given text style is null, returns this text style. */ @Stable fun merge(other: TextStyle? = null): TextStyle { if (other == null || other == Default) return this return TextStyle( spanStyle = toSpanStyle().merge(other.toSpanStyle()), paragraphStyle = toParagraphStyle().merge(other.toParagraphStyle()) ) } /** * Returns a new text style that is a combination of this style and the given [other] style. * * @see merge */ @Stable fun merge(other: SpanStyle): TextStyle { return TextStyle( spanStyle = toSpanStyle().merge(other), paragraphStyle = toParagraphStyle() ) } /** * Returns a new text style that is a combination of this style and the given [other] style. * * @see merge */ @Stable fun merge(other: ParagraphStyle): TextStyle { return TextStyle( spanStyle = toSpanStyle(), paragraphStyle = toParagraphStyle().merge(other) ) } /** * Plus operator overload that applies a [merge]. */ @Stable operator fun plus(other: TextStyle): TextStyle = this.merge(other) /** * Plus operator overload that applies a [merge]. */ @Stable operator fun plus(other: ParagraphStyle): TextStyle = this.merge(other) /** * Plus operator overload that applies a [merge]. */ @Stable operator fun plus(other: SpanStyle): TextStyle = this.merge(other) fun copy( color: Color = this.color, fontSize: TextUnit = this.fontSize, fontWeight: FontWeight? = this.fontWeight, fontStyle: FontStyle? = this.fontStyle, fontSynthesis: FontSynthesis? = this.fontSynthesis, fontFamily: FontFamily? = this.fontFamily, fontFeatureSettings: String? = this.fontFeatureSettings, letterSpacing: TextUnit = this.letterSpacing, baselineShift: BaselineShift? = this.baselineShift, textGeometricTransform: TextGeometricTransform? = this.textGeometricTransform, localeList: LocaleList? = this.localeList, background: Color = this.background, textDecoration: TextDecoration? = this.textDecoration, shadow: Shadow? = this.shadow, textAlign: TextAlign? = this.textAlign, textDirection: TextDirection? = this.textDirection, lineHeight: TextUnit = this.lineHeight, textIndent: TextIndent? = this.textIndent ): TextStyle { return TextStyle( color = color, fontSize = fontSize, fontWeight = fontWeight, fontStyle = fontStyle, fontSynthesis = fontSynthesis, fontFamily = fontFamily, fontFeatureSettings = fontFeatureSettings, letterSpacing = letterSpacing, baselineShift = baselineShift, textGeometricTransform = textGeometricTransform, localeList = localeList, background = background, textDecoration = textDecoration, shadow = shadow, textAlign = textAlign, textDirection = textDirection, lineHeight = lineHeight, textIndent = textIndent ) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is TextStyle) return false if (color != other.color) return false if (fontSize != other.fontSize) return false if (fontWeight != other.fontWeight) return false if (fontStyle != other.fontStyle) return false if (fontSynthesis != other.fontSynthesis) return false if (fontFamily != other.fontFamily) return false if (fontFeatureSettings != other.fontFeatureSettings) return false if (letterSpacing != other.letterSpacing) return false if (baselineShift != other.baselineShift) return false if (textGeometricTransform != other.textGeometricTransform) return false if (localeList != other.localeList) return false if (background != other.background) return false if (textDecoration != other.textDecoration) return false if (shadow != other.shadow) return false if (textAlign != other.textAlign) return false if (textDirection != other.textDirection) return false if (lineHeight != other.lineHeight) return false if (textIndent != other.textIndent) return false return true } override fun hashCode(): Int { var result = color.hashCode() result = 31 * result + fontSize.hashCode() result = 31 * result + (fontWeight?.hashCode() ?: 0) result = 31 * result + (fontStyle?.hashCode() ?: 0) result = 31 * result + (fontSynthesis?.hashCode() ?: 0) result = 31 * result + (fontFamily?.hashCode() ?: 0) result = 31 * result + (fontFeatureSettings?.hashCode() ?: 0) result = 31 * result + letterSpacing.hashCode() result = 31 * result + (baselineShift?.hashCode() ?: 0) result = 31 * result + (textGeometricTransform?.hashCode() ?: 0) result = 31 * result + (localeList?.hashCode() ?: 0) result = 31 * result + background.hashCode() result = 31 * result + (textDecoration?.hashCode() ?: 0) result = 31 * result + (shadow?.hashCode() ?: 0) result = 31 * result + (textAlign?.hashCode() ?: 0) result = 31 * result + (textDirection?.hashCode() ?: 0) result = 31 * result + lineHeight.hashCode() result = 31 * result + (textIndent?.hashCode() ?: 0) return result } override fun toString(): String { return "TextStyle(" + "color=$color, " + "fontSize=$fontSize, " + "fontWeight=$fontWeight, " + "fontStyle=$fontStyle, " + "fontSynthesis=$fontSynthesis, " + "fontFamily=$fontFamily, " + "fontFeatureSettings=$fontFeatureSettings, " + "letterSpacing=$letterSpacing, " + "baselineShift=$baselineShift, " + "textGeometricTransform=$textGeometricTransform, " + "localeList=$localeList, " + "background=$background, " + "textDecoration=$textDecoration, " + "shadow=$shadow, textAlign=$textAlign, " + "textDirection=$textDirection, " + "lineHeight=$lineHeight, " + "textIndent=$textIndent" + ")" } companion object { /** * Constant for default text style. */ @Stable val Default = TextStyle() } } /** * Interpolate between two text styles. * * This will not work well if the styles don't set the same fields. * * The [fraction] argument represents position on the timeline, with 0.0 meaning * that the interpolation has not started, returning [start] (or something * equivalent to [start]), 1.0 meaning that the interpolation has finished, * returning [stop] (or something equivalent to [stop]), and values in between * meaning that the interpolation is at the relevant point on the timeline * between [start] and [stop]. The interpolation can be extrapolated beyond 0.0 and * 1.0, so negative values and values greater than 1.0 are valid. */ fun lerp(start: TextStyle, stop: TextStyle, fraction: Float): TextStyle { return TextStyle( spanStyle = lerp(start.toSpanStyle(), stop.toSpanStyle(), fraction), paragraphStyle = lerp(start.toParagraphStyle(), stop.toParagraphStyle(), fraction) ) } /** * Fills missing values in TextStyle with default values and resolve [TextDirection]. * * This function will fill all null or [TextUnit.Unspecified] field with actual values. * @param style a text style to be resolved * @param direction a layout direction to be used for resolving text layout direction algorithm * @return resolved text style. */ fun resolveDefaults(style: TextStyle, direction: LayoutDirection) = TextStyle( color = style.color.takeOrElse { DefaultColor }, fontSize = if (style.fontSize.isUnspecified) DefaultFontSize else style.fontSize, fontWeight = style.fontWeight ?: FontWeight.Normal, fontStyle = style.fontStyle ?: FontStyle.Normal, fontSynthesis = style.fontSynthesis ?: FontSynthesis.All, fontFamily = style.fontFamily ?: FontFamily.Default, fontFeatureSettings = style.fontFeatureSettings ?: "", letterSpacing = if (style.letterSpacing.isUnspecified) { DefaultLetterSpacing } else { style.letterSpacing }, baselineShift = style.baselineShift ?: BaselineShift.None, textGeometricTransform = style.textGeometricTransform ?: TextGeometricTransform.None, localeList = style.localeList ?: LocaleList.current, background = style.background.takeOrElse { DefaultBackgroundColor }, textDecoration = style.textDecoration ?: TextDecoration.None, shadow = style.shadow ?: Shadow.None, textAlign = style.textAlign ?: TextAlign.Start, textDirection = resolveTextDirection(direction, style.textDirection), lineHeight = if (style.lineHeight.isUnspecified) DefaultLineHeight else style.lineHeight, textIndent = style.textIndent ?: TextIndent.None ) /** * If [textDirection] is null returns a [TextDirection] based on [layoutDirection]. */ internal fun resolveTextDirection( layoutDirection: LayoutDirection, textDirection: TextDirection? ): TextDirection { return when (textDirection) { TextDirection.Content -> when (layoutDirection) { LayoutDirection.Ltr -> TextDirection.ContentOrLtr LayoutDirection.Rtl -> TextDirection.ContentOrRtl } null -> when (layoutDirection) { LayoutDirection.Ltr -> TextDirection.Ltr LayoutDirection.Rtl -> TextDirection.Rtl } else -> textDirection } }
kotlin
26
0.679666
99
40.277108
415
starcoderdata
<gh_stars>1-10 package day13 import java.io.File data class Point( val x: Int, val y: Int ) data class Paper( val points: Map<Point, Boolean> ) { fun fold(instruction: Instruction): Paper { return when (instruction) { is Instruction.FoldUp -> foldUp(instruction.y) is Instruction.FoldLeft -> foldLeft(instruction.x) } } fun fold(instructions: List<Instruction>): Paper { var paper = this for (instruction in instructions) { paper = paper.fold(instruction) } return paper } fun foldLeft(x: Int): Paper { val newPoints = mutableMapOf<Point, Boolean>() points.keys.forEach { point -> if (point.x < x) { newPoints[point] = true } else if (point.x > x) { val steps = point.x - x val mirroredPoint = Point( x - steps, point.y ) newPoints[mirroredPoint] = true } else { throw IllegalStateException("Point on fold line") } } return Paper(newPoints) } fun foldUp(y: Int): Paper { val newPoints = mutableMapOf<Point, Boolean>() points.keys.forEach { point -> if (point.y < y) { newPoints[point] = true } else if (point.y > y) { val steps = point.y - y val mirroredPoint = Point( point.x, y - steps ) newPoints[mirroredPoint] = true } else { throw IllegalStateException("Point on fold line") } } return Paper(newPoints) } fun countPoints(): Int { return points.size } fun isMarked(x: Int, y: Int): Boolean { return isMarked(Point(x, y)) } fun isMarked(point: Point): Boolean { return points[point] == true } fun dump(): String { val size = size() return buildString { for (y in 0..size.y) { for (x in 0..size.x) { if (isMarked(x, y)) { append('#') } else { append('.') } } appendLine() } }.trim() } fun size(): Point { var x = 0 var y = 0 points.keys.forEach { point -> x = if (point.x > x) point.x else x y = if (point.y > y) point.y else y } return Point(x, y) } } sealed interface Instruction { data class FoldUp( val y: Int ) : Instruction data class FoldLeft( val x: Int ) : Instruction } fun readFromFile(fileName: String): Pair<Paper, List<Instruction>> { return readFromString(File(fileName) .readText()) } fun parsePoint(line: String): Point { val (x, y) = line.split(",") return Point(x.toInt(), y.toInt()) } fun parseInstruction(line: String): Instruction { return when { line.startsWith("fold along x=") -> Instruction.FoldLeft(line.split("=")[1].toInt()) line.startsWith("fold along y=") -> Instruction.FoldUp(line.split("=")[1].toInt()) else -> throw IllegalStateException("Unknown instruction: $line") } } fun readFromString(input: String): Pair<Paper, List<Instruction>> { var parsingPoints = true val points = mutableMapOf<Point, Boolean>() val instructions = mutableListOf<Instruction>() input.lines().forEach { line -> when { line.isEmpty() -> parsingPoints = false parsingPoints -> points[parsePoint(line)] = true else -> instructions.add(parseInstruction(line)) } } return Pair(Paper(points), instructions) } fun part1() { val (paper, instructions) = readFromFile("day13.txt") val instruction = instructions[0] val foldedPaper = paper.fold(instruction) val points = foldedPaper.countPoints() println("Points before fold: ${paper.countPoints()}") println("Points after fold: $points") } fun part2() { val (paper, instructions) = readFromFile("day13.txt") val foldedPaper = paper.fold(instructions) println(foldedPaper.dump()) } fun main() { part2() }
kotlin
28
0.52382
92
23.372222
180
starcoderdata
<reponame>djrain/dagger_study package com.example.example import com.example.example.utils.di.DaggerRootComponent import com.example.example.utils.di.applyAutoInjector import com.jakewharton.threetenabp.AndroidThreeTen import dagger.android.AndroidInjector import dagger.android.support.DaggerApplication import timber.log.Timber class MainApplication : DaggerApplication() { override fun applicationInjector(): AndroidInjector<out DaggerApplication> { return DaggerRootComponent.builder().create(this) } override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } AndroidThreeTen.init(this); applyAutoInjector() } }
kotlin
16
0.740891
80
27.5
26
starcoderdata
<reponame>triandamai/CashierBackend<gh_stars>1-10 package app.trian.cashierservice.model enum class OrderStatus { HOLD, CHECKOUT }
kotlin
5
0.776978
49
19
7
starcoderdata
<filename>src/test/kotlin/com/kru/kotboot/ControllerTest.kt package com.kru.kotboot import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.web.client.TestRestTemplate import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.http.ResponseEntity import org.springframework.boot.web.server.LocalServerPort import org.springframework.core.ParameterizedTypeReference /** * @author [<NAME>](mailto:<EMAIL>) * */ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) class ControllerTest : ApplicationTest() { @LocalServerPort private val port = 8080 @Autowired lateinit var restTemplate: TestRestTemplate protected fun getHeaders(): HttpHeaders { val headers: HttpHeaders //val basicAuth = String(Base64.encode("admin:admin@2018".getBytes(Charsets.UTF_8)), Charsets.UTF_8) headers = HttpHeaders() //headers.add("Authorization", "Basic " + basicAuth) headers.add("Accept", "application/json") //headers.add("Accept", "text/plain") return headers } protected fun createURLWithPort(uri: String): String { return "http://localhost:" + port + uri } protected fun get(uri: String, entity: HttpEntity<*>, clazz: Class<*>): ResponseEntity<*> { return restTemplate .exchange<Any>(createURLWithPort(uri), HttpMethod.GET, entity, ParameterizedTypeReference.forType(clazz)) } protected fun post(uri: String, entity: HttpEntity<*>, clazz: Class<*>): ResponseEntity<*> { return restTemplate .exchange<Any>(createURLWithPort(uri), HttpMethod.POST, entity, ParameterizedTypeReference.forType(clazz)) } protected fun delete(uri: String, entity: HttpEntity<*>, clazz: Class<*>): ResponseEntity<*> { return restTemplate .exchange<Any>(createURLWithPort(uri), HttpMethod.DELETE, entity, ParameterizedTypeReference.forType(clazz)) } protected fun put(uri: String, entity: HttpEntity<*>, clazz: Class<*>): ResponseEntity<*> { return restTemplate .exchange<Any>(createURLWithPort(uri), HttpMethod.PUT, entity, ParameterizedTypeReference.forType(clazz)) } }
kotlin
15
0.691004
108
37.734375
64
starcoderdata
<filename>src/main/kotlin/imgui/imgui/inputs.kt package imgui.imgui import glm_.glm import glm_.i import glm_.vec2.Vec2 import imgui.ImGui.style import imgui.IO import imgui.ImGui.calcTypematicPressedRepeatAmount import imgui.ImGui.io import imgui.MOUSE_INVALID import imgui.g import imgui.internal.Rect interface imgui_inputs { fun getKeyIndex(imguiKey: Int) = io.keyMap[imguiKey] /** is key being held. == io.KeysDown[user_key_index]. note that imgui doesn't know the semantic of each entry of io.KeyDown[]. * Use your own indices/enums according to how your back-end/engine stored them into KeyDown[]! */ fun isKeyDown(userKeyIndex: Int) = if (userKeyIndex < 0) false else io.keysDown[userKeyIndex] /** uses user's key indices as stored in the keys_down[] array. if repeat=true. * uses io.KeyRepeatDelay / KeyRepeatRate */ fun isKeyPressed(userKeyIndex: Int, repeat: Boolean = true) = if (userKeyIndex < 0) false else { val t = io.keysDownDuration[userKeyIndex] when { t == 0f -> true repeat && t > io.keyRepeatDelay -> getKeyPressedAmount(userKeyIndex, io.keyRepeatDelay, io.keyRepeatRate) > 0 else -> false } } /** was key released (went from Down to !Down).. */ fun isKeyReleased(userKeyIndex: Int) = if (userKeyIndex < 0) false else io.keysDownDurationPrev[userKeyIndex] >= 0f && !io.keysDown[userKeyIndex] /** Uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough * that DeltaTime > RepeatRate */ fun getKeyPressedAmount(keyIndex: Int, repeatDelay: Float, repeatRate: Float): Int { if (keyIndex < 0) return 0 assert(keyIndex in 0 until io.keysDown.size) val t = io.keysDownDuration[keyIndex] return calcTypematicPressedRepeatAmount(t, t - io.deltaTime, repeatDelay, repeatRate) } /** is mouse button held */ fun isMouseDown(button: Int): Boolean { assert(button in io.mouseDown.indices) return io.mouseDown[button] } /** is any mouse button held */ val isAnyMouseDown get() = io.mouseDown.any() /** did mouse button clicked (went from !Down to Down) */ fun isMouseClicked(button: Int, repeat: Boolean = false): Boolean { assert(button >= 0 && button < io.mouseDown.size) val t = io.mouseDownDuration[button] if (t == 0f) return true if (repeat && t > io.keyRepeatDelay) { val delay = io.keyRepeatDelay val rate = io.keyRepeatRate if ((glm.mod(t - delay, rate) > rate * 0.5f) != (glm.mod(t - delay - io.deltaTime, rate) > rate * 0.5f)) return true } return false } /** did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime. */ fun isMouseDoubleClicked(button: Int) = io.mouseDoubleClicked[button] /** did mouse button released (went from Down to !Down) */ fun isMouseReleased(button: Int) = io.mouseReleased[button] /** is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold */ fun isMouseDragging(button: Int = 0, lockThreshold: Float = -1f): Boolean { if (!io.mouseDown[button]) return false val lockThreshold = if (lockThreshold < 0f) io.mouseDragThreshold else lockThreshold return io.mouseDragMaxDistanceSqr[button] >= lockThreshold * lockThreshold } /** Test if mouse cursor is hovering given rectangle * NB- Rectangle is clipped by our current clip setting * NB- Expand the rectangle to be generous on imprecise inputs systems (g.style.TouchExtraPadding) * is mouse hovering given bounding rect (in screen space). clipped by current clipping settings. disregarding of * consideration of focus/window ordering/blocked by a popup. */ fun isMouseHoveringRect(r: Rect, clip: Boolean = true) = isMouseHoveringRect(r.min, r.max, clip) fun isMouseHoveringRect(rMin: Vec2, rMax: Vec2, clip: Boolean = true): Boolean { val window = g.currentWindow!! // Clip val rectClipped = Rect(rMin, rMax) if (clip) rectClipped.clipWith(window.clipRect) // Expand for touch input val rectForTouch = Rect(rectClipped.min - style.touchExtraPadding, rectClipped.max + style.touchExtraPadding) return rectForTouch contains io.mousePos } /** We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position */ fun isMousePosValid(mousePos: Vec2? = null) = (mousePos ?: io.mousePos) greaterThan MOUSE_INVALID /** shortcut to io.mousePos provided by user, to be consistent with other calls */ val mousePos get() = io.mousePos /** retrieve backup of mouse positioning at the time of opening popup we have BeginPopup() into */ val mousePosOnOpeningCurrentPopup get() = Vec2(g.currentPopupStack.lastOrNull()?.openMousePos ?: io.mousePos) /** dragging amount since clicking. if lockThreshold < -1.0f uses io.MouseDraggingThreshold * NB: This is only valid if isMousePosValid(). Back-ends in theory should always keep mouse position valid * when dragging even outside the client window. */ fun getMouseDragDelta(button: Int = 0, lockThreshold: Float = -1f): Vec2 { assert(button >= 0 && button < io.mouseDown.size) var lockThreshold = lockThreshold if (lockThreshold < 0f) lockThreshold = io.mouseDragThreshold if (io.mouseDown[button]) if (io.mouseDragMaxDistanceSqr[button] >= lockThreshold * lockThreshold) return io.mousePos - io.mouseClickedPos[button] // Assume we can only get active with left-mouse button (at the moment). return Vec2() } fun resetMouseDragDelta(button: Int = 0) = io.mouseClickedPos.get(button).put(io.mousePos) // NB: We don't need to reset g.io.MouseDragMaxDistanceSqr var mouseCursor /** Get desired cursor type, reset in newFrame(), this is updated during the frame. valid before render(). * If you use software rendering by setting io.mouseDrawCursor ImGui will render those for you */ get() = g.mouseCursor /** set desired cursor type */ set(value) { g.mouseCursor = value } /** Manually override io.wantCaptureKeyboard flag next frame (said flag is entirely left for your application handle). * e.g. force capture keyboard when your widget is being hovered. */ fun captureKeyboardFromApp(capture: Boolean = true) { g.wantCaptureKeyboardNextFrame = capture.i } /** Manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application handle). */ fun captureMouseFromApp(capture: Boolean = true) { g.wantCaptureMouseNextFrame = capture.i } }
kotlin
20
0.676275
153
44.130719
153
starcoderdata
<reponame>HorizonsEndMC/IonCore package net.starlegacy.command.misc import co.aikar.commands.annotation.CommandAlias import net.starlegacy.cache.nations.NationCache import net.starlegacy.cache.nations.PlayerCache import net.starlegacy.command.SLCommand import net.starlegacy.database.Oid import net.starlegacy.database.schema.nations.Nation import net.starlegacy.feature.progression.Levels import net.starlegacy.feature.progression.SLXP import net.starlegacy.util.msg import net.starlegacy.util.multimapOf import org.bukkit.Bukkit import org.bukkit.command.CommandSender import org.bukkit.entity.Player object ListCommand : SLCommand() { @CommandAlias("list|who") fun execute(sender: CommandSender) { val players: Collection<Player> = Bukkit.getOnlinePlayers() if (players.isEmpty()) { sender msg "&c&oNo players online" return } val nationMap = multimapOf<Oid<Nation>?, Player>() for (player in players) { val playerNation: Oid<Nation>? = PlayerCache[player].nation nationMap[playerNation].add(player) } val nationIdsSortedByName: List<Oid<Nation>?> = nationMap.keySet() .sortedBy { id -> id?.let { NationCache[it].name } ?: "_" } for (nationId: Oid<Nation>? in nationIdsSortedByName) { val members: Collection<Player> = nationMap[nationId].sortedBy { SLXP[it] } val nationText = nationId?.let { "&5${NationCache[it].name}" } ?: "&e&oNationless" sender msg "$nationText &8&l:(&d${members.count()}&8&l):&7 ${ members.joinToString { player -> val nationPrefix = PlayerCache[player].nationTag?.let { "&r$it " } ?: "" return@joinToString "&7[&b${Levels[player]}&7] $nationPrefix&7${player.name}" } }" } } }
kotlin
25
0.731388
85
31.921569
51
starcoderdata
<gh_stars>1-10 package de.rki.coronawarnapp.risk import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class RiskLevelTest { @Test fun testRiskLevelChangedFromHighToHigh() { val riskLevelHasChanged = RiskLevel.riskLevelChangedBetweenLowAndHigh( RiskLevel.INCREASED_RISK, RiskLevel.INCREASED_RISK ) assertFalse(riskLevelHasChanged) } @Test fun testRiskLevelChangedFromLowToLow() { val riskLevelHasChanged = RiskLevel.riskLevelChangedBetweenLowAndHigh( RiskLevel.UNKNOWN_RISK_INITIAL, RiskLevel.LOW_LEVEL_RISK ) assertFalse(riskLevelHasChanged) } @Test fun testRiskLevelChangedFromLowToHigh() { val riskLevelHasChanged = RiskLevel.riskLevelChangedBetweenLowAndHigh( RiskLevel.UNKNOWN_RISK_INITIAL, RiskLevel.INCREASED_RISK ) assertTrue(riskLevelHasChanged) } @Test fun testRiskLevelChangedFromHighToLow() { val riskLevelHasChanged = RiskLevel.riskLevelChangedBetweenLowAndHigh( RiskLevel.INCREASED_RISK, RiskLevel.UNKNOWN_RISK_INITIAL ) assertTrue(riskLevelHasChanged) } @Test fun testRiskLevelChangedFromUndeterminedToLow() { val riskLevelHasChanged = RiskLevel.riskLevelChangedBetweenLowAndHigh( RiskLevel.UNDETERMINED, RiskLevel.UNKNOWN_RISK_INITIAL ) assertFalse(riskLevelHasChanged) } @Test fun testRiskLevelChangedFromUndeterminedToHigh() { val riskLevelHasChanged = RiskLevel.riskLevelChangedBetweenLowAndHigh( RiskLevel.UNDETERMINED, RiskLevel.INCREASED_RISK ) assertTrue(riskLevelHasChanged) } @Test fun testRiskLevelChangedFromLowToUndetermined() { val riskLevelHasChanged = RiskLevel.riskLevelChangedBetweenLowAndHigh( RiskLevel.UNKNOWN_RISK_INITIAL, RiskLevel.UNDETERMINED ) assertFalse(riskLevelHasChanged) } @Test fun testRiskLevelChangedFromHighToUndetermined() { val riskLevelHasChanged = RiskLevel.riskLevelChangedBetweenLowAndHigh( RiskLevel.INCREASED_RISK, RiskLevel.UNDETERMINED ) assertTrue(riskLevelHasChanged) } }
kotlin
13
0.681049
78
28.185185
81
starcoderdata
<reponame>LeandroSQ/ledstrip-rgb package quevedo.soares.leandro.ledstriprgb.view.home.singlecolor import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.ColorInt import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.apandroid.colorwheel.gradientseekbar.setBlackToColor import org.koin.androidx.viewmodel.ext.android.sharedViewModel import quevedo.soares.leandro.ledstriprgb.databinding.FragmentLedColorBinding import quevedo.soares.leandro.ledstriprgb.extension.toColorHex import quevedo.soares.leandro.ledstriprgb.view.home.HomeFragmentViewModel private val MINIMUM_IDLE_TIME_TO_UPDATE = 1000 class LEDColorFragment : Fragment() { private lateinit var binding: FragmentLedColorBinding private val viewModel: HomeFragmentViewModel by sharedViewModel() private val navController by lazy { findNavController() } private var currentColor: Int = 0 private var lastUpdateRequestTime = -1L private var autoColorChangeHandler: Handler? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = FragmentLedColorBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) this.setupObservers() this.setupColorWheel() this.setupColorPreview() } private fun setupObservers() { this.viewModel.apply { isAnyRequestAlive.observe(viewLifecycleOwner, { // Inverse because of the GroupDispatcher behaviour binding.idLoader.visibility = if (!it) View.VISIBLE else View.INVISIBLE }) } } private fun setupColorWheel() { binding.idColorWheel.colorChangeListener = this::onHueChange binding.idColorLuminosity.colorChangeListener = this::onBrightnessChange } private fun onHueChange(color: Int) { onColorChange(binding.idColorLuminosity.offset, color) binding.idColorLuminosity.setBlackToColor(color) } private fun onBrightnessChange(alpha: Float, color: Int) { onColorChange(alpha, color) } private fun setupColorPreview() { binding.idColorPreview.setOnClickListener { this.viewModel.setColor(currentColor.toColorHex()) } } private fun onColorChange(alpha: Float, color: Int) { currentColor = getArgb(alpha, color) binding.idColorPreview.background = binding.idColorPreview.background.mutate().apply { setTint(currentColor) } scheduleAutoColorChangeTimer() } private fun scheduleAutoColorChangeTimer() { // Save the last update time this.lastUpdateRequestTime = System.currentTimeMillis() // Cancels all callbacks if any this.autoColorChangeHandler?.removeCallbacksAndMessages(null) // Schedule to one second in future to automatically set the new color to the API this.autoColorChangeHandler = Handler(Looper.getMainLooper()).apply { postDelayed({ // Calculate the elapsed time between now and the last update val now = System.currentTimeMillis() val elapsed = now - lastUpdateRequestTime // If greater than the threshold if (elapsed > MINIMUM_IDLE_TIME_TO_UPDATE) { // Update the LED color viewModel.setColor(currentColor.toColorHex()) lastUpdateRequestTime = now } }, 1000) } } private fun getArgb(alpha: Float, @ColorInt color: Int): Int { val a = (alpha * 255).toInt() // 0x00 - 0xFF ALPHA ALPHA // 0xFF00 - 0xFFFF RED RED // 0xFFFF00 - 0xFFFFFF GREEN GREEN // 0xFFFFFF00 - 0xFFFFFFFF BLUE BLUE return (a shl 24) or color } }
kotlin
28
0.775961
112
29.583333
120
starcoderdata
<reponame>SkPhilipp/cortex package com.hileco.cortex.processing.commands import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.options.option import com.hileco.cortex.ethereum.EthereumBarriers import com.hileco.cortex.processing.commands.Logger.Companion.logger import com.hileco.cortex.processing.database.Network import com.hileco.cortex.processing.web3rpc.Web3Client class BarriersDeployCommand : CliktCommand(name = "barriers-deploy", help = "Deploys barrier programs on the on the ${Network.ETHEREUM_PRIVATE} network") { private val network by option(help = "Network within which to operate").network() override fun run() { if (network != Network.ETHEREUM_PRIVATE) { throw IllegalStateException("This action is only allowed on programs on the ${Network.ETHEREUM_PRIVATE} network") } val web3Client = Web3Client(network) val web3ActiveNetworkId = web3Client.loadNetworkId() if (web3ActiveNetworkId != Network.ETHEREUM_PRIVATE.blockchainId) { throw IllegalStateException("Web3 client is not running against the ${Network.ETHEREUM_PRIVATE} network, instead has network id of $web3ActiveNetworkId") } val ethereumBarriers = EthereumBarriers() ethereumBarriers.all().forEach { ethereumBarrier -> val transactionHash = web3Client.createContract(ethereumBarrier.contractSetupCode) logger.log(network, "${ethereumBarrier.id} was created by transaction $transactionHash") } } }
kotlin
19
0.745466
165
52.241379
29
starcoderdata
/** * Copyright 2020 Materna Information & Communications SE * * 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 de.materna.fegen.core.maven import de.materna.fegen.core.log.FeGenLogger import java.io.* import java.util.* fun classesDirArray(buildOutputDirectory: String): List<File> { return listOf(File(buildOutputDirectory)) } fun resourcesDir(compileSourceRoots: List<String>, logger: FeGenLogger): File { if (compileSourceRoots.size > 1) { logger.warn("FeGen: Multiple compile source roots specified. Resources will only be read from the first one") } return File(compileSourceRoots.get(0)).resolve("resources") } @Throws(IOException::class, FileNotFoundException::class) fun classPath(scanPath: String, logger: FeGenLogger): List<File> { val isWindows = File.separator != "/" val windowsPreCommands = if (isWindows) arrayOf("cmd.exe", "/c ") else arrayOf() var mvnCmd = if (isWindows) ".\\mvnw.cmd" else "./mvnw" if (!File(mvnCmd).exists()) { mvnCmd = "mvn" } val args = arrayOf("dependency:build-classpath", "-f", scanPath, "-Dmdep.outputFile=build_classpath") val processCmd = arrayOf(*windowsPreCommands, mvnCmd, *args) val process = ProcessBuilder().command(*processCmd).start() val stdInput = BufferedReader(InputStreamReader(process.inputStream)) logger.info("Waiting for build-classpath to finish") stdInput.forEachLine { logger.info(it) } if (process.waitFor() != 0) { logger.error("Executing $processCmd failed") } val classpathFile = File("${scanPath}${File.separator}build_classpath") var classpaths = arrayOfNulls<String>(0) val scanner = Scanner(classpathFile) while (scanner.hasNextLine()) { classpaths = scanner.nextLine().split(File.pathSeparator).toTypedArray() logger.warn("classpaths: $classpaths") } scanner.close() classpathFile.delete() return classpaths.map { File(it!!) } }
kotlin
16
0.724715
117
42.911765
68
starcoderdata
<reponame>serebit/titan-bot package com.serebit.autotitan import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.options.flag import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.options.versionOption import com.serebit.autotitan.api.logger import com.serebit.autotitan.internal.EventDelegate import com.serebit.logkat.LogLevel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import net.dv8tion.jda.api.JDABuilder import net.dv8tion.jda.api.entities.Activity import net.dv8tion.jda.api.requests.GatewayIntent import java.util.* const val NAME = "AutoTitan" const val VERSION = "0.7.5" class Cli : CliktCommand(name = "autotitan") { private val token by option("-t", "--token", help = "Specifies the token to use when logging into Discord.") private val prefix by option("-p", "--prefix", help = "Specifies the command prefix to use.") private val trace by option("--trace", help = "Enables verbose log output that tracks program execution.") .flag() init { versionOption(VERSION, names = setOf("-v", "--version")) } override fun run() = runBlocking { if (trace) logger.level = LogLevel.TRACE val config = generateConfig(token, prefix) val delegate = EventDelegate(config) // start loading the modules now, and in the meantime, login to Discord val loadModules = delegate.loadModulesAsync() CoroutineScope(Dispatchers.IO).launch { keepTrying(config, delegate) } // wait for the module loaders to finish loadModules.await() } private tailrec fun keepTrying(config: BotConfig, delegate: EventDelegate) { try { JDABuilder.create(GatewayIntent.getIntents(GatewayIntent.ALL_INTENTS)).apply { setToken(config.token) addEventListeners(delegate) setActivity(Activity.listening("for ${config.prefix}help")) }.build() return // it worked, get out } catch (e: Exception) { println("Network failed to initialize, retrying in 10s...") Thread.sleep(10000) } keepTrying(config, delegate) // it didn't work, try again } private fun generateConfig(token: String?, prefix: String?) = BotConfig.generate()?.let { config -> prefix?.let { config.prefix = it } token?.let { config.copy(token = it) } ?: config } ?: Scanner(System.`in`).use { scanner -> BotConfig( token ?: prompt(scanner, "Enter token:"), prefix ?: prompt(scanner, "Enter command prefix:") ).also { it.serialize() } } private tailrec fun prompt(scanner: Scanner, text: String): String { print("$text\n> ") val input = scanner.nextLine().trim() return if (input.isBlank() || input.contains("\\s".toRegex())) { prompt(scanner, text) } else input } } fun main(args: Array<String>) = Cli().main(args)
kotlin
27
0.660594
112
36.698795
83
starcoderdata
package com.example.musicplayer.ui.home import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.material.ContentAlpha import androidx.compose.material.LocalContentAlpha import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.example.musicplayer.R @Composable fun HomeAppBar( backgroundColor: Color, modifier: Modifier = Modifier ) { TopAppBar( title = { Row { Text( modifier = Modifier .padding(start = 8.dp), text = "Music Player") } }, backgroundColor = backgroundColor, actions = { CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { } }, modifier = modifier ) }
kotlin
25
0.693998
86
29.358974
39
starcoderdata
package ch.famoser.mensa.services.providers import ch.famoser.mensa.services.SerializationService import ch.famoser.mensa.testServices.InMemoryAssetService import ch.famoser.mensa.testServices.NoCacheService import com.google.common.truth.Truth.assertThat import org.junit.Test import java.util.* class ETHMensaProviderTest { private fun getEthLocationsJson(): String { return """ [ { "title": "Zentrum", "mensas": [ { "id": "24e3a71a-ff05-4d20-a8c3-fa24f342c1dc", "title": "Mensa Polyterrasse", "mealTime": "11:00-13:30", "idSlug": 12, "timeSlug": "lunch", "infoUrlSlug": "zentrum/mensa-polyterrasse" } ] } ] """ } @Test fun locationsAndMenu_locationsAndMenuAreLoad() { // arrange val cacheService = NoCacheService() val inMemoryAssetService = InMemoryAssetService(mapOf("eth/locations.json" to getEthLocationsJson())) val serializationService = SerializationService() val provider = ETHMensaProvider(cacheService, inMemoryAssetService, serializationService) val c = Calendar.getInstance() val dayOfWeek = c.get(Calendar.DAY_OF_WEEK) if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) { c.add(Calendar.DAY_OF_WEEK, 2); } val nearestValidDate = Date.from(c.toInstant()) // act val locations = provider.getLocations() val response = provider.getMenus(ETHMensaProvider.MEAL_TIME_LUNCH, nearestValidDate, AbstractMensaProvider.Language.German, true) // assert val polymensa = locations.first().mensas.first() assertThat(response).contains(polymensa) assertThat(locations).hasSize(1) assertThat(locations.first().mensas).hasSize(1) assertThat(locations.first().mensas.filter { it.menus.isNotEmpty() }).isNotEmpty() } }
kotlin
21
0.612098
137
34.931034
58
starcoderdata
<gh_stars>1-10 package com.timcastelijns.chatexchange.chat import com.google.gson.JsonElement import com.google.gson.JsonParser import org.jsoup.HttpStatusException import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.parser.Parser import java.io.IOException import java.io.InputStream import java.nio.file.Files import java.nio.file.Path import java.time.LocalDateTime import java.time.LocalTime import java.time.ZoneOffset import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage import java.util.concurrent.TimeUnit import java.util.function.Supplier import java.util.regex.Pattern class Room( val host: ChatHost, val roomId: Int, private val httpClient: HttpClient, private val cookies: MutableMap<String, String> ) { companion object { private const val SUCCESS = "ok" private const val EDIT_WINDOW_SECONDS = 115 private const val WEB_SOCKET_RESTART_SECONDS = 30L private const val NUMBER_OF_RETRIES_ON_THROTTLE = 5 private val TRY_AGAIN_PATTERN = Pattern.compile("You can perform this action again in (\\d+) seconds") private val CURRENT_USERS_PATTERN = Pattern.compile("\\{id:\\s?(\\d+),") private val FAILED_UPLOAD_PATTERN = Pattern.compile("var error = '(.+)';") private val SUCCESS_UPLOAD_PATTERN = Pattern.compile("var result = '(.+)';") private val MESSAGE_TIME_FORMATTER = DateTimeFormatter.ofPattern("h:mm a").withZone(ZoneOffset.UTC) } var messagePostedEventListener: ((MessagePostedEvent) -> Unit)? = null var messageEditedEventListener: ((MessageEditedEvent) -> Unit)? = null var messageDeletedEventListener: ((MessageDeletedEvent) -> Unit)? = null var messageStarredEventListener: ((MessageStarredEvent) -> Unit)? = null var userEnteredEventListener: ((UserEnteredEvent) -> Unit)? = null var userLeftEventListener: ((UserLeftEvent) -> Unit)? = null var userNotificationEventListener: ((UserNotificationEvent) -> Unit)? = null var userMentionedEventListener: ((UserMentionedEvent) -> Unit)? = null var messageRepliedToEventListener: ((MessageRepliedToEvent) -> Unit)? = null var accessLevelChangedEventListener: ((AccessLevelChangedEvent) -> Unit)? = null private var scheduler = Scheduler() private lateinit var webSocket: WebSocket private var lastWebsocketMessageDate = LocalDateTime.now() private lateinit var fkey: String private var hostUrlBase: String = host.baseUrl private var hasLeft = false private var pingableUserIds = listOf<Long>() private val currentUserIds = mutableSetOf<Long>() init { syncCurrentUsers() setUpRecurringTasks() initWebsocket() } private fun setUpRecurringTasks() { scheduler.scheduleHourlyTask { fkey = retrieveFkey(roomId) } scheduler.scheduleDailyTask { syncPingableUsers() } scheduler.scheduleTaskWithCustomInterval(WEB_SOCKET_RESTART_SECONDS, TimeUnit.SECONDS) { if (ChronoUnit.SECONDS.between(lastWebsocketMessageDate, LocalDateTime.now()) > WEB_SOCKET_RESTART_SECONDS) { resetWebSocket() } } } private fun resetWebSocket() { closeWebSocket() try { Thread.sleep(3000) } catch (e: InterruptedException) { } initWebsocket() } private fun initWebsocket() { var webSocketUrl = post("$hostUrlBase/ws-auth", "roomid", roomId.toString()) .asJsonObject .get("url").asString val time = post("$hostUrlBase/chats/$roomId/events") .asJsonObject .get("time").asString webSocketUrl = "$webSocketUrl?l=$time" webSocket = WebSocket(hostUrlBase) webSocket.chatEventListener = { handleChatEvent(it) } webSocket.open(webSocketUrl) } private fun handleChatEvent(json: String) { lastWebsocketMessageDate = LocalDateTime.now() val events = JsonParser().parse(json) .asJsonObject .extractEventsForRoom(this) events.forEach { event -> when (event) { is MessagePostedEvent -> messagePostedEventListener?.invoke(event) is MessageEditedEvent -> messageEditedEventListener?.invoke(event) is MessageDeletedEvent -> messageDeletedEventListener?.invoke(event) is MessageStarredEvent -> messageStarredEventListener?.invoke(event) is UserEnteredEvent -> { currentUserIds += event.userId userEnteredEventListener?.invoke(event) } is UserLeftEvent -> { currentUserIds -= event.userId userLeftEventListener?.invoke(event) } is UserNotificationEvent -> userNotificationEventListener?.invoke(event) is UserMentionedEvent -> userMentionedEventListener?.invoke(event) is MessageRepliedToEvent -> messageRepliedToEventListener?.invoke(event) is AccessLevelChangedEvent -> accessLevelChangedEventListener?.invoke(event) } } } private fun retrieveFkey(roomId: Int): String { try { val response = httpClient.get("$hostUrlBase/rooms/$roomId", cookies) return response.parse().getElementById("fkey").`val`() } catch (e: IOException) { throw ChatOperationException(e) } } private fun syncPingableUsers() { val json = try { httpClient.get("$hostUrlBase/rooms/pingable/$roomId", cookies) .body() } catch (e: IOException) { throw ChatOperationException(e) } val jsonArray = JsonParser().parse(json).asJsonArray pingableUserIds = jsonArray.map { it.asJsonArray.get(0).asLong } } private fun syncCurrentUsers() { val document = try { httpClient.get("$hostUrlBase/rooms/$roomId", cookies) .parse() } catch (e: IOException) { throw ChatOperationException(e) } val html = document.getElementsByTag("script")[3].html() val matcher = CURRENT_USERS_PATTERN.matcher(html) currentUserIds.clear() while (matcher.find()) { currentUserIds.add(matcher.group(1).toLong()) } } private fun post(url: String, vararg data: String) = post(NUMBER_OF_RETRIES_ON_THROTTLE, url, *data) private fun post(retryCount: Int, url: String, vararg data: String): JsonElement { val response = try { httpClient.postIgnoringErrors(url, cookies, *withFkey(arrayOf(*data))) } catch (e: IOException) { throw ChatOperationException(e) } val body = response.body() if (response.statusCode() == 200) { return JsonParser().parse(body) } val matcher = TRY_AGAIN_PATTERN.matcher(body) if (retryCount > 0 && matcher.find()) { val throttle = matcher.group(1).toLong() try { Thread.sleep(1000 * throttle) } catch (e: InterruptedException) { } return post(retryCount - 1, url, *data) } else { throw ChatOperationException("The chat operation failed with the message: $body") } } private fun withFkey(data: Array<String>): Array<String> { val dataWithFkey = Array(data.size + 2) { "" } dataWithFkey[0] = ("fkey") dataWithFkey[1] = (fkey) System.arraycopy(data, 0, dataWithFkey, 2, data.size) return dataWithFkey } private fun <T> supplyAsync(supplier: Supplier<T>) = CompletableFuture.supplyAsync(supplier, scheduler.executor) .whenComplete { res, t -> if (res != null) { } if (t != null) { } } fun getUser(userId: Long) = getUsers(listOf(userId))[0] private fun getUsers(userIds: Iterable<Long>): List<User> { val ids = userIds.joinToString(separator = ",") { it.toString() } return post("$hostUrlBase/user/info", "ids", ids, "roomId", roomId.toString()) .asJsonObject .extractUsers() .map { it.apply { isCurrentlyInRoom = currentUserIds.contains(id) profileLink = "$hostUrlBase/users/$id" } it } } fun getMessage(messageId: Long): Message { val documentHistory: Document val content: String try { documentHistory = httpClient.get("$hostUrlBase/messages/$messageId/history", cookies, "fkey", fkey).parse() content = Parser.unescapeEntities(httpClient.get("$hostUrlBase/message/$messageId", cookies, "fkey", fkey).body(), false) } catch (e: HttpStatusException) { if (e.statusCode == 404) { // non-RO cannot see deleted message of another user: so if 404, it means message is deleted return Message(messageId, null, null, null, true, 0, false, 0) } throw ChatOperationException(e) } catch (e: IOException) { throw ChatOperationException(e) } val contents = documentHistory.select(".messages .content") val plainContent = contents.get(1).select(".message-source").first().text() val starVoteContainer = documentHistory.select(".messages .flash .stars.vote-count-container").first() val starCount = if (starVoteContainer == null) { 0 } else { val times = starVoteContainer.select(".times").first() if (times == null || !times.hasText()) 1 else times.text().toInt() } val pinned = !documentHistory.select(".vote-count-container.stars.owner-star").isEmpty() val editCount = contents.size - 2 // -2 to remove the current version and the first version val user = getUser(documentHistory.select(".username > a").first().attr("href").split("/")[2].toLong()) val deleted = contents.any { it.getElementsByTag("b").html().equals("deleted") } return Message(messageId, user, plainContent, content, deleted, starCount, pinned, editCount) } fun getPingableUsers() = getUsers(pingableUserIds) private fun getThumbs(): RoomThumbs { val json = try { httpClient.get("$hostUrlBase/rooms/thumbs/$roomId", cookies).body() } catch (e: IOException) { throw ChatOperationException(e) } val jsonObject = JsonParser().parse(json).asJsonObject val tags = Jsoup.parse(jsonObject.get("tags").asString).getElementsByTag("a").map { it.html() } with(jsonObject) { return RoomThumbs(get("id").asInt, get("name").asString, get("description").asString, get("isFavorite").asBoolean, tags) } } fun send(message: String): CompletionStage<Long> { val parts = message.toParts() for (i in 0 until parts.size) { val part = parts[i] supplyAsync(Supplier { val element = post("$hostUrlBase/chats/$roomId/messages/new", "text", part) return@Supplier element.asJsonObject.get("id").asLong }) } val part = parts.last() return supplyAsync(Supplier { val element = post("$hostUrlBase/chats/$roomId/messages/new", "text", part) return@Supplier element.asJsonObject.get("id").asLong }) } fun uploadImage(path: Path): CompletionStage<String> { val inputStream = try { Files.newInputStream(path) } catch (e: IOException) { throw ChatOperationException("Can't open path $path for reading", e) } return uploadImage(path.fileName.toString(), inputStream).whenComplete { _, _ -> try { inputStream.close() } catch (e: IOException) { } } } private fun uploadImage(fileName: String, inputStream: InputStream): CompletionStage<String> = supplyAsync(Supplier { val response = try { httpClient.postWithFile("$hostUrlBase/upload/image", cookies, "filename", fileName, inputStream) } catch (e: IOException) { throw ChatOperationException("Failed to upload image", e) } val html = Jsoup.parse(response.body()).getElementsByTag("script").first().html() val failedUploadMatched = FAILED_UPLOAD_PATTERN.matcher(html) if (failedUploadMatched.find()) { throw ChatOperationException(failedUploadMatched.group(1)) } val successUploadMatcher = SUCCESS_UPLOAD_PATTERN.matcher(html) if (successUploadMatcher.find()) { return@Supplier successUploadMatcher.group(1) } throw ChatOperationException("Failed to upload image") }) fun replyTo(messageId: Long, message: String) = send(":$messageId $message") fun isEditable(messageId: Long): Boolean { try { val documentHistory = httpClient.get("$hostUrlBase/messages/$messageId/history", cookies, "fkey", fkey).parse() val time = LocalTime.parse(documentHistory.getElementsByClass("timestamp").last().html(), MESSAGE_TIME_FORMATTER) return ChronoUnit.SECONDS.between(time, LocalTime.now(ZoneOffset.UTC)) < EDIT_WINDOW_SECONDS } catch (e: IOException) { throw ChatOperationException(e) } } fun delete(messageId: Long) = supplyAsync(Supplier { val result = post("$hostUrlBase/messages/$messageId/delete").asString if (SUCCESS != result) { throw ChatOperationException("Cannot delete message $messageId for reason: $result") } return@Supplier null }) fun toggleStar(messageId: Long) = supplyAsync(Supplier { val result = post("$hostUrlBase/messages/$messageId/star").asString if (SUCCESS != result) { throw ChatOperationException("Cannot star/unstar message $messageId for reason: $result") } return@Supplier null }) fun togglePin(messageId: Long) = supplyAsync(Supplier { val result = post("$hostUrlBase/messages/$messageId/owner-star").asString if (SUCCESS != result) { throw ChatOperationException("Cannot pin/unpin message $messageId for reason: $result") } return@Supplier null }) /** * @param accessLevel 'remove' for default, 'read-write' for write and 'read-only' for read. */ fun setUserAccess(userId: Long, accessLevel: String): CompletionStage<Nothing?> = supplyAsync(Supplier { val result = post("$hostUrlBase/rooms/setuseraccess/$roomId", "aclUserId", userId.toString(), "userAccess", accessLevel).asString if (SUCCESS != result) { throw ChatOperationException("Cannot alter userAccess for reason: $result") } return@Supplier null }) fun leave(quiet: Boolean = true) { if (hasLeft) { return } post("$hostUrlBase/chats/leave/$roomId", "quiet", quiet.toString()) hasLeft = true close() } private fun close() { scheduler.shutDown() closeWebSocket() } private fun closeWebSocket() { webSocket.close() } } private data class RoomThumbs( val id: Int, val name: String, val description: String, val isFavorite: Boolean, val tags: List<String> )
kotlin
28
0.598494
133
36.715935
433
starcoderdata
<filename>foundation/src/main/kotlin/com/neva/javarel/foundation/api/lang/MultimapHelper.kt<gh_stars>1-10 package com.neva.javarel.foundation.api.lang import com.google.common.collect.Maps /** * Provides useful methods for operating on e.g deserialized JSON objects. Notice that all nested maps should * have equal key type - string. */ class MultimapHelper(val pathSeparator: String = ".") { /** * Combine two multi-level maps recursively. */ @Suppress("UNCHECKED_CAST") fun extend(first: MutableMap<String, Any>, second: Map<String, Any>) { for ((key, value) in second) { if (value is Map<*, *>) { if (!first.containsKey(key)) { first.put(key, Maps.newLinkedHashMap<String, Any>()) } extend(first[key] as MutableMap<String, Any>, value as Map<String, Any>) } else { first.put(key, value) } } } /** * Get value from multi-level map. * @param path Keys sequence joined by '/' character) */ @Suppress("UNCHECKED_CAST") operator fun get(map: Map<String, Any>, path: String): Any? { val parts = path.split(pathSeparator.toRegex()).dropLastWhile(String::isEmpty).toTypedArray() var current = map for (i in parts.indices) { val key = parts[i] if (i + 1 < parts.size) { if (!current.containsKey(key)) { break } current = current[key] as Map<String, Any> } else { return current[key] } } return null } /** * Put value into multi-level map. * @param path Keys sequence joined by '/' character) */ @Suppress("UNCHECKED_CAST") fun put(map: MutableMap<String, in Any>, path: String, value: Any) { val parts = path.split(pathSeparator.toRegex()).dropLastWhile(String::isEmpty).toTypedArray() var current: MutableMap<String, in Any> = map for (i in parts.indices) { val key = parts[i] if (i + 1 < parts.size) { if (!current.containsKey(key)) { current.put(key, Maps.newLinkedHashMap<String, Any>()) } current = current[key] as MutableMap<String, Any> } else { current.put(key, value) } } } /** * Remove value from nested multi-level map. * @param path Keys sequence joined by '/' character) */ @Suppress("UNCHECKED_CAST") fun remove(map: MutableMap<String, in Any>, path: String): Boolean { val parts = path.split(pathSeparator.toRegex()).dropLastWhile(String::isEmpty).toTypedArray() var current: MutableMap<String, in Any> = map for (i in parts.indices) { val key = parts[i] if (i + 1 < parts.size) { if (!current.containsKey(key)) { return false } current = current[key] as MutableMap<String, Any> } else if (current.containsKey(key)) { current.remove(key) } } return true } /** * Copy value (or reference!) from one multi-level map to another. * @param path Keys sequence joined by '/' character) */ fun copy(source: Map<String, Any>, target: MutableMap<String, in Any>, path: String) { val value = get(source, path) if (value == null) { remove(target, path) } else { put(target, path, value) } } /** * Move value (or reference!) from one multi-level map to another. * @param path Keys sequence joined by '/' character) */ fun move(source: MutableMap<String, Any>, target: MutableMap<String, Any>, path: String) { copy(source, target, path) remove(source, path) } /** * Find parent map by its child property value. */ @Suppress("UNCHECKED_CAST") fun find(map: Map<String, Any>, property: String, value: Any): Map<String, Any> { var result: Map<String, Any> = mutableMapOf() for ((key, value1) in map) { if (map.containsKey(property) && map[property] == value) { return map } if (value1 is Map<*, *>) { result = find(value1 as Map<String, Any>, property, value) } } return result } }// hidden constructor
kotlin
24
0.541896
109
30.150685
146
starcoderdata
<gh_stars>1-10 package com.ibashkimi.wheel.core import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class User( val uid: String, val displayName: String? = null, val email: String? = null, val nickname: String? = null, val imageUrl: String? = null, val info: String? = null, val followerCount: Int = 0, val followedCount: Int = 0, val createdAt: Long = 0, val lastLogin: Long = 0 ) : Parcelable
kotlin
6
0.66318
39
16.107143
28
starcoderdata
<filename>sources-jvm/builders/MContractBuilder.kt package io.fluidsonic.meta import kotlinx.metadata.* internal class MContractBuilder : KmContractVisitor() { private var effects: MutableList<MEffectBuilder>? = null fun build() = MContract( effects = effects.mapOrEmpty { it.build() } ) override fun visitEffect(type: KmEffectType, invocationKind: KmEffectInvocationKind?) = MEffectBuilder( type = type, invocationKind = invocationKind ) .also { effects?.apply { add(it) } ?: { effects = mutableListOf(it) }() } }
kotlin
26
0.71949
88
20.96
25
starcoderdata
package world.phantasmal.psoserv.servers import world.phantasmal.psolib.Episode import world.phantasmal.psoserv.data.* import world.phantasmal.psoserv.encryption.BbCipher import world.phantasmal.psoserv.encryption.Cipher import world.phantasmal.psoserv.messages.* class BlockServer( private val store: Store, name: String, bindPair: Inet4Pair, private val blockId: Int, ) : GameServer<BbMessage>(name, bindPair) { override val messageDescriptor = BbMessageDescriptor override fun createCipher() = BbCipher() override fun createClientReceiver( ctx: ClientContext<BbMessage>, serverCipher: Cipher, clientCipher: Cipher, ): ClientReceiver<BbMessage> = object : ClientReceiver<BbMessage> { private var client: Client? = null override fun process(message: BbMessage): Boolean { when (message) { is BbMessage.Authenticate -> { val result = store.authenticate( message.username, message.password, ctx::send, ) when (result) { is AuthResult.Ok -> { client = result.client val account = result.client.account val char = account.characters.getOrNull(message.charSlot) if (char == null) { ctx.send( BbMessage.AuthData( AuthStatus.Nonexistent, message.guildCardNo, message.teamId, message.charSlot, message.charSelected, ) ) } else { result.client.setPlaying(char, blockId) ctx.send( BbMessage.AuthData( AuthStatus.Success, account.guildCardNo, account.teamId, message.charSlot, message.charSelected, ) ) val lobbies = store.getLobbies(blockId) ctx.send(BbMessage.LobbyList(lobbies.map { it.id })) ctx.send( BbMessage.FullCharacterData( // TODO: Fill in char data correctly. PsoCharData( hp = 0, level = char.level - 1, exp = char.exp, sectionId = char.sectionId.ordinal.toByte(), charClass = 0, name = char.name, ), ) ) ctx.send(BbMessage.GetCharData()) } } AuthResult.BadPassword -> { ctx.send( BbMessage.AuthData( AuthStatus.Nonexistent, message.guildCardNo, message.teamId, message.charSlot, message.charSelected, ) ) } AuthResult.AlreadyLoggedIn -> { ctx.send( BbMessage.AuthData( AuthStatus.Error, message.guildCardNo, message.teamId, message.charSlot, message.charSelected, ) ) } } return true } is BbMessage.CharData -> { val client = client ?: return false val lobby = store.joinFirstAvailableLobby(blockId, client) ?: return false val clientId = client.id ctx.send( BbMessage.JoinLobby( clientId = clientId, leaderId = 0, // TODO: What should leaderId be in lobbies? disableUdp = true, lobbyNo = lobby.id.toUByte(), blockNo = blockId.toUShort(), event = 0u, players = lobby.getClients().mapNotNull { c -> c.playing?.let { LobbyPlayer( playerTag = 0, guildCardNo = it.account.guildCardNo, clientId = c.id, charName = it.char.name, ) } } ) ) // Notify other clients. client.playing?.let { playingAccount -> val joinedMessage = BbMessage.JoinedLobby( clientId = clientId, leaderId = 0, // TODO: What should leaderId be in lobbies? disableUdp = true, lobbyNo = lobby.id.toUByte(), blockNo = blockId.toUShort(), event = 0u, player = LobbyPlayer( playerTag = 0, guildCardNo = playingAccount.account.guildCardNo, clientId = clientId, charName = playingAccount.char.name, ), ) lobby.broadcastMessage(joinedMessage, exclude = client) } return true } is BbMessage.CreateParty -> { val client = client ?: return false val difficulty = when (message.difficulty.toInt()) { 0 -> Difficulty.Normal 1 -> Difficulty.Hard 2 -> Difficulty.VHard 3 -> Difficulty.Ultimate else -> return false } val episode = when (message.episode.toInt()) { 1 -> Episode.I 2 -> Episode.II 3 -> Episode.IV else -> return false } val mode = when { message.battleMode -> Mode.Battle message.challengeMode -> Mode.Challenge message.soloMode -> Mode.Solo else -> Mode.Normal } val result = store.createAndJoinParty( blockId, message.name, message.password, difficulty, episode, mode, client, ) when (result) { is CreateAndJoinPartyResult.Ok -> { val party = result.party val details = party.details // TODO: Send lobby leave message to all clients. ctx.send(BbMessage.JoinParty( players = party.getClients().mapNotNull { c -> c.playing?.let { LobbyPlayer( playerTag = 0, guildCardNo = it.account.guildCardNo, clientId = c.id, charName = it.char.name, ) } }, clientId = client.id, leaderId = party.leaderId, difficulty = when (details.difficulty) { Difficulty.Normal -> 0 Difficulty.Hard -> 1 Difficulty.VHard -> 2 Difficulty.Ultimate -> 3 }, battleMode = details.mode == Mode.Battle, event = 0, sectionId = 0, challengeMode = details.mode == Mode.Challenge, prngSeed = 0, episode = when (details.episode) { Episode.I -> 1 Episode.II -> 2 Episode.IV -> 3 }, soloMode = details.mode == Mode.Solo, )) // TODO: Send player join message to other clients. return true } is CreateAndJoinPartyResult.NameInUse -> { // TODO: Just send message instead of disconnecting. return false } is CreateAndJoinPartyResult.AlreadyInParty -> { logger.warn { "${client.account} tried to create a party while in a party." } return true } } } is BbMessage.Broadcast -> { // TODO: Verify broadcast messages. client?.lop?.broadcastMessage(message, client) return true } is BbMessage.Disconnect -> { // Log out and disconnect. logOut() return false } else -> return ctx.unexpectedMessage(message) } } override fun connectionClosed() { logOut() } private fun logOut() { try { client?.let(store::logOut) } finally { client = null } } } }
kotlin
40
0.337521
93
40.637011
281
starcoderdata
package org.purescript.psi.classes import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.PsiNameIdentifierOwner import org.purescript.psi.name.PSProperName import org.purescript.psi.PSPsiElement import org.purescript.psi.name.PSClassName import org.purescript.psi.typevar.PSTypeVarBinding /** * A class declaration, e.g. * ``` * class Foldable f <= FoldableWithIndex i f | f -> i where * foldrWithIndex :: forall a b. (i -> a -> b -> b) -> b -> f a -> b * foldlWithIndex :: forall a b. (i -> b -> a -> b) -> b -> f a -> b * foldMapWithIndex :: forall a m. Monoid m => (i -> a -> m) -> f a -> m * ``` */ class PSClassDeclaration(node: ASTNode) : PSPsiElement(node), PsiNameIdentifierOwner { internal val classConstraintList: PSClassConstraintList? get() = findChildByClass(PSClassConstraintList::class.java) internal val className: PSClassName get() = findNotNullChildByClass(PSClassName::class.java) internal val typeVarBindings: Array<PSTypeVarBinding> get() = findChildrenByClass(PSTypeVarBinding::class.java) internal val functionalDependencyList: PSClassFunctionalDependencyList? get() = findChildByClass(PSClassFunctionalDependencyList::class.java) internal val classMemberList: PSClassMemberList? get() = findChildByClass(PSClassMemberList::class.java) /** * @return the [PSClassMember] elements in this declaration, * or an empty array if [classConstraintList] is null. */ val classConstraints: Array<PSClassConstraint> get() = classConstraintList?.classConstraints ?: emptyArray() /** * @return the [PSClassMember] elements in this declaration, * or an empty array if [classMemberList] is null. */ val classMembers: Array<PSClassMember> get() = classMemberList?.classMembers ?: emptyArray() override fun getName(): String = className.name override fun setName(name: String): PsiElement? = null override fun getNameIdentifier(): PsiElement = className override fun getTextOffset(): Int = className.textOffset }
kotlin
11
0.703513
77
34.583333
60
starcoderdata
<reponame>khalp/surface-duo-sdk<filename>screenmanager/wm/screenmanager-windowmanager/src/main/java/com/microsoft/device/dualscreen/ScreenManagerProvider.kt /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ package com.microsoft.device.dualscreen import android.app.Application import java.lang.IllegalStateException /** * Utility class used to initialize and retrieve [SurfaceDuoScreenManager] object. */ object ScreenManagerProvider { private var instance: SurfaceDuoScreenManager? = null /** * Use this method to initialize the screen manager object inside [Application.onCreate] */ @JvmStatic @Synchronized fun init(application: Application) { instance = SurfaceDuoScreenManagerImpl(application) } /** * @return the singleton instance of [SurfaceDuoScreenManager] */ @JvmStatic @Synchronized fun getScreenManager(): SurfaceDuoScreenManager { return instance ?: throw IllegalStateException(this::javaClass.toString() + " must be initialized inside Application#onCreate()") } }
kotlin
18
0.742194
156
31.057143
35
starcoderdata
package com.kinsight.kinsightmultiplatform.kinsightandroidsharedlibrary.ViewModels.Notifications import android.app.Activity import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.PendingIntent.FLAG_UPDATE_CURRENT import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.kinsight.kinsightmultiplatform.kinsightandroidsharedlibrary.R //import android.support.v4.app.NotificationManagerCompat //import android.support.v4.app.NotificationCompat.WearableExtender object NotificationHelper { /** * Sets up the notification channels for API 26+. * Note: This uses package name + channel name to create unique channelId's. * * @param context application context * @param importance importance level for the notificaiton channel * @param showBadge whether the channel should have a notification badge * @param name name for the notification channel * @param description description for the notification channel */ fun createNotificationChannel(context: Context, importance: Int, showBadge: Boolean, name: String, description: String) { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channelId = "${context.packageName}-kinsight" val channel = NotificationChannel(channelId, name, importance) channel.description = description channel.setShowBadge(showBadge) // Register the channel with the system val notificationManager = context.getSystemService(NotificationManager::class.java) notificationManager.createNotificationChannel(channel) println("notification channel created") val notChannel = notificationManager.getNotificationChannel(channelId) println(notChannel) } } /** * Helps issue the default application channels (package name + app name) notifications. * @param context current application context * @param title title for the notification * @param message content text for the notification when it's not expanded * @param bigText long form text for the expanded notification * @param autoCancel `true` or `false` for auto cancelling a notification. * if this is true, a [PendingIntent] is attached to the notification to * open the application. */ fun sendNotification(activity: Activity, context: Context, title: String, message: String, bigText: String, autoCancel: Boolean, ideaId: Int = 0) { val channelId = "${context.packageName}-kinsight" val intent = Intent(context, activity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP // intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP intent.putExtra("notificationExtra", ideaId) // setContentIntent(intent) val pendingIntent = PendingIntent.getActivity(context, 0, intent, FLAG_UPDATE_CURRENT) val mainAction = NotificationCompat.Action.Builder( R.drawable.ic_fish_24, "Open", pendingIntent) .build() val notificationBuilder = NotificationCompat.Builder(context, channelId).apply { setSmallIcon(R.drawable.ic_fish_24) setColor(Color.YELLOW) /*setLargeIcon( BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_fish_24))*/ setContentTitle(title) setContentText(message) setShowWhen(true) // setAutoCancel(autoCancel) // setSound(defaultSoundUri) // setStyle(NotificationCompat.BigTextStyle().bigText(bigText)) priority = NotificationCompat.PRIORITY_MAX setAutoCancel(false) val wearableExtender = NotificationCompat.WearableExtender() addAction(mainAction) extend(wearableExtender) /* val actionExtender = NotificationCompat.Action.WearableExtender() .setHintLaunchesActivity(true) .setHintDisplayActionInline(true) wearableExtender.addAction(actionBuilder.extend(actionExtender).build())*/ // val pendingIntent = PendingIntent.getActivity(context, 0, intent, FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_SINGLE_TOP) // setContentIntent(pendingIntent) } val notificationManager = NotificationManagerCompat.from(context) notificationManager.notify(1001, notificationBuilder.build()) } }
kotlin
19
0.688436
131
41.440678
118
starcoderdata
package org.buffer.android.boilerplate.ui.injection.module import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import dagger.Binds import dagger.MapKey import dagger.Module import dagger.multibindings.IntoMap import org.buffer.android.boilerplate.presentation.ViewModelFactory import org.buffer.android.boilerplate.presentation.browse.BrowseBufferoosViewModel import kotlin.reflect.KClass /** * Annotation class to identify view models by classname. */ @MustBeDocumented @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) @MapKey annotation class ViewModelKey(val value: KClass<out ViewModel>) /** * Module that provides all dependencies from the presentation package/layer. */ @Module abstract class PresentationModule { @Binds @IntoMap @ViewModelKey(BrowseBufferoosViewModel::class) abstract fun bindBrowseBufferoosViewModel(viewModel: BrowseBufferoosViewModel): ViewModel @Binds abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory }
kotlin
10
0.825352
93
29.428571
35
starcoderdata
package com.airbnb.mvrx.rxjava2 internal data class MvRxTuple1<A>(val a: A) internal data class MvRxTuple2<A, B>(val a: A, val b: B) internal data class MvRxTuple3<A, B, C>(val a: A, val b: B, val c: C) internal data class MvRxTuple4<A, B, C, D>(val a: A, val b: B, val c: C, val d: D) internal data class MvRxTuple5<A, B, C, D, E>(val a: A, val b: B, val c: C, val d: D, val e: E) internal data class MvRxTuple6<A, B, C, D, E, F>(val a: A, val b: B, val c: C, val d: D, val e: E, val f: F) internal data class MvRxTuple7<A, B, C, D, E, F, G>( val a: A, val b: B, val c: C, val d: D, val e: E, val f: F, val g: G )
kotlin
5
0.596273
108
36.882353
17
starcoderdata
<gh_stars>10-100 package com.lehaine.littlekt.graphics.font.internal import com.lehaine.littlekt.graphics.font.* import kotlin.math.max /** * @author <NAME> * @date 1/5/2022 */ internal class GpuGlyphCompiler { fun compile(glyph: TtfGlyph): List<Bezier> { // Tolerance for error when approximating cubic beziers with quadratics. // Too low and many quadratics are generated (slow), too high and not // enough are generated (looks bad). 5% works pretty well. val c2qResolution = max((((glyph.width + glyph.height) / 2) * 0.05f).toInt(), 1) val beziers = decompose(glyph, c2qResolution) if (glyph.xMin != 0 || glyph.yMin != 0) { translateBeziers(beziers, glyph.xMin, glyph.yMin) } // TODO calculate if glyph orientation is clockwise or counter clockwise. If, CCW then we need to flip the beziers val counterClockwise = false //glyph.orientation == FILL_LEFT if (counterClockwise) { flipBeziers(beziers) } return beziers } private fun flipBeziers(beziers: ArrayList<Bezier>) { beziers.forEach { bezier -> bezier.p0.x = bezier.p1.x.also { bezier.p1.x = bezier.p0.x } bezier.p0.y = bezier.p1.y.also { bezier.p1.y = bezier.p0.y } } } private fun decompose(glyph: TtfGlyph, c2qResolution: Int): ArrayList<Bezier> { if (glyph.path.isEmpty() || glyph.numberOfContours <= 0) { return ArrayList() } val curves = ArrayList<Bezier>(glyph.numberOfContours) val quadBeziers = Array(24) { QuadraticBezier(0f, 0f, 0f, 0f, 0f, 0f) } var startX = 0f var startY = 0f var prevX = 0f var prevY = 0f glyph.path.commands.forEach { cmd -> when (cmd.type) { GlyphPath.CommandType.MOVE_TO -> { startX = cmd.x startY = cmd.y prevX = cmd.x prevY = cmd.y } GlyphPath.CommandType.LINE_TO -> { curves += Bezier().apply { p0.set(prevX, prevY) control.set(prevX, prevY) p1.set(cmd.x, cmd.y) } prevX = cmd.x prevY = cmd.y } GlyphPath.CommandType.CURVE_TO -> { val cubicBezier = CubicBezier(prevX, prevY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y) val totalBeziers = 6 * cubicBezier.convertToQuadBezier(c2qResolution, quadBeziers) for (i in 0 until totalBeziers step 6) { val quadBezier = quadBeziers[i] curves += Bezier().apply { p0.set(quadBezier.p1x, quadBezier.p1y) control.set(quadBezier.c1x, quadBezier.c1y) p1.set(quadBezier.p2x, quadBezier.p2y) } } prevX = cmd.x prevY = cmd.y } GlyphPath.CommandType.QUADRATIC_CURVE_TO -> { curves += Bezier().apply { p0.set(prevX, prevY) control.set(cmd.x1, cmd.y1) p1.set(cmd.x, cmd.y) } prevX = cmd.x prevY = cmd.y } GlyphPath.CommandType.CLOSE -> { prevX = startX prevY = startY } } } return curves } private fun translateBeziers(beziers: ArrayList<Bezier>, xMin: Int, yMin: Int) { beziers.forEach { it.p0.x -= xMin it.p0.y -= yMin it.p1.x -= xMin it.p1.y -= yMin it.control.x -= xMin it.control.y -= yMin } } }
kotlin
30
0.489261
122
34.75
112
starcoderdata
<reponame>masfian77/kotlin // FIR_IDENTICAL // FIR_COMPARISON seal<caret> open class A // ABSENT: "sealed"
kotlin
3
0.745283
26
20.4
5
starcoderdata
<gh_stars>10-100 // WITH_RUNTIME fun test(a: String, b: String?): Boolean { return <caret>a.toLowerCase() == b?.toLowerCase() }
kotlin
9
0.656489
53
25.4
5
starcoderdata
<reponame>goncaloperes/intellij-rust /* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter.processors import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiRecursiveElementVisitor import com.intellij.psi.impl.source.codeStyle.PreFormatProcessor import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RsElementTypes.SEMICOLON import org.rust.lang.core.psi.ext.elementType import org.rust.lang.core.psi.ext.getNextNonCommentSibling class RsStatementSemicolonFormatProcessor : PreFormatProcessor { override fun process(node: ASTNode, range: TextRange): TextRange { if (!shouldRunPunctuationProcessor(node)) return range val elements = arrayListOf<PsiElement>() node.psi.accept(object : PsiRecursiveElementVisitor() { override fun visitElement(element: PsiElement) { if (element.textRange in range) { super.visitElement(element) } // no semicolons inside "match" if (element.parent !is RsMatchArm) { if (element is RsRetExpr || element is RsBreakExpr || element is RsContExpr) { elements.add(element) } } } }) return range.grown(elements.count(::tryAddSemicolonAfter)) } private fun tryAddSemicolonAfter(element: PsiElement): Boolean { val nextSibling = element.getNextNonCommentSibling() if (nextSibling == null || nextSibling.elementType != SEMICOLON) { val psiFactory = RsPsiFactory(element.project) element.parent.addAfter(psiFactory.createSemicolon(), element) return true } return false } }
kotlin
25
0.665961
98
34.641509
53
starcoderdata
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.vk.knet.cornet.experiment import android.os.SystemClock import com.vk.knet.core.http.HttpRequest import com.vk.knet.core.http.metric.HttpMetricsListener import com.vk.knet.core.http.metric.HttpResponseMeta import com.vk.knet.cornet.ext.addHeaders import com.vk.knet.cornet.ext.toHttpMetrics import com.vk.knet.cornet.ext.toHttpProtocol import com.vk.knet.cornet.pool.thread.CronetExecutor import org.chromium.net.ExperimentalCronetEngine import org.chromium.net.RequestFinishedInfo import org.chromium.net.UploadDataProvider import org.chromium.net.UrlRequest import java.util.concurrent.Executors class CronetConnectionBuilder( private val engine: ExperimentalCronetEngine, private val metric: HttpMetricsListener? ) { private val executorMetric = Executors.newSingleThreadExecutor { runnable -> Thread(runnable, "Cronet-Requests-Metrics") } fun buildRequest( request: HttpRequest, executor: CronetExecutor, callback: UrlRequest.Callback, provider: UploadDataProvider? ): UrlRequest { // since all metrics inside cornet in absolute values of time we write our own val requestInitTime = SystemClock.elapsedRealtime() val requestInitTimestamp = System.currentTimeMillis() // Callback, called when the request finishes its work (no matter what the reason) val requestCompleteHandler = object : RequestFinishedInfo.Listener(executorMetric) { override fun onRequestFinished(requestInfo: RequestFinishedInfo) { // Scattering an event about HttpMetrics if (metric != null) { val info = requestInfo.responseInfo if (info == null) { val metrics = requestInfo.toHttpMetrics(requestInitTime, requestInitTimestamp, null) metric.onMetricsCollected(metrics, request, null) return } val headers = info.allHeaders val contentType = headers.getHeader("Content-Type") val contentLength = headers.getHeader("Content-Length")?.toLongOrNull() val data = HttpResponseMeta( info.httpStatusCode, info.httpStatusText, contentType, contentLength, requestInfo.responseInfo?.negotiatedProtocol?.toHttpProtocol(), headers ) val metrics = requestInfo.toHttpMetrics(requestInitTime, requestInitTimestamp, data) metric.onMetricsCollected(metrics, request, data) } } } // Form the urlRequest used by Cronet to launch the request return engine .newUrlRequestBuilder(request.url, callback, executor) .disableCache() .setHttpMethod(request.method.methodName) .setRequestFinishedListener(requestCompleteHandler) .addHeaders(request.headers) .apply { val requestBody = request.body if (requestBody != null && provider != null) { if (request.getHeaders("Content-Type") == null) { addHeader("Content-Type", requestBody.getContentType()) } if (request.getHeaders("Content-Length") == null) { addHeader("Content-Length", requestBody.getContentLength().toString()) } setUploadDataProvider(provider, executor) } } .build() } private fun Map<String, List<String>>.getHeader(name: String): String? { return get(name)?.joinToString() ?: get(name.lowercase())?.joinToString() } }
kotlin
28
0.643509
108
40.983333
120
starcoderdata
package me.saket.dank.reddit.jraw import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import io.reactivex.schedulers.Schedulers.io import me.saket.dank.data.FullNameType.* import me.saket.dank.data.PaginationAnchor import me.saket.dank.reddit.Reddit import me.saket.dank.ui.user.messages.InboxFolder import net.dean.jraw.RedditClient import net.dean.jraw.models.* import net.dean.jraw.oauth.AccountHelper class JrawLoggedInUser(private val clients: Observable<RedditClient>, private val accountHelper: AccountHelper) : Reddit.LoggedInUser { @Suppress("DEPRECATION") override fun about(): Single<Account> { return clients .firstOrError() .map { it.me().about() } } override fun logout(): Completable { clients .firstOrError() .flatMapCompletable { Completable.fromAction { it.authManager.revokeAccessToken() } } .onErrorComplete() .subscribeOn(io()) .subscribe() return Completable.fromAction { accountHelper.logout() accountHelper.switchToUserless() } } override fun reply(parent: Identifiable, body: String): Single<out Identifiable> { return clients .firstOrError() .map<Identifiable> { when (parse(parent.fullName)) { COMMENT -> it.comment(parent.id).reply(body) SUBMISSION -> it.submission(parent.id).reply(body) MESSAGE -> it.me().inbox().replyTo(parent.fullName, body) else -> throw AssertionError("Unknown contribution for reply: $parent") } } } override fun vote(thing: Identifiable, voteDirection: VoteDirection): Completable { return clients .firstOrError() .flatMapCompletable { Completable.fromAction { when (thing) { is Comment -> it.comment(thing.id).setVote(voteDirection) is Submission -> it.submission(thing.id).setVote(voteDirection) else -> throw AssertionError("Unknown contribution for vote: $thing") } } } } override fun messages(folder: InboxFolder, limit: Int, paginationAnchor: PaginationAnchor): Single<Iterator<Listing<Message>>> { return clients .firstOrError() .map { it.me().inbox() .iterate(folder.value) .limit(limit) .customAnchor(paginationAnchor.fullName()) .build() .iterator() } } override fun setMessagesRead(read: Boolean, vararg messages: Identifiable): Completable { val firstMessageFullName = messages.first().fullName val otherMessageFullNames = messages .filterIndexed { index, _ -> index > 0 } .map { it.fullName } .toTypedArray() return clients .firstOrError() .flatMapCompletable { Completable.fromAction { it.me().inbox().markRead(read, firstMessageFullName, *otherMessageFullNames) } } } override fun setAllMessagesRead(): Completable { return clients .firstOrError() .flatMapCompletable { Completable.fromAction { it.me().inbox().markAllRead() } } } }
kotlin
28
0.651458
135
31.875
96
starcoderdata
package to fun f(t: a.b.c.A): a.b.c.B = a.b.c.B()
kotlin
8
0.52
38
16
3
starcoderdata
// "Create class 'Foo'" "true" class A<T>(val n: T) { } fun test() { val a = A(1).<caret>Foo(2) }
kotlin
11
0.5
30
10.666667
9
starcoderdata
<filename>j2k/new/testData/newJ2k/detectProperties/InCompanionObject.kt class AAA { fun foo() { x = x + 1 } companion object { var x = 42 } }
kotlin
8
0.58046
71
16.5
10
starcoderdata
<filename>tmp/arrays/kt15196.kt<gh_stars>100-1000 // KJS_WITH_FULL_RUNTIME // WITH_RUNTIME fun foo() { val array = Array(0, { IntArray(0) } ) array.forEach { println(it.asList()) } } fun box(): String { foo() // just to be sure, that no exception happens return "OK" }
kotlin
16
0.636364
55
22.833333
12
starcoderdata
<gh_stars>10-100 package org.jetbrains.cabal.util import com.intellij.openapi.externalSystem.model.ProjectSystemId val SYSTEM_ID: ProjectSystemId = ProjectSystemId("CABAL")
kotlin
7
0.818182
64
24.142857
7
starcoderdata
<reponame>Kinway050/bk-ci<gh_stars>1000+ /* * Tencent is pleased to support the open source community by making BK-CI 蓝鲸持续集成平台 available. * * Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. * * BK-CI 蓝鲸持续集成平台 is licensed under the MIT license. * * A copy of the MIT License is included in this file. * * * Terms of the MIT License: * --------------------------------------------------- * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.tencent.bkrepo.common.storage.innercos.http import com.tencent.bkrepo.common.storage.innercos.exception.InnerCosException import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.slf4j.LoggerFactory import java.io.IOException import java.net.HttpURLConnection.HTTP_NOT_FOUND import java.nio.charset.Charset import java.util.concurrent.TimeUnit object CosHttpClient { private val logger = LoggerFactory.getLogger(CosHttpClient::class.java) private const val CONNECT_TIMEOUT = 30L private const val WRITE_TIMEOUT = 30L private const val READ_TIMEOUT = 30L private val client = OkHttpClient().newBuilder() .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) .build() fun <T> execute(request: Request, handler: HttpResponseHandler<T>): T { val response = try { client.newCall(request).execute() } catch (exception: IOException) { val message = buildMessage(request) throw InnerCosException("Failed to execute http request: $message", exception) } return resolveResponse(request, response, handler) } private fun <T> resolveResponse(request: Request, response: Response, handler: HttpResponseHandler<T>): T { response.useOnCondition(!handler.keepConnection()) { try { if (it.isSuccessful) { return handler.handle(it) } else if (it.code() == HTTP_NOT_FOUND) { val handle404Result = handler.handle404() if (handle404Result != null) { return handle404Result } } throw IOException("Response status error") } catch (exception: IOException) { val message = buildMessage(request, it) throw InnerCosException("Failed to execute http request: $message", exception) } } } private fun buildMessage(request: Request, response: Response? = null): String { val requestTitle = "${request.method()} ${request.url()} ${response?.protocol()}" val builder = StringBuilder() .append(">>>> ") .appendln(requestTitle) .appendln(request.headers()) if (response != null) { builder.append("<<<< ") .append(requestTitle) .append(response.code()) .appendln("[${response.message()}]") .appendln(response.headers()) .appendln(response.body()?.bytes()?.toString(Charset.forName("GB2312"))) } val message = builder.toString() logger.warn(message) return message } }
kotlin
23
0.652424
111
40.066038
106
starcoderdata
package com.egoriku.ladyhappy.postcreator.domain.model.image import android.net.Uri data class ImageItem(val uri: Uri)
kotlin
5
0.825
60
23.2
5
starcoderdata
package org.simple.clinic.teleconsultlog.prescription.patientinfo import com.spotify.mobius.rx2.RxMobius import io.reactivex.ObservableTransformer import org.simple.clinic.patient.PatientRepository import org.simple.clinic.util.extractIfPresent import org.simple.clinic.util.scheduler.SchedulersProvider import javax.inject.Inject class TeleconsultPatientInfoEffectHandler @Inject constructor( private val patientRepository: PatientRepository, private val schedulersProvider: SchedulersProvider ) { fun build(): ObservableTransformer<TeleconsultPatientInfoEffect, TeleconsultPatientInfoEvent> { return RxMobius .subtypeEffectHandler<TeleconsultPatientInfoEffect, TeleconsultPatientInfoEvent>() .addTransformer(LoadPatientProfile::class.java, loadPatientProfile()) .build() } private fun loadPatientProfile(): ObservableTransformer<LoadPatientProfile, TeleconsultPatientInfoEvent> { return ObservableTransformer { effects -> effects .observeOn(schedulersProvider.io()) .map { patientRepository.patientProfileImmediate(it.patientUuid) } .extractIfPresent() .map(::PatientProfileLoaded) } } }
kotlin
27
0.783557
108
37.451613
31
starcoderdata
package com.yalantis.library /** * Created by anna on 11/16/17. */ enum class AnimationCycle { NO_ANIMATION, ANIMATION_START, ANIMATION_IN_PROGRESS }
kotlin
4
0.724359
56
18.625
8
starcoderdata
<gh_stars>0 /* * Copyright 2018 Google Inc. All rights reserved. * * 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 kg.delletenebre.yamus.viewmodels import android.support.v4.media.MediaBrowserCompat import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import kg.delletenebre.yamus.common.MediaSessionConnection import kg.delletenebre.yamus.media.extensions.id import kg.delletenebre.yamus.media.extensions.isPlayEnabled import kg.delletenebre.yamus.media.extensions.isPlaying import kg.delletenebre.yamus.media.extensions.isPrepared import kg.delletenebre.yamus.media.library.CurrentPlaylist import kg.delletenebre.yamus.utils.Event import kotlinx.coroutines.Job /** * Small [ViewModel] that watches a [MediaSessionConnection] to become connected * and provides the root/initial media ID of the underlying [MediaBrowserCompat]. */ class MainActivityViewModel( val mediaSessionConnection: MediaSessionConnection ) : ViewModel() { /** * [navigateToMediaItem] acts as an "event", rather than state. [Observer]s * are notified of the change as usual with [LiveData], but only one [Observer] * will actually read the data. For more information, check the [Event] class. */ // val navigateToMediaItem: LiveData<Event<String>> get() = _navigateToMediaItem // private val _navigateToMediaItem = MutableLiveData<Event<String>>() /** * This [LiveData] object is used to notify the MainActivity that the main * content fragment needs to be swapped. Information about the new fragment * is conveniently wrapped by the [Event] class. */ // val navigateToFragment: LiveData<Event<FragmentNavigationRequest>> get() = _navigateToFragment // private val _navigateToFragment = MutableLiveData<Event<FragmentNavigationRequest>>() private var currentJob: Job? = null // fun trackClicked(clickedTrack: Track, tracks: List<Track>) { // currentJob?.cancel() // currentJob = viewModelScope.launch { // CurrentPlaylist.batchId = "" // CurrentPlaylist.updatePlaylist("playlist", tracks, CurrentPlaylist.TYPE_TRACKS) // playTrack(clickedTrack, pauseAllowed = true) // currentJob = null // } // } // fun trackClicked(clickedTrack: Track, tracks: List<Track>, playlistIdentifier: String) { // if (CurrentPlaylist.id == playlistIdentifier) { // playTrack(clickedTrack, pauseAllowed = true) // } else { // currentJob?.cancel() // currentJob = viewModelScope.launch { // CurrentPlaylist.batchId = "" // CurrentPlaylist.updatePlaylist(playlistIdentifier, tracks, CurrentPlaylist.TYPE_TRACKS) // playTrack(clickedTrack, pauseAllowed = true) // currentJob = null // } // } // } // // fun stationClicked(station: Station) { // viewModelScope.launch { // playStation(station.getId()) // } // } fun playTrack(trackId: String, pauseAllowed: Boolean = true) { val currentTrack = CurrentPlaylist.currentTrack.value val transportControls = mediaSessionConnection.transportControls val isPrepared = mediaSessionConnection.playbackState.value?.isPrepared ?: false if (isPrepared && trackId == currentTrack?.id) { mediaSessionConnection.playbackState.value?.let { playbackState -> when { playbackState.isPlaying -> { if (pauseAllowed) { transportControls.pause() } else { Unit } } playbackState.isPlayEnabled -> { transportControls.play() } else -> { Log.w( TAG, "Playable item clicked but neither play nor pause are enabled!" + " (mediaId=$trackId)" ) } } } } else { transportControls.playFromMediaId(trackId, null) } } fun playStation(mediaId: String) { val transportControls = mediaSessionConnection.transportControls val isPrepared = mediaSessionConnection.playbackState.value?.isPrepared ?: false if (isPrepared && mediaId == CurrentPlaylist.id) { mediaSessionConnection.playbackState.value?.let { playbackState -> when { playbackState.isPlaying -> transportControls.pause() playbackState.isPlayEnabled -> transportControls.play() else -> { Log.w( TAG, "Playable item clicked but neither play nor pause are enabled!" + " (Station: $mediaId" ) } } } } else { transportControls.playFromMediaId(mediaId, null) } } fun playMediaId(mediaId: String) { val currentTrack = CurrentPlaylist.currentTrack.value val transportControls = mediaSessionConnection.transportControls val isPrepared = mediaSessionConnection.playbackState.value?.isPrepared ?: false if (isPrepared && mediaId == currentTrack?.id) { mediaSessionConnection.playbackState.value?.let { playbackState -> when { playbackState.isPlaying -> transportControls.pause() playbackState.isPlayEnabled -> transportControls.play() else -> { Log.w( TAG, "Playable item clicked but neither play nor pause are enabled!" + " (mediaId=$mediaId)" ) } } } } else { transportControls.playFromMediaId(mediaId, null) } } fun playerViewPlayPauseClick() { mediaSessionConnection.playbackState.value?.let { playbackState -> val transportControls = mediaSessionConnection.transportControls when { playbackState.isPlaying -> { transportControls.pause() } playbackState.isPlayEnabled -> { transportControls.play() } else -> { Log.w(TAG, "Playable item clicked but neither play nor pause are enabled!") } } } } class Factory( private val mediaSessionConnection: MediaSessionConnection ) : ViewModelProvider.NewInstanceFactory() { @Suppress("unchecked_cast") override fun <T : ViewModel?> create(modelClass: Class<T>): T { return MainActivityViewModel(mediaSessionConnection) as T } } } private const val TAG = "MainActivitytVM"
kotlin
24
0.60177
105
38.813472
193
starcoderdata
<filename>detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/UnsafeCallOnNullableTypeSpec.kt package io.gitlab.arturbosch.detekt.rules.bugs import io.gitlab.arturbosch.detekt.test.compileAndLint import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe /** * @author <NAME> * @author schalkms */ class UnsafeCallOnNullableTypeSpec : Spek({ val subject by memoized { UnsafeCallOnNullableType() } describe("check all variants of safe/unsafe calls on nullable types") { it("reports unsafe call on nullable type") { val code = """ fun test(str: String?) { println(str!!.length) }""" assertThat(subject.compileAndLint(code)).hasSize(1) } it("does not report safe call on nullable type") { val code = """ fun test(str: String?) { println(str?.length) }""" assertThat(subject.compileAndLint(code)).hasSize(0) } it("does not report safe call in combination with the elvis operator") { val code = """ fun test(str: String?) { println(str?.length ?: 0) }""" assertThat(subject.compileAndLint(code)).hasSize(0) } } })
kotlin
28
0.653251
109
29.761905
42
starcoderdata
<reponame>Placu95/DingNet package it.unibo.acdingnet.protelis.application import application.Application import iot.GlobalClock import iot.networkentity.Mote import org.jxmapviewer.JXMapViewer import org.jxmapviewer.painter.Painter abstract class ProtelisApplication( val motes: List<Mote>, val timer: GlobalClock, protelisProgram: String, topics: List<String> ) : Application(topics) { val protelisProgramResource: String = getProgram(protelisProgram) private fun getProgram(path: String) = ProtelisApplication::class.java.getResourceAsStream(path).bufferedReader().readText() abstract fun getPainters(): List<Painter<JXMapViewer>> }
kotlin
13
0.790419
128
29.363636
22
starcoderdata
/* * Copyright (c) 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 kohii.v1.core import android.view.View import android.view.ViewGroup import androidx.annotation.RestrictTo import androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP import androidx.collection.arraySetOf import androidx.core.view.ViewCompat import androidx.core.view.doOnAttach import androidx.core.view.doOnDetach import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.Lifecycle.Event import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import kohii.v1.core.MemoryMode.LOW import kohii.v1.core.Scope.BUCKET import kohii.v1.core.Scope.GLOBAL import kohii.v1.core.Scope.GROUP import kohii.v1.core.Scope.MANAGER import kohii.v1.core.Scope.PLAYBACK import kohii.v1.media.VolumeInfo import kohii.v1.partitionToMutableSets import java.util.ArrayDeque import kotlin.properties.Delegates class Manager( internal val master: Master, internal val group: Group, val host: Any, internal val lifecycleOwner: LifecycleOwner, internal val memoryMode: MemoryMode = LOW ) : PlayableManager, DefaultLifecycleObserver, LifecycleEventObserver, Comparable<Manager> { companion object { internal fun compareAndCheck( left: Prioritized, right: Prioritized ): Int { val ltr = left.compareTo(right) val rtl = right.compareTo(left) check(ltr + rtl == 0) { "Sum of comparison result of 2 directions must be 0, get ${ltr + rtl}." } return ltr } } internal var lock: Boolean = group.lock set(value) { if (field == value) return field = value buckets.forEach { it.lock = value } refresh() } private val rendererProviders = mutableMapOf<Class<*>, RendererProvider>() // Use as both Queue and Stack. // - When adding new Bucket, we add it to tail of the Queue. // - When promoting a Bucket as sticky, we push it to head of the Queue. // - When demoting a Bucket from sticky, we just poll the head. internal val buckets = ArrayDeque<Bucket>(4 /* less than default minimum of ArrayDeque */) // Up to one Bucket can be sticky at a time. private var stickyBucket by Delegates.observable<Bucket?>( initialValue = null, onChange = { _, from, to -> if (from === to) return@observable // Move 'to' from buckets. if (to != null /* set new sticky Bucket */) { buckets.push(to) // Push it to head. } else { // 'to' is null then 'from' must be nonnull. Consider to remove it from head. if (buckets.peek() === from) buckets.pop() } } ) internal val playbacks = mutableMapOf<Any /* container */, Playback>() internal var sticky: Boolean = false internal var volumeInfoUpdater: VolumeInfo by Delegates.observable( initialValue = VolumeInfo(), onChange = { _, from, to -> if (from == to) return@observable // Update VolumeInfo of all Buckets. This operation will then callback to this #applyVolumeInfo buckets.forEach { it.volumeInfoUpdater = to } } ) internal val volumeInfo: VolumeInfo get() = volumeInfoUpdater init { volumeInfoUpdater = group.volumeInfo group.onManagerCreated(this) lifecycleOwner.lifecycle.addObserver(this) } override fun compareTo(other: Manager): Int { return if (other.host !is Prioritized) { if (this.host is Prioritized) 1 else 0 } else { if (this.host is Prioritized) { compareAndCheck(this.host, other.host) } else -1 } } override fun onStateChanged( source: LifecycleOwner, event: Event ) { playbacks.forEach { it.value.lifecycleState = source.lifecycle.currentState } } override fun onDestroy(owner: LifecycleOwner) { playbacks.values.toMutableList() .also { group.organizer.selection -= it } .onEach { removePlayback(it) /* also modify 'playbacks' content */ } .clear() stickyBucket = null // will pop current sticky Bucket from the Stack buckets.toMutableList() .onEach { onRemoveBucket(it.root) } .clear() rendererProviders.onEach { it.value.clear() } .clear() owner.lifecycle.removeObserver(this) group.onManagerDestroyed(this) } override fun onStart(owner: LifecycleOwner) { refresh() // This will also update active/inactive Playbacks accordingly. } override fun onStop(owner: LifecycleOwner) { playbacks.forEach { if (it.value.isActive) onPlaybackInActive(it.value) } refresh() } internal fun findRendererProvider(playable: Playable): RendererProvider { val cache = rendererProviders[playable.config.rendererType] ?: rendererProviders.asSequence().firstOrNull { // If there is a RendererProvider of subclass, we can use it. playable.config.rendererType.isAssignableFrom(it.key) }?.value return requireNotNull(cache) } fun registerRendererProvider( type: Class<*>, provider: RendererProvider ) { val prev = rendererProviders.put(type, provider) if (prev !== provider) prev?.clear() } internal fun isChangingConfigurations(): Boolean { return group.activity.isChangingConfigurations } @RestrictTo(LIBRARY_GROUP) fun findPlayableForContainer(container: ViewGroup): Playable? { return playbacks[container]?.playable } internal fun findBucketForContainer(container: ViewGroup): Bucket? { require(ViewCompat.isAttachedToWindow(container)) return buckets.find { it.accepts(container) } } internal fun onContainerAttachedToWindow(container: Any?) { val playback = playbacks[container] if (playback != null) { onPlaybackAttached(playback) onPlaybackActive(playback) refresh() } } internal fun onContainerDetachedFromWindow(container: Any?) { // A detached Container can be re-attached later (in case of RecyclerView) val playback = playbacks[container] if (playback != null) { if (playback.isAttached) { if (playback.isActive) onPlaybackInActive(playback) onPlaybackDetached(playback) } refresh() } } internal fun onContainerLayoutChanged(container: Any?) { val playback = playbacks[container] if (playback != null) refresh() } private fun onAddBucket(view: View) { val existing = buckets.find { it.root === view } if (existing != null) return val bucket = Bucket[this@Manager, view] if (buckets.add(bucket)) { bucket.onAdded() view.doOnAttach { v -> bucket.onAttached() v.doOnDetach { buckets.firstOrNull { bucket -> bucket.root === it } ?.onDetached() } } } } private fun onRemoveBucket(view: View) { buckets.firstOrNull { it.root === view && buckets.remove(it) } ?.onRemoved() } internal fun refresh() { group.onRefresh() } private fun refreshPlaybackStates(): Pair<MutableSet<Playback> /* Active */, MutableSet<Playback> /* InActive */> { val toActive = playbacks.filterValues { !it.isActive && it.token.shouldPrepare() } .values val toInActive = playbacks.filterValues { it.isActive && !it.token.shouldPrepare() } .values toActive.forEach { onPlaybackActive(it) } toInActive.forEach { onPlaybackInActive(it) } return playbacks.entries.filter { it.value.isAttached } .partitionToMutableSets( predicate = { it.value.isActive }, transform = { it.value } ) } internal fun splitPlaybacks(): Pair<Set<Playback> /* toPlay */, Set<Playback> /* toPause */> { val (activePlaybacks, inactivePlaybacks) = refreshPlaybackStates() val toPlay = arraySetOf<Playback>() val bucketToPlaybacks = playbacks.values.groupBy { it.bucket } // -> Map<Bucket, List<Playback> buckets.asSequence() .filter { !bucketToPlaybacks[it].isNullOrEmpty() } .map { val candidates = bucketToPlaybacks.getValue(it) .filter { playback -> val kohiiCannotPause = master.plannedManualPlayables.contains(playback.tag) && master.playablesStartedByClient.contains(playback.tag) && (!requireNotNull(playback.config.controller).kohiiCanPause()) kohiiCannotPause || it.allowToPlay(playback) } it to candidates } .map { (bucket, candidates) -> bucket.selectToPlay(candidates) } .find { it.isNotEmpty() } ?.also { toPlay.addAll(it) activePlaybacks.removeAll(it) } activePlaybacks.addAll(inactivePlaybacks) return if (lock) emptySet<Playback>() to (toPlay + activePlaybacks) else toPlay to activePlaybacks } internal fun addPlayback(playback: Playback) { val prev = playbacks.put(playback.container, playback) require(prev == null) playback.lifecycleState = lifecycleOwner.lifecycle.currentState playback.onAdded() } internal fun removePlayback(playback: Playback) { if (playbacks.remove(playback.container) === playback) { if (playback.isAttached) { if (playback.isActive) onPlaybackInActive(playback) onPlaybackDetached(playback) } playback.onRemoved() refresh() } } internal fun onRemoveContainer(container: Any) { playbacks[container]?.let { removePlayback(it) } } private fun onPlaybackAttached(playback: Playback) { playback.onAttached() } private fun onPlaybackDetached(playback: Playback) { playback.onDetached() } private fun onPlaybackActive(playback: Playback) { playback.onActive() } private fun onPlaybackInActive(playback: Playback) { playback.onInActive() } // Public APIs fun addBucket(vararg views: View): Manager { views.forEach { this.onAddBucket(it) } return this } fun removeBucket(vararg views: View): Manager { views.forEach { this.onRemoveBucket(it) } return this } internal fun stick(bucket: Bucket) { this.stickyBucket = bucket } // Null bucket --> unstick all current sticky buckets internal fun unstick(bucket: Bucket?) { if (bucket == null || this.stickyBucket === bucket) { this.stickyBucket = null } } internal fun updateBucketVolumeInfo( bucket: Bucket, volumeInfo: VolumeInfo ) { playbacks.forEach { if (it.value.bucket === bucket) it.value.volumeInfoUpdater = volumeInfo } } /** * Apply a specific [VolumeInfo] to all Playbacks in a [Scope]. * - The smaller a scope's priority is, the wider applicable range it will be. * - Applying new [VolumeInfo] to smaller [Scope] will change [VolumeInfo] of Playbacks in that [Scope]. * - If the [Scope] is from [Scope.BUCKET], any new [Playback] added to that [Bucket] will be configured * with the updated [VolumeInfo]. * * @param target is the container to apply new [VolumeInfo] to. This must be set together with the [Scope]. * For example, if client wants to apply the [VolumeInfo] to [Scope.PLAYBACK], the receiver must be the [Playback] * to apply to. If client wants to apply to [Scope.BUCKET], the receiver must be either the [Playback] inside that [Bucket], * or the root object of a [Bucket]. */ fun applyVolumeInfo( volumeInfo: VolumeInfo, target: Any, scope: Scope ) { when (scope) { PLAYBACK -> { require(target is Playback) { "Expected Playback, found ${target.javaClass.canonicalName}" } target.volumeInfoUpdater = volumeInfo } BUCKET -> { when (target) { is Bucket -> target.volumeInfoUpdater = volumeInfo is Playback -> target.bucket.volumeInfoUpdater = volumeInfo // If neither Playback nor Bucket, must be the root View of the Bucket. else -> { requireNotNull(buckets.find { it.root === target }) { "$target is not a root of any Bucket." } .volumeInfoUpdater = volumeInfo } } } MANAGER -> { this.volumeInfoUpdater = volumeInfo } GROUP -> { this.group.volumeInfoUpdater = volumeInfo } GLOBAL -> { this.master.groups.forEach { it.volumeInfoUpdater = volumeInfo } } } } fun play(playable: Playable) { master.play(playable) } fun pause(playable: Playable) { master.pause(playable) } interface OnSelectionListener { // Called when some Playbacks under this Manager are selected. fun onSelection(selection: Collection<Playback>) } }
kotlin
36
0.66834
126
30.830508
413
starcoderdata
/* * This file is part of Dis4IRC. * * Copyright (c) 2018-2021 Dis4IRC contributors * * MIT License */ package io.zachbr.dis4irc.bridge.pier.discord import io.zachbr.dis4irc.bridge.message.PlatformType import io.zachbr.dis4irc.bridge.message.Sender import io.zachbr.dis4irc.bridge.message.Source import net.dv8tion.jda.api.entities.Message import net.dv8tion.jda.api.entities.MessageChannel import org.slf4j.Logger fun MessageChannel.asBridgeSource(): Source = Source(this.name, this.idLong, PlatformType.DISCORD) fun Message.toBridgeMsg(logger: Logger, receiveTimestamp: Long = System.nanoTime(), shouldResolveReference: Boolean = true) : io.zachbr.dis4irc.bridge.message.Message { // We need to get the guild member in order to grab their display name val guildMember = this.guild.getMember(this.author) if (guildMember == null && !this.author.isBot) { logger.debug("Cannot get Discord guild member from user information: ${this.author}!") } // handle attachments val attachmentUrls = ArrayList<String>() for (attachment in this.attachments) { var url = attachment.url if (attachment.isImage) { url = attachment.proxyUrl } attachmentUrls.add(url) } // handle custom emotes var messageText = this.contentDisplay for (emote in this.emotes) { messageText = messageText.replace(":${emote.name}:", "") attachmentUrls.add(emote.imageUrl) } // discord replies var bridgeMsgRef: io.zachbr.dis4irc.bridge.message.Message? = null val discordMsgRef = this.referencedMessage if (shouldResolveReference && discordMsgRef != null) { bridgeMsgRef = discordMsgRef.toBridgeMsg(logger, receiveTimestamp, shouldResolveReference = false) // do not endlessly resolve references } val displayName = guildMember?.effectiveName ?: this.author.name // webhooks won't have an effective name val sender = Sender(displayName, this.author.idLong, null) return io.zachbr.dis4irc.bridge.message.Message( messageText, sender, this.channel.asBridgeSource(), receiveTimestamp, attachmentUrls, bridgeMsgRef ) }
kotlin
16
0.708182
168
34.483871
62
starcoderdata
package com.car300.cameralib.api_new.result_data /** * BaseResult * * @author panfei.pf * @since 2021/3/15 17:59 */ open class BaseResult
kotlin
4
0.699301
48
15
9
starcoderdata
package io.kotest.property.arbitrary import io.kotest.property.Shrinker import kotlin.math.abs import kotlin.random.nextLong fun Arb.Companion.long(min: Long = Long.MIN_VALUE, max: Long = Long.MAX_VALUE) = long(min..max) fun Arb.Companion.long(range: LongRange = Long.MIN_VALUE..Long.MAX_VALUE): Arb<Long> { val edgecases = listOf(0, Long.MAX_VALUE, Long.MIN_VALUE) return arb(LongShrinker, edgecases) { it.random.nextLong(range) } } object LongShrinker : Shrinker<Long> { override fun shrink(value: Long): List<Long> = when (value) { 0L -> emptyList() 1L, -1L -> listOf(0L) else -> { val a = listOf(0, 1, -1, abs(value), value / 3, value / 2, value * 2 / 3) val b = (1..5).map { value - it }.reversed().filter { it > 0 } (a + b).distinct() .filterNot { it == value } } } }
kotlin
26
0.599323
95
33.076923
26
starcoderdata
<gh_stars>0 package gg.rsmod.plugins.content.areas.draynor.manor.objs import gg.rsmod.game.model.attr.NO_CLIP_ATTR val OPEN_DOOR_1 = DynamicObject(135, 0, 2, Tile(3109, 3354, 0)) val OPEN_DOOR_2 = DynamicObject(134, 0, 0, Tile(3108, 3354, 0)) val CLOSE_DOOR_1 = StaticObject(135, 0, 0, Tile(3109, 3353, 0)) val CLOSE_DOOR_2 = StaticObject(134, 0, 0, Tile(3108, 3353, 0)) val CLOSE_DOOR_3 = DynamicObject(135, 0, 1, Tile(3109, 3353, 0)) val CLOSE_DOOR_4 = DynamicObject(134, 0, 1, Tile(3108, 3353, 0)) val INVISIBLE_DOOR_1 = DynamicObject(83, 0, 1, Tile(3109, 3353, 0)) val INVISIBLE_DOOR_2 = DynamicObject(83, 0, 1, Tile(3108, 3353, 0)) val CHAIR_SPAWN_TILE = Tile(3122,3357,0) val ENTRY_DOORS = listOf (135,134) val ENTRY_SFX = listOf (46,45) ENTRY_DOORS.forEach { door -> on_obj_option(door, "Open") { if (player.tile.z >= 3354){ player.message("The doors won't open.") return@on_obj_option } else { player.openEntryDoor() } } } fun Player.openEntryDoor() { queue { val FOLLOW_CHAIR = Npc(player, 3567, CHAIR_SPAWN_TILE, world) // if (!FOLLOW_CHAIR.isSpawned()) { // world.spawn(FOLLOW_CHAIR) // } player.lock() world.remove(CLOSE_DOOR_1) world.remove(CLOSE_DOOR_2) world.remove(CLOSE_DOOR_3) world.remove(CLOSE_DOOR_4) world.spawn(OPEN_DOOR_1) world.spawn(OPEN_DOOR_2) world.spawn(INVISIBLE_DOOR_1) world.spawn(INVISIBLE_DOOR_2) player.moveTo(player.tile.x, player.tile.z + 1) wait(2) world.remove(OPEN_DOOR_1) world.remove(OPEN_DOOR_2) world.remove(INVISIBLE_DOOR_1) world.remove(INVISIBLE_DOOR_2) world.spawn(CLOSE_DOOR_3) world.spawn(CLOSE_DOOR_4) player.playSound(ENTRY_SFX[0]) player.playSound(ENTRY_SFX[1]) player.message("The doors slam shut behind you.") player.faceTile(Tile(player.tile.x, player.tile.z - 1)) player.unlock() } }
kotlin
21
0.616822
69
32.344262
61
starcoderdata
<reponame>phreed/tinkerpop4<gh_stars>0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tinkerpop4.gremlin.process.traversal.step.map import org.apache.tinkerpop4.gremlin.process.traversal.Traversal /** * @author <NAME> (http://markorodriguez.com) */ class EdgeVertexStep(traversal: Traversal.Admin?, direction: Direction) : FlatMapStep<Edge?, Vertex?>(traversal), AutoCloseable, Configuring { protected var parameters: Parameters = Parameters() protected var direction: Direction init { this.direction = direction } @Override fun getParameters(): Parameters { return parameters } @Override fun configure(vararg keyValues: Object?) { parameters.set(null, keyValues) } @Override protected fun flatMap(traverser: Traverser.Admin<Edge?>): Iterator<Vertex> { return traverser.get().vertices(direction) } @Override override fun toString(): String { return StringFactory.stepString(this, direction) } @Override override fun hashCode(): Int { return super.hashCode() xor direction.hashCode() } fun getDirection(): Direction { return direction } fun reverseDirection() { direction = direction.opposite() } @get:Override val requirements: Set<Any> get() = Collections.singleton(TraverserRequirement.OBJECT) @Override @Throws(Exception::class) fun close() { closeIterator() } }
kotlin
13
0.696943
113
27.948718
78
starcoderdata
<gh_stars>0 package org.jeecg.modules.ilang.service import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl import org.jeecg.modules.ilang.mapper.SysParamsItemMapper import org.jeecg.modules.ilang.entity.SysParamsItem import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service /** * @Description: 参数详情 * @Author: jeecg-boot * @Date: 2021-01-02 * @Version: V1.0 */ @Service class SysParamsItemService(private val sysParamsItemMapper: SysParamsItemMapper) : ServiceImpl<SysParamsItemMapper?, SysParamsItem?>() { fun selectByMainId(mainId: String?): List<SysParamsItem> { return sysParamsItemMapper.selectByMainId(mainId) } }
kotlin
11
0.782913
82
28.75
24
starcoderdata
package com.example.anticovid.ui.profile.risk_assessment_test.test import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.anticovid.R import com.example.anticovid.data.model.RiskAssessmentTestResult import kotlinx.android.synthetic.main.fragment_risk_assessment_test_info.* import kotlinx.android.synthetic.main.fragment_risk_assessment_test_summary.* class RiskAssessmentTestSummaryFragment(private val testResult: RiskAssessmentTestResult) : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_risk_assessment_test_summary, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) when (testResult) { RiskAssessmentTestResult.LowRisk -> low_risk.visibility = View.VISIBLE RiskAssessmentTestResult.MediumRisk -> medium_risk.visibility = View.VISIBLE RiskAssessmentTestResult.HighRisk -> high_risk.visibility = View.VISIBLE else -> {} } } }
kotlin
14
0.763767
116
42.241379
29
starcoderdata
<filename>src/main/kotlin/com/solution/prode/exception/BadRequestException.kt package com.solution.prode.exception import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ResponseStatus @ResponseStatus(HttpStatus.BAD_REQUEST) class BadRequestException( override var message: String ) : RuntimeException()
kotlin
9
0.83815
77
30.454545
11
starcoderdata
package com.brins.riceweather.ui.view import android.animation.ValueAnimator import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import com.brins.riceweather.utils.DeviceUtils.dip2px import java.util.ArrayList import kotlin.math.cos import kotlin.math.sin class CircleProgressView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet) : View(context, attributeSet) { companion object { private val PROGRESS_START_ANGLE = 165 private val PROGRESS_SWEEP_ANGLE = 210 private val POINT_RADIUS = dip2px(2f) private val PROGRESS_STROKE_WIDTH = dip2px(10f) private val STEP_LIST = intArrayOf(0, 25, 50, 75, 100) private val STEP_ANGLE_LIST = intArrayOf(-15, 37, 90, 143, 195) } private val mProgressPaint = Paint(Paint.ANTI_ALIAS_FLAG) private val mProgressBgPaint = Paint(Paint.ANTI_ALIAS_FLAG) private val mHeadPointPaint = Paint(Paint.ANTI_ALIAS_FLAG) private val mStepCountPaint = Paint(Paint.ANTI_ALIAS_FLAG) private var mProgressRect: RectF? = null var mStep = STEP_LIST[0] set(value) { field = value drawStep() } private val mTextPoints = ArrayList<Point>() private var mSweepAngle: Float = 0f init { // 进度条画笔 mProgressPaint.strokeCap = Paint.Cap.ROUND mProgressPaint.strokeWidth = PROGRESS_STROKE_WIDTH.toFloat() mProgressPaint.style = Paint.Style.STROKE // 进度背景画笔 mProgressBgPaint.strokeCap = Paint.Cap.ROUND mProgressBgPaint.strokeWidth = PROGRESS_STROKE_WIDTH.toFloat() mProgressBgPaint.color = Color.WHITE mProgressBgPaint.style = Paint.Style.STROKE // 进度条头部原点画笔 mHeadPointPaint.color = Color.WHITE // 步数画笔 mStepCountPaint.color = -0xbb3f7e mStepCountPaint.textSize = dip2px(10f).toFloat() mStepCountPaint.typeface = Typeface.createFromAsset( getContext().assets, "fonts/DIN-Condensed-Bold.ttf" ) // 进度绘制角度计算 mSweepAngle = (PROGRESS_SWEEP_ANGLE * mStep / STEP_LIST[STEP_LIST.size - 1].toFloat()).toInt() .toFloat() mSweepAngle = Math.min(PROGRESS_SWEEP_ANGLE.toFloat(), mSweepAngle) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val width = MeasureSpec.getSize(widthMeasureSpec) setMeasuredDimension(width, measureHeightByWidth(width)) calculateSize() } /** * 初始化尺寸相关参数 */ private fun calculateSize() { // 设置进度条渐变范围 mProgressPaint.shader = LinearGradient( 0f, 0f, width.toFloat(), 0f, -0x501b95, -0xa43671, Shader.TileMode.CLAMP ) // 设置进度条边框大小 val clampWidth = PROGRESS_STROKE_WIDTH / 2 mProgressRect = RectF( clampWidth.toFloat(), clampWidth.toFloat(), (measuredWidth - clampWidth).toFloat(), (measuredWidth - clampWidth).toFloat() ) // 计算步数的坐标位置(只能这样 - - ) val stepTextRadius = (mProgressRect!!.width() / 2 - dip2px(12f)).toInt() val step0 = Point( -(stepTextRadius * cos(Math.toRadians((-STEP_ANGLE_LIST[0]).toDouble()))).toInt(), (stepTextRadius * sin(Math.toRadians((-STEP_ANGLE_LIST[0]).toDouble()))).toInt() ) val step1 = Point( -(stepTextRadius * cos(Math.toRadians(STEP_ANGLE_LIST[1].toDouble()))).toInt(), -(stepTextRadius * sin(Math.toRadians(STEP_ANGLE_LIST[1].toDouble()))).toInt() ) val step2 = Point(0, -stepTextRadius) val step3 = Point( (stepTextRadius * cos(Math.toRadians((180 - STEP_ANGLE_LIST[3]).toDouble()))).toInt(), -(stepTextRadius * sin(Math.toRadians((180 - STEP_ANGLE_LIST[3]).toDouble()))).toInt() ) val step4 = Point( (stepTextRadius * cos(Math.toRadians((STEP_ANGLE_LIST[4] - 180).toDouble()))).toInt(), (stepTextRadius * sin(Math.toRadians((STEP_ANGLE_LIST[4] - 180).toDouble()))).toInt() ) // 调整位置 step0.x += dip2px(5f) step0.y += dip2px(4f) step1.x += dip2px(5f) step1.y += dip2px(8f) step2.x -= dip2px(3f) step2.y += dip2px(13f) step3.x -= dip2px(15f) step3.y += dip2px(8f) step4.x -= dip2px(15f) step4.y += dip2px(4f) // 好了好了 mTextPoints.add(step0) mTextPoints.add(step1) mTextPoints.add(step2) mTextPoints.add(step3) mTextPoints.add(step4) } private fun measureHeightByWidth(width: Int): Int { return (width * 460 / 690f).toInt() // 根据UI提供的尺寸宽高比来算 } private fun drawStep() { var sweepAngle = PROGRESS_SWEEP_ANGLE * mStep / STEP_LIST[STEP_LIST.size - 1].toFloat() sweepAngle = Math.min(PROGRESS_SWEEP_ANGLE.toFloat(), sweepAngle) val valueAnimator = ValueAnimator.ofFloat(sweepAngle) valueAnimator.duration = 1500 valueAnimator.interpolator = AccelerateDecelerateInterpolator() valueAnimator.addUpdateListener { animation -> mSweepAngle = animation.animatedValue as Float postInvalidate() } valueAnimator.start() mSweepAngle = (PROGRESS_SWEEP_ANGLE * mStep / STEP_LIST[STEP_LIST.size - 1].toFloat()) mSweepAngle = Math.min(PROGRESS_SWEEP_ANGLE.toFloat(), mSweepAngle) postInvalidate() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) // 画出进度条背景 canvas.drawArc( mProgressRect, PROGRESS_START_ANGLE.toFloat(), PROGRESS_SWEEP_ANGLE.toFloat(), false, mProgressBgPaint ) // 画进度 canvas.drawArc( mProgressRect, PROGRESS_START_ANGLE.toFloat(), mSweepAngle, false, mProgressPaint ) // 画进度白点 canvas.translate(mProgressRect!!.centerX(), mProgressRect!!.centerY()) canvas.save() canvas.rotate(mSweepAngle - 180 + PROGRESS_START_ANGLE) canvas.drawCircle(-mProgressRect!!.width() / 2, 0f, POINT_RADIUS.toFloat(), mHeadPointPaint) canvas.restore() // 画出步数及圆点 for (i in STEP_LIST.indices) { canvas.save() canvas.rotate(STEP_ANGLE_LIST[i].toFloat()) canvas.drawCircle( -(mProgressRect!!.width() / 2) + dip2px(12f), 0f, POINT_RADIUS.toFloat(), mStepCountPaint ) canvas.restore() val step = STEP_LIST[i] canvas.drawText( step.toString(), mTextPoints[i].x.toFloat(), mTextPoints[i].y.toFloat(), mStepCountPaint ) } } }
kotlin
30
0.614238
100
36.978022
182
starcoderdata
package com.project.seungjun.model.network import com.project.network.RetrofitClient import com.project.seungjun.model.network.api.TestApiService object ApiController { val testApiService get() = RetrofitClient.build().create(TestApiService::class.java) }
kotlin
11
0.789668
73
23.727273
11
starcoderdata
package com.microservices.chapter03 import com.beust.klaxon.JsonObject import com.beust.klaxon.Klaxon import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.test.web.servlet.result.MockMvcResultHandlers.print import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @RunWith(SpringRunner::class) @SpringBootTest @AutoConfigureMockMvc class JsonExamplesControllerTest { @Autowired private lateinit var mockMvc: MockMvc @Test fun getJson() { val json = requestJson("/json") assertEquals("hello", json["name"]) assertNull(json["place"]) } @Test fun getJson2() { val json = requestJson("/json2") assertEquals("hello", json["name"]) assertEquals("world", json["place"]) } @Test fun getJson3() { val json = requestJson("/json3") assertEquals("hi", json["name"]) assertEquals("kotlin", json["place"]) } @Test fun getJson4() { val json = requestJson("/json4") assertEquals("more", json.obj("object1")?.get("name")) assertEquals("complex", json.obj("object1")?.get("place")) } private fun requestJson(uri: String): JsonObject { val action = mockMvc.perform(get(uri)).andDo(print()).andExpect(status().isOk) val content = action.andReturn().response.contentAsString return Klaxon().parseJsonObject(content.reader()) } }
kotlin
19
0.715029
86
29.539683
63
starcoderdata
package com.kneelawk.magicalmahou.client.render.player import com.kneelawk.magicalmahou.MMLog import com.kneelawk.magicalmahou.mixin.api.PlayerEntityRendererEvents object MMFeatureRenderers { fun init() { PlayerEntityRendererEvents.ADD_FEATURES.register { renderer, _, _, consumer -> MMLog.info("Adding cat ears...") consumer.accept(CatEarsFeatureRenderer(renderer)) consumer.accept(TeleportAtFeatureRenderer(renderer)) consumer.accept(LongFallFeatureRenderer(renderer)) } } }
kotlin
19
0.718182
86
35.733333
15
starcoderdata
<filename>src/main/kotlin/no/nav/sbl/dialogarena/mininnboks/provider/rest/ubehandletmelding/SporsmalController.kt package no.nav.sbl.dialogarena.mininnboks.provider.rest.ubehandletmelding import io.ktor.application.* import io.ktor.response.* import io.ktor.routing.* import no.nav.sbl.dialogarena.mininnboks.AuthLevel import no.nav.sbl.dialogarena.mininnboks.consumer.HenvendelseService import no.nav.sbl.dialogarena.mininnboks.withSubject fun Route.sporsmalController(henvendelseService: HenvendelseService) { route("/sporsmal") { get("/ubehandlet") { withSubject(AuthLevel.Level3) { subject -> call.respond( UbehandletMeldingUtils.hentUbehandledeMeldinger(henvendelseService.hentAlleHenvendelser(subject)) ) } } } }
kotlin
31
0.730816
117
38.095238
21
starcoderdata
<filename>src/test/kotlin/com/github/ohtomi/kotlin/sandbox/AppTest.kt package com.github.ohtomi.kotlin.sandbox import kotlin.test.Test import kotlin.test.assertNotNull class AppTest { @Test fun testAppHasAGreeting() { val classUnderTest = App() assertNotNull(classUnderTest.greeting, "app should have a greeting") } }
kotlin
12
0.747093
76
27.666667
12
starcoderdata
<reponame>oneliang/frame-kotlin<gh_stars>0 package com.oneliang.ktx.frame.expression import com.oneliang.ktx.Constants import com.oneliang.ktx.util.common.perform import com.oneliang.ktx.util.common.toUtilDate import java.util.* import kotlin.math.pow object Expression { private val INVALID_DATA = Any() val INVALID_EVAL_RESULT = INVALID_DATA /** * 将算术表达式转换为逆波兰表达式 * @param expression 要计算的表达式,如"1+2+3+4" * @return MutableList<ExpressionNode> */ private fun parseExpression(expression: String): MutableList<ExpressionNode> { if (expression.isEmpty()) { return mutableListOf() } val listOperator = mutableListOf<ExpressionNode>() val stackOperator = Stack<ExpressionNode>() val expressionParser = ExpressionParser(expression) var beforeExpNode: ExpressionNode? // 前一个节点 var unitaryNode: ExpressionNode? = null // 一元操作符 var (success, currentExpressionNode) = expressionParser.readNode() // 是否需要操作数 var requireOperand = false while (success) { if (currentExpressionNode.type == ExpressionNode.Type.NUMBER || currentExpressionNode.type == ExpressionNode.Type.STRING || currentExpressionNode.type == ExpressionNode.Type.DATE ) { // 操作数, 直接加入后缀表达式中 if (unitaryNode != null) { // 设置一元操作符节点 currentExpressionNode.unitaryNode = unitaryNode unitaryNode = null } listOperator.add(currentExpressionNode) requireOperand = false } else if (currentExpressionNode.type == ExpressionNode.Type.BRACKET_LEFT) { // 左括号, 直接加入操作符栈 stackOperator.push(currentExpressionNode) } else if (currentExpressionNode.type == ExpressionNode.Type.BRACKET_RIGHT) { // 右括号则在操作符栈中反向搜索,直到遇到匹配的左括号为止,将中间的操作符依次加到后缀表达式中。 var lpNode: ExpressionNode? = null while (stackOperator.size > 0) { lpNode = stackOperator.pop() if (lpNode.type == ExpressionNode.Type.BRACKET_LEFT) break listOperator.add(lpNode) } if (lpNode == null || lpNode.type != ExpressionNode.Type.BRACKET_LEFT) { throw ExpressionException(String.format("expression \"%s\" in position(%s) lose \")\"", expressionParser.expression, expressionParser.position)) } } else { if (stackOperator.size == 0) { // 第一个节点则判断此节点是否是一元操作符"+,-,!,("中的一个,否则其它都非法 if (listOperator.size == 0 && !(currentExpressionNode.type == ExpressionNode.Type.BRACKET_LEFT || currentExpressionNode.type == ExpressionNode.Type.NOT)) { // 后缀表达式没有任何数据则判断是否是一元操作数 unitaryNode = if (ExpressionNode.isUnitaryNode(currentExpressionNode.type)) { currentExpressionNode } else { // 丢失操作数 throw ExpressionException(String.format("expression \"%s\" in position(%s) lose operator", expressionParser.expression, expressionParser.position)) } } else { // 直接压入操作符栈 stackOperator.push(currentExpressionNode) } requireOperand = true // 下一个节点需要操作数 } else { if (requireOperand) { // 如果需要操作数则判断当前的是否是"+","-"号(一元操作符),如果是则继续 unitaryNode = if (ExpressionNode.isUnitaryNode(currentExpressionNode.type) && unitaryNode == null) { currentExpressionNode } else { // 丢失操作数 throw ExpressionException(String.format("expression \"%s\" in position (%s) lose operator", expressionParser.expression, expressionParser.position)) } } else { // 对前面的所有操作符进行优先级比较 do { // 取得上一次的操作符 beforeExpNode = stackOperator.peek() // 如果前一个操作符优先级较高,则将前一个操作符加入后缀表达式中 if (beforeExpNode.type != ExpressionNode.Type.BRACKET_LEFT && beforeExpNode.priority - currentExpressionNode.priority >= 0 ) { listOperator.add(stackOperator.pop()) } else { break } } while (stackOperator.size > 0) // 将操作符压入操作符栈 stackOperator.push(currentExpressionNode) requireOperand = true } } } val readNodeResult = expressionParser.readNode() success = readNodeResult.first currentExpressionNode = readNodeResult.second } if (requireOperand) { // 丢失操作数 throw ExpressionException(String.format("expression \"%s\" in position(%s) lose operate data", expressionParser.expression, expressionParser.position)) } // 清空堆栈 while (stackOperator.size > 0) { // 取得操作符 beforeExpNode = stackOperator.pop() if (beforeExpNode.type == ExpressionNode.Type.BRACKET_LEFT) { throw ExpressionException(String.format("expression \"%s\" in position(%s) lose \")\"", expressionParser.expression, expressionParser.position)) } listOperator.add(beforeExpNode) } return listOperator } /** * eval expression * @param nodeList * @return Any, in fact is boolean or double or string or INVALID_EVAL_RESULT */ private fun evalExpression(nodeList: MutableList<ExpressionNode>): Any { if (nodeList.size == 0) return INVALID_EVAL_RESULT if (nodeList.size > 1) { var index = 0 // 储存数据 val valueList = mutableListOf<Any>()//not include operator while (index < nodeList.size) { val node = nodeList[index] if (node.isDataNode()) { valueList.add(node.calculateValue) index++ } else { // 二元表达式,需要二个参数, 如果是Not的话,则只要一个参数 var paramCount = 2 if (node.type == ExpressionNode.Type.NOT) paramCount = 1 // 计算操作数的值 if (valueList.size < paramCount) { throw ExpressionException("lose operator") } // 传入参数 val data = Array(paramCount) { valueList[index - paramCount + it] } // 将计算结果再存入当前节点 node.calculateValue = calculate(node.type, data) node.type = if (node.calculateValue is String) { ExpressionNode.Type.STRING } else { ExpressionNode.Type.NUMBER } // 将操作数节点删除 var i = 0 while (i < paramCount) { nodeList.removeAt(index - i - 1) valueList.removeAt(index - i - 1) i++ } index -= paramCount } } } if (nodeList.size != 1) { throw ExpressionException("lose operator") } val node = nodeList[0] return when (node.type) { ExpressionNode.Type.NUMBER -> node.calculateValue ExpressionNode.Type.STRING, ExpressionNode.Type.DATE -> node.calculateValue.toString().replace("\"", Constants.String.BLANK) else -> { throw ExpressionException("lose operator") } } } /** * calculate node * @param type type * @param dataArray size may be one or two * @return Any, in fact is boolean or double or string or INVALID_EVAL_RESULT */ private fun calculate(type: ExpressionNode.Type, dataArray: Array<Any>): Any { if (!(dataArray.size == 1 || dataArray.size == 2)) { return INVALID_EVAL_RESULT } val dataOne = dataArray[0] val dataTwo = dataArray.getOrElse(1) { INVALID_DATA } var stringOne = dataOne.toString() var stringTwo = dataTwo.toString() val dateFlag = ExpressionNode.isDatetime(stringOne) || ExpressionNode.isDatetime(stringTwo) val stringFlag = stringOne.contains("\"") || stringTwo.contains("\"") stringOne = stringOne.replace("\"", Constants.String.BLANK) stringTwo = stringTwo.replace("\"", Constants.String.BLANK) when (type) { ExpressionNode.Type.PLUS -> { if (!stringFlag) { return convertToDouble(dataOne) + convertToDouble(dataTwo) } return stringOne + stringTwo } ExpressionNode.Type.MINUS -> { return convertToDouble(dataOne) - convertToDouble(dataTwo) } ExpressionNode.Type.MULTIPLY -> { return convertToDouble(dataOne) * convertToDouble(dataTwo) } ExpressionNode.Type.DIVIDE -> { val one = convertToDouble(dataOne) val two = convertToDouble(dataTwo) if (two == 0.0) error("can not divide zero") return one / two } ExpressionNode.Type.POWER -> { return convertToDouble(dataOne).pow(convertToDouble(dataTwo)) } ExpressionNode.Type.MODULUS -> { val one = convertToDouble(dataOne) val two = convertToDouble(dataTwo) if (two == 0.0) error("can not modulus zero") return one % two } ExpressionNode.Type.BITWISE_AND -> { val one = convertToDouble(dataOne) val two = convertToDouble(dataTwo) return one.toInt() and two.toInt() } ExpressionNode.Type.BITWISE_OR -> { val one = convertToDouble(dataOne) val two = convertToDouble(dataTwo) return one.toInt() or two.toInt() } ExpressionNode.Type.AND -> { return convertToBoolean(dataOne) && convertToBoolean(dataTwo) } ExpressionNode.Type.OR -> { return convertToBoolean(dataOne) || convertToBoolean(dataTwo) } ExpressionNode.Type.NOT -> { return !convertToBoolean(dataOne) } ExpressionNode.Type.EQUAL -> { if (!dateFlag) { if (stringFlag) { return stringOne == stringTwo } val one = convertToDouble(dataOne) val two = convertToDouble(dataTwo) return one == two } val timeOne = stringOne.toUtilDate() val timeTwo = stringTwo.toUtilDate() return timeOne.time == timeTwo.time } ExpressionNode.Type.UNEQUAL -> { if (!dateFlag) { if (stringFlag) { return stringOne != stringTwo } return convertToDouble(dataOne) != convertToDouble(dataTwo) } val time1 = stringOne.toUtilDate() val time2 = stringTwo.toUtilDate() return time1.time != time2.time } ExpressionNode.Type.GREATER_THAN -> { if (!dateFlag) { return convertToDouble(dataOne) > convertToDouble(dataTwo) } val timeOne = stringOne.toUtilDate() val timeTwo = stringTwo.toUtilDate() return timeOne.time > timeTwo.time } ExpressionNode.Type.LESS_THAN -> { if (!dateFlag) { return convertToDouble(dataOne) < convertToDouble(dataTwo) } val timeOne = stringOne.toUtilDate() val timeTwo = stringTwo.toUtilDate() return timeOne.time < timeTwo.time } ExpressionNode.Type.GREATER_THAN_OR_EQUAL -> { if (!dateFlag) { return convertToDouble(dataOne) >= convertToDouble(dataTwo) } val timeOne = stringOne.toUtilDate() val timeTwo = stringTwo.toUtilDate() return timeOne.time >= timeTwo.time } ExpressionNode.Type.LESS_THAN_OR_EQUAL -> { if (!dateFlag) { return convertToDouble(dataOne) <= convertToDouble(dataTwo) } val timeOne = stringOne.toUtilDate() val timeTwo = stringTwo.toUtilDate() return timeOne.time <= timeTwo.time } ExpressionNode.Type.LEFT_SHIFT -> { return convertToDouble(dataOne).toLong() shl convertToDouble(dataTwo).toInt() } ExpressionNode.Type.RIGHT_SHIFT -> { return convertToDouble(dataOne).toLong() shr convertToDouble(dataTwo).toInt() } ExpressionNode.Type.LIKE -> { return if (!stringFlag) { false } else stringOne.contains(stringTwo) } ExpressionNode.Type.NOT_LIKE -> { return if (!stringFlag) { false } else !stringOne.contains(stringTwo) } ExpressionNode.Type.STARTS_WITH -> { return if (!stringFlag) { false } else stringOne.startsWith(stringTwo) } ExpressionNode.Type.ENDS_WITH -> { return if (!stringFlag) { false } else stringOne.endsWith(stringTwo) } else -> return 0 } } /** * convert to boolean * @param value * @return */ private fun convertToBoolean(value: Any): Boolean { return if (value is Boolean) { value } else { false } } /** * convert to double * @param value * @return Double */ private fun convertToDouble(value: Any): Double { return if (value is Boolean) { if (value) 1.0 else 0.0 } else { value.toString().toDouble() } } fun eval(expression: String): Any { val value = try { evalExpression(parseExpression(expression)) } catch (e: Throwable) { INVALID_EVAL_RESULT } return if (value != INVALID_EVAL_RESULT) { value } else { expression } } fun evalBoolean(expression: String): Boolean = try { val result = eval(expression) if (result is Boolean) { result } else { false } } catch (e: Throwable) { false } fun evalNumber(expression: String): Double = try { val result = eval(expression) if (result is Double) { result } else { 0.0 } } catch (e: Throwable) { 0.0 } fun evalString(expression: String) = try { val result = eval(expression) if (result is String) { result } else { Constants.String.BLANK } } catch (e: Throwable) { Constants.String.BLANK } fun evalThreeOperand(expression: String): Any? { var index = expression.indexOf("?") if (index > -1) { val stringOne = expression.substring(0, index) val stringTwo = expression.substring(index + 1) index = stringTwo.indexOf(":") return if (java.lang.Boolean.parseBoolean(evalExpression(parseExpression(stringOne)).toString())) { eval(stringTwo.substring(0, index)) } else eval(stringTwo.substring(index + 1)) } return evalExpression(parseExpression(expression)) } }
kotlin
37
0.518179
201
39.816377
403
starcoderdata
<reponame>Pikkuninja/Birdwatcher package fi.jara.birdwatcher.screens import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.fragment.app.FragmentFactory import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import fi.jara.birdwatcher.R import fi.jara.birdwatcher.common.di.application.ApplicationComponentOwner import fi.jara.birdwatcher.common.di.presentation.PresentationComponent import javax.inject.Inject class MainActivity : AppCompatActivity() { val presentationComponent: PresentationComponent by lazy { (application as ApplicationComponentOwner).applicationComponent.newPresentationComponent() } @Inject lateinit var fragmentFactory: FragmentFactory private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { presentationComponent.inject(this) supportFragmentManager.fragmentFactory = fragmentFactory super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) navController = Navigation.findNavController(this, R.id.nav_host_fragment) appBarConfiguration = AppBarConfiguration(navController.graph) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) setupActionBarWithNavController(navController, appBarConfiguration) } override fun onSupportNavigateUp(): Boolean { return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
kotlin
16
0.802442
98
36.541667
48
starcoderdata
package org.divy.ai.snake.model.food import org.divy.ai.snake.model.game.GameBoardModel import org.divy.ai.snake.model.Position import org.divy.ai.snake.model.game.Event import org.divy.ai.snake.model.game.EventType import java.lang.Math.random class RandomFoodDropper(private val boardModel: GameBoardModel): FoodDropper { override fun drop(): FoodModel { var pos = generateRandomPosition() while (!boardModel.isEmptyPosition(pos)) { pos = generateRandomPosition() } return FoodModel(pos) } private fun generateRandomPosition(): Position { val x: Long = (random() * (boardModel.boardWidth.toDouble())).toLong() val y: Long = (random() * (boardModel.boardHeight.toDouble())).toLong() return Position(x, y) } }
kotlin
16
0.690088
79
33.652174
23
starcoderdata
package io.rover.core.data.domain data class ID( var rawValue: String )
kotlin
5
0.727273
33
14.4
5
starcoderdata
<gh_stars>0 package org.apache.isis.client.kroviz.ui import org.apache.isis.client.kroviz.core.event.LogEntry import org.apache.isis.client.kroviz.ui.kv.RoDialog import org.apache.isis.client.kroviz.utils.Utils class EventLogDetail(val logEntry: LogEntry) : Command { fun open() { val formItems = mutableListOf<FormItem>() formItems.add(FormItem("Url", "Response", logEntry.url)) var jsonStr = logEntry.response if (jsonStr.isNotEmpty()) { jsonStr = Utils.format(jsonStr) } formItems.add(FormItem("Text", "TextArea", jsonStr, 15)) val label = logEntry.title val rd = RoDialog(caption = label, items = formItems, command = this, defaultAction = "Visualize") rd.open() } override fun execute() { ImageAlert().open() } }
kotlin
16
0.65343
106
29.777778
27
starcoderdata
package org.firstinspires.ftc.teamcode
kotlin
3
0.85
38
19
2
starcoderdata
<gh_stars>0 package com.github.theapache64.retrosheet.core import com.github.theapache64.retrosheet.utils.TypeIdentifier /** * Created by theapache64 : Jul 21 Tue,2020 @ 22:37 */ class QueryConverter( private val smartQuery: String, private val smartQueryMap: Map<String, String>, private val paramMap: Map<String, String>? ) { fun convert(): String { var outputQuery = smartQuery // Replacing values paramMap?.let { for (entry in paramMap.entries) { val value = sanitizeValue(entry.value) outputQuery = outputQuery.replace(":${entry.key}", value) } } // Replacing keys for (entry in smartQueryMap) { outputQuery = outputQuery.replace(entry.key, entry.value) } return outputQuery } private fun sanitizeValue(value: String): String { return if (TypeIdentifier.isNumber(value)) { value } else { "'$value'" } } }
kotlin
23
0.594727
73
25.947368
38
starcoderdata
package com.julioapps.commons.views import android.content.Context import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.util.AttributeSet import android.widget.SeekBar class MySeekBar : SeekBar { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) { progressDrawable.colorFilter = PorterDuffColorFilter(accentColor, PorterDuff.Mode.SRC_IN) thumb.colorFilter = PorterDuffColorFilter(accentColor, PorterDuff.Mode.SRC_IN) } }
kotlin
14
0.779116
103
36.35
20
starcoderdata
<reponame>aSoft-Ltd/kotlin-stdlib<gh_stars>0 import identifier.Name import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import kotlin.test.Test class NameTest { @Test fun can_serialize_a_name() { val name = Name("<NAME>") println(Json.encodeToString(name)) } @Test fun can_deserialize_a_name() { val name = Json.decodeFromString<Name>(""""<NAME>"""") println(name) } }
kotlin
14
0.685885
62
24.2
20
starcoderdata
<reponame>daerich/covpass-android<filename>common-app-covpass/src/main/java/de/rki/covpass/app/main/CertificateFragment.kt /* * (C) Copyright IBM Deutschland GmbH 2021 * (C) Copyright IBM Corp. 2021 */ package de.rki.covpass.app.main import android.graphics.Bitmap import android.os.Bundle import android.view.View import com.ensody.reactivestate.android.autoRun import com.ensody.reactivestate.android.reactiveState import com.ensody.reactivestate.dispatchers import com.ensody.reactivestate.get import com.google.zxing.BarcodeFormat import com.google.zxing.EncodeHintType import com.ibm.health.common.android.utils.viewBinding import com.ibm.health.common.navigation.android.FragmentNav import com.ibm.health.common.navigation.android.findNavigator import com.ibm.health.common.navigation.android.getArgs import com.journeyapps.barcodescanner.BarcodeEncoder import de.rki.covpass.app.databinding.CertificateBinding import de.rki.covpass.app.dependencies.covpassDeps import de.rki.covpass.app.detail.DetailFragmentNav import de.rki.covpass.commonapp.BaseFragment import de.rki.covpass.sdk.cert.models.BoosterResult import de.rki.covpass.sdk.cert.models.CovCertificate import de.rki.covpass.sdk.cert.models.GroupedCertificatesId import de.rki.covpass.sdk.cert.models.GroupedCertificatesList import kotlinx.coroutines.invoke import kotlinx.parcelize.Parcelize @Parcelize internal class CertificateFragmentNav(val certId: GroupedCertificatesId) : FragmentNav(CertificateFragment::class) /** * Fragment which shows a [CovCertificate] */ internal class CertificateFragment : BaseFragment() { internal val args: CertificateFragmentNav by lazy { getArgs() } private val viewModel by reactiveState { CertificateViewModel(scope) } private val binding by viewBinding(CertificateBinding::inflate) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) autoRun { // TODO: Optimize this, so we only update if our cert has changed and not something else updateViews(get(covpassDeps.certRepository.certs)) } } private fun updateViews(certificateList: GroupedCertificatesList) { val certId = args.certId val groupedCertificate = certificateList.getGroupedCertificates(certId) ?: return val mainCombinedCertificate = groupedCertificate.getMainCertificate() val mainCertificate = mainCombinedCertificate.covCertificate val isMarkedAsFavorite = certificateList.isMarkedAsFavorite(certId) val certStatus = mainCombinedCertificate.status val isFavoriteButtonVisible = certificateList.certificates.size > 1 launchWhenStarted { binding.certificateCard.qrCodeImage = generateQRCode(mainCombinedCertificate.qrContent) } val showBoosterNotification = !groupedCertificate.hasSeenBoosterDetailNotification && groupedCertificate.boosterNotification.result == BoosterResult.Passed binding.certificateCard.createCertificateCardView( mainCertificate.fullName, isMarkedAsFavorite, certStatus, showBoosterNotification ) binding.certificateCard.isFavoriteButtonVisible = isFavoriteButtonVisible binding.certificateCard.setOnFavoriteClickListener { viewModel.onFavoriteClick(args.certId) } binding.certificateCard.setOnCardClickListener { findNavigator().push(DetailFragmentNav(args.certId)) } binding.certificateCard.setOnCertificateStatusClickListener { findNavigator().push(DetailFragmentNav(args.certId)) } } private suspend fun generateQRCode(qrContent: String): Bitmap { return dispatchers.default { BarcodeEncoder().encodeBitmap( qrContent, BarcodeFormat.QR_CODE, resources.displayMetrics.widthPixels, resources.displayMetrics.widthPixels, mapOf(EncodeHintType.MARGIN to 0) ) } } }
kotlin
23
0.749329
122
39.564356
101
starcoderdata
rootProject.name = "Day6"
kotlin
4
0.678571
25
8.333333
3
starcoderdata
package me.shouheng.api.sample import com.alibaba.android.arouter.facade.template.IProvider import me.shouheng.api.bean.User /** Service to get user data */ interface UserService : IProvider { /** Request user data */ fun requestUser() /** Register user data change listener */ fun registerUserChangeListener(userChangeListener: OnUserChangeListener) /** Unregister user data change listener */ fun unRegisterUserChangeListener(userChangeListener: OnUserChangeListener) } /** User data change listener */ interface OnUserChangeListener { /** Called when user data changed */ fun onUserChanged(user: User) }
kotlin
7
0.744977
78
24.88
25
starcoderdata
/* * The MIT License * * Copyright (c) 2014- High-Mobility GmbH (https://high-mobility.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.highmobility.hmkitfleet import com.highmobility.crypto.Crypto import com.highmobility.hmkitfleet.network.* import com.highmobility.hmkitfleet.network.AccessCertificateRequests import com.highmobility.hmkitfleet.network.AuthTokenRequests import com.highmobility.hmkitfleet.network.Cache import com.highmobility.hmkitfleet.network.ClearanceRequests import com.highmobility.hmkitfleet.network.Requests import okhttp3.OkHttpClient import org.koin.core.Koin import org.koin.core.KoinApplication import org.koin.core.component.KoinComponent import org.koin.dsl.koinApplication import org.koin.dsl.module import org.slf4j.LoggerFactory internal object Koin { val koinModules = module { single { LoggerFactory.getLogger(HMKitFleet::class.java) } single { OkHttpClient() } single { HMKitFleet.environment } single { Crypto() } single { Requests(get(), get(), HMKitFleet.environment.url) } single { Cache() } single { AuthTokenRequests( get(), get(), get(), HMKitFleet.environment.url, HMKitFleet.configuration, get() ) } single { AccessTokenRequests( get(), get(), HMKitFleet.environment.url, get(), HMKitFleet.configuration ) } single { ClearanceRequests(get(), get(), HMKitFleet.environment.url, get()) } single { AccessCertificateRequests( get(), get(), HMKitFleet.environment.url, HMKitFleet.configuration.getClientPrivateKey(), HMKitFleet.configuration.clientCertificate, get() ) } single { TelematicsRequests( get(), get(), HMKitFleet.environment.url, HMKitFleet.configuration.getClientPrivateKey(), HMKitFleet.configuration.clientCertificate, get() ) } } lateinit var koinApplication: KoinApplication fun start() { koinApplication = koinApplication { modules(koinModules) } } interface FleetSdkKoinComponent : KoinComponent { override fun getKoin(): Koin { return koinApplication.koin } } }
kotlin
22
0.641349
85
34.076923
104
starcoderdata
package com.samrans.labtest.ui.labselect import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.samrans.labtest.R import com.samrans.labtest.responseModel.DetailList import com.samrans.labtest.ui.listeners.OnClickListenerWithPositionType class LabSelectListAdapter( val filteredList: ArrayList<DetailList> , val listener: OnClickListenerWithPositionType ) : RecyclerView.Adapter<LabSelectListAdapter.DataHolder>() { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): LabSelectListAdapter.DataHolder { val v = LayoutInflater.from(parent?.context).inflate(R.layout.item_lab_select, parent, false) return LabSelectListAdapter.DataHolder(v) } override fun getItemCount(): Int { return filteredList.size } override fun onBindViewHolder(holder: LabSelectListAdapter.DataHolder, position: Int) { val labListModel = filteredList.get(position) // holder.tv_sublabtitle.text = labListModel.mTitle holder.itemView.setOnClickListener { listener.onClickItem(labListModel, -1, R.layout.item_lab) } } class DataHolder(itemViewHolder: View) : RecyclerView.ViewHolder(itemViewHolder) { val tv_sublabtitle = itemView.findViewById<TextView>(R.id.tv_sublabtitle) val iv_image_back = itemView.findViewById<ImageView>(R.id.iv_image_back) } }
kotlin
18
0.747416
101
35.023256
43
starcoderdata
package com.rickclephas.kmp.nativecoroutines.compiler import com.google.auto.service.AutoService import org.jetbrains.kotlin.compiler.plugin.AbstractCliOption import org.jetbrains.kotlin.compiler.plugin.CliOption import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor import org.jetbrains.kotlin.config.CompilerConfiguration @AutoService(CommandLineProcessor::class) class KmpNativeCoroutinesCommandLineProcessor: CommandLineProcessor { override val pluginId: String = "com.rickclephas.kmp.nativecoroutines" override val pluginOptions: Collection<AbstractCliOption> = listOf( CliOption(SUFFIX_OPTION_NAME, "string", "suffix used for the generated functions", true) ) override fun processOption( option: AbstractCliOption, value: String, configuration: CompilerConfiguration ) = when (option.optionName) { SUFFIX_OPTION_NAME -> configuration.put(SUFFIX_KEY, value) else -> error("Unexpected config option ${option.optionName}") } }
kotlin
16
0.771878
96
38.153846
26
starcoderdata
<reponame>goshaginyan/pyrusservicedesk package com.pyrus.pyrusservicedesk.sdk.updates internal interface Preferences { /** * Save the last user's comment in shared preferences. */ fun saveLastComment(comment: LastComment) /** * @return The LastComment instance from shared preferences. */ fun getLastComment(): LastComment? /** * Remove the last user's comment from preferences. */ fun removeLastComment() /** * Save the last user's active time. */ fun saveLastActiveTime(time: Long) /** * @return the last user's active time. */ fun getLastActiveTime(): Long /** * Save the list of token registration times */ fun setTokenRegisterTimeList(timeList: List<Long>) /** * @return the list of token registration times */ fun getTokenRegisterTimeList(): List<Long> /** * Save the map of token registration time to user */ fun setLastTokenRegisterMap(timeMap: Map<String, Long>) /** * @return the map of token registration time to user */ fun getLastTokenRegisterMap(): Map<String, Long> }
kotlin
10
0.641558
64
21.666667
51
starcoderdata
<filename>plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/library/LibraryDescriptor.kt // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.library import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Repository import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version sealed class LibraryArtifact data class MavenArtifact( val repository: Repository, @NonNls val groupId: String, @NonNls val artifactId: String ) : LibraryArtifact() data class NpmArtifact( @NonNls val name: String ) : LibraryArtifact() sealed class LibraryDescriptor { abstract val artifact: LibraryArtifact abstract val type: LibraryType abstract val version: Version } data class MavenLibraryDescriptor( override val artifact: MavenArtifact, override val type: LibraryType, override val version: Version ) : LibraryDescriptor() data class NpmLibraryDescriptor( override val artifact: NpmArtifact, override val version: Version ) : LibraryDescriptor() { override val type: LibraryType get() = LibraryType.NPM } sealed class LibraryType( val supportJvm: Boolean, val supportJs: Boolean, val supportNative: Boolean ) { object JVM_ONLY : LibraryType(supportJvm = true, supportJs = false, supportNative = false) object JS_ONLY : LibraryType(supportJvm = false, supportJs = true, supportNative = false) object NPM : LibraryType(supportJvm = false, supportJs = true, supportNative = false) object MULTIPLATFORM : LibraryType(supportJvm = true, supportJs = true, supportNative = true) }
kotlin
12
0.768462
158
32.981132
53
starcoderdata
<gh_stars>0 package com.vishalgaur.shoppingapp.data import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.android.parcel.Parcelize @Parcelize @Entity(tableName = "products") data class Product @JvmOverloads constructor( @PrimaryKey var productId: String = "", var name: String = "", var unit: String = "", var owner: String = "", var description: String = "", var category: String = "", var price: Double = 0.0, var mrp: Double = 0.0, var availableSizes: List<Int> = ArrayList(), var availableColors: List<String> = ArrayList(), var images: List<String> = ArrayList(), var rating: Double = 0.0 ) : Parcelable { fun toHashMap(): HashMap<String, Any> { return hashMapOf( "productId" to productId, "name" to name, "unit" to unit, "owner" to owner, "description" to description, "category" to category, "price" to price, "mrp" to mrp, "availableSizes" to availableSizes, "availableColors" to availableColors, "images" to images, "rating" to rating ) } }
kotlin
12
0.694129
49
24.166667
42
starcoderdata
package com.aptopayments.sdk.core.di.fragment import com.aptopayments.mobile.data.transaction.MCC import com.aptopayments.sdk.core.data.TestDataProvider import com.aptopayments.sdk.core.platform.BaseFragment import com.aptopayments.sdk.features.card.transactionlist.TransactionListConfig import com.aptopayments.sdk.features.card.transactionlist.TransactionListFragment import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import kotlin.test.assertEquals class FragmentFactoryTest { private lateinit var sut: FragmentFactory @BeforeEach fun setUp() { sut = FragmentFactoryImpl() } @Test fun `transaction list fragment for theme2 return expected fragment and set TAG`() { // Given val config = TransactionListConfig(startDate = null, endDate = null, mcc = MCC(name = null, icon = null)) val tag = "TRANSACTION_LIST_TEST_TAG" // When val fragment = sut.transactionListFragment(TestDataProvider.provideCardId(), config, tag) // Then assert(fragment is TransactionListFragment) assertEquals(tag, (fragment as BaseFragment).TAG) } }
kotlin
15
0.741349
113
33
34
starcoderdata
import tk.q11mk.accounts.changeClassData import tk.q11mk.database.* import tk.q11mk.schedule.Schedule fun main() { /*Database("jdbc:mysql://127.0.0.1:3306", "Test", "test").use { db -> /*val s = db.createSchema("schema").getOrThrow() val t = s.createTable("table", "id").getOrThrow() t.addColumn("column", Table.Column.Type.JSON).getOrThrow()*/ val s = db.getSchema("schedule").getOrThrow() val mon = s.getTable<Int>("mon").getOrThrow() val c = mon.get<String>(0, "SCHN").getOrThrow() println(c) }*/ /*Database("jdbc:mysql://127.0.0.1:3306", "Test", "test").use { db -> val t = db.getSchema("schedules").getOrThrow().getTable<Int>("mon").getOrThrow() //t.addColumn("SCHN", DataType.STRING(100)).getOrThrow() //t.set("SCHN", 0, "{}").getOrThrow() t.insertRow(listOf(0, "{}")).getOrThrow() }*/ /*getScheduleTable(0).addColumn("SCHN", DataType.STRING(256)).getOrThrow() getScheduleTable(0)//.set("SCHN", 1, """{"class": "7A"}""").getOrThrow() .insertRow(listOf(1, """{"class": "7A"}""")).getOrThrow()*/ //getScheduleTable(0).set("SCHN", 1, """{"class":"7A","subject":"M"}""") //getScheduleTable(1).set("POHL", 5, """{"class":"7A","teacher":"POHL","subject":"Inf","room":"E209","substituted":true,"substitute_teacher":"SCHN","substitute_room":"E209"}""").getOrThrow() //println(Schedule.Day.fromRequest(1, "7A", "Inf, M, D")) //println(getScheduleTable(1).getLike<String>("POHL", """%"class"%:%"7A"%""")) //Schedule.Day.fromRequest(0, "7A", "D,E,M,F") //idsTable.insertRow(listOf(1234567890L, "Simon", "Neumann", "<EMAIL>", false)).getOrThrow() //println(getAccountFromId(1234567890)) //println(idsTable.has("51234567890")) //println(changeClassData(1234567890.toString(), "11Q", "M1,D3")) }
kotlin
4
0.605192
194
47.684211
38
starcoderdata
/* * AppCompatWebComponents (https://github.com/androidovshchik/AppCompatWebComponents) * Copyright (c) 2019. <NAME> <<EMAIL>> */ package androidovshchik.webcomponents.models import android.os.Parcel import android.os.Parcelable open class WebRequest(val data: CharSequence?, baseUrl: CharSequence? = null) : Parcelable { constructor(parcel: Parcel) : this( parcel.readString(), TODO("baseUrl")) { } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(data?.toString()) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<WebRequest> { override fun createFromParcel(parcel: Parcel): WebRequest { return WebRequest(parcel) } override fun newArray(size: Int): Array<WebRequest?> { return arrayOfNulls(size) } } }
kotlin
13
0.659715
92
25.057143
35
starcoderdata
<filename>walletconnectv2/src/main/kotlin/com/walletconnect/walletconnectv2/relay/data/serializer/JsonRpcSerializer.kt package com.walletconnect.walletconnectv2.relay.data.serializer import com.squareup.moshi.Moshi import com.walletconnect.walletconnectv2.core.model.type.ClientParams import com.walletconnect.walletconnectv2.core.model.type.SerializableJsonRpc import com.walletconnect.walletconnectv2.core.model.utils.JsonRpcMethod import com.walletconnect.walletconnectv2.core.model.vo.TopicVO import com.walletconnect.walletconnectv2.core.model.vo.clientsync.pairing.PairingSettlementVO import com.walletconnect.walletconnectv2.core.model.vo.clientsync.session.SessionSettlementVO import com.walletconnect.walletconnectv2.crypto.CryptoRepository import com.walletconnect.walletconnectv2.relay.Codec import com.walletconnect.walletconnectv2.relay.model.RelayDO import com.walletconnect.walletconnectv2.util.Empty import com.walletconnect.walletconnectv2.util.Logger internal class JsonRpcSerializer( private val authenticatedEncryptionCodec: Codec, private val crypto: CryptoRepository, private val moshi: Moshi, ) { internal fun encode(payload: String, topic: TopicVO): String { val symmetricKey = crypto.getSymmetricKey(topic) return authenticatedEncryptionCodec.encrypt(payload, symmetricKey) } internal fun decode(message: String, topic: TopicVO): String { return try { val symmetricKey = crypto.getSymmetricKey(topic) authenticatedEncryptionCodec.decrypt(message, symmetricKey) } catch (e: Exception) { Logger.error("Decoding error: ${e.message}") String.Empty } } internal fun deserialize(method: String, json: String): ClientParams? = when (method) { JsonRpcMethod.WC_SESSION_PROPOSE -> tryDeserialize<PairingSettlementVO.SessionPropose>(json)?.params JsonRpcMethod.WC_PAIRING_PING -> tryDeserialize<PairingSettlementVO.PairingPing>(json)?.params JsonRpcMethod.WC_SESSION_SETTLE -> tryDeserialize<SessionSettlementVO.SessionSettle>(json)?.params JsonRpcMethod.WC_SESSION_REQUEST -> tryDeserialize<SessionSettlementVO.SessionRequest>(json)?.params JsonRpcMethod.WC_SESSION_DELETE -> tryDeserialize<SessionSettlementVO.SessionDelete>(json)?.params JsonRpcMethod.WC_SESSION_PING -> tryDeserialize<SessionSettlementVO.SessionPing>(json)?.params JsonRpcMethod.WC_SESSION_EVENT -> tryDeserialize<SessionSettlementVO.SessionEvent>(json)?.params JsonRpcMethod.WC_SESSION_UPDATE_EVENTS -> tryDeserialize<SessionSettlementVO.SessionUpdateEvents>(json)?.params JsonRpcMethod.WC_SESSION_UPDATE_ACCOUNTS -> tryDeserialize<SessionSettlementVO.SessionUpdateAccounts>(json)?.params JsonRpcMethod.WC_SESSION_UPDATE_METHODS -> tryDeserialize<SessionSettlementVO.SessionUpdateMethods>(json)?.params JsonRpcMethod.WC_SESSION_UPDATE_EXPIRY -> tryDeserialize<SessionSettlementVO.SessionUpdateExpiry>(json)?.params else -> null } fun serialize(payload: SerializableJsonRpc): String = when (payload) { is PairingSettlementVO.SessionPropose -> trySerialize(payload) is PairingSettlementVO.PairingPing -> trySerialize(payload) is PairingSettlementVO.PairingDelete -> trySerialize(payload) is SessionSettlementVO.SessionPing -> trySerialize(payload) is SessionSettlementVO.SessionEvent -> trySerialize(payload) is SessionSettlementVO.SessionUpdateAccounts -> trySerialize(payload) is SessionSettlementVO.SessionUpdateMethods -> trySerialize(payload) is SessionSettlementVO.SessionUpdateEvents -> trySerialize(payload) is SessionSettlementVO.SessionUpdateExpiry -> trySerialize(payload) is SessionSettlementVO.SessionRequest -> trySerialize(payload) is SessionSettlementVO.SessionDelete -> trySerialize(payload) is SessionSettlementVO.SessionSettle -> trySerialize(payload) is RelayDO.JsonRpcResponse.JsonRpcResult -> trySerialize(payload) is RelayDO.JsonRpcResponse.JsonRpcError -> trySerialize(payload) else -> String.Empty } inline fun <reified T> tryDeserialize(json: String): T? = runCatching { moshi.adapter(T::class.java).fromJson(json) }.getOrNull() private inline fun <reified T> trySerialize(type: T): String = moshi.adapter(T::class.java).toJson(type) }
kotlin
20
0.750055
133
59.56
75
starcoderdata
<filename>app/src/main/java/com/binaracademy/binarandroidchapter3/MainActivity.kt package com.binaracademy.binarandroidchapter3 import android.content.Context import android.content.Intent import android.net.wifi.WifiManager import android.os.Bundle import android.view.Window import android.widget.CompoundButton import androidx.appcompat.app.AppCompatActivity import com.binaracademy.binarandroidchapter3.databinding.ActivityMainBinding import com.bumptech.glide.Glide class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestWindowFeature(Window.FEATURE_NO_TITLE) supportActionBar?.hide() binding = ActivityMainBinding.inflate(layoutInflater) Glide.with(this) .load("https://i.ibb.co/zJHYGBP/binarlogo.jpg") .circleCrop() .into(binding.imageView) setContentView(binding.root) binding.moveActivity.setOnClickListener { val intent = Intent(this@MainActivity, SecondActivity::class.java) startActivity(intent) } var changeImage = 1 binding.buttonView.setOnClickListener { if (changeImage == 1){ Glide.with(this) .load("https://i.ibb.co/zJHYGBP/binarlogo.jpg") .circleCrop() .into(binding.imageView) changeImage = 2 } else { Glide.with(this) .load("https://global-uploads.webflow.com/6100d0111a4ed76bc1b9fd54/616fd70b2be60a72b46f2da3_logo_7b6caab85699ca72e06917e9bad7512c.png") .into(binding.imageView) changeImage = 1 } } binding.buttonSpecialView.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { compoundButton, checked -> if (checked) { binding.viewStatusText.text = "WiFi is ON" val wifi = getSystemService(Context.WIFI_SERVICE) as WifiManager wifi.isWifiEnabled = true } else { binding.viewStatusText.text = "WiFi is OFF" val wifi = getSystemService(Context.WIFI_SERVICE) as WifiManager wifi.isWifiEnabled = false } }) // For initial setting if (binding.buttonSpecialView.isChecked) { binding.viewStatusText.text = "WiFi is ON" val wifi = getSystemService(Context.WIFI_SERVICE) as WifiManager wifi.isWifiEnabled = true } else { binding.viewStatusText.text = "WiFi is OFF" val wifi = getSystemService(Context.WIFI_SERVICE) as WifiManager wifi.isWifiEnabled = false } } }
kotlin
26
0.639944
155
37.445946
74
starcoderdata
package magnet.processor.factory import com.squareup.javapoet.JavaFile import com.squareup.javapoet.TypeSpec import javax.annotation.processing.Filer class CodeWriter( private var filePackage: String, private var fileTypeSpec: TypeSpec ) { fun writeInto(filer: Filer) { JavaFile .builder(filePackage, fileTypeSpec) .skipJavaLangImports(true) .build() .writeTo(filer) } }
kotlin
16
0.679372
47
21.35
20
starcoderdata
<filename>src/Aula07/exercicioAula-4-Consumo-Exercicio4.kt package Aula07 fun main() { var suvDaPat = Carro(12.35) suvDaPat.adicionarGasolina(80.0) suvDaPat.obterGasolina() suvDaPat.andar(222.0) suvDaPat.obterGasolina() suvDaPat.andar(835.0) suvDaPat.obterGasolina() }
kotlin
10
0.723906
58
23.833333
12
starcoderdata
<reponame>Moosphan/G2Video<filename>app/src/main/java/com/moosphon/g2v/model/SectionHeader.kt<gh_stars>1-10 package com.moosphon.g2v.model import androidx.annotation.StringRes data class SectionHeader( @StringRes val titleId: Int, val useHorizontalPadding: Boolean = true )
kotlin
12
0.798587
107
30.555556
9
starcoderdata
package org.lexem.angmar.analyzer.nodes.functional.statements.selective import org.lexem.angmar.* import org.lexem.angmar.analyzer.* import org.lexem.angmar.analyzer.data.primitives.* import org.lexem.angmar.analyzer.data.referenced.* import org.lexem.angmar.analyzer.nodes.* import org.lexem.angmar.analyzer.stdlib.types.* import org.lexem.angmar.config.* import org.lexem.angmar.errors.* import org.lexem.angmar.parser.functional.statements.* import org.lexem.angmar.parser.functional.statements.selective.* /** * Analyzer for variable patterns of the selective statements. */ internal object VarPatternSelectiveStmtAnalyzer { const val signalEndIdentifier = AnalyzerNodesCommons.signalStart + 1 const val signalEndConditional = signalEndIdentifier + 1 // METHODS ---------------------------------------------------------------- fun stateMachine(analyzer: LexemAnalyzer, signal: Int, node: VarPatternSelectiveStmtNode) { when (signal) { AnalyzerNodesCommons.signalStart -> { return analyzer.nextNode(node.identifier) } signalEndIdentifier -> { val identifier = analyzer.memory.getLastFromStack() val mainValue = analyzer.memory.getFromStack(AnalyzerCommons.Identifiers.SelectiveCondition) val context = AnalyzerCommons.getCurrentContext(analyzer.memory) // Check identifier if it is not a destructuring. if (node.identifier !is DestructuringStmtNode) { if (identifier !is LxmString) { throw AngmarAnalyzerException(AngmarAnalyzerExceptionType.IncompatibleType, "The returned value by the identifier expression must be a ${StringType.TypeName}. Actual value: $identifier") { val fullText = node.parser.reader.readAllText() addSourceCode(fullText, node.parser.reader.getSource()) { title = Consts.Logger.codeTitle highlightSection(node.from.position(), node.to.position() - 1) } addSourceCode(fullText) { title = Consts.Logger.hintTitle highlightSection(node.identifier.from.position(), node.identifier.to.position() - 1) message = "Review the returned value of this expression" } } } } // Perform the destructuring. if (node.identifier is DestructuringStmtNode) { identifier as LxmDestructuring when (val derefValue = mainValue.dereference(analyzer.memory)) { is LxmObject -> identifier.destructureObject(analyzer.memory, derefValue, context, node.isConstant) is LxmList -> identifier.destructureList(analyzer.memory, derefValue, context, node.isConstant) else -> throw AngmarAnalyzerException(AngmarAnalyzerExceptionType.IncompatibleType, "Destructuring is only available for ${ObjectType.TypeName}s and ${ListType.TypeName}s. Actual value: $derefValue") { val fullText = node.parser.reader.readAllText() addSourceCode(fullText, node.parser.reader.getSource()) { title = Consts.Logger.codeTitle highlightSection(node.from.position(), node.to.position() - 1) } addNote(Consts.Logger.hintTitle, "The value is received from the ${SelectiveStmtNode.keyword} statement's condition. Review that value.") } } } else { identifier as LxmString context.setPropertyAsContext(analyzer.memory, identifier.primitive, mainValue, isConstant = node.isConstant) } // Remove Last from the stack. analyzer.memory.removeLastFromStack() if (node.conditional != null) { return analyzer.nextNode(node.conditional) } analyzer.memory.addToStackAsLast(LxmLogic.True) } signalEndConditional -> { // Returns the value of the conditional. } } return analyzer.nextNode(node.parent, node.parentSignal) } }
kotlin
37
0.56495
149
48.673684
95
starcoderdata