path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
PluginsAndFeatures/azure-toolkit-for-intellij/rider/src/org/jetbrains/plugins/azure/storage/azurite/actions/StopAzuriteAction.kt
JetBrains
137,064,201
true
{"Java": 6824035, "Kotlin": 2388176, "C#": 183917, "Scala": 151332, "Gherkin": 108427, "JavaScript": 98350, "HTML": 23518, "CSS": 21770, "Groovy": 21447, "Shell": 21354, "XSLT": 7141, "Dockerfile": 3518, "Batchfile": 2155}
/** * Copyright (c) 2020-2023 JetBrains s.r.o. * * All rights reserved. * * 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 org.jetbrains.plugins.azure.storage.azurite.actions import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.service import org.jetbrains.plugins.azure.RiderAzureBundle.message import org.jetbrains.plugins.azure.storage.azurite.AzuriteService class StopAzuriteAction : AnAction( message("action.azurite.stop.name"), message("action.azurite.stop.description"), AllIcons.Actions.Suspend) { private val azuriteService = service<AzuriteService>() override fun update(e: AnActionEvent) { e.presentation.isEnabled = azuriteService.isRunning } override fun actionPerformed(e: AnActionEvent) { if (azuriteService.isRunning) { azuriteService.stop() } } override fun getActionUpdateThread() = ActionUpdateThread.BGT }
73
Java
10
41
a8b64627376a5144a71725853ba4217b97044722
2,152
azure-tools-for-intellij
MIT License
_old/experiments/ref2.kt
sangohan
53,041,538
true
{"YAML": 1, "Markdown": 6, "Maven POM": 17, "EditorConfig": 1, "Text": 2, "Ignore List": 14, "Java": 430, "Batchfile": 1, "Kotlin": 96, "Haxe": 13, "SVG": 1, "Ant Build System": 1}
/* * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jtransc.input.asm import org.objectweb.asm.* class ArrayReader<T>(val list: List<T>, var offset: Int) { } // https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.6 class TestMethodVisitor : MethodVisitor(Opcodes.ASM5) { init { println("------------ METHOD") } override fun visitMultiANewArrayInsn(desc: String?, dims: Int) { println("visitMultiANewArrayInsn: $desc, $dims") super.visitMultiANewArrayInsn(desc, dims) } override fun visitFrame(type: Int, nLocal: Int, local: Array<out Any>?, nStack: Int, stack: Array<out Any>?) { println("visitFrame: $type, $nLocal, $local, $nStack, $stack") super.visitFrame(type, nLocal, local, nStack, stack) } override fun visitVarInsn(opcode: Int, `var`: Int) { println("visitVarInsn: $opcode, $`var`") super.visitVarInsn(opcode, `var`) } override fun visitTryCatchBlock(start: Label?, end: Label?, handler: Label?, type: String?) { println("visitTryCatchBlock: $start, $end, $handler, $type") super.visitTryCatchBlock(start, end, handler, type) } override fun visitLookupSwitchInsn(dflt: Label?, keys: IntArray?, labels: Array<out Label>?) { println("visitLookupSwitchInsn: $dflt, $keys, $labels") super.visitLookupSwitchInsn(dflt, keys, labels) } override fun visitJumpInsn(opcode: Int, label: Label?) { println("visitJumpInsn: $opcode, $label") super.visitJumpInsn(opcode, label) } override fun visitLdcInsn(cst: Any?) { println("visitLdcInsn: $cst") super.visitLdcInsn(cst) } override fun visitIntInsn(opcode: Int, operand: Int) { println("visitIntInsn: $opcode, $operand") super.visitIntInsn(opcode, operand) } override fun visitTypeInsn(opcode: Int, type: String?) { println("visitTypeInsn: $opcode, $type") super.visitTypeInsn(opcode, type) } override fun visitAnnotationDefault(): AnnotationVisitor? { println("visitAnnotationDefault") return super.visitAnnotationDefault() } override fun visitAnnotation(desc: String?, visible: Boolean): AnnotationVisitor? { println("visitAnnotation: $desc, $visible") return super.visitAnnotation(desc, visible) } override fun visitTypeAnnotation(typeRef: Int, typePath: TypePath?, desc: String?, visible: Boolean): AnnotationVisitor? { println("visitTypeAnnotation: $typeRef, $typePath, $desc, $visible") return super.visitTypeAnnotation(typeRef, typePath, desc, visible) } override fun visitMaxs(maxStack: Int, maxLocals: Int) { println("visitMaxs: $maxStack, $maxLocals") super.visitMaxs(maxStack, maxLocals) } override fun visitInvokeDynamicInsn(name: String?, desc: String?, bsm: Handle?, vararg bsmArgs: Any?) { println("visitInvokeDynamicInsn: $name, $desc, $bsm, $bsmArgs") super.visitInvokeDynamicInsn(name, desc, bsm, *bsmArgs) } override fun visitLabel(label: Label?) { println("visitLabel: $label") super.visitLabel(label) } override fun visitTryCatchAnnotation(typeRef: Int, typePath: TypePath?, desc: String?, visible: Boolean): AnnotationVisitor? { println("visitTryCatchAnnotation: $typeRef, $typePath, $desc, $visible") return super.visitTryCatchAnnotation(typeRef, typePath, desc, visible) } override fun visitMethodInsn(opcode: Int, owner: String?, name: String?, desc: String?, itf: Boolean) { println("visitMethodInsn: $opcode, $owner, $name, $desc, $itf") super.visitMethodInsn(opcode, owner, name, desc, itf) } override fun visitInsn(opcode: Int) { println("visitInsn: $opcode") super.visitInsn(opcode) } override fun visitInsnAnnotation(typeRef: Int, typePath: TypePath?, desc: String?, visible: Boolean): AnnotationVisitor? { println("visitInsnAnnotation: $typeRef, $typePath, $desc, $visible") return super.visitInsnAnnotation(typeRef, typePath, desc, visible) } override fun visitParameterAnnotation(parameter: Int, desc: String?, visible: Boolean): AnnotationVisitor? { println("visitParameterAnnotation: $parameter, $desc, $visible") return super.visitParameterAnnotation(parameter, desc, visible) } override fun visitIincInsn(`var`: Int, increment: Int) { println("visitIincInsn: $`var`, $increment") super.visitIincInsn(`var`, increment) } override fun visitLineNumber(line: Int, start: Label?) { println("visitLineNumber: $line, $start") super.visitLineNumber(line, start) } override fun visitLocalVariableAnnotation(typeRef: Int, typePath: TypePath?, start: Array<out Label>?, end: Array<out Label>?, index: IntArray?, desc: String?, visible: Boolean): AnnotationVisitor? { println("visitLocalVariableAnnotation: $typeRef, $typePath, $start, $end, $index, $desc, $visible") return super.visitLocalVariableAnnotation(typeRef, typePath, start, end, index, desc, visible) } override fun visitTableSwitchInsn(min: Int, max: Int, dflt: Label?, vararg labels: Label?) { println("visitTableSwitchInsn: $min, $max, $dflt, $labels") super.visitTableSwitchInsn(min, max, dflt, *labels) } override fun visitEnd() { println("visitEnd") super.visitEnd() } override fun visitLocalVariable(name: String?, desc: String?, signature: String?, start: Label?, end: Label?, index: Int) { println("visitLocalVariable: $name, $desc, $signature, $start, $end, $index") super.visitLocalVariable(name, desc, signature, start, end, index) } override fun visitParameter(name: String?, access: Int) { println("visitParameter: $name, $access") super.visitParameter(name, access) } override fun visitAttribute(attr: Attribute?) { println("visitAttribute: $attr") super.visitAttribute(attr) } override fun visitFieldInsn(opcode: Int, owner: String?, name: String?, desc: String?) { println("visitFieldInsn: $opcode, $owner, $name, $desc") super.visitFieldInsn(opcode, owner, name, desc) } override fun visitCode() { println("visitCode") super.visitCode() } } class TestFieldVisitor : FieldVisitor(Opcodes.ASM5) { init { println("------------ FIELD") } override fun visitEnd() { println("visitEnd") super.visitEnd() } override fun visitAnnotation(desc: String?, visible: Boolean): AnnotationVisitor? { println("visitAnnotation: $desc, $visible") return super.visitAnnotation(desc, visible) } override fun visitTypeAnnotation(typeRef: Int, typePath: TypePath?, desc: String?, visible: Boolean): AnnotationVisitor? { println("visitTypeAnnotation: $typeRef, $typePath, $desc, $visible") return super.visitTypeAnnotation(typeRef, typePath, desc, visible) } override fun visitAttribute(attr: Attribute?) { println("visitAttribute: $attr") super.visitAttribute(attr) } } class TestClassVisitor : ClassVisitor(Opcodes.ASM5) { init { println("------------ CLASS") } override fun visitMethod(access: Int, name: String?, desc: String?, signature: String?, exceptions: Array<out String>?): MethodVisitor? { println("visitMethod: $access, $name, $desc, $signature, $exceptions") //return super.visitMethod(access, name, desc, signature, exceptions) return TestMethodVisitor() } override fun visitInnerClass(name: String?, outerName: String?, innerName: String?, access: Int) { println("visitInnerClass: $name, $outerName, $innerName, $access") super.visitInnerClass(name, outerName, innerName, access) } override fun visitSource(source: String?, debug: String?) { println("visitSource: $source, $debug") super.visitSource(source, debug) } override fun visitOuterClass(owner: String?, name: String?, desc: String?) { println("visitOuterClass: $owner, $name, $desc") super.visitOuterClass(owner, name, desc) } override fun visit(version: Int, access: Int, name: String?, signature: String?, superName: String?, interfaces: Array<out String>?) { println("visit: $version, $access, $name, $signature, $superName, $interfaces") super.visit(version, access, name, signature, superName, interfaces) } override fun visitField(access: Int, name: String?, desc: String?, signature: String?, value: Any?): FieldVisitor? { println("visitField: $access, $name, $desc, $signature, $value") return super.visitField(access, name, desc, signature, value) } override fun visitEnd() { println("visitEnd") super.visitEnd() } override fun visitAnnotation(desc: String?, visible: Boolean): AnnotationVisitor? { println("visitAnnotation: $desc, $visible") return super.visitAnnotation(desc, visible) } override fun visitTypeAnnotation(typeRef: Int, typePath: TypePath?, desc: String?, visible: Boolean): AnnotationVisitor? { println("visitTypeAnnotation: $typeRef, $typePath, $desc, $visible") return super.visitTypeAnnotation(typeRef, typePath, desc, visible) } override fun visitAttribute(attr: Attribute?) { println("visitAttribute: $attr") super.visitAttribute(attr) } } object Main4 { @JvmStatic fun main(args: Array<String>) { //println(Simple1::class.qualifiedName.replace()) val path = Simple1::class.java.canonicalName.replace('.', '/') println(path) val clazzStream = javaClass.getResourceAsStream("/$path.class") ClassReader(clazzStream).accept(TestClassVisitor(), ClassReader.EXPAND_FRAMES) } }
0
Java
0
0
90ba3655363b802a55efec5bd6ce77a721dc2b31
9,616
jtransc
Apache License 2.0
src/commonMain/kotlin/Farmos.kt
applecreekacres
301,203,846
false
null
class Farmos { }
4
Kotlin
0
0
85b71c39e63b95615d88cd2093f2cf7139f0ee9f
16
farmos.kt
MIT License
dragtoclosedialog/src/main/java/com/wengelef/dragtoclosedialog/DragDialogFragment.kt
wengelef
79,580,102
false
null
package com.wengelef.dragtoclosedialog import android.support.v4.view.MotionEventCompat import android.view.MotionEvent import android.view.View abstract class DragDialogFragment : BaseDialogFragment() { enum class CloseDirection { DEFAULT, BOTTOM, TOP } private val DRAG_TO_DISMISS_DISTANCE = 400 private var initialDragContainerPosition = 0f override fun onStart() { mAnimationListener = getDialogAnimationListener() getContentView().setOnTouchListener(getTouchListener()) super.onStart() } protected open fun getCloseDirection(): CloseDirection = CloseDirection.DEFAULT private fun getDialogAnimationListener(): DialogAnimationListener = object : DialogAnimationListener { override fun onAnimationEnd() { initialDragContainerPosition = getContentView().y } } private fun getTouchListener(): View.OnTouchListener = object : View.OnTouchListener { private var lastTouchY: Float = 0f private var distanceCovered: Float = 0f override fun onTouch(v: View, event: MotionEvent): Boolean { val action = MotionEventCompat.getActionMasked(event) when (action) { MotionEvent.ACTION_DOWN -> { lastTouchY = event.rawY distanceCovered = 0f } MotionEvent.ACTION_MOVE -> { val y = event.rawY val dy = y - lastTouchY distanceCovered += dy getContentView().y = getContentView().y + dy lastTouchY = y } MotionEvent.ACTION_UP -> onDragEnd() MotionEvent.ACTION_CANCEL -> onDragEnd() else -> return true } return true } private fun onDragEnd() { if (getCloseableBottom()) { if (distanceCovered > DRAG_TO_DISMISS_DISTANCE) { close() } else { getContentView().animate().y(initialDragContainerPosition) } } if (getCloseableTop()) { if (distanceCovered < (DRAG_TO_DISMISS_DISTANCE * -1)) { close() } else { getContentView().animate().y(initialDragContainerPosition) } } } } private fun getCloseableBottom(): Boolean { return getCloseDirection() == CloseDirection.DEFAULT || getCloseDirection() == CloseDirection.BOTTOM } private fun getCloseableTop(): Boolean { return getCloseDirection() == CloseDirection.DEFAULT || getCloseDirection() == CloseDirection.TOP } }
1
null
1
1
bc6d1fbd8c8510f0f468d40ebfda37355d4b2f8b
2,754
DragToCloseDialog
Apache License 2.0
app/android/src/main/java/AppActivity.kt
DRSchlaubi
641,131,010
false
{"Kotlin": 185003, "Rust": 3125, "Swift": 2384, "PowerShell": 617, "HTML": 440, "Shell": 274, "Dockerfile": 243, "Ruby": 132}
package dev.schlaubi.tonbrett.app.android import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import dev.schlaubi.tonbrett.app.MobileTonbrettApp import dev.schlaubi.tonbrett.app.ProvideImageLoader import dev.schlaubi.tonbrett.app.api.AppContext import dev.schlaubi.tonbrett.app.api.ProvideContext import dev.schlaubi.tonbrett.app.api.tokenKey class AppActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val token = if (intent.data?.scheme == "tonbrett" && intent.data?.host == "login") { intent.data?.getQueryParameter("token") } else { null } setContent { val context = object : AppContext(this) { override fun reAuthorize() { vault.deleteObject(tokenKey) super.reAuthorize() } } ProvideContext(context) { ProvideImageLoader { UpdateAwareAppScope(activity = this) { MobileTonbrettApp(token) } } } } } }
0
Kotlin
1
6
d684d6b1eec14b0f88baab899eb15366844e415b
1,238
tonbrett
MIT License
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/covidcertificate/execution/TestCertificateProcessorTest.kt
hd42
384,661,671
false
null
package de.rki.coronawarnapp.covidcertificate.execution import de.rki.coronawarnapp.appconfig.AppConfigProvider import de.rki.coronawarnapp.appconfig.ConfigData import de.rki.coronawarnapp.appconfig.CovidCertificateConfig import de.rki.coronawarnapp.covidcertificate.test.core.qrcode.TestCertificateQRCode import de.rki.coronawarnapp.covidcertificate.test.core.qrcode.TestCertificateQRCodeExtractor import de.rki.coronawarnapp.covidcertificate.test.core.server.TestCertificateComponents import de.rki.coronawarnapp.covidcertificate.test.core.server.TestCertificateServer import de.rki.coronawarnapp.covidcertificate.test.core.storage.PCRCertificateData import de.rki.coronawarnapp.covidcertificate.test.core.storage.StoredTestCertificateData import de.rki.coronawarnapp.covidcertificate.test.core.storage.TestCertificateProcessor import de.rki.coronawarnapp.util.TimeStamper import de.rki.coronawarnapp.util.encryption.rsa.RSACryptography import de.rki.coronawarnapp.util.encryption.rsa.RSAKeyPairGenerator import io.mockk.MockKAnnotations import io.mockk.Runs import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.just import io.mockk.mockk import kotlinx.coroutines.flow.flowOf import okio.ByteString import org.joda.time.Duration import org.joda.time.Instant import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import testhelpers.BaseTest import testhelpers.coroutines.runBlockingTest2 class TestCertificateProcessorTest : BaseTest() { @MockK lateinit var timeStamper: TimeStamper @MockK lateinit var certificateServer: TestCertificateServer @MockK lateinit var rsaCryptography: RSACryptography @MockK lateinit var qrCodeExtractor: TestCertificateQRCodeExtractor @MockK lateinit var appConfigProvider: AppConfigProvider @MockK lateinit var appConfigData: ConfigData @MockK lateinit var covidTestCertificateConfig: CovidCertificateConfig.TestCertificate private val testCertificateNew = PCRCertificateData( identifier = "identifier1", registrationToken = "<PASSWORD>", registeredAt = Instant.EPOCH, ) private val testCertificateWithPubKey = testCertificateNew.copy( publicKeyRegisteredAt = Instant.EPOCH, rsaPublicKey = mockk(), rsaPrivateKey = mockk(), ) private val testCerticateComponents = mockk<TestCertificateComponents>().apply { every { dataEncryptionKeyBase64 } returns "dek" every { encryptedCoseTestCertificateBase64 } returns "" } private var storageSet = mutableSetOf<StoredTestCertificateData>() @BeforeEach fun setup() { MockKAnnotations.init(this) every { timeStamper.nowUTC } returns Instant.EPOCH every { appConfigProvider.currentConfig } returns flowOf(appConfigData) every { appConfigData.covidCertificateParameters } returns mockk<CovidCertificateConfig>().apply { every { testCertificate } returns covidTestCertificateConfig } covidTestCertificateConfig.apply { every { waitForRetry } returns Duration.standardSeconds(10) every { waitAfterPublicKeyRegistration } returns Duration.standardSeconds(10) } certificateServer.apply { coEvery { registerPublicKeyForTest(any(), any()) } just Runs coEvery { requestCertificateForTest(any()) } returns testCerticateComponents } every { rsaCryptography.decrypt(any(), any()) } returns ByteString.Companion.EMPTY coEvery { qrCodeExtractor.extract(any(), any()) } returns mockk<TestCertificateQRCode>().apply { every { qrCode } returns "qrCode" every { data } returns mockk() } } private fun createInstance() = TestCertificateProcessor( qrCodeExtractor = qrCodeExtractor, timeStamper = timeStamper, certificateServer = certificateServer, rsaKeyPairGenerator = RSAKeyPairGenerator(), rsaCryptography = rsaCryptography, appConfigProvider = appConfigProvider, ) @Test fun `public key registration`() = runBlockingTest2(ignoreActive = true) { val instance = createInstance() instance.registerPublicKey(testCertificateNew) coVerify { certificateServer.registerPublicKeyForTest(testCertificateNew.registrationToken, any()) } } @Test fun `obtain certificate components`() = runBlockingTest2(ignoreActive = true) { val instance = createInstance() instance.obtainCertificate(testCertificateWithPubKey) coVerify { covidTestCertificateConfig.waitAfterPublicKeyRegistration certificateServer.requestCertificateForTest(testCertificateNew.registrationToken) } } }
1
null
1
1
ec812c6c409fd79852f75ea38a683ebeab823734
4,816
cwa-app-android
Apache License 2.0
src/main/kotlin/com/david/mocassin/view/components/wizards/user_structures_wizards/union_wizard/UnionWizardStep2.kt
david6983
249,154,515
false
null
package com.david.mocassin.view.components.wizards.user_structures_wizards.struct_wizard import com.david.mocassin.controller.ProjectController import com.david.mocassin.model.c_components.CtypeEnum import com.david.mocassin.model.c_components.CuserType import com.david.mocassin.model.c_components.c_struct.CuserStructureModel import com.david.mocassin.model.c_components.c_variable.Cvariable import com.david.mocassin.model.c_components.c_variable.CvariableModel import com.david.mocassin.utils.isNameReservedWords import com.david.mocassin.utils.isNameSyntaxFollowCstandard import com.david.mocassin.view.components.fragments.cell_fragments.struct_attributes_cell_fragments.CstructAttributeNameCellFragment import com.david.mocassin.view.components.fragments.cell_fragments.struct_attributes_cell_fragments.CstructAttributeTypeCellFragment import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleStringProperty import javafx.scene.control.* import tornadofx.* class StructWizardStep2 : View() { val projectController: ProjectController by inject() private val attributeModel = CvariableModel() val structModel: CuserStructureModel by inject() var variableNameField : TextField by singleAssign() private var variableSimpleField : ComboBox<String> by singleAssign() private var variableFromProjectField : ComboBox<String> by singleAssign() var variablePointerField : CheckBox by singleAssign() var variableComparableField : CheckBox by singleAssign() var attributesTable: TableView<Cvariable> by singleAssign() var selectedSimpleType = SimpleStringProperty() var typeCategory = SimpleBooleanProperty(true) var isProjectEmpty = SimpleBooleanProperty(false) var hasNotEnumInProject = SimpleBooleanProperty(false) var hasNotUnionInProject = SimpleBooleanProperty(false) var hasNotStructInProject = SimpleBooleanProperty(false) var selectedProjectType = SimpleStringProperty("enum") var selectedType: Cvariable? = null init { title = messages["usw_sw_step2_title"] attributeModel.isPointer.value = false attributeModel.isComparable.value = false } override val root = hbox { form { fieldset(messages["add_fields_inside"]) { field(messages["name"]) { textfield(attributeModel.name) { variableNameField = this validator { if (!it.isNullOrBlank() && !isNameSyntaxFollowCstandard(it)) error(messages["v_not_alphanumeric_error"]) else if (it.isNullOrBlank()) error(messages["v_blank_field_error"]) else if(!it.isNullOrBlank() && !projectController.isNameUniqueExcept(it, listOf(structModel.name.value))) { error(messages["v_already_exist_error"]) } else if(!it.isNullOrBlank() && isNameReservedWords(it)) { error(messages["v_reserved_error"]) } else if(!it.isNullOrBlank() && !structModel.item.isAttributeUniqueInStructure(it)) { error(messages["v_exist_in_struct_error"]) } else null } } } field(messages["type"]) { vbox { togglegroup { radiobutton(messages["tcf_simple"], this, value= true) radiobutton(messages["tcf_from_project"], this, value= false) { removeWhen(isProjectEmpty) } bind(typeCategory) } } } field(messages["choose_type"]) { vbox { removeWhen(typeCategory.not()) combobox<String>(selectedSimpleType) { variableSimpleField = this items = CtypeEnum.toObservableArrayList() }.selectionModel.selectFirst() } vbox { removeWhen(typeCategory) togglegroup { radiobutton("enum", this, value = "enum"){ removeWhen(hasNotEnumInProject) }.action { variableFromProjectField.items = projectController.getListOfAllNamesUsed( ProjectController.ENUM ).asObservable() variableFromProjectField.selectionModel.selectFirst() } radiobutton("union", this, value = "union"){ removeWhen(hasNotUnionInProject) }.action { variableFromProjectField.items = projectController.getListOfAllNamesUsed( ProjectController.UNION ).asObservable() variableFromProjectField.selectionModel.selectFirst() } radiobutton("struct", this, value = "struct"){ removeWhen(hasNotStructInProject) }.action { variableFromProjectField.items = projectController.getListOfAllNamesUsed( ProjectController.STRUCT ).asObservable() variableFromProjectField.selectionModel.selectFirst() } bind(selectedProjectType) } } } field(messages["choose_from_list"]) { removeWhen(typeCategory) vbox { combobox<String>() { variableFromProjectField = this items = projectController.getListOfAllNamesUsed().asObservable() }.selectionModel.selectFirst() } } field(messages["pointer_type"]) { checkbox(messages["is_pointer"], attributeModel.isPointer) { variablePointerField = this } } field(messages["comparison"]) { checkbox(messages["is_comparable"], attributeModel.isComparable) { variableComparableField = this } } button(messages["add_button"]) { enableWhen(attributeModel.valid) action { val tmpVariable = Cvariable( attributeModel.name.value, CtypeEnum.find( variableSimpleField.value ) as CuserType, attributeModel.isPointer.value, attributeModel.isComparable.value ) if (!typeCategory.value) { when(selectedProjectType.value) { "enum" -> { tmpVariable.type = projectController.userModel.findEnumByName(variableFromProjectField.value) } "union" -> { tmpVariable.type = projectController.userModel.findUnionByName(variableFromProjectField.value) } "struct" -> { tmpVariable.type = projectController.userModel.findStructByName(variableFromProjectField.value) } } } structModel.attributes.value.add(tmpVariable) //form reset variableNameField.textProperty().value = "" variableSimpleField.selectionModel.selectFirst() variableFromProjectField.selectionModel.selectFirst() typeCategory.value = true selectedProjectType.value = "enum" variablePointerField.isSelected = false variableComparableField.isSelected = false } } } } tableview(structModel.attributes) { attributesTable = this isEditable = true column(messages["name"], Cvariable::name).cellFragment(CstructAttributeNameCellFragment::class) column(messages["type"], Cvariable::getTypeAsString) column(messages["pointer"], Cvariable::isPointer).cellFormat { text = this.rowItem.isPointer.toString() onDoubleClick { if (text == "true") { text = "false" this.rowItem.isPointer = false } else { text = "true" this.rowItem.isPointer = true } attributesTable.refresh() } } column(messages["comparable"], Cvariable::isComparable).makeEditable() // remove attribute from model contextMenu = ContextMenu().apply{ item(messages["delete"]).action { selectedItem?.apply{ structModel.attributes.value.removeIf { it.name == this.name } } } } onDoubleClick { if (selectedCell?.column == 1) { selectedType = selectedCell?.row?.let { it -> selectedCell?.tableView?.items?.get(it) } find<CstructAttributeTypeCellFragment>().openModal() } } columnResizePolicy = SmartResize.POLICY } } override fun onDock() { // init the fields variableNameField.text = "" variablePointerField.isSelected = false variableComparableField.isSelected = false // fill type combobox with enums variableFromProjectField.items = projectController.getListOfAllNamesUsed(ProjectController.ENUM).asObservable() variableFromProjectField.selectionModel.selectFirst() isProjectEmpty.value = projectController.userModel.isEmpty() //TODO to simplify and add unit test hasNotEnumInProject.value = projectController.userModel.userEnumList.isEmpty() hasNotUnionInProject.value = projectController.userModel.userUnionList.isEmpty() hasNotStructInProject.value = projectController.userModel.userStructureList.isEmpty() super.onDock() } }
0
Kotlin
0
1
a99a785d5d7f3e06020bf01c03707f61169989f0
11,445
mocassin
MIT License
app/src/main/java/com/erickcapilla/dcyourself/Home.kt
erickcapilla
626,143,431
false
null
package com.erickcapilla.dcyourself import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.ImageButton import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class Home : AppCompatActivity() { private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) auth = Firebase.auth val logoutButton = findViewById<ImageButton>(R.id.logOut) logoutButton.setOnClickListener { FirebaseAuth.getInstance().signOut() onBackPressed() } val changePassword = findViewById<ImageButton>(R.id.changePassword) changePassword.setOnClickListener { val change = Intent(this, ChangePassword::class.java) startActivity(change) } } }
0
Kotlin
0
0
5c7c1c8b97f197988fae2718ba2c7da328213a85
1,060
DCYourself
MIT License
app/src/main/kotlin/com/github/typ0520/codee/mvp/contract/UsersContract.kt
typ0520
115,848,990
false
null
package com.github.typ0520.codee.mvp.contract import com.github.typ0520.codee.base.IBaseView import com.github.typ0520.codee.base.IPresenter import com.github.typ0520.codee.mvp.bean.User /** * Created by tong on 2017-12-29. */ interface UsersContract { interface View : IBaseView { fun setData(followers: List<User>, loadMore: Boolean) fun showError(loadMode: Boolean) } interface Presenter : IPresenter<View> { fun getData() fun loadMore() } }
1
null
1
4
8fde9be47123528a4bfdf09a78f9a2264dea6900
498
Codee
Apache License 2.0
app/src/main/java/com/moataz/afternoonhadeeth/ui/offline/viewmodel/HadithOfflineViewModel.kt
ahmed-tasaly
533,010,125
false
null
package com.moataz.afternoonhadeeth.ui.offline.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.moataz.afternoonhadeeth.data.model.offline.HadithOffline import com.moataz.afternoonhadeeth.utils.status.Resource import java.util.* class HadithOfflineViewModel : ViewModel() { private val hadithLiveData = MutableLiveData<Resource<List<HadithOffline>>>() private val hadithOfflineArrayList: MutableList<HadithOffline> = ArrayList() val hadithList: LiveData<Resource<List<HadithOffline>>> get() { hadithLiveData.postValue(Resource.success(hadithOfflineArrayList)) populateList() return hadithLiveData } private fun populateList() { hadithOfflineArrayList.add( HadithOffline( "عن أبي موسى الأشعري رضي الله عنه عن النبي صلى الله عليه وسلم قال: (تعاهدوا القرآن، فوالذي نفسي بيده لهو أشد تفصيِّا من الإبل في عُقُلها)", "رواه البخاري" ) ) hadithOfflineArrayList.add( HadithOffline( "عن عبدالله بن عمر رضي الله عنه أن رسول الله صلى الله عليه وسلم قال: (لا حسد إلا في اثنتين: رجل آتاه الله القرآن فهو يقوم به آناء الليل وآناء النهار، ورجل آتاه الله مالاً فهو ينفقه آناء الليل وآناء النهار)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أنس رضي الله عنه قال: كان أكثر دعاء النبي صلى الله عليه وسلم: (اللهم ربنا آتنا في الدنيا حسنة وفي الآخرة حسنة وقنا عذاب النار)", "رواه البخاري" ) ) hadithOfflineArrayList.add( HadithOffline( "عن عمر بن الخطاب رضي الله عنه قال: قال رسول الله صلى الله عليه وسلم: (إن الله يرفع بهذا الكتاب أقواما، ويضع به آخرين)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي هريرة رضي الله عنه قال: كان رسول الله صلى الله عليه وسلم يقول: (اللهم أصلح لي ديني الذي هو عصمة أمري، وأصلح لي دنياي التي فيها معاشي، وأصلح لي آخرتي التي فيها معادي، واجعل الحياة زيادة لي في كل خير، واجعل الموت راحة لي من كل شر)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن عبدالله بن مسعود رضي الله عنه عن النبي صلى الله عليه وسلم أنه كان يقول: (اللهم إني أسألك الهدى والتقى، والعفاف والغنى)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عَنْ أَبي سَعِيدٍ الخُدْرِي: أنَّ النَّبيَّ ﷺ قَال: لِكُلِّ غَادِرٍ لِواءٌ عِندَ اسْتِه يَوْمَ القِيامةِ، يُرْفَعُ لَهُ بِقَدْرِ غَدْرِهِ، ألَا وَلا غَادر أعْظمُ غَدْرًا مِنْ أمِيرِ عامَّةٍ ", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي هريرة رضي الله عنه عن رسول الله صلى الله عليه وسلم قال: (لا تقوم الساعة حتى تقاتلوا اليهود، حتى يقول الحجر وراءه اليهودي: يا مسلم، هذا يهودي ورائي فاقتله)", "رواه البخاري" ) ) hadithOfflineArrayList.add( HadithOffline( "عن سهل بن حَنيف رضي الله عنه قال: قال رسول الله صلى الله عليه وسلم: (من سأل الله تعالى الشهادة بصدق بلَّغه الله منازل الشهداء وإن مات على فراشه)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي موسى الأشعري رضي الله عنه أن رسول الله صلى الله عليه وسلم قال: (من قاتل لتكون كلمةُ الله هي العليا، فهو في سبيل الله)", "رواه البخاري" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي هريرة رضي الله عنه قال: قال رسول الله صلى الله عليه وسلم: (بدأ الإسلام غريبا، وسيعود كما بدأ غريبا، فطوبى للغرباء)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي سعيد الخدري رضي الله عنه قال: سمعت رسول الله صلى الله عليه وسلم يقول: (من رأى منكم منكرا فليغيره بيده، فإن لم يستطع فبلسانه، فإن لم يستطع فبقلبه، وذلك أضعف الإيمان)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "قال رسول الله صلى الله عليه وسلم: (إن أحدكم إذا مات عُرض عليه مقعدُه بالغداة والعشي، إن كان من أهل الجنة فمن أهل الجنة، وإن كان من أهل النار فمن أهل النار، يقال: هذا مقعدك، حتى يبعثك الله إليه يوم القيامة)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي هريرة رضي الله عنه أن رسول الله صلى الله عليه وسلم قال: (إذا مات الإنسان انقطع عمله إلا من ثلاث: صدقة جارية، أو علم ينتفع به، أو ولد صالح يدعو له)", "رواه البخاري" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي هريرة رضي الله عنه أن رسول الله صلى الله عليه وسلم قال: (من شهد الجنازة حتى يصلي عليها فله قيراط، ومن شهدها حتى تدفن فله قيراطان) قيل: وما القيراطان؟ قال: (مثل الجبلين العظيمين)", "رواه البخاري" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أنس رضي الله عنه عن النبي صلى الله عليه وسلم أنه قال: (يتبع الميت ثلاثة فيرجع اثنان ويبقى معه واحد، يتبعه أهله وماله وعمله، فيرجع أهله وماله، ويبقى عمله)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي هريرة رضي الله عنه عن النبي صلى الله عليه وسلم قال: (دعوني ما تركتكم، إنما هلك من كان قبلكم بسؤالهم واختلافهم على أنبيائهم، فإذا نهيتكم عن شيء فاجتنبوه، وإذا أمرتكم بأمر فأتوا منه ما استطعتم)", "رواه البخاري" ) ) hadithOfflineArrayList.add( HadithOffline( "عن جابر رضي الله عنه قال: سمعت النبي صلى الله عليه وسلم قبل وفاته بثلاثٍ يقول: (لا يموتن أحدكم إلا وهو يُحسِن بالله الظن)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن شداد بن أوس رضي الله عنه عن النبي صلى الله عليه وسلم قال: (سيد الاستغفار أن تقول: اللهم أنت ربي لا إله إلا أنت، خلقتني وأنا عبدك، وأنا على عهدك ووعدك ما استطعت، أعوذ بك من شر ما صنعت، أبوء لك بنعمتك علي، وأبوء لك بذنبي، فاغفر لي، فإنه لا يغفر الذنوب إلا أنت)", "رواه البخاري" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي هريرة رضي الله عنه أن النبي صلى الله عليه وسلم قال: (خير يوم طلعت عليه الشمس يوم الجمعة، فيه خلق آدم، وفيه أدخل الجنة، وفيه أخرج منها، ولا تقوم الساعة إلا في يوم الجمعة)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي هريرة رضي الله عنه أن رسول الله صلى الله عليه وسلم قال:( إن الله يقول يوم القيامة: أين المتحابون بجلالي اليوم أظلهم في ظلي يوم لا ظل إلا ظلي) والمتحابين بجلاله هم المتحابون في الله", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( " عن أبي هريرة رضي الله عنه أن رسول الله صلى الله عليه وسلم قال: (لا تدخلوا الجنة حتى تؤمنوا، ولا تؤمنوا حتى تحابوا، أولا أدلكم على شيء إذا فعلتموه تحاببتم؟ أفشوا السلام بينكم)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن ابن عمر رضي الله عنهما أن رسول الله صلى الله عليه وسلم قال:( المسلم من سلم المسلمون من لسانه ويده والمهاجر من هجر ما نهى الله عنه)", "رواه البخاري" ) ) hadithOfflineArrayList.add( HadithOffline( "عن ابن عمر رضي الله عنهما أن رسول الله صلى الله عليه وسلم قال: (المسلم أخو المسلم لا يظلمه ولا يسلمه، من كان في حاجة أخيه كان الله في حاجته، ومن فرّج عن مسلم كربة فرج الله عنه بها كربة من كرب يوم القيامة، ومن ستر مسلماً ستره الله يوم القيامة)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي هريرة رضي الله عنه قال: سمعت رسول الله صلى الله عليه وسلم يقول: (إذا أقيمت الصلاة، فلا تأتوها تسعون، وأتوها تمشون، عليكم السكينة، فما أدركتم فصلوا، وما فاتكم فأتموا)", "رواه البخاري" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي هريرة رضي الله عنه عن النبي صلى الله عليه وسلم قال: (تُنكح المرأة لأربع: لمالها، ولحسبها، ولجمالها، ولدينها، فاظفر بذات الدين تَرِبَت يداك)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي هريرة رضي الله عنه قال: أوصاني خليلي صلى الله عليه وسلم بثلاث: (صيام ثلاثة أيام من كل شهر، وركعتي الضحى، وأن أوتر قبل أن أنام)", "رواه البخاري" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي هريرة رضي الله عنه أن رسول الله صلى الله عليه وسلم قال: (ليس الشديد بالصرعة، إنما الشديد الذي يملك نفسه عند الغضب)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي هريرة رضي الله عنه أن رسول الله صلى الله عليه وسلم قال: (من دعا إلى هدى كان له من الأجر مثل أجور من تبعه لا ينقص ذلك من أجورهم شيئاً ومن دعا إلى ضلالة كان عليه من الإثم مثل آثام من تبعه لا ينقص ذلك من آثامهم شيئاً)", "رواه مسلم" ) ) hadithOfflineArrayList.add( HadithOffline( "عن أبي سعيد الخدري رضي الله عنه أن النبي صلى الله عليه وسلم قال: (لتتبعن سَنَن من قبلَكم شِبرا بشبر، وذراعا بذراع، حتى لو سلكوا جُحر ضبٍ لسلكتموه)، قلنا يا رسول الله: اليهود، والنصارى قال: (فمن؟!)", "رواه البخاري" ) ) } }
0
Kotlin
0
1
ec70b362b5966475693e7f7a406a397ee08099d4
9,911
Sunset-Hadith-Market
Apache License 2.0
app/src/test/java/com/tahadardev/exchangerate/feature/currency_exchange/domain/use_case/FetchExchangeRateUseCaseTest.kt
hysekbutt
667,988,678
false
null
package com.tahadardev.exchangerate.feature.currency_exchange.domain.use_case import com.tahadardev.exchangerate.common.Constants import com.tahadardev.exchangerate.common.Resource import com.tahadardev.exchangerate.feature.currency_exchange.data.repository.FakeCurrencyRepository import com.tahadardev.exchangerate.feature.currency_exchange.domain.model.Currency import com.tahadardev.exchangerate.feature.currency_exchange.domain.model.CurrencyRate import kotlinx.coroutines.test.runTest import org.junit.Assert.* import org.junit.Before import org.junit.Test class FetchExchangeRateUseCaseTest { private lateinit var repo : FakeCurrencyRepository @Before fun setup() { repo = FakeCurrencyRepository() } @Test fun fetchCurrenciesShouldReturnListOfCurrencyRate() { var currencyRates : List<CurrencyRate>? = listOf() runTest { try { repo.fetchExchangeRates(System.currentTimeMillis()).collect{ currencyRates = when (it) { is Resource.Success -> it.data else -> { emptyList() } } } } catch (e: Exception) { currencyRates = null } } assertTrue(currencyRates?.isNotEmpty() == true && currencyRates?.toTypedArray()?.isArrayOf<CurrencyRate>() == true) } @Test fun fetchCurrenciesShouldFetchFromServerIfTimestampHasCrossedThreshold() { var responseMsg :String = "" runTest { try { val savedExchangeRateTimestamp = System.currentTimeMillis() - Constants.EXCHANGE_RATE_UPDATE_THRESHOLD repo.fetchExchangeRates(savedExchangeRateTimestamp).collect{ responseMsg = when (it) { is Resource.Success -> it.message!! else -> { "" } } } } catch (e: Exception) { responseMsg = "" } } assertTrue(responseMsg == "Fetched from Server") } @Test fun fetchCurrenciesShouldFetchFromDbIfTimestampHasNotCrossedThreshold() { var responseMsg :String = "" runTest { try { val savedExchangeRateTimestamp = System.currentTimeMillis() repo.fetchExchangeRates(savedExchangeRateTimestamp).collect{ responseMsg = when (it) { is Resource.Success -> it.message!! else -> { "" } } } } catch (e: Exception) { responseMsg = "" } } assertTrue(responseMsg == "Fetched from local db") } }
0
Kotlin
0
1
693e47225eae61a5b6f8be31fb0fc93a7576c85d
2,912
currency-exchange-automate
MIT License
core/src/main/java/com/flyview/core/barcode/domain/BarcodeBinder.kt
DmiMukh
676,402,705
false
{"Kotlin": 288475, "Java": 130379}
package com.flyview.core.barcode.domain import com.flyview.core.barcode.data.Barcode interface BarcodeBinder { fun createBarcode(data: String): Barcode }
0
Kotlin
0
0
5c184121116c08abe217946ba7da27804c232edb
159
PharmMobile
MIT License
src/client/kotlin/slatemagic/SlateMagicModClient.kt
Jempasam
717,593,852
false
{"Kotlin": 146073, "Java": 1020}
package slatemagic import net.fabricmc.api.ClientModInitializer import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback import slatemagic.command.SlateMagicClientCommands import slatemagic.entity.SlateMagicRenderers import slatemagic.network.SlateMagicClientNetwork import slatemagic.particle.SlateMagicClientParticles import slatemagic.spell.effect.SpellEffect import slatemagic.ui.ShowSpellGUI object SlateMagicModClient : ClientModInitializer { var spell: SpellEffect?=null var lastTime: Long=0 override fun onInitializeClient() { SlateMagicClientParticles SlateMagicClientCommands SlateMagicClientParticles SlateMagicClientNetwork SlateMagicRenderers HudRenderCallback.EVENT.register(ShowSpellGUI()) } }
0
Kotlin
0
0
051f9bb093721f6c269218ab30e01bf89daea514
741
SlateMagic
Creative Commons Zero v1.0 Universal
applications/vehicle-generator-streaming-source/src/main/kotlin/com/vmware/tanzu/data/IoT/vehicles/generator/streaming/RabbitmqStreamConfig.kt
ggreen
385,973,299
false
{"Gradle": 1, "Gradle Kotlin DSL": 51, "Text": 1, "Ignore List": 26, "Markdown": 16, "Shell": 25, "Batchfile": 25, "INI": 25, "Kotlin": 113, "YAML": 1, "Java": 2, "XML": 9, "HTML": 8, "SQL": 4, "JSON": 1}
package com.vmware.tanzu.data.IoT.vehicles.generator.streaming import com.vmware.tanzu.data.IoT.vehicles.generator.VehicleLoadSimulator import com.vmware.tanzu.data.IoT.vehicles.messaging.vehicle.publisher.VehicleSender import com.vmware.tanzu.data.IoT.vehicles.messaging.streaming.creational.RabbitStreamEnvironmentCreator import com.vmware.tanzu.data.IoT.vehicles.messaging.streaming.publisher.RabbitStreamingVehicleSender import com.vmware.tanzu.data.IoT.vehicles.messaging.vehicle.publisher.converter.VehicleToBytes import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration import org.springframework.scheduling.annotation.EnableAsync /** * @author <NAME> */ @Configuration @ComponentScan(basePackageClasses = [ RabbitStreamEnvironmentCreator::class, RabbitStreamingVehicleSender::class, VehicleLoadSimulator::class]) @EnableAsync class RabbitmqStreamConfig { /** * Conversion strategy used by the sender */ @Bean fun vehicleToBytes() : VehicleToBytes { return VehicleToBytes(); } }
1
null
1
1
02861106751d65ad2653cd51369630d456bded22
1,213
IoT-connected-vehicles-showcase
Apache License 2.0
app/src/main/java/club/stockgro/pocchatlongpress/ui/components/chat/ChatMessageInputFeild.kt
nitink133
766,531,038
false
{"Kotlin": 35044}
package club.stockgro.pocchatlongpress.ui.components.chat import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Call import androidx.compose.material.icons.filled.Send import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import club.stockgro.pocchatlongpress.R import club.stockgro.pocchatlongpress.ui.theme.WhatsAppTheme @OptIn(ExperimentalComposeUiApi::class, ExperimentalMaterial3Api::class) @Composable fun MessageInputField(modifier: Modifier) { var text by remember { mutableStateOf("") } val keyboardController = LocalSoftwareKeyboardController.current // Define the colors based on your theme or as they are in WhatsApp val backgroundColor = Color.Transparent // WhatsApp input field background color val sendButtonColor = MaterialTheme.colorScheme.primaryContainer // WhatsApp send button color Surface( modifier = modifier.padding(bottom = 6.dp), color = Color.Transparent, // Use a transparent color if you don't want any background ) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 8.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically ) { // Emoji icon on the left inside the input field Icon( painter = painterResource(id = R.drawable.ic_emoji), // Replace with actual emoji icon contentDescription = "Emoji", modifier = Modifier .padding(end = 4.dp) .size(24.dp), tint = Color.DarkGray ) // Input field Box( modifier = Modifier .weight(1f) .background(Color.White, RoundedCornerShape(18.dp)) .padding(horizontal = 12.dp, vertical = 0.dp) ) { TextField( value = text, onValueChange = { newText -> text = newText }, placeholder = { Text("Type a message") }, singleLine = true, colors = TextFieldDefaults.textFieldColors( containerColor = Color.Transparent, cursorColor = Color.DarkGray, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent ), modifier = Modifier.fillMaxWidth(), keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Send), keyboardActions = KeyboardActions(onSend = { // TODO: Send message action text = "" keyboardController?.hide() }), trailingIcon = { if (text.isNotEmpty()) { IconButton(onClick = { // TODO: Send message action text = "" keyboardController?.hide() }) { Icon( imageVector = Icons.Filled.Send, contentDescription = "Send", tint = sendButtonColor ) } } else { // Camera icon on the right inside the input field Icon( imageVector = Icons.Filled.Call, contentDescription = "Camera", tint = Color.DarkGray ) } } ) } // Send button (floating to the right of the input field) val sendIconTint = if (text.isNotEmpty()) Color.White else sendButtonColor Box( modifier = Modifier .size(48.dp) .clip(CircleShape) .background(if (text.isNotEmpty()) sendButtonColor else Color.Transparent) .padding(12.dp) ) { IconButton(onClick = { // TODO: Send message action text = "" keyboardController?.hide() }) { Icon( imageVector = Icons.Filled.Send, contentDescription = "Send", tint = sendIconTint ) } } } } } @Preview @Composable fun PreviewMessageInputField() { WhatsAppTheme { Box() { // Your chat screen content goes here MessageInputField(modifier = Modifier.align(Alignment.BottomCenter)) } } }
0
Kotlin
0
0
5e636045393cf3be0b1388947cb770859adebb7b
5,804
iOS-Style-Context-Menu
MIT License
recommend-sdk/src/main/java/com/recommend/sdk/core/data/RepeatRequestWorker.kt
recommend-pro
609,114,602
false
null
package com.recommend.sdk.core.data import android.content.Context import android.util.Log import androidx.work.Worker import androidx.work.WorkerParameters import com.recommend.sdk.core.data.api.ApiServiceBuilder import com.recommend.sdk.core.data.util.ApiHelper import com.recommend.sdk.core.util.RecommendLogger import okhttp3.Request import okhttp3.RequestBody class RepeatRequestWorker(private val appContext: Context, workerParams: WorkerParameters): Worker(appContext, workerParams) { companion object { const val SERIALIZED_REPEATABLE_TASK_PARAMS = "SERIALIZED_REPEATABLE_TASK" } override fun doWork(): Result { Log.d(RecommendLogger.LOG_TAG, "Request worker start work") val rawRepeatableApiTask = inputData.getString(SERIALIZED_REPEATABLE_TASK_PARAMS) if (rawRepeatableApiTask !is String) { return Result.failure() } val repeatableApiTask = ApiTask.RepeatableApiTask.deserializedFromJson(rawRepeatableApiTask) repeatableApiTask.incrementAttemptNumber() val serializedRequest = repeatableApiTask.request val recommendLogger = RecommendLogger() val okHttpClient = ApiServiceBuilder.getApiClient(recommendLogger) val request = Request.Builder() request.url(serializedRequest.url) val requestBody = if (serializedRequest.body.isNotEmpty()) { RequestBody.create(null, serializedRequest.body) } else { null } request.method(serializedRequest.method, requestBody) if (serializedRequest.headers.isNotEmpty()) { serializedRequest.headers.forEach { request.header(it.key, it.value) } } Log.d(RecommendLogger.LOG_TAG, "Request worker is repeating request: $request") val apiManager = ApiManager(appContext, recommendLogger, ApiHelper(appContext)) return try { val response = okHttpClient.newCall(request.build()).execute() Log.d(RecommendLogger.LOG_TAG, "Request worker got response: ${response.body()?.string()} with code: ${response.code()}") Result.success() } catch (e: Throwable) { apiManager.handleError(repeatableApiTask, e) Log.d(RecommendLogger.LOG_TAG, "Request worker got error: $e") Result.failure() } } }
0
Kotlin
0
2
85e0816a8e21f1247fabc196b30127d6e525e918
2,372
recommend-android-sdk
MIT License
sample/src/main/java/com/github/droibit/chopstick/sample/prefs/SettingsActivityCompat.kt
droibit
61,474,791
false
{"Gradle": 7, "Java Properties": 2, "Shell": 1, "Ignore List": 5, "Batchfile": 1, "Text": 1, "Markdown": 1, "Proguard": 1, "XML": 24, "Java": 1, "Kotlin": 21, "YAML": 1}
package com.github.droibit.chopstick.sample.prefs import android.content.Context import android.content.Intent import android.os.Bundle import android.preference.CheckBoxPreference import android.preference.EditTextPreference import android.preference.Preference import android.preference.SwitchPreference import com.example.android.supportv7.app.AppCompatPreferenceActivity import com.github.droibit.chopstick.preference.bindPreference import com.github.droibit.chopstick.sample.R @Suppress("DEPRECATION") class SettingsActivityCompat : AppCompatPreferenceActivity() { companion object { @JvmStatic fun makeIntent(context: Context) = Intent(context, SettingsActivityCompat::class.java) } private val checkboxPref: CheckBoxPreference by bindPreference(R.string.key_checkbox_preference) private val switchPref: SwitchPreference by bindPreference("switch_preference") private val editPref: EditTextPreference by bindPreference(R.string.key_edittext_preference) private val listPref: Preference by bindPreference("list_preference") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.settings) checkboxPref.apply { isChecked = false title = "Edited: ${checkboxPref.title}" } switchPref.apply { isChecked = false title = "Edited: ${switchPref.title}" } editPref.title = "Edited: ${editPref.title}" listPref.title = "Edited: ${listPref.title}" } }
0
Kotlin
0
0
cc3da028bf985ccaab1514e2ef1228468a3d5de9
1,579
chopsticks
Apache License 2.0
sample/src/main/java/com/github/droibit/chopstick/sample/prefs/SettingsActivityCompat.kt
droibit
61,474,791
false
{"Gradle": 7, "Java Properties": 2, "Shell": 1, "Ignore List": 5, "Batchfile": 1, "Text": 1, "Markdown": 1, "Proguard": 1, "XML": 24, "Java": 1, "Kotlin": 21, "YAML": 1}
package com.github.droibit.chopstick.sample.prefs import android.content.Context import android.content.Intent import android.os.Bundle import android.preference.CheckBoxPreference import android.preference.EditTextPreference import android.preference.Preference import android.preference.SwitchPreference import com.example.android.supportv7.app.AppCompatPreferenceActivity import com.github.droibit.chopstick.preference.bindPreference import com.github.droibit.chopstick.sample.R @Suppress("DEPRECATION") class SettingsActivityCompat : AppCompatPreferenceActivity() { companion object { @JvmStatic fun makeIntent(context: Context) = Intent(context, SettingsActivityCompat::class.java) } private val checkboxPref: CheckBoxPreference by bindPreference(R.string.key_checkbox_preference) private val switchPref: SwitchPreference by bindPreference("switch_preference") private val editPref: EditTextPreference by bindPreference(R.string.key_edittext_preference) private val listPref: Preference by bindPreference("list_preference") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.settings) checkboxPref.apply { isChecked = false title = "Edited: ${checkboxPref.title}" } switchPref.apply { isChecked = false title = "Edited: ${switchPref.title}" } editPref.title = "Edited: ${editPref.title}" listPref.title = "Edited: ${listPref.title}" } }
0
Kotlin
0
0
cc3da028bf985ccaab1514e2ef1228468a3d5de9
1,579
chopsticks
Apache License 2.0
safeToRunCore/src/main/kotlin/io/github/dllewellyn/safetorun/features/oscheck/builders/bannedBoard.kt
Safetorun
274,838,056
false
null
package io.github.dllewellyn.safetorun.features.oscheck.builders import io.github.dllewellyn.safetorun.conditional.Conditional import io.github.dllewellyn.safetorun.features.oscheck.OSInformationQuery import io.github.dllewellyn.safetorun.features.oscheck.baseOsCheck /** * Add a banned board to the list * * @param bannedBoard the model to ban */ fun OSInformationQuery.bannedBoard(bannedBoard: String): Conditional = baseOsCheck({ "Banned board ${board()} == $bannedBoard" }) { board() == bannedBoard }
9
Kotlin
0
8
501a06497485cb40c2b54f4d2a885fc34bcc1898
527
safe_to_run
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/web/serviceworker/ExtendableMessageEvent.types.kt
karakum-team
393,199,102
false
{"Kotlin": 6214094}
// Automatically generated - do not modify! package web.serviceworker import seskar.js.JsValue import web.events.EventTarget import web.events.EventType sealed external class ExtendableMessageEventTypes { @JsValue("message") fun <C : EventTarget> message(): EventType<ExtendableMessageEvent, C> }
0
Kotlin
7
35
ac6d96e24eb8d07539990dc2d88cbe85aa811312
309
types-kotlin
Apache License 2.0
src/test/resources/testSources/Resources.kt
hexlabsio
137,217,471
false
null
package testSources import io.kloudformation.json import io.kloudformation.model.KloudFormationTemplate import io.kloudformation.resource.aws.cloudformation.waitConditionHandle import io.kloudformation.resource.aws.sqs.queue object Resources{ fun KloudFormationTemplate.Builder.nameCheck(){ waitConditionHandle(logicalName = "WindowsServerWaitHandle") } fun KloudFormationTemplate.Builder.redrivePolicy(){ queue(logicalName = "MySourceQueue"){ redrivePolicy(json( mapOf( "deadLetterTargetArn" to mapOf( "Fn::GetAtt" to listOf( "MyDeadLetterQueue", "Arn" ) ), "maxReceiveCount" to 5 ) )) } } }
3
Kotlin
1
33
19b703f6f57f1f4b24ddc835c6d96d02d007b1cd
870
kloudformation
Apache License 2.0
Kotlin/Unit_15/src/model/Person.kt
jstevenperry
145,141,647
false
null
/* * Copyright 2018 Makoto Consulting Group Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.makotogo.learn.kotlin.model import com.makotogo.learn.kotlin.util.createPerson import com.makotogo.learn.kotlin.util.createWorker import java.time.LocalDate import java.time.LocalDateTime /** * Interface - a simple marker interface */ interface Marked /** * Interface - for objects that are configurable */ interface Configurable { /** * Function - configure the object */ fun configure() } /** * Interface - for things that have identity */ interface Identifiable { /** * Property - identity for the object */ val identity: String get() = "UNKNOWN" /** * Function - identify the object */ fun identify(): String { return "Identity: $identity" } } /** * Interface - marks an object as Human * Also Identifiable and Configurable */ interface Human : Identifiable { /** * Property - when the Human was born */ val dateOfBirth: LocalDate } /** * Interface - an entity with a name * Also Configurable */ interface Nameable : Configurable, Identifiable { /** * Property - the family name */ val familyName: String /** * Property - the given name */ val givenName: String } /** * Person class - subclass of Human */ open class Person( final override val familyName: String, final override val givenName: String, final override val dateOfBirth: LocalDate) : Human, Nameable { /** * Private property - lateinit */ private lateinit var whenCreated: LocalDateTime /** * Override identity property */ override lateinit var identity: String /** * Initializer block */ init { // // Call Human.init() function configure() } /** * Abstract function implementation */ final override fun configure() { // // Init identity property identity = "$givenName $familyName" // // Init whenCreated property whenCreated = LocalDateTime.now() } /** * toString() override */ override fun toString(): String { return "Person(identity=$identity, whenCreated=$whenCreated, familyName=$familyName, givenName=$givenName, dateOfBirth=$dateOfBirth)" } } /** * Worker - subclass of Person */ class Worker(familyName: String, givenName: String, dateOfBirth: LocalDate, val taxIdNumber: String) : Person(familyName, givenName, dateOfBirth), Marked { /** * Override identity property from parent class * * Use taxIdNumber property (filter out dashes) */ override var identity = taxIdNumber.filter { charAt -> charAt != '-' } /** * toString() override */ override fun toString(): String { return "Worker(${super.toString()}, taxIdNumber=$taxIdNumber)" } } /** * The ubiquitous main function. We meet again. */ fun main(args: Array<String>) { // // Create a Human. Oh, wait, you can't instantiate an abstract class // val human = Human() // // Create a Person. Print it out to see what's up. val person = createPerson() println("Person(${person.identify()}): $person") // // Create a Worker. Print it out to see what's up. val worker = createWorker() println("Worker(${worker.identify()}): $worker") }
5
null
322
259
3ba05f4bb4c1210759b350717c3cad9b61f7c41a
4,030
IBM-Developer
Apache License 2.0
app/src/main/java/fr/azhot/realestatemanager/utils/TypeConverter.kt
Azhot
317,513,160
false
null
package fr.azhot.realestatemanager.utils import androidx.room.TypeConverter import fr.azhot.realestatemanager.model.PointOfInterestType import fr.azhot.realestatemanager.model.PropertyType class TypeConverter { @TypeConverter fun fromPropertyType(propertyType: PropertyType?): String? { return propertyType?.name } @TypeConverter fun toPropertyType(name: String?): PropertyType? { return name?.let { PropertyType.valueOf(name) } } @TypeConverter fun fromPointOfInterestType(pointOfInterestType: PointOfInterestType?): String? { return pointOfInterestType?.name } @TypeConverter fun toPointOfInterestType(name: String?): PointOfInterestType? { return name?.let { name.replace(" ", "_") PointOfInterestType.valueOf(name) } } }
1
null
1
1
3bb6b80dba9c6715c8ee29319788c8ac6fc15416
842
RealEstateManager
MIT License
src/main/kotlin/org/linguamachina/klinguamachina/generation/bytecode/Bytecode.kt
Lingua-Machina
254,106,597
false
{"Java": 165058, "Kotlin": 118787, "ANTLR": 3004, "Makefile": 1404}
package org.linguamachina.klinguamachina.generation.bytecode import org.linguamachina.klinguamachina.generation.bytecode.exceptions.UnknownBytecode enum class Bytecode( val immediateArgsCount: Int, val stackArgsCount: Int, val stackResultCount: Int = 1 ) { // Data read GET_GLOBAL(1, 0), GET_MODULE(1, 0), GET_INSTANCE(1, 0), GET_CLASS(1, 0), GET_LOCAL(1, 0), // Data write SET_GLOBAL(1, 1, 0), SET_MODULE(1, 1, 0), SET_INSTANCE(1, 1, 0), SET_CLASS(1, 1, 0), SET_LOCAL(1, 1, 0), // Refs CREATE_REF(1, 0, 1), GET_REF(1, 0, 1), SET_REF(1, 1, 0), // Message sending SEND(1, Int.MAX_VALUE), COMPILE(1, 0, 0), BIND_PRIMITIVE(2, 1, 0), AND(0, 2), OR(0, 2), ADD(0, 2), MINUS(0, 2), MUL(0, 2), DIV(0, 2), MOD(0, 2), EQ(0, 2), NEQ(0, 2), LOWER(0, 2), LOWER_EQ(0, 2), GREATER(0, 2), GREATER_EQ(0, 2), POS(0, 1), NEG(0, 1), NOT(0, 1), // Literal values ARRAY(1, Int.MAX_VALUE), SELF(0, 0), CONTEXT(0, 0), TRUE(0, 0), FALSE(0, 0), NIL(0, 0), CONST(1, 0), CONST_INT(1, 0), // Blocks CLOSURE(3, Int.MAX_VALUE), RETURN(0, 1, 0), NON_LOCAL_RETURN(0, 1, 0), // Stack manipulation POP(0, 1, 0), DUP(0, 1, 2), SWAP(0, 2, 2); companion object { fun fromInt(value: Int) = values().firstOrNull { it.ordinal == value } ?: throw UnknownBytecode(value) } }
6
Java
1
1
267c1c73b39ec57f235cb4ce3374b6f283b31eb7
1,493
KLinguaMachina
MIT License
prime-router/src/main/kotlin/metadata/Mappers.kt
CDCgov
304,423,150
false
null
package gov.cdc.prime.router.metadata import gov.cdc.prime.router.Element import gov.cdc.prime.router.ElementResult import gov.cdc.prime.router.InvalidReportMessage import gov.cdc.prime.router.Sender import gov.cdc.prime.router.common.NPIUtilities import gov.cdc.prime.router.serializers.Hl7Serializer import java.security.MessageDigest import java.time.LocalDateTime import java.time.OffsetDateTime import java.time.format.DateTimeFormatter import java.time.format.DateTimeParseException import java.util.Locale import javax.xml.bind.DatatypeConverter import kotlin.reflect.full.memberProperties /** * A *Mapper* is defined as a property of a schema element. It is used to create * a value for the element when no value is present. For example, the middle_initial element has * this mapper: * * `mapper: middleInitial(patient_middle_name)` * * A mapper object is stateless. It has a name which corresponds to * the function name in the property. It has a set of arguments, which * corresponding to the arguments of the function. Before applying the * mapper, the elementName list is generated from the arguments. All element values * are then fetched and provided to the apply function. */ interface Mapper { /** * Name of the mapper */ val name: String /** * * The element names of the values that should be requested. Called before apply. * * For example, if the schema had a mapper field defined for a `minus` mapper * * - name: some_element * mapper: minus(x, 1) * * `valueNames` would be called with an args list of ["x", "1"]. * The minus mapper would return ["x"]. The minus mapper is treating * the second argument as a parameter, not as an element name. * * @param element that contains the mapper definition * @param args from the schema */ fun valueNames(element: Element, args: List<String>): List<String> /** * Apply the mapper using the values from the current report item. Called after valueNames(). * * For example, if the schema had a mapper field defined for a `minus` mapper * * - name: some_element * mapper: minus(x, 1) * * `apply` would be called with an `args` list of ["x", "1"] and a * `values` list of [ElementAndValue(Element(x, ...), "9")] where "9" is * the value of the x element for the current item. The `apply` method * would return "8", thus mapping the `some_element` value to the `x` value minus 1. * * @param args from the schema * @param values that where fetched based on valueNames */ fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? = null ): ElementResult } data class ElementAndValue( val element: Element, val value: String ) class MiddleInitialMapper : Mapper { override val name = "middleInitial" override fun valueNames(element: Element, args: List<String>): List<String> { if (args.size != 1) error("Schema Error: Invalid number of arguments") return args } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { return ElementResult( if (values.isEmpty()) { null } else { if (values.size != 1) error("Found ${values.size} values. Expecting 1 value. Args: $args, Values: $values") else if (values.first().value.isEmpty()) null else values.first().value.substring(0..0).uppercase() } ) } } /** * The args for the use mapper is a list of element names in order of priority. * The mapper will use the first with a value */ class UseMapper : Mapper { override val name = "use" override fun valueNames(element: Element, args: List<String>) = args override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { return ElementResult( if (values.isEmpty()) { null } else { val (fromElement, fromValue) = values.first() when { element.type == fromElement.type -> fromValue element.type == Element.Type.DATE && fromElement.type == Element.Type.DATETIME -> { LocalDateTime.parse(fromValue, Element.datetimeFormatter).format(Element.dateFormatter) } element.type == Element.Type.TEXT -> fromValue // TODO: Unchecked conversions should probably be removed, but the PIMA schema relies on this, right now. else -> fromValue } } ) } } /** * Use a string value found in the Sender's setting object as the value for this element. * Example call * - name: sender_id * cardinality: ONE * mapper: useSenderSetting(fullName) * csvFields: [{ name: senderId}] * * As of this writing mappers are called in three places: * - during initial read (in [Element.processValue]) * - during creation of internal data (in [Report.buildColumnPass2]) * - during creation of outgoing data (in, eg, [Hl7Serializer.setComponentForTable]) * ONLY the first of those has access to Sender info. However, the mapper may be called in * any or all of those three places. Therefore, its incumbent upon the * writer of any mapper to ensure it works without failure if the Sender obj is null. * * Notes: * 1. If you use mapperOverridesValue with this, you will get unexpected results. * 2. [UseSenderSettingMapper] always returns the toString() value regardless of the field type. * 3. This does not work with commandline ./prime, because the CLI knows nothing about settings. */ class UseSenderSettingMapper : Mapper { override val name = "useSenderSetting" override fun valueNames(element: Element, args: List<String>): List<String> { if (args.size != 1) { error("Schema Error for ${element.name}: useSenderSetting expects a single argument") } // The arg is the name of the field in the Sender settings to extract, not a field in the data. return emptyList() } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { val valueToUse = when { sender == null -> null // will null out existing value if you use mapperOverridesValue args.size != 1 -> error("Schema Error for ${element.name}: useSenderSetting expects a single argument") else -> { try { val senderProperty = Sender::class.memberProperties.first { it.name == args[0] } senderProperty.get(sender).toString() } catch (e: NoSuchElementException) { return ElementResult( null, mutableListOf( InvalidReportMessage( "ReportStream internal error in $name: ${args[0]} is not a sender setting field" ) ) ) } } } return ElementResult(valueToUse) } } /** * The mapper concatenates a list of column values together. * Call this like this: * concat(organization_name, ordering_facility_name) * @todo add a separator arg. * @todo generalize this to call any kotlin string function? */ class ConcatenateMapper : Mapper { override val name = "concat" override fun valueNames(element: Element, args: List<String>): List<String> { if (args.size < 2) error( "Schema Error: concat mapper expects to concat two or more column names" ) return args } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { return ElementResult( if (values.isEmpty()) { null } else { // default ", " separator for now. values.joinToString(separator = element.delimiter ?: ", ") { it.value } } ) } } /** * The args for the ifPresent mapper are an element name and a value. * If the elementName is present, the value is used */ class IfPresentMapper : Mapper { override val name = "ifPresent" override fun valueNames(element: Element, args: List<String>): List<String> { if (args.size != 2) error("Schema Error: ifPresent expects dependency and value parameters") return args.subList(0, 1) // The element name } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { return ElementResult( if (values.size == 1) { args[1] } else { null } ) } } /** * This mapper checks if one or more elements are blank or not present on a row, * and if so, will replace an element's value with either some literal string value * or the value from a different field on a row * ex. ifNotPresent($mode:literal, $string:NO ADDRESS, patient_zip_code, patient_state) * - if patient_zip_code and patient_state are missing or blank, then replace element's value with "NO ADDRESS" * ifNotPresent($mode:lookup, ordering_provider_city, patient_zip_code) * - if patient_zip_code is missing or blank, then replace element's value with that of the ordering_provider_city */ class IfNotPresentMapper : Mapper { override val name = "ifNotPresent" override fun valueNames(element: Element, args: List<String>): List<String> { if (args.isEmpty()) error("Schema Error: ifNotPresent expects dependency and value parameters") return args } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { val mode = args[0].split(":")[1] val modeOperator = if (args[1].contains(":")) args[1].split(":")[1] else args[1] val conditionList = args.subList(2, args.size) conditionList.forEach { val valuesElement = values.find { v -> v.element.name == it } if (valuesElement != null && valuesElement.value.isNotBlank()) { return ElementResult(null) } } return ElementResult( when (mode) { "literal" -> modeOperator "lookup" -> { val lookupValue = values.find { v -> v.element.name == modeOperator } lookupValue?.value.toString() } else -> null } ) } } /** * The args for the [IfNPIMapper] mapper are an element name, true value and false value. * * Example Usage: * ``` * ifNPI(ordering_provider_id, NPI, U) * ``` * * Test if the value is a valid NPI according to CMS. Return the second parameter if test is true. * Return third parameter if the test is false and the parameter is present */ class IfNPIMapper : Mapper { override val name = "ifNPI" override fun valueNames(element: Element, args: List<String>): List<String> { if (args.size !in 2..3) error("Schema Error: ifPresent expects dependency and value parameters") return args.subList(0, 1) // The element name } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { return ElementResult( if (values.size != 1) null else if (NPIUtilities.isValidNPI(values[0].value)) args[1] else if (args.size == 3) args[2] else null ) } } /** * The LookupMapper is used to lookup values from a lookup table * The args for the lookup mapper is the name of the element with the index value * The table involved is the element.table field * The lookupColumn is the element.tableColumn field */ class LookupMapper : Mapper { override val name = "lookup" override fun valueNames(element: Element, args: List<String>): List<String> { if (args.size !in 1..2) error("Schema Error: lookup mapper expected one or two args") return args } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { return ElementResult( if (values.size != args.size) { null } else { val lookupTable = element.tableRef ?: error("Schema Error: could not find table ${element.table}") val tableFilter = lookupTable.FilterBuilder() values.forEach { val indexColumn = it.element.tableColumn ?: error("Schema Error: no tableColumn for element ${it.element.name}") tableFilter.equalsIgnoreCase(indexColumn, it.value) } val lookupColumn = element.tableColumn ?: error("Schema Error: no tableColumn for element ${element.name}") tableFilter.findSingleResult(lookupColumn) } ) } } /** * The LookupSenderValuesetsMapper is used to lookup values from the "sender_valuesets" table/csv * The args for the mapper are: * args[0] --> lookupColumn = the primary lookup field (usually "sender_id") * args[1] --> questionColumn = the secondary lookup field, expected to be the element name (i.e. patient_gender) * The mapper uses the above arguments + the question's answer to retrieve a row from the table */ class LookupSenderValuesetsMapper : Mapper { override val name = "lookupSenderValuesets" override fun valueNames(element: Element, args: List<String>): List<String> { return args } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { return ElementResult( if (values.size != args.size) { null } else { val lookupTable = element.tableRef ?: error("Schema Error: could not find table ${element.table}") val lookupColumn = args[0] val lookupValue = values.find { it.element.name == lookupColumn }?.value ?: return ElementResult(null) val questionColumn = args[1] val answer = values.find { it.element.name == questionColumn }?.value ?: return ElementResult(null) lookupTable.FilterBuilder() .equalsIgnoreCase(lookupColumn, lookupValue) .equalsIgnoreCase("element_name", element.name) .equalsIgnoreCase("free_text_substring", answer) .findSingleResult("result") } ) } } /** * The NpiLookupMapper is a specific implementation of the lookupMapper and * thus no output values are present in this function. This function requires * the same lookup table configuration as lookupMapper. * * In-schema usage: * ``` * type: TABLE * table: my-table * tableColumn: my-column * mapper: npiLookup(provider_id, facility_clia, sender_id) * ``` */ class NpiLookupMapper : Mapper { override val name = "npiLookup" override fun valueNames(element: Element, args: List<String>): List<String> { if (args.isEmpty()) error("Schema Error: lookup mapper expected one or more args") return args } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { /* The table ref and column from the element that called the mapper */ val lookupTable = element.tableRef ?: error("Schema Error: could not find table ${element.table}") val lookupColumn = element.tableColumn ?: error("Schema Error: no tableColumn for element ${element.name}") /* Column names passed in via schema */ /* Because of the specificity here, we need args = provider_id (npi), facility_id, sender_id */ val npiColumn = args[0] val facilityCliaColumn = args[1] val senderIdColumn = args[2] /* The values provided from the incoming row of data */ val npiSent = values.find { it.element.name == npiColumn }?.value ?: "" val facilityCliaSent = values.find { it.element.name == facilityCliaColumn }?.value ?: "" val senderIdSent = values.find { it.element.name == senderIdColumn }?.value ?: "" /* The result stored after filtering the table */ val filterResult: String? if (npiSent.isBlank()) { /* Returns the lookupColumn value based on Facility_CLIA and Sender_ID where Default is true */ filterResult = lookupTable.FilterBuilder() .equalsIgnoreCase(facilityCliaColumn, facilityCliaSent) .equalsIgnoreCase(senderIdColumn, senderIdSent) .equalsIgnoreCase("default", "true") .findSingleResult(lookupColumn) } else { /* Uses NPI to lookup value */ filterResult = lookupTable.FilterBuilder() .equalsIgnoreCase(npiColumn, npiSent) .findSingleResult(lookupColumn) } return ElementResult(filterResult) } } /** * The obx8 mapper fills in OBX-8. This indicates the normalcy of OBX-5 * * @See <a href=https://confluence.hl7.org/display/OO/Proposed+HHS+ELR+Submission+Guidance+using+HL7+v2+Messages#ProposedHHSELRSubmissionGuidanceusingHL7v2Messages-DeviceIdentification>HHS Submission Guidance</a>Do not use it for other fields and tables. */ class Obx8Mapper : Mapper { override val name = "obx8" override fun valueNames(element: Element, args: List<String>): List<String> { return listOf("test_result") } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { return ElementResult( if (values.isEmpty() || values.size > 1) { null } else { when (values[0].value) { "260373001" -> "A" // Detected "260415000" -> "N" // Not Detected "720735008" -> "A" // Presumptive positive "42425007" -> "N" // Equivocal "260385009" -> "N" // Negative "10828004" -> "A" // Positive "895231008" -> "N" // Not detected in pooled specimen "462371000124108" -> "A" // Detected in pooled specimen "419984006" -> "N" // Inconclusive "125154007" -> "N" // Specimen unsatisfactory for evaluation "455371000124106" -> "N" // Invalid result "840539006" -> "A" // Disease caused by sever acute respiratory syndrome coronavirus 2 (disorder) "840544004" -> "A" // Disease caused by severe acute respiratory coronavirus 2 (situation) "840546002" -> "A" // Exposure to severe acute respiratory syndrome coronavirus 2 (event) "840533007" -> "A" // Severe acute respiratory syndrome coronavirus 2 (organism) "840536004" -> "A" // Antigen of severe acute respiratory syndrome coronavirus 2 (substance) "840535000" -> "A" // Antibody to severe acute respiratory syndrome coronavirus 2 (substance) "840534001" -> "A" // Severe acute respiratory syndrome coronavirus 2 vaccination (procedure) "373121007" -> "N" // Test not done "82334004" -> "N" // Indeterminate else -> null } } ) } } class TimestampMapper : Mapper { override val name = "timestamp" override fun valueNames(element: Element, args: List<String>): List<String> { return emptyList() } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { val tsFormat = if (args.isEmpty()) { "yyyyMMddHHmmss.SSSSZZZ" } else { args[0] } val ts = OffsetDateTime.now() return ElementResult( try { val formatter = DateTimeFormatter.ofPattern(tsFormat) formatter.format(ts) } catch (_: Exception) { val formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss") formatter.format(ts) } ) } } class DateTimeOffsetMapper : Mapper { private val expandedDateTimeFormatPattern = "yyyyMMddHHmmss.SSSSZZZ" private val formatter = DateTimeFormatter.ofPattern(expandedDateTimeFormatPattern) override val name = "offsetDateTime" override fun valueNames(element: Element, args: List<String>): List<String> { return listOf(args[0]) } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { fun parseDateTime(value: String): OffsetDateTime { return try { OffsetDateTime.parse(value) } catch (e: DateTimeParseException) { null } ?: try { val formatter = DateTimeFormatter.ofPattern(Element.datetimePattern, Locale.ENGLISH) OffsetDateTime.parse(value, formatter) } catch (e: DateTimeParseException) { null } ?: try { val formatter = DateTimeFormatter.ofPattern(expandedDateTimeFormatPattern, Locale.ENGLISH) OffsetDateTime.parse(value, formatter) } catch (e: DateTimeParseException) { error("Invalid date: '$value' for element '${element.name}'") } } return ElementResult( if (values.isEmpty() || values.size > 1 || values[0].value.isBlank()) { null } else { val unit = args[1] val offsetValue = args[2].toLong() val normalDate = parseDateTime(values[0].value) val adjustedDateTime = when (unit.lowercase()) { "second", "seconds" -> normalDate.plusSeconds(offsetValue) "minute", "minutes" -> normalDate.plusMinutes(offsetValue) "day", "days" -> normalDate.plusDays(offsetValue) "month", "months" -> normalDate.plusMonths(offsetValue) "year", "years" -> normalDate.plusYears(offsetValue) else -> error("Unit passed into mapper is not valid: $unit") } formatter.format(adjustedDateTime) } ) } } // todo: add the option for a default value class CoalesceMapper : Mapper { override val name = "coalesce" override fun valueNames(element: Element, args: List<String>): List<String> { return args } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { if (values.isEmpty()) return ElementResult(null) val ev = values.firstOrNull { it.value.isNotEmpty() } return ElementResult(ev?.value ?: "") } } class TrimBlanksMapper : Mapper { override val name = "trimBlanks" override fun valueNames(element: Element, args: List<String>): List<String> { return listOf(args[0]) } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { val ev = values.firstOrNull()?.value ?: "" return ElementResult(ev.trim()) } } class StripPhoneFormattingMapper : Mapper { override val name = "stripPhoneFormatting" override fun valueNames(element: Element, args: List<String>): List<String> { if (args.isEmpty()) error("StripFormatting mapper requires one or more arguments") return listOf(args[0]) } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { if (values.isEmpty()) return ElementResult(null) val returnValue = values.firstOrNull()?.value ?: "" val nonDigitRegex = "\\D".toRegex() val cleanedNumber = nonDigitRegex.replace(returnValue, "") return ElementResult("$cleanedNumber:1:") } } class StripNonNumericDataMapper : Mapper { override val name = "stripNonNumeric" override fun valueNames(element: Element, args: List<String>): List<String> { return args } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { if (values.isEmpty()) return ElementResult(null) val returnValue = values.firstOrNull()?.value ?: "" val nonDigitRegex = "\\D".toRegex() return ElementResult(nonDigitRegex.replace(returnValue, "").trim()) } } class StripNumericDataMapper : Mapper { override val name = "stripNumeric" override fun valueNames(element: Element, args: List<String>): List<String> { return args } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { if (values.isEmpty()) return ElementResult(null) val returnValue = values.firstOrNull()?.value ?: "" val nonDigitRegex = "\\d".toRegex() return ElementResult(nonDigitRegex.replace(returnValue, "").trim()) } } class SplitMapper : Mapper { override val name = "split" override fun valueNames(element: Element, args: List<String>): List<String> { return listOf(args[0]) } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { if (values.isEmpty()) return ElementResult(null) val value = values.firstOrNull()?.value ?: "" val delimiter = if (args.count() > 2) { args[2] } else { " " } val splitElements = value.split(delimiter) val index = args[1].toInt() return ElementResult(splitElements.getOrNull(index)?.trim()) } } class SplitByCommaMapper : Mapper { override val name = "splitByComma" override fun valueNames(element: Element, args: List<String>): List<String> { return listOf(args[0]) } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { if (values.isEmpty()) return ElementResult(null) val value = values.firstOrNull()?.value ?: "" val delimiter = "," val splitElements = value.split(delimiter) val index = args[1].toInt() return ElementResult(splitElements.getOrNull(index)?.trim()) } } class ZipCodeToCountyMapper : Mapper { override val name = "zipCodeToCounty" override fun valueNames(element: Element, args: List<String>): List<String> { return args } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { val table = element.tableRef ?: error("Cannot perform lookup on a null table") val zipCode = values.firstOrNull()?.value ?: return ElementResult(null) val cleanedZip = if (zipCode.contains("-")) { zipCode.split("-").first() } else { zipCode } return ElementResult( table.FilterBuilder().equalsIgnoreCase("zipcode", cleanedZip) .findSingleResult("county") ) } } /** * The CountryMapper examines both the patient_country and the patient_zip_code fields for a row * and makes a determination based on both values whether the patient is in the US or is in Canada. * It is currently restricted to those two choices because we do not have a need to extend it beyond * those countries. * * The functionality works as follows: * - If a value exists for patient_country, pass that through untouched. We always assume that whatever * the sender gives us is correct and should not be enriched. * - If there is not a value for patient_country we then look at the patient_zip_code field. If the patient * zip code matches the pattern for a Canadian postal code then we assume we are dealing with a Canadian * address. Canadian postal codes follow a pattern of A9A 9A9 where 'A' represents a letter between A-Z * and '9' represents a number between 0-9. * - If the patient_zip_code doesn't match a Canadian postal code pattern, then we default to USA. */ class CountryMapper : Mapper { override val name = "countryMapper" override fun valueNames(element: Element, args: List<String>): List<String> { return args } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { val patientCountry = values.firstOrNull { it.element.name == element.name }?.value val patientPostalCode = values.firstOrNull { it.element.name == "patient_zip_code" }?.value return ElementResult( when (patientCountry.isNullOrEmpty()) { true -> { if (patientPostalCode != null && canadianPostalCodeRegex.matches(patientPostalCode)) { CAN } else { USA } } else -> patientCountry } ) } companion object { /** * This regex matches Canadian postal codes, which follow a pattern of A9A 9A9, where 'A' means any * alpha character from [A-Z] and 9 represents any number between [0-9]. The space between the two * groupings is technically part of their postal code standard, but in the case of our processing, * we typically have stripped it out. So a Canadian postal code could look like J0A 0A0, or J0A0A0. * * A Canadian postal code is broken down by the first character being the postal district, for example, * Ontario, and the next two characters representing the forward sortation area.The second set of three * digits is the local delivery unit. Small fun fact, Canada Post has a special postal code for Santa * so children can address their letters to him at H0H 0H0. */ private val canadianPostalCodeRegex = "[A-Z][0-9][A-Z]\\s?[0-9][A-Z][0-9]".toRegex(RegexOption.IGNORE_CASE) /** No magic strings. */ /** No magic strings. */ private const val USA = "USA" /** No magic strings. */ private const val CAN = "CAN" } } /** * Create a SHA-256 digest hash of the concatenation of values * Example: hash(patient_last_name,patient_first_name) */ class HashMapper : Mapper { override val name = "hash" override fun valueNames(element: Element, args: List<String>) = args override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { if (args.isEmpty()) error("Must pass at least one element name to $name") if (values.isEmpty()) return ElementResult(null) val concatenation = values.joinToString("") { it.value } if (concatenation.isEmpty()) return ElementResult(null) return ElementResult(digest(concatenation.toByteArray()).lowercase()) } companion object { fun digest(input: ByteArray): String { val digest = MessageDigest.getInstance("SHA-256").digest(input) return DatatypeConverter.printHexBinary(digest) } } } /** * This mapper performs no operation and is meant to override mappers set on parent schemas, so no mapper runs. * It does not change any values. * If you want to 'blank out' a value, use 'defaultOverridesValue: true', along with an empty 'default:' * Arguments: None * Returns: null */ class NullMapper : Mapper { override val name = "none" override fun valueNames(element: Element, args: List<String>): List<String> { if (args.isNotEmpty()) error("Schema Error: none mapper does not expect args") return emptyList() } override fun apply( element: Element, args: List<String>, values: List<ElementAndValue>, sender: Sender? ): ElementResult { return ElementResult(null) } } object Mappers { fun parseMapperField(field: String): Pair<String, List<String>> { val match = Regex("([a-zA-Z0-9]+)\\x28([a-z, \\x2E_\\x2DA-Z0-9?&$*:^]*)\\x29").find(field) ?: error("Mapper field $field does not parse") val args = if (match.groupValues[2].isEmpty()) emptyList() else match.groupValues[2].split(',').map { it.trim() } val mapperName = match.groupValues[1] return Pair(mapperName, args) } }
829
Kotlin
34
35
2d9551487ce5b352a9043cd677b67ab7711ea509
34,378
prime-reportstream
Creative Commons Zero v1.0 Universal
typesafe/src/commonTest/kotlin/tech/annexflow/precompose/navigation/typesafe/internal/PathEncoderTest.kt
Lavmee
718,952,897
false
{"Kotlin": 40255}
package tech.annexflow.precompose.navigation.typesafe.internal import kotlinx.serialization.serializer import kotlin.test.Test import kotlin.test.assertEquals class PathEncoderTest { @Test fun encodeDataObject() { val url = StringBuilder() val model = AppRoutes.Empty PathEncoder(url).encodeSerializableValue( serializer = serializer<AppRoutes.Empty>(), value = model ) assertEquals(expected = "", actual = url.toString()) } @Test fun encodeDataClass() { val url = StringBuilder() val model = AppRoutes.Simple(value = 1) PathEncoder(url).encodeSerializableValue( serializer = serializer<AppRoutes.Simple>(), value = model ) assertEquals(expected = "/1", actual = url.toString()) } @Test fun encodeDataClassTwoArgs() { val url = StringBuilder() val model = AppRoutes.TwoArgs(value = 1, text = "Test") PathEncoder(url).encodeSerializableValue( serializer = serializer<AppRoutes.TwoArgs>(), value = model ) assertEquals(expected = "/1/Test", actual = url.toString()) } @Test fun encodeDataClassNullableWithNull() { val url = StringBuilder() val model = AppRoutes.Nullable(value = null) PathEncoder(url).encodeSerializableValue( serializer = serializer<AppRoutes.Nullable>(), value = model ) assertEquals(expected = "", actual = url.toString()) } @Test fun encodeDataClassNullableWithNotNull() { val url = StringBuilder() val model = AppRoutes.Nullable(value = 1) PathEncoder(url).encodeSerializableValue( serializer = serializer<AppRoutes.Nullable>(), value = model ) assertEquals(expected = "?value=1", actual = url.toString()) } @Test fun encodeDataClassNullableTwoArgsWithNotNull() { val url = StringBuilder() val model = AppRoutes.NullableTwoArgs(value = 1, text = "Test") PathEncoder(url).encodeSerializableValue( serializer = serializer<AppRoutes.NullableTwoArgs>(), value = model ) assertEquals(expected = "?value=1&text=Test", actual = url.toString()) } @Test fun encodeDataClassNullableTwoArgsWithNulls() { val url = StringBuilder() val model = AppRoutes.NullableTwoArgs(value = null, text = null) PathEncoder(url).encodeSerializableValue( serializer = serializer<AppRoutes.NullableTwoArgs>(), value = model ) assertEquals(expected = "", actual = url.toString()) } @Test fun encodeDataClassNullableWithDefault() { val url = StringBuilder() val model = AppRoutes.NullableWithDefault() PathEncoder(url).encodeSerializableValue( serializer = serializer<AppRoutes.NullableWithDefault>(), value = model ) assertEquals(expected = "", actual = url.toString()) } @Test fun encodeDataClassNullableWithDefaults() { val url = StringBuilder() val model = AppRoutes.NullableWithDefaults() PathEncoder(url).encodeSerializableValue( serializer = serializer<AppRoutes.NullableWithDefaults>(), value = model ) assertEquals(expected = "?text=Test", actual = url.toString()) } @Test fun encodeDataClassWithComplexData() { val url = StringBuilder() val model = AppRoutes.WithComplexData(data = AppRoutes.ComplexData(2)) PathEncoder(url).encodeSerializableValue( serializer = serializer<AppRoutes.WithComplexData>(), value = model ) assertEquals(expected = """/{"id":2}""", actual = url.toString()) } @Test fun encodeDataClassWithComplexDataWithDefault() { val url = StringBuilder() val model = AppRoutes.WithComplexData(data = AppRoutes.ComplexData()) PathEncoder(url).encodeSerializableValue( serializer = serializer<AppRoutes.WithComplexData>(), value = model ) assertEquals(expected = "/{}", actual = url.toString()) } }
3
Kotlin
0
3
edc6883af94da886584a72b01e1ba7643e849a18
4,268
precompose-navigation-typesafe
MIT License
feature/home/src/main/java/com/mobilebreakero/home/ui/screens/GameDetails.kt
OmarLkhalil
672,856,200
false
null
package com.mobilebreakero.home.ui.screens import android.net.Uri import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.Button import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.mobilebreakero.common.components.CoilImage @Composable fun DetailsScreen( name: String, description: String, image: String, rating: Int, link: String ) { Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) ) { CoilImage( data = image, contentDescription = name, modifier = Modifier .fillMaxWidth() .height(300.dp), contentScale = ContentScale.Crop, gameTitle = name, onClick = {} ) Spacer(modifier = Modifier.height(10.dp)) Text( text = name, style = TextStyle( fontWeight = FontWeight.Bold, fontSize = 20.sp ), modifier = Modifier.padding(10.dp) ) Spacer(modifier = Modifier.height(10.dp)) Text( text = description, style = TextStyle( fontWeight = FontWeight.Bold, fontSize = 20.sp ), modifier = Modifier.padding(10.dp) ) Spacer(modifier = Modifier.height(10.dp)) Text( text = "Rating: $rating", style = TextStyle( fontWeight = FontWeight.Bold, fontSize = 20.sp ), modifier = Modifier.padding(10.dp) ) val uriHandler = LocalUriHandler.current Spacer(modifier = Modifier.height(10.dp)) Button(onClick = { val uri = Uri.parse("http://$link") uriHandler.openUri(uri.toString()) }) { Text(text = "Play Now") } } }
0
Kotlin
0
0
6178d99e7f45a471539f0d9da0baf8fc7bc6c60e
2,667
GameZone
MIT License
app/src/main/java/com/cybershark/jokes/util/UIState.kt
Sharkaboi
322,821,166
false
null
package com.cybershark.jokes.util sealed class UIState { object Loading : UIState() object Idle : UIState() data class Error(val message: String) : UIState() data class Success(val message: String) : UIState() }
0
Kotlin
1
3
5a33220212cd21b7583c25d0b6220b51ca42fc08
229
Jokes
MIT License
src/main/kotlin/com/github/snabbdom/class.kt
gbaldeck
94,640,750
false
null
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS") package com.github.snabbdom @JsModule("snabbdom/modules/class") @JsNonModule external val classModule_ext: dynamic = definedExternally val classModule: Module = classModule_ext.default external interface Classes operator fun Classes.get(key: String): Boolean = this._get(key) operator fun Classes.set(key: String, value: Boolean) { this._set(key, value) }
0
Kotlin
1
4
3de0752966e4b4231efe3200b140142565520087
490
snabbdom-kotlin
MIT License
components/crypto/crypto-persistence/src/main/kotlin/net/corda/crypto/persistence/SigningKeyStatus.kt
corda
346,070,752
false
null
package net.corda.crypto.persistence /** * The key status, currently only NORMAL */ enum class SigningKeyStatus { NORMAL }
126
Kotlin
12
37
e5b0c3fb8180331fb026370ffff751a1c79e5b43
129
corda-runtime-os
Apache License 2.0
app/src/main/java/com/tungnui/abccomputer/models/TopSallersReport.kt
ngthtung2805
105,776,185
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 3, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "JSON": 3, "Proguard": 1, "XML": 200, "Kotlin": 154, "Java": 100}
package com.tungnui.abccomputer.models /** * Created by thanh on 12/12/2017. */ import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName data class TopSallersReport( var title:String, @SerializedName("product_id") @Expose var productId:Int, var quantity:Int )
1
null
1
1
f80905971310015cc4444b838395f70432a71c8b
337
dalatlaptop
MIT License
app/src/main/java/com/getcode/navigation/screens/Modals.kt
code-payments
723,049,264
false
{"Kotlin": 1464732, "C": 198685, "C++": 83029, "Java": 51811, "CMake": 2594, "Ruby": 1714, "Shell": 1577}
package com.getcode.navigation.screens import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.LocalOverscrollConfiguration import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalSoftwareKeyboardController import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.core.screen.ScreenKey import cafe.adriel.voyager.core.screen.uniqueScreenKey import com.getcode.navigation.core.CodeNavigator import com.getcode.navigation.core.LocalCodeNavigator import com.getcode.theme.CodeTheme import com.getcode.theme.sheetHeight import com.getcode.util.recomposeHighlighter import com.getcode.view.components.SheetTitle import kotlinx.coroutines.delay import kotlinx.coroutines.launch import timber.log.Timber internal interface ModalContent { @Composable fun Screen.ModalContainer( closeButton: (Screen?) -> Boolean = { false }, screenContent: @Composable () -> Unit ) { ModalContainer( navigator = LocalCodeNavigator.current, displayLogo = false, backButton = { false }, onLogoClicked = {}, closeButton = closeButton, screenContent = screenContent, ) } @Composable fun Screen.ModalContainer( displayLogo: Boolean = false, onLogoClicked: () -> Unit = { }, closeButton: (Screen?) -> Boolean = { false }, screenContent: @Composable () -> Unit ) { ModalContainer( navigator = LocalCodeNavigator.current, displayLogo = displayLogo, backButton = { false }, onLogoClicked = onLogoClicked, closeButton = closeButton, screenContent = screenContent, ) } @OptIn(ExperimentalFoundationApi::class) @Composable fun Screen.ModalContainer( navigator: CodeNavigator = LocalCodeNavigator.current, displayLogo: Boolean = false, backButton: (Screen?) -> Boolean = { false }, onBackClicked: (() -> Unit)? = null, closeButton: (Screen?) -> Boolean = { false }, onCloseClicked: (() -> Unit)? = null, onLogoClicked: () -> Unit = { }, screenContent: @Composable () -> Unit ) { Column( modifier = Modifier .fillMaxWidth() .fillMaxHeight(sheetHeight) ) { val lastItem by remember(navigator.lastModalItem) { derivedStateOf { navigator.lastModalItem } } val isBackEnabled by remember(backButton, lastItem) { derivedStateOf { backButton(lastItem) } } val isCloseEnabled by remember(closeButton, lastItem) { derivedStateOf { closeButton(lastItem) } } val keyboardController = LocalSoftwareKeyboardController.current val composeScope = rememberCoroutineScope() val hideSheet = { composeScope.launch { keyboardController?.hide() delay(500) navigator.hide() } } SheetTitle( modifier = Modifier, title = { val name = (lastItem as? NamedScreen)?.name val sheetName by remember(lastItem) { derivedStateOf { name } } sheetName.takeIf { !displayLogo && lastItem == this@ModalContainer } }, displayLogo = displayLogo, onLogoClicked = onLogoClicked, // hide while transitioning to/from other destinations backButton = isBackEnabled, closeButton = isCloseEnabled, onBackIconClicked = onBackClicked?.let { { it() } } ?: { navigator.pop() }, onCloseIconClicked = onCloseClicked?.let { { it() } } ?: { hideSheet() } ) Box( modifier = Modifier .windowInsetsPadding(WindowInsets.navigationBars) ) { CompositionLocalProvider( LocalOverscrollConfiguration provides null ) { screenContent() } } } } } internal sealed interface ModalRoot : ModalContent data object MainRoot : Screen { override val key: ScreenKey = uniqueScreenKey private fun readResolve(): Any = this @Composable override fun Content() { // TODO: potentially add a loading state here // so app doesn't appear stuck in a dead state // while we wait for auth check to complete Box(modifier = Modifier.fillMaxSize().background(CodeTheme.colors.background)) } }
2
Kotlin
10
12
46d21ee4cda087fe6914cf51e871be16812db041
5,586
code-android-app
MIT License
korim/src/commonMain/kotlin/com/soywiz/korim/bitmap/Bitmap8.kt
dandanx
257,100,686
true
{"Kotlin": 606339, "C": 13764, "Shell": 1701, "Batchfile": 1531}
package com.soywiz.korim.bitmap import com.soywiz.korim.color.* class Bitmap8( width: Int, height: Int, data: ByteArray = ByteArray(width * height), palette: RgbaArray = RgbaArray(0x100) ) : BitmapIndexed(8, width, height, data, palette) { override fun createWithThisFormat(width: Int, height: Int): Bitmap = Bitmap8(width, height, palette = palette) override fun setInt(x: Int, y: Int, color: Int) = Unit.apply { datau[index(x, y)] = color } override fun getInt(x: Int, y: Int): Int = datau[index(x, y)] override fun getRgba(x: Int, y: Int): RGBA = palette[get(x, y)] override fun clone() = Bitmap8(width, height, data.copyOf(), RgbaArray(palette.ints.copyOf())) override fun toString(): String = "Bitmap8($width, $height, palette=${palette.size})" companion object { fun copyRect( src: Bitmap8, srcX: Int, srcY: Int, dst: Bitmap8, dstX: Int, dstY: Int, width: Int, height: Int ) = src.copy(srcX, srcY, dst, dstX, dstY, width, height) } }
0
Kotlin
0
0
43d2591c7136545d6ad61fea4ee73ea82c04a2cf
1,079
korim
Apache License 2.0
src/test/kotlin/com/github/debop/kodatimes/TimeIntervalWindowedTest.kt
RepoForks
119,803,117
true
{"Kotlin": 108970}
package com.github.debop.kodatimes import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test class TimeIntervalWindowedTest : AbstractKodaTimesTest() { @Test fun `windowed year`() { val start = now().startOfYear() val endExclusive = start + 5.years() val interval = start .. endExclusive logger.debug("interval=$interval") val windowed = interval.windowedYear(3, 2) windowed.forEach { items -> logger.debug("items = $items") assertTrue(items.first() in interval) assertTrue(items.last() in interval) } assertEquals(3, windowed.count()) assertThrows(IllegalArgumentException::class.java) { interval.windowedYear(-1, 2) } assertThrows(IllegalArgumentException::class.java) { interval.windowedYear(2, -2) } } @Test fun `windowed month`() { val start = now().startOfMonth() val endExclusive = start + 5.months() val interval = start .. endExclusive logger.debug("interval=$interval") val windowed = interval.windowedMonth(3, 2) windowed.forEach { items -> logger.debug("items = $items") assertTrue { items.all { it in interval } } } assertEquals(3, windowed.count()) assertThrows(IllegalArgumentException::class.java) { interval.windowedMonth(-1, 2) } assertThrows(IllegalArgumentException::class.java) { interval.windowedMonth(2, -2) } } @Test fun `windowed week`() { val start = now().startOfWeek() val endExclusive = start + 5.weeks() val interval = start .. endExclusive logger.debug("interval=$interval") val windowed = interval.windowedWeek(3, 2) windowed.forEach { items -> logger.debug("items = $items") assertTrue(items.all { it in interval }) } assertEquals(3, windowed.count()) assertThrows(IllegalArgumentException::class.java) { interval.windowedWeek(-1, 2) } assertThrows(IllegalArgumentException::class.java) { interval.windowedWeek(2, -2) } } @Test fun `windowed day`() { val start = now().startOfDay() val endExclusive = start + 5.days() val interval = start .. endExclusive logger.debug("interval=$interval") val windowed = interval.windowedDay(3, 2) windowed.forEach { items -> logger.debug("items = $items") assertTrue(items.all { it in interval }) } assertEquals(3, windowed.count()) assertThrows(IllegalArgumentException::class.java) { interval.windowedDay(-1, 2) } assertThrows(IllegalArgumentException::class.java) { interval.windowedDay(2, -2) } } @Test fun `windowed hour`() { val start = now().trimToHour() val endExclusive = start + 5.hours() val interval = start .. endExclusive logger.debug("interval=$interval") val windowed = interval.windowedHour(3, 2) windowed.forEach { items -> logger.debug("items = $items") assertTrue(items.all { it in interval }) } assertEquals(3, windowed.count()) assertThrows(IllegalArgumentException::class.java) { interval.windowedHour(-1, 2) } assertThrows(IllegalArgumentException::class.java) { interval.windowedHour(2, -2) } } @Test fun `windowed minute`() { val start = now().trimToMinute() val endExclusive = start + 5.minutes() val interval = start .. endExclusive logger.debug("interval=$interval") val windowed = interval.windowedMinute(3, 2) windowed.forEach { items -> logger.debug("items = $items") assertTrue(items.all { it in interval }) } assertEquals(3, windowed.count()) assertThrows(IllegalArgumentException::class.java) { interval.windowedMinute(-1, 2) } assertThrows(IllegalArgumentException::class.java) { interval.windowedMinute(2, -2) } } @Test fun `windowed second`() { val start = now().trimToSecond() val endExclusive = start + 5.seconds() val interval = start .. endExclusive logger.debug("interval=$interval") val windowed = interval.windowedSecond(3, 2) windowed.forEach { items -> logger.debug("items = $items") assertTrue(items.all { it in interval }) } assertEquals(3, windowed.count()) assertThrows(IllegalArgumentException::class.java) { interval.windowedSecond(-1, 2) } assertThrows(IllegalArgumentException::class.java) { interval.windowedSecond(2, -2) } } @Test fun `zipWithNext years`() { val start = now().startOfYear() val endExclusive = start + 5.years() val interval = start .. endExclusive logger.debug("interval=$interval") val pairs = interval.zipWithNextYear().toList() assertEquals(4, pairs.size) pairs.forEach { (current, next) -> logger.debug("current=$current, next=$next") assertTrue { current in interval } assertTrue { next in interval } } } @Test fun `zipWithNext months`() { val start = now().startOfMonth() val endExclusive = start + 5.months() val interval = start .. endExclusive logger.debug("interval=$interval") val pairs = interval.zipWithNextMonth().toList() assertEquals(4, pairs.size) pairs.forEach { (current, next) -> logger.debug("current=$current, next=$next") assertTrue { current in interval } assertTrue { next in interval } } } @Test fun `zipWithNext weeks`() { val start = now().startOfWeek() val endExclusive = start + 5.weeks() val interval = start .. endExclusive logger.debug("interval=$interval") val pairs = interval.zipWithNextWeek().toList() assertEquals(4, pairs.size) pairs.forEach { (current, next) -> logger.debug("current=$current, next=$next") assertTrue { current in interval } assertTrue { next in interval } } } @Test fun `zipWithNext days`() { val start = now().startOfDay() val endExclusive = start + 5.days() val interval = start .. endExclusive logger.debug("interval=$interval") val pairs = interval.zipWithNextDay().toList() assertEquals(4, pairs.size) pairs.forEach { (current, next) -> logger.debug("current=$current, next=$next") assertTrue { current in interval } assertTrue { next in interval } } } @Test fun `zipWithNext hours`() { val start = now().trimToHour() val endExclusive = start + 5.hours() val interval = start .. endExclusive logger.debug("interval=$interval") val pairs = interval.zipWithNextHour().toList() assertEquals(4, pairs.size) pairs.forEach { (current, next) -> logger.debug("current=$current, next=$next") assertTrue { current in interval } assertTrue { next in interval } } } @Test fun `zipWithNext minutes`() { val start = now().trimToMinute() val endExclusive = start + 5.minutes() val interval = start .. endExclusive logger.debug("interval=$interval") val pairs = interval.zipWithNextMinute().toList() assertEquals(4, pairs.size) pairs.forEach { (current, next) -> logger.debug("current=$current, next=$next") assertTrue { current in interval } assertTrue { next in interval } } } @Test fun `zipWithNext seconds`() { val start = now().trimToSecond() val endExclusive = start + 5.seconds() val interval = start .. endExclusive logger.debug("interval=$interval") val pairs = interval.zipWithNextSecond().toList() assertEquals(4, pairs.size) pairs.forEach { (current, next) -> logger.debug("current=$current, next=$next") assertTrue { current in interval } assertTrue { next in interval } } } }
0
Kotlin
0
0
7ace468f0ca02512db1faf13bd0cdf1259593b1e
7,799
koda-time
Apache License 2.0
src/jvmMain/kotlin/matt/shell/commands/codesign/codesign.kt
mgroth0
640,054,316
false
{"Kotlin": 94115}
package matt.shell.commands.codesign import matt.collect.itr.mapToArray import matt.lang.common.If import matt.lang.common.opt import matt.lang.common.optArray import matt.model.data.id.CodesignIdentity import matt.model.data.message.AbsMacFile import matt.shell.common.Shell fun <R> Shell<R>.codesign( identity: CodesignIdentity? = null, verbosity: Int? = null, force: Boolean = false /*replace existing signatures (otherwise it would fail if other signatures exist)*/, entitlements: AbsMacFile? = null, executable: AbsMacFile, /*makes the code signature more trustworthy, especially in the long term when a certificate might expire*/ timestamp: Boolean? = null, options: Set<CodesignOption> = setOf(), prefix: String? = null, display: Boolean = false ): R { require(verbosity in 1..4) { "I think verbosity has to be from 1 to 4 but I cannot find a straight answer" } val opts = options.toSet() return sendCommand( CODESIGN_PATH, *optArray(identity) { arrayOf("-s", arg) }, /* (HORRIBLE DESIGN NOTE) `-v` could mean VERIFY not VERBOSE in different contexts So use --verbose instead so there is 0 ambiguity */ *opt(verbosity) { "--verbose=$this" }, *If(force).then("-f"), *optArray(entitlements) { arrayOf("--entitlements", path) }, *optArray(timestamp) { arrayOf("--timestamp", *If(!this).then("none")) }, *If(opts.isNotEmpty()).then("--options", *opts.mapToArray { it.name }), *optArray(prefix) { arrayOf("--prefix", this) }, *If(display).then("-d"), executable.path ) } const val CODESIGN_PATH = "/usr/bin/codesign" enum class CodesignOption { /*required for notarizing (and thus for distributing outside the Mac App Store)*/ runtime }
0
Kotlin
0
0
6bed93f8596f52fe2292bb84c97b0bee22ac0f2b
1,866
shell
MIT License
data/src/main/java/com/csosa/fntest/data/remote/models/VehiclesByBoundsResponse.kt
cdavidsp
351,837,504
false
null
package com.csosa.fntest.data.remote.models data class VehiclesByBoundsResponse( val poiList: List<VehicleResponse> ) data class VehicleResponse( val id: Long, val coordinate: CoordinateResponse, val fleetType: String, val heading: Float ) data class CoordinateResponse( val latitude: Double, val longitude: Double )
0
Kotlin
0
0
21d27913d946ef13fc7e204ff634155444aa37ed
348
fntest
Apache License 2.0
lcc-content-data/src/main/kotlin/com/joshmanisdabomb/lcc/data/factory/recipe/HeartRecipeFactory.kt
joshmanisdabomb
537,458,013
false
{"Kotlin": 2724329, "Java": 138822}
package com.joshmanisdabomb.lcc.data.factory.recipe import com.joshmanisdabomb.lcc.data.DataAccessor import com.joshmanisdabomb.lcc.data.factory.tag.HeartItemTagFactory import com.joshmanisdabomb.lcc.directory.LCCItems import com.joshmanisdabomb.lcc.item.HeartContainerItem import com.joshmanisdabomb.lcc.item.HeartItem import net.minecraft.advancement.criterion.InventoryChangedCriterion import net.minecraft.data.server.recipe.ShapelessRecipeJsonBuilder import net.minecraft.item.Item import net.minecraft.predicate.item.ItemPredicate object HeartRecipeFactory : RecipeFactory { override fun apply(data: DataAccessor, entry: Item) { if (entry !is HeartItem) return if (entry is HeartContainerItem) return if (entry.value == 1f) { ShapelessRecipeJsonBuilder.create(entry, 2) .input(LCCItems.heart_full[entry.heart]) .criterion("has_${entry.heart.asString()}_hearts", InventoryChangedCriterion.Conditions.items(ItemPredicate.Builder.create().tag(HeartItemTagFactory.getTag(entry.heart)).build())) .apply { offerShapeless(this, data) } } else { ShapelessRecipeJsonBuilder.create(entry) .input(LCCItems.heart_half[entry.heart], 2) .criterion("has_${entry.heart.asString()}_hearts", InventoryChangedCriterion.Conditions.items(ItemPredicate.Builder.create().tag(HeartItemTagFactory.getTag(entry.heart)).build())) .apply { offerShapeless(this, data) } } } }
0
Kotlin
0
0
a836162eaf64a75ca97daffa02c1f9e66bdde1b4
1,525
loosely-connected-concepts
Creative Commons Zero v1.0 Universal
app/src/androidTest/java/ir/amirsobhan/sticknote/module/NoteViewModelTest.kt
a1383n
342,316,747
false
null
package ir.amirsobhan.sticknote.module import android.content.Context import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.room.Room import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import ir.amirsobhan.sticknote.database.AppDatabase import ir.amirsobhan.sticknote.database.Note import ir.amirsobhan.sticknote.repositories.NoteRepository import ir.amirsobhan.sticknote.utils.getOrAwaitValue import ir.amirsobhan.sticknote.viewmodel.NoteViewModel import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class NoteViewModelTest{ private val context: Context = ApplicationProvider.getApplicationContext() private lateinit var noteViewModel: NoteViewModel private lateinit var database : AppDatabase private val note = Note(title = "Title",text = "Body") @get:Rule val instantTaskExecutorRule = InstantTaskExecutorRule() @Before fun setUp() { database = Room.inMemoryDatabaseBuilder(context,AppDatabase::class.java).build() noteViewModel = NoteViewModel(NoteRepository(database.noteDao())) } @Test fun testViewModel(){ database.noteDao().insert(note) val result = noteViewModel.notes.getOrAwaitValue().find { note == it } assertThat(result != null).isTrue() } @After fun closeDB(){ database.close() } }
11
Kotlin
0
1
f34e4f45e63cd5965fbd883502d15bb0e0e99daf
1,563
sticknote
MIT License
app/src/main/java/io/wookey/wallet/data/remote/HashUtils.kt
WooKeyWallet
176,637,569
false
{"Kotlin": 448185, "Java": 407883, "C++": 135434, "CMake": 7579, "Shell": 1922}
package io.gamerope.wallet.data.remote import java.security.MessageDigest import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec fun String.md5(): String { return hashString(this, "MD5") } fun String.sha256(): String { return hashString(this, "SHA-256") } fun String.sha512(): String { return hashString(this, "SHA-512") } private fun hashString(message: String, algorithm: String): String { return MessageDigest .getInstance(algorithm) .digest(message.toByteArray()) .hexDigest() } fun String.hmacMD5(key: String): String { return hmacString(this, key, "HmacMD5") } fun String.hmacSHA256(key: String): String { return hmacString(this, key, "HmacSHA256") } fun String.hmacSHA512(key: String): String { return hmacString(this, key, "HmacSHA512") } private fun hmacString(message: String, key: String, algorithm: String): String { return Mac.getInstance(algorithm) .apply { init(SecretKeySpec(key.toByteArray(), algorithm)) } .doFinal(message.toByteArray()) .hexDigest() } private fun ByteArray.hexDigest(): String { return fold("", { str, it -> str + "%02x".format(it) }) }
6
Kotlin
20
23
93d0d6a4743e95ab2455bb6ae24b2cc6b616bd90
1,174
monero-wallet-android-app
MIT License
ffc/src/main/kotlin/ffc/app/location/HouseApi.kt
ffc-nectec
125,313,191
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "EditorConfig": 1, "YAML": 1, "Markdown": 1, "Proguard": 1, "JSON": 12, "Kotlin": 175, "XML": 216, "Java": 60, "HTML": 1, "JavaScript": 11}
package ffc.app.location import ffc.entity.Person import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path interface HouseApi { @GET("org/{orgId}/house/{houseId}/resident") fun personInHouse( @Path("orgId") orgId: String, @Path("houseId") houseId: String ): Call<List<Person>> }
5
JavaScript
1
2
f19e7ea2cb3f891d3786b0f66d7c0cdf1c114eab
328
android
Apache License 2.0
app/src/main/java/com/zerogdev/setmyhome/data/PreferenceProvider.kt
zerogdev
165,848,642
false
{"Kotlin": 41558, "Java": 1497}
package com.zerogdev.setmyhome.data import android.content.Context import android.preference.PreferenceManager import io.reactivex.Observable import io.reactivex.ObservableEmitter import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.BehaviorSubject class PreferenceProvider(private val context: Context) { companion object { private const val KEY_MODE_OUT = "mode_out" } val updateObserver: BehaviorSubject<Int> = BehaviorSubject.createDefault(getModeOut()) fun updateModeOut(mode: Int): Disposable{ return Observable.fromCallable { PreferenceManager.getDefaultSharedPreferences(context).edit() .putInt(KEY_MODE_OUT, mode) .apply() }.flatMap { Observable.just(getModeOut()) }.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe {mode -> updateObserver.onNext(mode) } } val modeOut: Observable<Int> get() { return updateObserver } fun getModeOut(): Int = PreferenceManager.getDefaultSharedPreferences(context) .getInt(KEY_MODE_OUT, -1) }
0
Kotlin
0
1
e0784946a2012c56499ba0f729d14d0a7dc7d7aa
1,299
SetMyHome-kotlin
Apache License 2.0
idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/KotlinMavenImporterTest.kt
AlexeyTsvetkov
17,321,988
false
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.maven import java.io.File class KotlinMavenImporterTest : MavenImportingTestCase() { private val kotlinVersion = "1.0.0-beta-2423" override fun setUp() { super.setUp() repositoryPath = File(myDir, "repo").path createStdProjectFolders() } fun testSimpleKotlinProject() { importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>1.0.0</version> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> <version>$kotlinVersion</version> </dependency> </dependencies> """) assertModules("project") assertImporterStatePresent() assertSources("project", "src/main/java") } fun testWithSpecifiedSourceRoot() { createProjectSubDir("src/main/kotlin") importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>1.0.0</version> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> <version>$kotlinVersion</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/kotlin</sourceDirectory> </build> """) assertModules("project") assertImporterStatePresent() assertSources("project", "src/main/kotlin") } fun testWithCustomSourceDirs() { createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm") importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>1.0.0</version> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> <version>$kotlinVersion</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/kotlin</sourceDirectory> <plugins> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <executions> <execution> <id>compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> <configuration> <sourceDirs> <dir>src/main/kotlin</dir> <dir>src/main/kotlin.jvm</dir> </sourceDirs> </configuration> </execution> <execution> <id>test-compile</id> <phase>test-compile</phase> <goals> <goal>test-compile</goal> </goals> <configuration> <sourceDirs> <dir>src/test/kotlin</dir> <dir>src/test/kotlin.jvm</dir> </sourceDirs> </configuration> </execution> </executions> </plugin> </plugins> </build> """) assertModules("project") assertImporterStatePresent() assertSources("project", "src/main/kotlin", "src/main/kotlin.jvm") assertTestSources("project", "src/test/java", "src/test/kotlin", "src/test/kotlin.jvm") } fun testReImportRemoveDir() { createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm") importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>1.0.0</version> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> <version>$kotlinVersion</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/kotlin</sourceDirectory> <plugins> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <executions> <execution> <id>compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> <configuration> <sourceDirs> <dir>src/main/kotlin</dir> <dir>src/main/kotlin.jvm</dir> </sourceDirs> </configuration> </execution> <execution> <id>test-compile</id> <phase>test-compile</phase> <goals> <goal>test-compile</goal> </goals> <configuration> <sourceDirs> <dir>src/test/kotlin</dir> <dir>src/test/kotlin.jvm</dir> </sourceDirs> </configuration> </execution> </executions> </plugin> </plugins> </build> """) assertModules("project") assertImporterStatePresent() assertSources("project", "src/main/kotlin", "src/main/kotlin.jvm") assertTestSources("project", "src/test/java", "src/test/kotlin", "src/test/kotlin.jvm") // reimport importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>1.0.0</version> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> <version>$kotlinVersion</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/kotlin</sourceDirectory> <plugins> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <executions> <execution> <id>compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> <configuration> <sourceDirs> <dir>src/main/kotlin</dir> </sourceDirs> </configuration> </execution> <execution> <id>test-compile</id> <phase>test-compile</phase> <goals> <goal>test-compile</goal> </goals> <configuration> <sourceDirs> <dir>src/test/kotlin</dir> <dir>src/test/kotlin.jvm</dir> </sourceDirs> </configuration> </execution> </executions> </plugin> </plugins> </build> """) assertSources("project", "src/main/kotlin") assertTestSources("project", "src/test/java", "src/test/kotlin", "src/test/kotlin.jvm") } fun testReImportAddDir() { createProjectSubDirs("src/main/kotlin", "src/main/kotlin.jvm", "src/test/kotlin", "src/test/kotlin.jvm") importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>1.0.0</version> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> <version>$kotlinVersion</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/kotlin</sourceDirectory> <plugins> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <executions> <execution> <id>compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> <configuration> <sourceDirs> <dir>src/main/kotlin</dir> </sourceDirs> </configuration> </execution> <execution> <id>test-compile</id> <phase>test-compile</phase> <goals> <goal>test-compile</goal> </goals> <configuration> <sourceDirs> <dir>src/test/kotlin</dir> <dir>src/test/kotlin.jvm</dir> </sourceDirs> </configuration> </execution> </executions> </plugin> </plugins> </build> """) assertModules("project") assertImporterStatePresent() assertSources("project", "src/main/kotlin") assertTestSources("project", "src/test/java", "src/test/kotlin", "src/test/kotlin.jvm") // reimport importProject(""" <groupId>test</groupId> <artifactId>project</artifactId> <version>1.0.0</version> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> <version>$kotlinVersion</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/kotlin</sourceDirectory> <plugins> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <executions> <execution> <id>compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> <configuration> <sourceDirs> <dir>src/main/kotlin</dir> <dir>src/main/kotlin.jvm</dir> </sourceDirs> </configuration> </execution> <execution> <id>test-compile</id> <phase>test-compile</phase> <goals> <goal>test-compile</goal> </goals> <configuration> <sourceDirs> <dir>src/test/kotlin</dir> <dir>src/test/kotlin.jvm</dir> </sourceDirs> </configuration> </execution> </executions> </plugin> </plugins> </build> """) assertSources("project", "src/main/kotlin", "src/main/kotlin.jvm") assertTestSources("project", "src/test/java", "src/test/kotlin", "src/test/kotlin.jvm") } private fun assertImporterStatePresent() { assertNotNull("Kotlin importer component is not present", myTestFixture.module.getComponent(KotlinImporterComponent::class.java)) } }
1
null
0
2
72a84083fbe50d3d12226925b94ed0fe86c9d794
13,885
kotlin
Apache License 2.0
src/test/kotlin/com/kru/kotboot/controller/UserControllerTest.kt
krunalsabnis
122,632,700
false
{"XML": 3, "Gradle": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Kotlin": 20, "YAML": 6, "Java": 1}
package com.kru.kotboot.controller import com.kru.kotboot.ControllerTest import com.kru.kotboot.model.RestResponsePage import com.kru.kotboot.model.UserCreateRequest import com.kru.kotboot.model.UserDto import junit.framework.Assert.assertEquals import junit.framework.Assert.assertNotNull import org.junit.Before import org.junit.FixMethodOrder import org.junit.Test import org.junit.runners.MethodSorters import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpEntity import org.springframework.http.HttpMethod import org.springframework.http.HttpStatus import java.util.stream.IntStream /** * @author [<NAME>](mailto:<EMAIL>) * * REST Controller Test Cases for User Entity * sequence of test case is important hence MethodSorters.NAME_ASCENDING */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) class UserControllerTest : ControllerTest() { internal lateinit var entity: HttpEntity<String> var responseType: ParameterizedTypeReference<RestResponsePage<UserDto>>? = null @Before fun setUp() { responseType = object : ParameterizedTypeReference<RestResponsePage<UserDto>>(){} } /** * Test POST with valid Request. Then do GET for USER * posts 10 parallel requests to run it quicker * verify Get Call after creating */ @Test fun aVerifyUserPost() { val requestNumbers = 10 IntStream.range(65, requestNumbers).parallel().forEach { x -> val u = UserCreateRequest("FirstName" + x.toChar(), "LastName" + x.toChar(), "email-" + x.toChar() + "@email.com" ) val entity = HttpEntity(u, getHeaders()) val response = post("/api/v1/user", entity, UserDto::class.java!!) assertNotNull(response) assertEquals(HttpStatus.CREATED, response.statusCode) responseType = object : ParameterizedTypeReference<RestResponsePage<UserDto>>() {} val response1 = restTemplate .exchange(createURLWithPort("/api/v1/user?page=0&size=10"), HttpMethod.GET, null, responseType) val users = response1.body!!.content assertNotNull(users) assertEquals(10, users.size) users.stream().parallel().forEach { x -> assertNotNull(x.email) } users.stream().parallel().forEach { x -> assertNotNull(x.firstName) } users.stream().parallel().forEach { x -> assertNotNull(x.lastName) } } } /** * Verify there is no more entities to return in page 100, size 2500 * we loaded and created too few records in H2 in test profile * */ @Test fun cVerifyUserGetForEmptyResponse() { val response = restTemplate .exchange(createURLWithPort("/api/v1/user?page=100&size=2500"), HttpMethod.GET, null, responseType) responseType = object : ParameterizedTypeReference<RestResponsePage<UserDto>>() {} val users = response.body!!.content assertEquals(0, users.size) } }
0
Kotlin
0
4
e848d80e8e477e87d074ed104196ede1d7fb1fee
3,121
kotboot
MIT License
plugins/base/src/main/kotlin/templating/InsertTemplateExtra.kt
Kotlin
21,763,603
false
null
package org.jetbrains.dokka.base.templating import org.jetbrains.dokka.model.properties.ExtraProperty import org.jetbrains.dokka.pages.ContentNode data class InsertTemplateExtra(val command: Command) : ExtraProperty<ContentNode> { companion object : ExtraProperty.Key<ContentNode, InsertTemplateExtra> override val key: ExtraProperty.Key<ContentNode, *> get() = Companion }
421
null
388
3,010
97bccc0e12fdc8c3bd6d178e17fdfb57c3514489
393
dokka
Apache License 2.0
mybatis-plus-join-test/test-kotlin/src/main/kotlin/com/github/yulichang/test/kt/dto/AreaDTO.kt
yulichang
333,340,595
false
{"Java": 820747, "Kotlin": 63365}
package com.github.leheyue.test.kt.dto @Suppress("unused") class AreaDTO { private val id: Int? = null private val province: String? = null private val city: String? = null private val area: String? = null private val postcode: String? = null private val del: Boolean? = null }
56
Java
92
721
91c67c5e8251420bb031e178f363089737449179
304
mybatis-plus-join
Apache License 2.0
app-kotlin/src/main/java/ly/count/android/demo/kotlin/MainActivity.kt
Countly
4,487,574
false
{"Java": 1633920, "C": 183613, "Kotlin": 8706, "Groovy": 6779, "C++": 5542, "CMake": 1590, "Shell": 641, "Makefile": 465}
package ly.count.android.demo.kotlin import android.content.res.Configuration import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupActionBarWithNavController import ly.count.android.demo.kotlin.databinding.ActivityMainBinding import ly.count.android.sdk.Countly import ly.count.android.sdk.CountlyConfig class MainActivity : AppCompatActivity() { private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val navHostFragment = supportFragmentManager .findFragmentById(R.id.nav_host_fragment) as NavHostFragment navController = navHostFragment.navController setupActionBarWithNavController(navController) } override fun onSupportNavigateUp(): Boolean { return navController.navigateUp() || super.onSupportNavigateUp() } override fun onStart() { super.onStart() Countly.sharedInstance().onStart(this) } override fun onStop() { Countly.sharedInstance().onStop() super.onStop() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) Countly.sharedInstance().onConfigurationChanged(newConfig) } }
9
Java
297
679
e6944d30a06755e1eb7fd86756942f588b5f2de3
1,448
countly-sdk-android
MIT License
common/src/main/java/com/ruzhan/lion/network/CommonHttpClient.kt
ckrgithub
150,102,569
false
null
package com.ruzhan.lion.network import okhttp3.OkHttpClient /** * Created by ruzhan123 on 2018/7/24. */ class CommonHttpClient private constructor() { private val okHttpClient: OkHttpClient = OkHttpClient.Builder().build() companion object { private var httpClient: CommonHttpClient? = null fun get(): CommonHttpClient { if (httpClient == null) { synchronized(CommonHttpClient::class.java) { if (httpClient == null) { httpClient = CommonHttpClient() } } } return this.httpClient!! } @JvmStatic fun getCommonHttpClient(): OkHttpClient = get().okHttpClient } }
1
null
1
1
e73bcaf999e3de04905e781004f02ede6d85eaea
752
Lion
Apache License 2.0
app/src/main/java/com/github/vase4kin/teamcityapp/buildlist/filter/BuildListFilter.kt
vase4kin
68,111,887
false
null
/* * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.buildlist.filter import java.io.Serializable /** * Filter for build list */ interface BuildListFilter : Serializable { /** * Set filter type * * @param filter - filter to set */ fun setFilter(filter: Int) /** * Set branch * * @param branch - branch to filter with */ fun setBranch(branch: String) /** * Filter personal * * @param isPersonal - flag */ fun setPersonal(isPersonal: Boolean) /** * Filter pinned * * @param isPinned - flag */ fun setPinned(isPinned: Boolean) /** * @return {String} as param locator */ fun toLocator(): String companion object { /** * Default build list filter */ const val DEFAULT_FILTER_LOCATOR = "state:any,branch:default:any,personal:any,pinned:any,canceled:any,failedToStart:any,count:10" } }
0
null
11
52
9abb1ed56c127d64679124c38d30b0014ec024de
1,551
TeamCityApp
Apache License 2.0
idea/idea-frontend-fir/src/org/jetbrains/kotlin/idea/frontend/api/fir/utils/firUtils.kt
nskvortsov
4,137,859
true
{"Kotlin": 54887563, "Java": 7682828, "JavaScript": 185344, "HTML": 79768, "Lex": 23805, "TypeScript": 21756, "Groovy": 11196, "Swift": 9789, "CSS": 9270, "Shell": 7220, "Batchfile": 5727, "Ruby": 2655, "Objective-C": 444, "Scala": 80, "C": 59}
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.frontend.api.fir.utils import org.jetbrains.kotlin.fir.FirSymbolOwner import org.jetbrains.kotlin.fir.declarations.FirDeclaration import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol internal inline val FirDeclaration.overriddenDeclaration: FirDeclaration? get() { val symbol = (this as? FirSymbolOwner<*>)?.symbol ?: return null return (symbol as? FirCallableSymbol)?.overriddenSymbol?.fir as? FirDeclaration }
1
Kotlin
0
3
39d15501abb06f18026bbcabfd78ae4fbcbbe2cb
690
kotlin
Apache License 2.0
researchsuiteextensions-predicate/src/main/java/org/researchsuite/researchsuiteextensions/predicate/RSExpression.kt
ResearchSuite
141,743,701
false
{"Gradle": 9, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "Proguard": 4, "Kotlin": 36, "XML": 17, "INI": 2, "Java": 6}
package org.researchsuite.researchsuiteextensions.predicate import com.google.common.base.Optional import java.util.* abstract class RSExpression { //TODO: possibly change substituions map to Map<String, Optional<Any>> @Throws(RSExpressionParserError::class) abstract fun evaluate(substitutions: Map<String, Optional<Any>>, context: Any?): Any? @Throws(RSExpressionParserError::class) fun equals(other: RSExpression, substitutions: Map<String, Optional<Any>>, context: Any?): Boolean { val value = this.evaluate(substitutions, context) val otherValue = other.evaluate(substitutions, context) //note that this is equivalent to value?.equals(otherValue) return value == otherValue } @Throws(RSExpressionParserError::class) fun greaterThan(other: RSExpression, substitutions: Map<String, Optional<Any>>, context: Any?): Boolean { val value = this.evaluate(substitutions, context) val otherValue = other.evaluate(substitutions, context) when(value) { is String -> { if (otherValue is String) { return value > otherValue } else { throw RSExpressionParserError.evaluationError("incompatible types") } } is Int -> { if (otherValue is Int) { return value > otherValue } else { throw RSExpressionParserError.evaluationError("incompatible types") } } is Date -> { if (otherValue is Date) { return value > otherValue } else { throw RSExpressionParserError.evaluationError("incompatible types") } } else -> { throw RSExpressionParserError.evaluationError("incompatible types") } } } }
1
null
1
1
8a1c707c8b8787a41178d73d498f006995809d04
2,019
ResearchSuiteExtensions-Android
Apache License 2.0
azura-server/src/main/java/com/server/service/login/ServiceManager.kt
oz420
520,552,743
false
{"Java": 8539102, "Kotlin": 35337}
package com.server.service.login /** * Manages all [Service] implementations used by the game. * * @author <NAME> */ object ServiceManager { /** * [Service] for handling login requests. */ val loginService = LoginService() /** * Executes at the startup of the game, before any of the game assets are loaded. * Invokes [Service.init] for all [services][Service] contained within scope. */ fun init(){ loginService.init() } }
1
null
1
1
0e6428591561ff029681d4721f00d6a7eb81f182
483
refer-ps
Apache License 2.0
location/src/main/java/com/github/kacso/androidcommons/location/LocationProvider.kt
kacso
204,923,341
false
{"Gradle": 16, "Java Properties": 2, "Shell": 1, "Text": 4, "Ignore List": 13, "Batchfile": 1, "Markdown": 616, "Kotlin": 181, "XML": 69, "INI": 8, "Proguard": 9, "Java": 1}
package com.github.kacso.androidcommons.location import android.Manifest import android.content.Context import android.location.Location import android.os.Looper import androidx.annotation.RequiresPermission import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.github.kacso.androidcommons.data.ErrorHolder import com.github.kacso.androidcommons.data.Resource import com.github.kacso.androidcommons.location.exceptions.LocationDisabledException import com.google.android.gms.location.* import java.util.concurrent.atomic.AtomicBoolean /** * Use this class to retrieve real-time location updates. * Location updates are emitted through [LiveData] inside [Resource] model. * This class makes sure that location updates are generated only when there are active observers. * * @param context App active context * @param locationRequest A data object that contains quality of service parameters for location updates. */ class LocationProvider( context: Context, private val locationRequest: LocationRequest = LocationRequest.create() ) { private val provider = FusedLocationProviderClient(context) private val locationLd: MutableLiveData<Resource<Location>> = object : MutableLiveData<Resource<Location>>() { private var started = AtomicBoolean(false) override fun onActive() { super.onActive() if (started.compareAndSet(false, true)) { provider.requestLocationUpdates( locationRequest, locationCallback, Looper.getMainLooper() ) } } override fun onInactive() { super.onInactive() if (started.compareAndSet(true, false)) { provider.removeLocationUpdates(locationCallback) } } } private val locationCallback = object : LocationCallback() { override fun onLocationResult(res: LocationResult?) { res?.lastLocation?.let { locationLd.postValue(Resource.Success(it)) } } override fun onLocationAvailability(availability: LocationAvailability?) { if (availability?.isLocationAvailable == false) { locationLd.postValue( Resource.Error( ErrorHolder( message = "Location not available. Action required by user to obtain location again.", cause = LocationDisabledException() ) ) ) } } } /** * Retrieve [LiveData] object on which [Location] or [ErrorHolder] will be emitted * * @return [LiveData] on which [Location] will be emitted */ @RequiresPermission(allOf = [Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION]) fun getLocation(): LiveData<Resource<Location>> { return locationLd } }
0
Kotlin
1
5
9620f80428f4b00a8b683f4e94294e9e64c85b99
3,017
android-commons
Apache License 2.0
compose/ui/ui/src/desktopTest/kotlin/androidx/compose/ui/TestUtils.kt
serandel
508,553,581
true
{"Java Properties": 44, "Shell": 84, "INI": 26, "Text": 7154, "Gradle": 663, "TOML": 2, "Markdown": 124, "Ignore List": 36, "Java": 5986, "XML": 16622, "HTML": 18, "Kotlin": 7367, "Python": 29, "JSON": 64, "Proguard": 54, "Protocol Buffer": 51, "Batchfile": 14, "JavaScript": 3, "CMake": 8, "C++": 30, "SVG": 5, "YAML": 11, "Gradle Kotlin DSL": 6, "CSS": 2, "OpenStep Property List": 1, "Swift": 2, "Ant Build System": 5, "C": 5, "AIDL": 191, "ANTLR": 1, "Protocol Buffer Text Format": 54, "Objective-C++": 1, "JSON with Comments": 1, "HAProxy": 1, "desktop": 1, "Linker Script": 1}
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.Paint import androidx.compose.ui.graphics.painter.BitmapPainter import androidx.compose.ui.graphics.painter.Painter import java.awt.AWTEvent import java.awt.Component import java.awt.EventQueue import java.awt.Image import java.awt.Toolkit import java.awt.Window import java.awt.event.InvocationEvent import java.awt.event.KeyEvent import java.awt.event.MouseEvent import java.awt.event.MouseWheelEvent import java.awt.image.BufferedImage import java.awt.image.MultiResolutionImage import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.util.Objects import java.util.concurrent.atomic.AtomicReference import javax.swing.Icon import javax.swing.ImageIcon import javax.swing.JFrame import javax.swing.SwingUtilities import kotlin.coroutines.resume import kotlinx.coroutines.runBlocking import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.yield import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.TestOnly import org.jetbrains.skiko.MainUIDispatcher fun testImage(color: Color): Painter = run { val bitmap = ImageBitmap(100, 100) val paint = Paint().apply { this.color = color } Canvas(bitmap).drawRect(0f, 0f, 100f, 100f, paint) BitmapPainter(bitmap) } fun Image.readFirstPixel(): Color { val image = (this as MultiResolutionImage).getResolutionVariant(1.0, 1.0) as BufferedImage return Color(image.getRGB(0, 0)) } fun Icon.readFirstPixel() = (this as ImageIcon).image.readFirstPixel() private val os = System.getProperty("os.name").lowercase() internal val isLinux = os.startsWith("linux") internal val isWindows = os.startsWith("win") internal val isMacOs = os.startsWith("mac") fun Window.sendKeyEvent( code: Int, modifiers: Int = 0 ): Boolean { val event = KeyEvent( // if we would just use `focusOwner` then it will be null if the window is minimized mostRecentFocusOwner, KeyEvent.KEY_PRESSED, 0, modifiers, code, code.toChar(), KeyEvent.KEY_LOCATION_STANDARD ) dispatchEvent(event) return event.isConsumed } fun JFrame.sendMouseEvent( id: Int, x: Int, y: Int, modifiers: Int = 0 ): Boolean { // we use width and height instead of x and y because we can send (-1, -1), but still need // the component inside window val component = findComponentAt(width / 2, height / 2) val event = MouseEvent( component, id, 0, modifiers, x, y, 1, false ) component.dispatchEvent(event) return event.isConsumed } fun JFrame.sendMouseWheelEvent( x: Int, y: Int, scrollType: Int = MouseWheelEvent.WHEEL_UNIT_SCROLL, wheelRotation: Double = 0.0, modifiers: Int = 0, ): Boolean { // we use width and height instead of x and y because we can send (-1, -1), but still need // the component inside window val component = findComponentAt(width / 2, height / 2) val event = MouseWheelEvent( component, MouseWheelEvent.MOUSE_WHEEL, 0, modifiers, x, y, x, y, 1, false, scrollType, 1, wheelRotation.toInt(), wheelRotation ) component.dispatchEvent(event) return event.isConsumed } private val EventComponent = object : Component() {} internal fun awtWheelEvent(isScrollByPages: Boolean = false) = MouseWheelEvent( EventComponent, MouseWheelEvent.MOUSE_WHEEL, 0, 0, 0, 0, 0, false, if (isScrollByPages) { MouseWheelEvent.WHEEL_BLOCK_SCROLL } else { MouseWheelEvent.WHEEL_UNIT_SCROLL }, 1, 0 ) fun Component.performClick() { dispatchEvent(MouseEvent(this, MouseEvent.MOUSE_PRESSED, 0, 0,1, 1, 1, false, MouseEvent.BUTTON1)) dispatchEvent(MouseEvent(this, MouseEvent.MOUSE_RELEASED, 0, 0,1, 1, 1, false, MouseEvent.BUTTON1)) } // TODO(demin): It seems this not-so-good synchronization // doesn't cause flakiness in our window tests. // But more robust solution will be to using something like UiUtil /** * Wait until all scheduled tasks in Event Dispatch Thread are performed. * New scheduled tasks in these tasks also will be performed */ suspend fun awaitEDT() { // Most of the work usually is done after the first yield(), almost all of the work - // after fourth yield() repeat(100) { yield() } }
0
null
0
0
7d85ae1bf8b109f7c751af7120b225e397702df4
5,273
androidx
Apache License 2.0
shared/src/commonMain/kotlin/me/eduardo/shared/network/responses/prevision/WeatherPrevisionResponse.kt
eduardocodigo0
373,240,286
false
null
package me.eduardo.shared.network.responses.prevision import kotlinx.serialization.Contextual import kotlinx.serialization.Serializable @Serializable data class WeatherPrevisionResponse( @Contextual val daily: List<@Contextual Daily>, val lat: Double, val lon: Double, val timezone: String, val timezone_offset: Int )
1
null
1
1
d425af35b42567c6617fa52b4e0c9bf4b35433d7
343
ClimaAPP
Apache License 2.0
idea/testData/addImport/DropExplicitImports2.dependency.kt
JakeWharton
99,388,807
true
null
package dependency fun function(){} val property: Int = 0 class Class1 class Class2
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
84
kotlin
Apache License 2.0
analysis/low-level-api-fir/testData/partialRawBuilder/simpleFunction.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// FUNCTION: foo package test fun bar(): Int { return -1 } fun foo(): Int { return 0 }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
97
kotlin
Apache License 2.0
intellij-plugin/educational-core/src/com/jetbrains/edu/learning/command/EduAppStarterBase.kt
JetBrains
43,696,115
false
null
package com.jetbrains.edu.learning.command import com.intellij.openapi.application.ModernApplicationStarter import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.diagnostic.logger import com.jetbrains.edu.learning.Err import com.jetbrains.edu.learning.Ok import com.jetbrains.edu.learning.courseFormat.Course import com.jetbrains.edu.learning.onError import kotlin.system.exitProcess @Suppress("UnstableApiUsage") abstract class EduAppStarterBase<T : Args> : ModernApplicationStarter() { @Suppress("OVERRIDE_DEPRECATION") abstract override val commandName: String override suspend fun start(args: List<String>) { try { val parsedArgs = parseArgs(args) val course = loadCourse(parsedArgs) val result = doMain(course, parsedArgs) if (result is CommandResult.Error) { LOG.error(result.message, result.throwable) } ApplicationManagerEx.getApplicationEx().exit(true, true, result.exitCode) } catch (e: Throwable) { LOG.error(e) exitProcess(1) } } protected abstract fun createArgParser(): ArgParser<T> protected abstract suspend fun doMain(course: Course, args: T): CommandResult private fun parseArgs(args: List<String>): T { val parser = createArgParser() return when (val result = parser.parseArgs(args)) { is Ok -> result.value is Err -> { logErrorAndExit(result.error) } } } private suspend fun loadCourse(args: Args): Course { return args.loadCourse().onError { error -> logErrorAndExit(error) } } companion object { @JvmStatic protected val LOG = logger<EduCourseCreatorAppStarter>() @JvmStatic fun logErrorAndExit(message: String): Nothing { LOG.error(message) exitProcess(1) } @JvmStatic protected fun Course.incompatibleCourseMessage(): String { return buildString { append("""Can't open `${course.name}` course (type="${course.itemType}", language="${course.languageId}", """) if (!course.languageVersion.isNullOrEmpty()) { append("""language version="${course.languageVersion}", """) } append("""environment="${course.environment}") with current IDE setup""") } } } }
7
null
49
150
9cec6c97d896f4485e76cf9a2a95f8a8dd21c982
2,271
educational-plugin
Apache License 2.0
app/src/main/java/com/example/kotlinlearning/ControlFlowAct.kt
happyfsyy
168,460,034
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "XML": 15, "Kotlin": 8, "Java": 1}
package com.example.kotlinlearning import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log /** * 控制流(if表达式,when表达式,for循环,while循环) * 返回和跳转(break,continue,return以及标签处返回) * 参考链接:https://www.kotlincn.net/docs/reference/control-flow.html * https://www.kotlincn.net/docs/reference/returns.html */ class ControlFlowAct:AppCompatActivity(){ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) testIf() testWhen(3) Log.e("hasPrefix",hasPrefix("xx").toString()) testWhen2(10) testFor() testWhile2() testDoWhile() testBreakLabel() testReturnLabel() testReturnLabel2() testReturnLabel3() testReturnLabel4() } fun testIf(){ var a=3 var b=4 var max=a if(a<b) max=b var max2:Int if(a>b){ max2=a }else{ max2=b } var max3=if(a>b) a else b Log.e("testIf","max=$max") Log.e("testIf","max2=$max2") Log.e("testIf","max3=$max3") var max4=if(a>b){ Log.e("testIf","Choose a") a }else{ Log.e("testIf","Choose b") b } Log.e("testIf","max4=$max4") } fun testWhen(x:Int){ when(x){ 1->Log.e("testWhen","x=1") 2->Log.e("testWhen","x=2") else->{ Log.e("testWhen","x is neither 1 nor 2") } } when(x){ 1,2->Log.e("testWhen","x==1 or x==2") else->Log.e("testWhen","otherwise") } var s="1" when(x){ parseInt(s)->Log.e("testWhen","s encodes x") else->Log.e("testWhen","s does not encode x") } when(x){ in 1..10->Log.e("testWhen","x is in the range") !in 10..20->Log.e("testWhen","x is outside the range") else->Log.e("testWhen","none of the above") } } fun parseInt(s:String):Int{ return s.toInt() } fun hasPrefix(x:Any)=when(x){ is String->x.startsWith("prefix") else->false } fun testWhen2(x:Int){ when{ isOdd(x)->Log.e("testWhen2","$x is odd") !isOdd(x)->Log.e("testWhen2","$x is even") else->Log.e("testWhen2","x if funny") } } fun isOdd(x:Int)=x%2==0 fun testFor(){ var collection= arrayOf("1",22,"3") for(item in collection) Log.e("array",item.toString()) val ints:IntArray= intArrayOf(4,5,6) for(item:Int in ints){ Log.e("array",item.toString()) } for(i in 1..3){ Log.e("range",i.toString()) } for(i in 6 downTo 0 step 2){ Log.e("range","$i") } var array= arrayOf("a","b","c") for(i in array.indices){ Log.e("indices",array[i]) } for((index,value)in array.withIndex()){ Log.e("indices","the element at $index is $value") } } /** 原来,函数的参数肯定就是不变的了。。。 * var on fuction parameter is not allowed */ fun testWhile( x:Int){ while(x>0){ Log.e("while","x=$x") //val cannot be reassigned //x-- } } fun testWhile2(){ var x:Int=3 while(x>0){ Log.e("testWhile2",x.toString()) x-- } } fun testDoWhile(){ var num=3; do{ var y:String?="dd" if(num==0){ y=null }else{ Log.e("testDoWhile","num=$num") num-- } }while(y!=null) } fun testBreakLabel(){ loop@ for(i in 1..5){ for(j in 1..5){ Log.e("testBreakLabel","i=$i,j=$j") if(i==1&&j==2){ break@loop } } } } fun testReturnLabel(){ listOf(1,2,3,4,5).forEach { if(it==3) return Log.e("testReturnLabel",it.toString()) } Log.e("testReturnLabel","到不了这里咯") } fun testReturnLabel2(){ listOf(1,2,3,4,5).forEach{ if(it==3) return@forEach Log.e("testReturnLabel2",it.toString()) } Log.e("testReturnLabel2","真能到这里") } fun testReturnLabel3(){ listOf(1,2,3,4,5).forEach(fun(value:Int){ if(value==3) return Log.e("testReturnLabel3",value.toString()) }) Log.e("testReturnLabel3","加了个匿名函数替代lambda表达式") } fun testReturnLabel4(){ run loop@{ listOf(1,2,3,4,5).forEach{ if (it==3) return@loop Log.e("testReturnLabel4",it.toString()) } } Log.e("testReturnLabel4","这种外层嵌套lambda蛮靠谱的") } }
1
null
1
1
23336359e8b2885f7852cc529192e8dae8c1e891
4,973
KotlinLearning
Apache License 2.0
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/hierarchical-mpp-with-js-project-dependency/my-lib-foo/src/main/kotlin/Foo.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package com.example.foo fun foo() = "foo"
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
253
kotlin
Apache License 2.0
compose/foundation/foundation/samples/src/main/java/androidx/compose/foundation/samples/ScrollableSamples.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.samples import androidx.annotation.Sampled import androidx.compose.foundation.background import androidx.compose.foundation.gestures.rememberScrollableState import androidx.compose.foundation.gestures.scrollable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.preferredSize import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.gesture.scrollorientationlocking.Orientation import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlin.math.roundToInt @Sampled @Composable fun ScrollableSample() { // actual composable state that we will show on UI and update in `Scrollable` val offset = remember { mutableStateOf(0f) } Box( Modifier .preferredSize(150.dp) .scrollable( orientation = Orientation.Vertical, // state for Scrollable, describes how consume scroll amount state = rememberScrollableState { delta -> offset.value = offset.value + delta // update the state delta // indicate that we consumed all the pixels available } ) .background(Color.LightGray), contentAlignment = Alignment.Center ) { Text(offset.value.roundToInt().toString(), style = TextStyle(fontSize = 32.sp)) } }
0
null
0
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
2,295
androidx
Apache License 2.0
app/src/test/java/dev/suhockii/lifetest/ui/products/ProductsPresenterTest.kt
suhocki
109,488,457
false
{"Gradle": 3, "INI": 1, "Java Properties": 3, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 53, "XML": 18, "Java": 1}
package dev.suhockii.lifetest.ui.products import android.content.res.Resources import dev.suhockii.lifetest.model.Product import dev.suhockii.lifetest.repo.AppRepository import dev.suhockii.lifetest.repo.LocalRepository import dev.suhockii.lifetest.repo.RemoteRepository import dev.suhockii.lifetest.util.rx_transformers.RxSchedulers import io.reactivex.Single import io.reactivex.SingleTransformer import org.junit.Before import org.junit.Test import org.mockito.ArgumentMatchers.any import org.mockito.ArgumentMatchers.eq import org.mockito.Mockito.* import java.util.* class ProductsPresenterTest { private var productsView: ProductsView? = null private var productsPresenter: ProductsPresenter? = null private var localRepository: AppRepository? = null private var remoteRepository: AppRepository? = null private var rxSchedulers: RxSchedulers? = null @Before @Throws(Exception::class) fun setUp() { productsView = mock(ProductsView::class.java) rxSchedulers = mock(RxSchedulers::class.java) localRepository = mock(LocalRepository::class.java) remoteRepository = mock(RemoteRepository::class.java) productsPresenter = ProductsPresenter(localRepository!!, remoteRepository!!, rxSchedulers!!) } @Test fun onFirstViewAttachLoadLocal() { val products = ArrayList<Product>() `when`(rxSchedulers!!.getIoToMainTransformerSingle<Any>()).thenReturn(SingleTransformer { upstream -> upstream }) `when`(localRepository!!.getProducts()).thenReturn(Single.just(products)) productsPresenter!!.attachView(productsView) verify<AppRepository>(localRepository, times(1)).getProducts() verify<ProductsView>(productsView, times(1)).clearShowSnackbarCommand() verify<ProductsView>(productsView, times(1)).showProducts(products) } @Test @Throws(Exception::class) fun onFirstViewAttachLoadRemote_NetworkConnected() { val products = ArrayList<Product>() `when`(rxSchedulers!!.getIoToMainTransformerSingle<Any>()).thenReturn(SingleTransformer { upstream -> upstream }) `when`(localRepository!!.getProducts()).thenReturn(Single.error(Exception())) `when`(remoteRepository!!.getProducts()).thenReturn(Single.just(products)) productsPresenter!!.attachView(productsView) verify<AppRepository>(localRepository, times(1)).getProducts() verify<AppRepository>(remoteRepository, times(1)).getProducts() verify<ProductsView>(productsView, times(1)).clearShowSnackbarCommand() verify<ProductsView>(productsView, times(1)).showProducts(products) } @Test @Throws(Exception::class) fun onFirstViewAttachLoadRemote_NetworkDisconnected() { val message = "Error message." `when`(rxSchedulers!!.getIoToMainTransformerSingle<Any>()).thenReturn(SingleTransformer { upstream -> upstream }) `when`(localRepository!!.getProducts()).thenReturn(Single.error(Resources.NotFoundException())) `when`(remoteRepository!!.getProducts()).thenReturn(Single.error(Exception(message))) productsPresenter!!.attachView(productsView) verify<AppRepository>(localRepository, times(1)).getProducts() verify<AppRepository>(remoteRepository, times(1)).getProducts() verify<ProductsView>(productsView, times(1)).showSnackbar(eq(message), any<Runnable>()) } }
1
null
1
1
0ae8fd92a7133f22edb02d662794c28f1e95d522
3,418
LifeTech-Test
The Unlicense
repo/gradle-settings-conventions/internal-gradle-setup/src/main/kotlin/LocalPropertiesModifier.kt
JetBrains
3,432,266
false
{"Kotlin": 79248651, "Java": 6821839, "Swift": 4063506, "C": 2609288, "C++": 1969323, "Objective-C++": 171723, "JavaScript": 138329, "Python": 59488, "Shell": 32251, "TypeScript": 22800, "Objective-C": 22132, "Lex": 21352, "Groovy": 17400, "Batchfile": 11695, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9857, "EJS": 5241, "HTML": 4877, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.build import java.io.File import java.io.StringReader import java.util.Properties private const val SYNCED_PROPERTIES_START_LINE = "# Automatically configured by the `internal-gradle-setup` plugin" internal val SYNCED_PROPERTIES_START_LINES = """ $SYNCED_PROPERTIES_START_LINE # Please do not edit these properties manually, the changes will be lost # If you want to override some values, put them before this section and remove from this section """.trimIndent() internal const val SYNCED_PROPERTIES_END_LINE = "# the end of automatically configured properties" internal class LocalPropertiesModifier(private val localProperties: File) { private val initialUserConfiguredPropertiesContent = getUserConfiguredPropertiesContent() private fun getUserConfiguredPropertiesContent(): String { if (!localProperties.exists()) return "" var insideAutomaticallyConfiguredSection = false // filter out the automatically configured lines return localProperties.readLines().filter { line -> if (line == SYNCED_PROPERTIES_START_LINE) { insideAutomaticallyConfiguredSection = true } val shouldIncludeThisLine = !insideAutomaticallyConfiguredSection if (line == SYNCED_PROPERTIES_END_LINE) { insideAutomaticallyConfiguredSection = false } shouldIncludeThisLine }.joinToString("\n") } fun applySetup(setupFile: SetupFile) { localProperties.parentFile.apply { if (!exists()) { mkdirs() } } if (localProperties.exists() && !localProperties.isFile) { error("$localProperties is not a file!") } val content = getUserConfiguredPropertiesContent() val manuallyConfiguredProperties = Properties().apply { StringReader(content).use { load(it) } } val propertiesToSetup = setupFile.properties.mapValues { val overridingValue = manuallyConfiguredProperties[it.key] if (overridingValue != null) { PropertyValue.Overridden(it.value, overridingValue.toString()) } else { PropertyValue.Configured(it.value) } } localProperties.writeText( """ |${content.addSuffix("\n")} |$SYNCED_PROPERTIES_START_LINES |${propertiesToSetup.asPropertiesLines} |$SYNCED_PROPERTIES_END_LINE | """.trimMargin() ) } fun initiallyContains(line: String) = initialUserConfiguredPropertiesContent.contains(line) fun putLine(line: String) = localProperties.appendText("\n$line") } private fun String.addSuffix(suffix: String): String { if (this.endsWith(suffix)) return this return "$this$suffix" } internal sealed class PropertyValue( val value: String, ) { class Configured(value: String) : PropertyValue(value) class Overridden(value: String, val overridingValue: String) : PropertyValue(value) } internal val Map<String, PropertyValue>.asPropertiesLines: String get() = map { (key, valueWrapper) -> when (valueWrapper) { is PropertyValue.Overridden -> "#$key=${valueWrapper.value} the property is overridden by '${valueWrapper.overridingValue}'" is PropertyValue.Configured -> "$key=${valueWrapper.value}" } }.joinToString("\n")
182
Kotlin
5646
48,182
bc1ddd8205f6107c7aec87a9fb3bd7713e68902d
3,723
kotlin
Apache License 2.0
src/test/kotlin/io/github/intellij/dlanguage/quickfix/SwitchToNewAliasSyntaxTest.kt
intellij-dlanguage
27,922,930
false
null
package io.github.intellij.dlanguage.quickfix import io.github.intellij.dlanguage.inspections.OldAliasSyntax class SwitchToNewAliasSyntaxTest : DQuickFixTestBase() { override fun setUp() { super.setUp() enableInspectionTools(OldAliasSyntax()) } fun test() { doSingleTest("SwitchToNewAlias.d") } }
135
Java
46
293
f2f172e625c9ffe8db967d078644763cae59dc4f
341
intellij-dlanguage
MIT License
lib/src/main/kotlin/com/lemonappdev/konsist/api/provider/KoAnnotationProvider.kt
LemonAppDev
621,181,534
false
{"Kotlin": 5054558, "Python": 46133}
package com.lemonappdev.konsist.api.provider import com.lemonappdev.konsist.api.declaration.KoAnnotationDeclaration import kotlin.reflect.KClass /** * An interface representing a Kotlin declaration that provides an annotations. */ interface KoAnnotationProvider : KoBaseProvider { /** * List of annotations. */ val annotations: List<KoAnnotationDeclaration> /** * The number of annotations. */ val numAnnotations: Int /** * Returns the number of annotations that satisfies the specified predicate present in the declaration. * * @param predicate The predicate function to determine if an annotation satisfies a condition. * @return The number of annotations in the declaration. */ fun countAnnotations(predicate: (KoAnnotationDeclaration) -> Boolean): Int /** * Determines whatever declaration has any annotation. * * @return `true` if the declaration has any annotation, `false` otherwise. */ fun hasAnnotations(): Boolean /** * Determines whether the declaration has at least one annotation whose name matches any of the specified names. * * @param name the name of the annotations to check. It can be either a simple name or a fully qualified name. * @param names the names of the annotations to check. It can be either a simple name or a fully qualified name. * @return `true` if there is a matching declaration, `false` otherwise. */ fun hasAnnotationWithName( name: String, vararg names: String, ): Boolean /** * Determines whether the declaration has at least one annotation whose name matches any of the specified names. * * @param names the names of the annotations to check. It can be either a simple name or a fully qualified name. * @return `true` if there is a matching declaration, `false` otherwise. */ fun hasAnnotationWithName(names: Collection<String>): Boolean /** * Determines whether the declaration has annotations with all the specified names. * * @param name the name of the annotations to check. It can be either a simple name or a fully qualified name. * @param names The names of the annotations to check. It can be either a simple name or a fully qualified name. * @return `true` if there are declarations with all the specified names, `false` otherwise. */ fun hasAnnotationsWithAllNames( name: String, vararg names: String, ): Boolean /** * Determines whether the declaration has annotations with all the specified names. * * @param names The names of the annotations to check. It can be either a simple name or a fully qualified name. * @return `true` if there are declarations with all the specified names, `false` otherwise. */ fun hasAnnotationsWithAllNames(names: Collection<String>): Boolean /** * Determines whether the declaration has at least one annotation that satisfies the provided predicate. * * @param predicate A function that defines the condition to be met by an annotation declaration. * @return `true` if there is a matching declaration, `false` otherwise. */ fun hasAnnotation(predicate: (KoAnnotationDeclaration) -> Boolean): Boolean /** * Determines whether the declaration has all annotations that satisfy the provided predicate. * * Note that if the annotations contains no elements, the function returns `true` because there are no elements in it * that do not match the predicate. * * @param predicate A function that defines the condition to be met by annotation declarations. * @return `true` if all annotation declarations satisfy the predicate, `false` otherwise. */ fun hasAllAnnotations(predicate: (KoAnnotationDeclaration) -> Boolean): Boolean /** * Determines whether the declaration has at least one annotation of the specified `KClass` type. * * @param name the `KClass` type of the annotation to check. * @param names the `KClass` types of the annotations to check. * @return `true` if there is a matching declaration, `false` otherwise. */ fun hasAnnotationOf( name: KClass<*>, vararg names: KClass<*>, ): Boolean /** * Determines whether the declaration has at least one annotation of the specified `KClass` type. * * @param names the `KClass` types of the annotations to check. * @return `true` if there is a matching declaration, `false` otherwise. */ fun hasAnnotationOf(names: Collection<KClass<*>>): Boolean /** * Determines whether the declaration has annotations with all the specified `KClass` type. * * @param name the `KClass` type of the annotation to check. * @param names the `KClass` types of the annotations to check. * @return `true` if the declaration has annotations of all the specified `KClass` types, `false` otherwise. */ fun hasAllAnnotationsOf( name: KClass<*>, vararg names: KClass<*>, ): Boolean /** * Determines whether the declaration has annotations with all the specified `KClass` type. * * @param names the `KClass` types of the annotations to check. * @return `true` if the declaration has annotations of all the specified `KClass` types, `false` otherwise. */ fun hasAllAnnotationsOf(names: Collection<KClass<*>>): Boolean }
6
Kotlin
27
1,141
696b67799655e2154447ab45f748e983d8bcc1b5
5,487
konsist
Apache License 2.0
security-crypto-datastore-preferences/src/main/kotlin/EncryptedPreferencesDataStoreDelegate.kt
osipxd
416,317,697
false
{"Kotlin": 45089, "Java": 911}
package io.github.osipxd.security.crypto import android.content.Context import androidx.annotation.GuardedBy import androidx.datastore.core.DataMigration import androidx.datastore.core.DataStore import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStoreFile import androidx.security.crypto.EncryptedFile import androidx.security.crypto.EncryptedFile.FileEncryptionScheme import androidx.security.crypto.MasterKeys import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty /** * Creates a property delegate for a single process DataStore with encryption. This should only * be called once in a file (at the top level), and all usages of the DataStore should use * a reference the same Instance. The receiver type for the property delegate must be an instance * of [Context]. * * This should only be used from a single application in a single classloader in a single process. * * Example usage: * ``` * val Context.settingsDataStore by encryptedPreferencesDataStore(name = "settings") * * class SomeClass(val context: Context) { * suspend fun update() = context.settingsDataStore.edit {...} * } * ``` * * @param name The name of the preferences. The preferences will be stored in a file in the * "datastore/" subdirectory in the application context's files directory and is generated using * [preferencesDataStoreFile]. * @param corruptionHandler The corruptionHandler is invoked if DataStore encounters a * [androidx.datastore.core.CorruptionException] when attempting to read data. CorruptionExceptions * are thrown by serializers when data can not be de-serialized. * @param produceMigrations produce the migrations. The ApplicationContext is passed in to these * callbacks as a parameter. DataMigrations are run before any access to data can occur. Each * producer and migration may be run more than once whether or not it already succeeded * (potentially because another migration failed or a write to disk failed.) * @param scope The scope in which IO operations and transform functions will execute. * @param masterKey The master key to use, defaults to `AES256-GCM` key with default alias * [MasterKeys.MASTER_KEY_ALIAS]. * @param fileEncryptionScheme The [FileEncryptionScheme] to use, defaulting to * [FileEncryptionScheme.AES256_GCM_HKDF_4KB]. * @param encryptionOptions Additional encryption options. * * @return a property delegate that manages a datastore as a singleton. * * @see PreferenceDataStoreFactory.createEncrypted * @see EncryptedFile */ public fun encryptedPreferencesDataStore( name: String, corruptionHandler: ReplaceFileCorruptionHandler<Preferences>? = null, produceMigrations: (Context) -> List<DataMigration<Preferences>> = { emptyList() }, scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()), masterKey: String = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC), fileEncryptionScheme: FileEncryptionScheme = FileEncryptionScheme.AES256_GCM_HKDF_4KB, encryptionOptions: EncryptedDataStoreOptions.() -> Unit = {}, ): ReadOnlyProperty<Context, DataStore<Preferences>> { return EncryptedPreferenceDataStoreSingletonDelegate( name = name, corruptionHandler = corruptionHandler, produceMigrations = produceMigrations, scope = scope, masterKey = masterKey, fileEncryptionScheme = fileEncryptionScheme, encryptionOptions = encryptionOptions, ) } /** * Delegate class to manage Preferences DataStore as a singleton. * Copied from [androidx.datastore.preferences.PreferenceDataStoreSingletonDelegate] */ internal class EncryptedPreferenceDataStoreSingletonDelegate internal constructor( private val name: String, private val corruptionHandler: ReplaceFileCorruptionHandler<Preferences>?, private val produceMigrations: (Context) -> List<DataMigration<Preferences>>, private val scope: CoroutineScope, private val masterKey: String, private val fileEncryptionScheme: FileEncryptionScheme, private val encryptionOptions: EncryptedDataStoreOptions.() -> Unit ) : ReadOnlyProperty<Context, DataStore<Preferences>> { private val lock = Any() @GuardedBy("lock") @Volatile private var INSTANCE: DataStore<Preferences>? = null /** * Gets the instance of the DataStore. * * @param thisRef must be an instance of [Context] * @param property not used */ override fun getValue(thisRef: Context, property: KProperty<*>): DataStore<Preferences> { return INSTANCE ?: synchronized(lock) { if (INSTANCE == null) { val applicationContext = thisRef.applicationContext INSTANCE = PreferenceDataStoreFactory.createEncrypted( corruptionHandler = corruptionHandler, migrations = produceMigrations(applicationContext), scope = scope, encryptionOptions = encryptionOptions, ) { EncryptedFile.Builder( applicationContext.preferencesDataStoreFile(name), applicationContext, masterKey, fileEncryptionScheme, ).build() } } INSTANCE!! } } }
11
Kotlin
11
151
73a9898f64b7bcf3b8420982c796f0066d28206a
5,638
encrypted-datastore
MIT License
game/src/main/kotlin/org/rsmod/game/model/client/PlayerEntity.kt
rsmod
293,875,986
false
{"Kotlin": 812861}
package org.rsmod.game.model.client public class PlayerEntity : MobEntity(size = 1) { public var name: String = "" public companion object { public val ZERO: PlayerEntity = PlayerEntity() } }
2
Kotlin
63
79
e1e1a85d7a4d1840ca0738e3401d18ee40424860
216
rsmod
ISC License
kotlin/src/main/kotlin/com/laioffer/Kotlin基础/pkg15_对象表达式/HiKotlin4.kt
yuanuscfighton
632,030,844
false
{"Kotlin": 1007874, "Java": 774893}
package Kotlin基础.pkg15_对象表达式 class MyClass2 { private fun method1() = object { val str = "hello" } internal fun method2() = object { val str = "world" } fun test() { val s = method1().str // val s1 = method2().str // error ❌ } }
0
Kotlin
0
0
b4091c1374f5f0dc0eb8387f7d09ce00eeaacc9d
260
SiberianHusky
Apache License 2.0
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/pojo/apiv2/embed/StreamableFile.kt
feelfreelinux
97,154,881
false
null
package io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.embed import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty @JsonIgnoreProperties(ignoreUnknown = true) data class StreamableFile( @JsonProperty("url") val url: String )
47
Kotlin
51
166
ec6365b9570818a7ee00c5b512f01cedead30867
298
WykopMobilny
MIT License
telegram/src/main/kotlin/com/github/kotlintelegrambot/entities/files/PhotoSize.kt
kotlin-telegram-bot
121,235,631
false
{"Kotlin": 618749}
package com.github.kotlintelegrambot.entities.files import com.google.gson.annotations.SerializedName /** * Represents one size of a photo or a file / sticker thumbnail. * https://core.telegram.org/bots/api#photosize */ data class PhotoSize( @SerializedName(FilesFields.fileId) val fileId: String, @SerializedName(FilesFields.fileUniqueId) val fileUniqueId: String, @SerializedName(FilesFields.width) val width: Int, @SerializedName(FilesFields.height) val height: Int, @SerializedName(FilesFields.fileSize) val fileSize: Int? = null, )
67
Kotlin
161
794
18013912c6a8c395b6491c2323a8f5eb7288b4f5
562
kotlin-telegram-bot
Apache License 2.0
producer_kotlin_ftw/src/test/resources/contracts/fraudname/shouldReturnNonFraudForTheName.kts
spring-cloud-samples
73,282,380
false
{"Java": 629880, "Groovy": 90627, "Kotlin": 79442, "Shell": 66350, "JavaScript": 17226, "HTML": 4057}
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fraudname import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract contract { request { method = PUT url = url("/frauds/name") body = body("name" to value(anyAlphaUnicode)) headers { contentType = "application/json" } } response { status = OK body = body("result" to "Don't worry ${fromRequest().body("$.name")} you're not a fraud") headers { contentType = fromRequest().header(CONTENT_TYPE) } } }
30
Java
311
381
2ed2bb0fea6e749eda762c08e5f951619968d724
1,080
spring-cloud-contract-samples
Apache License 2.0
sharding/src/main/kotlin/io/kommons/designpatterns/sharding/managers/ShardManager.kt
debop
235,066,649
false
null
package io.kommons.designpatterns.sharding.managers import io.kommons.designpatterns.sharding.Data import io.kommons.designpatterns.sharding.Shard import io.kommons.logging.KLogging abstract class ShardManager { companion object: KLogging() protected val shardMap = LinkedHashMap<Int, Shard>() /** * Add a provided shard instance to shardMap. * * @param shard new shard instance. * @return {@code true} if succeed to add the new instance. * {@code false} if the shardId is already existed. */ fun addNewShard(shard: Shard): Boolean { val shardId = shard.id return if (!shardMap.containsKey(shardId)) { shardMap[shardId] = shard true } else { false } } /** * Remove a shard instance by provided Id. * * @param shardId Id of shard instance to remove. * @return {@code true} if removed. {@code false} if the shardId is not existed. */ fun removeShardById(shardId: Int): Boolean { return if (shardMap.containsKey(shardId)) { shardMap.remove(shardId) != null } else { false } } fun getShardById(shardId: Int): Shard? = shardMap[shardId] fun clearShard() { shardMap.clear() } /** * Store data in proper shard instance. * * @param data new data * @return id of shard that the data is stored in */ abstract fun storeData(data: Data): Int /** * Allocate proper shard to provided data. * * @param data new data * @return id of shard that the data should be stored */ protected abstract fun allocateShard(data: Data): Int }
0
Kotlin
11
53
c00bcc0542985bbcfc4652d0045f31e5c1304a70
1,711
kotlin-design-patterns
Apache License 2.0
Dermateapps/app/src/main/java/com/example/dermate/ui/welcomeslider/pagefragment/SecondPageFragment.kt
wahyutirta
368,202,149
false
{"Jupyter Notebook": 688046, "Kotlin": 50475}
package com.example.dermate.ui.welcomeslider.pagefragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.dermate.R class SecondPageFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_second_page, container, false) } }
0
Jupyter Notebook
3
3
227d6c2bceb261889d99bf0ef815ae65626a5b68
559
Dermate
Freetype Project License
app/src/main/java/com/rajchenbergstudios/hoygenda/ui/core/taskssetedit/TasksInSetListAdapter.kt
Davidhk2891
524,378,818
false
null
package com.rajchenbergstudios.hoygenda.ui.core.taskssetedit import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.rajchenbergstudios.hoygenda.data.taskinset.TaskInSet import com.rajchenbergstudios.hoygenda.databinding.SingleItemTaskBinding class TasksInSetListAdapter(private val listener: OnItemClickListener) : ListAdapter<TaskInSet, TasksInSetListAdapter.TaskInSetEditListViewHolder>( DiffCallback() ){ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskInSetEditListViewHolder { val binding = SingleItemTaskBinding.inflate(LayoutInflater.from(parent.context), parent, false) return TaskInSetEditListViewHolder(binding) } override fun onBindViewHolder(holder: TaskInSetEditListViewHolder, position: Int) { val currentItem = getItem(position) holder.bind(currentItem) } inner class TaskInSetEditListViewHolder(private val binding: SingleItemTaskBinding) : RecyclerView.ViewHolder(binding.root) { init { binding.apply { root.setOnClickListener { val position = adapterPosition if (position != RecyclerView.NO_POSITION) { val taskInSet = getItem(position) listener.onItemClick(taskInSet) } } } } fun bind(taskInSet: TaskInSet) { binding.apply { itemTaskCompletedCheckbox.isChecked = false itemTaskCompletedCheckbox.isClickable = false itemTaskTitleTextview.text = taskInSet.taskInSet itemTaskImportantImageview.visibility = View.INVISIBLE } } } interface OnItemClickListener { fun onItemClick(taskInSet: TaskInSet) } class DiffCallback : DiffUtil.ItemCallback<TaskInSet>() { override fun areItemsTheSame(oldItem: TaskInSet, newItem: TaskInSet): Boolean = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: TaskInSet, newItem: TaskInSet): Boolean = oldItem == newItem } }
0
Kotlin
0
0
1154bbfb5865cb48a87497582b3149573c17efae
2,318
Rajchenberg_Studios-Hoytask
Apache License 2.0
pws-data-proxy/src/main/kotlin/dev/shchuko/pwsproxy/api/service/model/PwsData.kt
shchuko
849,979,848
false
{"Kotlin": 856584}
package dev.shchuko.pwsproxy.api.service.model class PwsData( history: List<PwsMeasurement>?, ) { val ready: Boolean = history != null val history: List<PwsMeasurement>? = history?.sortedBy { it.timestamp } override fun toString(): String { return "PwsData(ready=$ready, history=${history?.size})" } }
0
Kotlin
0
0
5f77d428cf2c84ce924452eaf8f79149f8f87376
331
weather-station-screen
Apache License 2.0
app/src/main/java/app/glucostats/GlucostatsApplication.kt
vapoyan
875,236,683
false
{"Kotlin": 43557}
package app.glucostats import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class GlucostatsApplication: Application()
0
Kotlin
0
0
178b72fd5e6d9cba8059b912f9c11469c14737d3
156
Glucostats
FSF All Permissive License
benchmark/benchmark-darwin-samples/src/iosMain/kotlin/androidx/benchmark/darwin/samples/ArrayListAllocationBenchmark.kt
androidx
256,589,781
false
null
/* * Copyright 2022 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.benchmark.darwin.samples import androidx.benchmark.darwin.TestCase import androidx.benchmark.darwin.TestCaseContext import platform.XCTest.XCTMeasureOptions class ArrayListAllocationBenchmark : TestCase() { override fun setUp() { // does nothing } override fun benchmark(context: TestCaseContext) { val options = XCTMeasureOptions.defaultOptions() // 5 Iterations options.iterationCount = 5.toULong() context.measureWithMetrics( listOf( platform.XCTest.XCTCPUMetric(), platform.XCTest.XCTMemoryMetric(), platform.XCTest.XCTClockMetric() ), options ) { // Do something a bit expensive repeat(1000) { ArrayList<Float>(SIZE) } } } override fun testDescription(): String { return "Allocate an ArrayList of size $SIZE" } companion object { // The initial capacity of the allocation private const val SIZE = 1000 } }
28
null
937
5,108
89ec14e39cf771106a8719337062572717cbad31
1,670
androidx
Apache License 2.0
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/solid/GlobeEurope.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.fontawesomeicons.solid import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Butt import androidx.compose.ui.graphics.StrokeJoin.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.fontawesomeicons.SolidGroup public val SolidGroup.GlobeEurope: ImageVector get() { if (_globeEurope != null) { return _globeEurope!! } _globeEurope = Builder(name = "GlobeEurope", defaultWidth = 496.0.dp, defaultHeight = 512.0.dp, viewportWidth = 496.0f, viewportHeight = 512.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(248.0f, 8.0f) curveTo(111.0f, 8.0f, 0.0f, 119.0f, 0.0f, 256.0f) reflectiveCurveToRelative(111.0f, 248.0f, 248.0f, 248.0f) reflectiveCurveToRelative(248.0f, -111.0f, 248.0f, -248.0f) reflectiveCurveTo(385.0f, 8.0f, 248.0f, 8.0f) close() moveTo(448.0f, 256.0f) curveToRelative(0.0f, 22.5f, -3.9f, 44.2f, -10.8f, 64.4f) horizontalLineToRelative(-20.3f) curveToRelative(-4.3f, 0.0f, -8.4f, -1.7f, -11.4f, -4.8f) lineToRelative(-32.0f, -32.6f) curveToRelative(-4.5f, -4.6f, -4.5f, -12.1f, 0.1f, -16.7f) lineToRelative(12.5f, -12.5f) verticalLineToRelative(-8.7f) curveToRelative(0.0f, -3.0f, -1.2f, -5.9f, -3.3f, -8.0f) lineToRelative(-9.4f, -9.4f) curveToRelative(-2.1f, -2.1f, -5.0f, -3.3f, -8.0f, -3.3f) horizontalLineToRelative(-16.0f) curveToRelative(-6.2f, 0.0f, -11.3f, -5.1f, -11.3f, -11.3f) curveToRelative(0.0f, -3.0f, 1.2f, -5.9f, 3.3f, -8.0f) lineToRelative(9.4f, -9.4f) curveToRelative(2.1f, -2.1f, 5.0f, -3.3f, 8.0f, -3.3f) horizontalLineToRelative(32.0f) curveToRelative(6.2f, 0.0f, 11.3f, -5.1f, 11.3f, -11.3f) verticalLineToRelative(-9.4f) curveToRelative(0.0f, -6.2f, -5.1f, -11.3f, -11.3f, -11.3f) horizontalLineToRelative(-36.7f) curveToRelative(-8.8f, 0.0f, -16.0f, 7.2f, -16.0f, 16.0f) verticalLineToRelative(4.5f) curveToRelative(0.0f, 6.9f, -4.4f, 13.0f, -10.9f, 15.2f) lineToRelative(-31.6f, 10.5f) curveToRelative(-3.3f, 1.1f, -5.5f, 4.1f, -5.5f, 7.6f) verticalLineToRelative(2.2f) curveToRelative(0.0f, 4.4f, -3.6f, 8.0f, -8.0f, 8.0f) horizontalLineToRelative(-16.0f) curveToRelative(-4.4f, 0.0f, -8.0f, -3.6f, -8.0f, -8.0f) reflectiveCurveToRelative(-3.6f, -8.0f, -8.0f, -8.0f) lineTo(247.0f, 208.4f) curveToRelative(-3.0f, 0.0f, -5.8f, 1.7f, -7.2f, 4.4f) lineToRelative(-9.4f, 18.7f) curveToRelative(-2.7f, 5.4f, -8.2f, 8.8f, -14.3f, 8.8f) lineTo(194.0f, 240.3f) curveToRelative(-8.8f, 0.0f, -16.0f, -7.2f, -16.0f, -16.0f) lineTo(178.0f, 199.0f) curveToRelative(0.0f, -4.2f, 1.7f, -8.3f, 4.7f, -11.3f) lineToRelative(20.1f, -20.1f) curveToRelative(4.6f, -4.6f, 7.2f, -10.9f, 7.2f, -17.5f) curveToRelative(0.0f, -3.4f, 2.2f, -6.5f, 5.5f, -7.6f) lineToRelative(40.0f, -13.3f) curveToRelative(1.7f, -0.6f, 3.2f, -1.5f, 4.4f, -2.7f) lineToRelative(26.8f, -26.8f) curveToRelative(2.1f, -2.1f, 3.3f, -5.0f, 3.3f, -8.0f) curveToRelative(0.0f, -6.2f, -5.1f, -11.3f, -11.3f, -11.3f) lineTo(258.0f, 80.4f) lineToRelative(-16.0f, 16.0f) verticalLineToRelative(8.0f) curveToRelative(0.0f, 4.4f, -3.6f, 8.0f, -8.0f, 8.0f) horizontalLineToRelative(-16.0f) curveToRelative(-4.4f, 0.0f, -8.0f, -3.6f, -8.0f, -8.0f) verticalLineToRelative(-20.0f) curveToRelative(0.0f, -2.5f, 1.2f, -4.9f, 3.2f, -6.4f) lineToRelative(28.9f, -21.7f) curveToRelative(1.9f, -0.1f, 3.8f, -0.3f, 5.7f, -0.3f) curveTo(358.3f, 56.0f, 448.0f, 145.7f, 448.0f, 256.0f) close() moveTo(130.1f, 149.1f) curveToRelative(0.0f, -3.0f, 1.2f, -5.9f, 3.3f, -8.0f) lineToRelative(25.4f, -25.4f) curveToRelative(2.1f, -2.1f, 5.0f, -3.3f, 8.0f, -3.3f) curveToRelative(6.2f, 0.0f, 11.3f, 5.1f, 11.3f, 11.3f) verticalLineToRelative(16.0f) curveToRelative(0.0f, 3.0f, -1.2f, 5.9f, -3.3f, 8.0f) lineToRelative(-9.4f, 9.4f) curveToRelative(-2.1f, 2.1f, -5.0f, 3.3f, -8.0f, 3.3f) horizontalLineToRelative(-16.0f) curveToRelative(-6.2f, 0.0f, -11.3f, -5.1f, -11.3f, -11.3f) close() moveTo(258.1f, 455.5f) verticalLineToRelative(-7.1f) curveToRelative(0.0f, -8.8f, -7.2f, -16.0f, -16.0f, -16.0f) horizontalLineToRelative(-20.2f) curveToRelative(-10.8f, 0.0f, -26.7f, -5.3f, -35.4f, -11.8f) lineToRelative(-22.2f, -16.7f) curveToRelative(-11.5f, -8.6f, -18.2f, -22.1f, -18.2f, -36.4f) verticalLineToRelative(-23.9f) curveToRelative(0.0f, -16.0f, 8.4f, -30.8f, 22.1f, -39.0f) lineToRelative(42.9f, -25.7f) curveToRelative(7.1f, -4.2f, 15.2f, -6.5f, 23.4f, -6.5f) horizontalLineToRelative(31.2f) curveToRelative(10.9f, 0.0f, 21.4f, 3.9f, 29.6f, 10.9f) lineToRelative(43.2f, 37.1f) horizontalLineToRelative(18.3f) curveToRelative(8.5f, 0.0f, 16.6f, 3.4f, 22.6f, 9.4f) lineToRelative(17.3f, 17.3f) curveToRelative(3.4f, 3.4f, 8.1f, 5.3f, 12.9f, 5.3f) lineTo(423.0f, 352.4f) curveToRelative(-32.4f, 58.9f, -93.8f, 99.5f, -164.9f, 103.1f) close() } } .build() return _globeEurope!! } private var _globeEurope: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
6,892
compose-icons
MIT License
app/src/main/java/com/mynimef/foodmood/data/repository/dao/ClientDao.kt
MYnimef
637,497,996
false
{"Kotlin": 238301}
package com.mynimef.foodmood.data.repository.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.mynimef.foodmood.data.models.database.ClientEntity import kotlinx.coroutines.flow.Flow @Dao interface ClientDao { @Query("SELECT * FROM client") fun getAll(): Flow<List<ClientEntity>> @Query("SELECT * FROM client WHERE client.id = :id") fun getClientById(id: Long): Flow<ClientEntity?> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(client: ClientEntity): Long @Delete suspend fun delete(client: ClientEntity) @Query("DELETE FROM client WHERE client.id = :id") suspend fun deleteById(id: Long) @Query("UPDATE client SET water_amount = :waterAmount WHERE id = :id") suspend fun updateWaterAmount(id: Long, waterAmount: Float) }
0
Kotlin
1
0
913dc33b0b970bc50834109a47a3e868dd07ac7c
913
FoodMood-Android
MIT License
core/network/src/main/java/com/danielefavaro/openweather/core/network/EnvironmentConfig.kt
dfavaro
637,725,290
false
null
package com.danielefavaro.openweather.core.network import okhttp3.logging.HttpLoggingInterceptor interface EnvironmentConfig { val url: String val apiKey: String val logLevel: HttpLoggingInterceptor.Level }
0
Kotlin
0
0
3f0930a20337ce47f651d1e9085e5cad58b8de7e
221
openweather-android
MIT License
src/test/kotlin/io/andrewohara/awsmock/dynamodb/v2/V2DescribeTableTest.kt
oharaandrew314
276,702,915
false
{"Kotlin": 459818}
package io.andrewohara.awsmock.dynamodb.v2 import io.andrewohara.awsmock.dynamodb.DynamoFixtures import io.andrewohara.awsmock.dynamodb.DynamoUtils.createCatsTable import io.andrewohara.awsmock.dynamodb.DynamoUtils.createOwnersTable import io.andrewohara.awsmock.dynamodb.MockDynamoDbV2 import io.andrewohara.awsmock.dynamodb.backend.MockDynamoBackend import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test import software.amazon.awssdk.services.dynamodb.model.* import java.time.Clock import java.time.Instant import java.time.ZoneOffset class V2DescribeTableTest { private val clock = Clock.fixed(Instant.parse("2021-09-18T12:00:00Z"), ZoneOffset.UTC) private val backend = MockDynamoBackend(clock) private val client = MockDynamoDbV2(backend) private val cats = backend.createCatsTable() private val owners = backend.createOwnersTable() @Test fun `describe missing table`() { shouldThrow<ResourceNotFoundException> { client.describeTable { it.tableName("missingTable") } } } @Test fun `describe owners table with 0 items`() { client.describeTable { it.tableName(owners.name) } shouldBe DescribeTableResponse.builder() .table(TableDescription.builder() .tableArn(owners.arn) .tableName(owners.name) .creationDateTime(clock.instant()) .tableStatus(TableStatus.ACTIVE) .attributeDefinitions( AttributeDefinition.builder() .attributeName("ownerId") .attributeType(ScalarAttributeType.N) .build() ) .keySchema( KeySchemaElement.builder() .attributeName("ownerId") .keyType(KeyType.HASH) .build() ) .itemCount(0) .globalSecondaryIndexes(emptyList()) .localSecondaryIndexes(emptyList()) .build() ) .build() } @Test fun `describe cats table with 1 item`() { cats.save(DynamoFixtures.toggles) client.describeTable { it.tableName(cats.name) } shouldBe DescribeTableResponse.builder() .table(TableDescription.builder() .tableArn(cats.arn) .tableName(cats.name) .tableStatus(TableStatus.ACTIVE) .creationDateTime(clock.instant()) .attributeDefinitions( AttributeDefinition.builder().attributeName("ownerId").attributeType(ScalarAttributeType.N).build(), AttributeDefinition.builder().attributeName("name").attributeType(ScalarAttributeType.S).build(), AttributeDefinition.builder().attributeName("gender").attributeType(ScalarAttributeType.S).build() ) .keySchema( KeySchemaElement.builder().attributeName("ownerId").keyType(KeyType.HASH).build(), KeySchemaElement.builder().attributeName("name").keyType(KeyType.RANGE).build() ) .itemCount(1) .globalSecondaryIndexes( GlobalSecondaryIndexDescription.builder() .indexName("names") .indexArn("${cats.arn}/index/names") .itemCount(1) .indexStatus(IndexStatus.ACTIVE) .keySchema( KeySchemaElement.builder().attributeName("name").keyType(KeyType.HASH).build() ) .build() ) .localSecondaryIndexes( LocalSecondaryIndexDescription.builder() .indexName("genders") .indexArn("${cats.arn}/index/genders") .itemCount(1) .keySchema( KeySchemaElement.builder().attributeName("ownerId").keyType(KeyType.HASH).build(), KeySchemaElement.builder().attributeName("gender").keyType(KeyType.RANGE).build() ) .build() ) .build() ) .build() } }
0
Kotlin
1
5
abd135f64f0f6e5fdfce8ae8a30f0d8dd9166751
4,479
mock-aws-java-sdk
Apache License 2.0
app/src/main/java/hofjs/hofandroid/workers/PullNotificationWorker.kt
hofjs
512,435,455
false
null
package hofjs.hofandroid.workers import android.content.Context import android.content.Intent import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.toBitmap import androidx.work.Data import androidx.work.Worker import androidx.work.WorkerParameters import hofjs.hofandroid.helpers.NotificationHelper import hofjs.hofandroid.helpers.RequestHelper abstract class PullNotificationWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) { private val requestHelper = RequestHelper(ctx) private val notificationHelper = NotificationHelper(ctx) // Save original context because applicationContext can differ from original context // in case of app restart and as a consequence shared prefs would not work private val context: Context init { this.context = ctx } companion object { const val NOTIFICATION_CATEGORY_PARAMETER_KEY = "category" const val NOTIFICATION_SMALLICON_PARAMETER_KEY = "smallIcon" const val NOTIFICATION_LARGEICON_PARAMETER_KEY = "largeIcon" } override fun doWork(): Result { return try { val entries = getUpdatedEntries() ?: return Result.failure() makeNotifications(entries) Result.success() } catch (throwable: Throwable) { throwable.printStackTrace() Result.failure() } } open fun getUpdatedEntries(params: Data? = null, currentContent: Set<String>? = makeRequests(params ?: inputData), oldEntries: Set<NotificationEntry> = loadEntries()): Set<NotificationEntry>? { val currentEntries = parseContents(currentContent ?: return null, params ?: inputData) val updatedEntries = currentEntries.subtract(oldEntries) // Save current data if there are changes if (updatedEntries.isNotEmpty()) saveEntries(currentEntries) // Return updated entries return updatedEntries } abstract fun makeRequests(params: Data): Set<String>? abstract fun parseContent(content: String, params: Data): Set<NotificationEntry> protected fun loadUrl(url: String, credentials: String? = null) = requestHelper.loadUrl(url, credentials) protected fun parseContents(contents: Set<String>, params: Data): Set<NotificationEntry> { val entries = mutableSetOf<NotificationEntry>() contents.forEach { entries += parseContent(it, params) } return entries } protected fun loadEntries(): Set<NotificationEntry> { val sharedPrefs = context.getSharedPreferences( this::class.java.name, Context.MODE_PRIVATE) val entries = mutableSetOf<NotificationEntry>() with(sharedPrefs) { var index = -1 while (getString("TITLE_${++index}", null) != null) { entries.add( NotificationEntry( getString("TITLE_$index", null) ?: "-", getString("TEXT_$index", null) ?: "-", getString("DATA_$index", null) ?: "" ) ) } } return entries } protected fun saveEntries(entries: Set<NotificationEntry>) { val sharedPrefs = context.getSharedPreferences( this::class.java.name, Context.MODE_PRIVATE) with (sharedPrefs.edit()) { clear() entries.forEachIndexed { index: Int, entry: NotificationEntry -> putString("TITLE_$index", entry.title) putString("TEXT_$index", entry.text) putString("DATA_$index", entry.data) } apply() } } protected fun makeNotifications(entries: Set<NotificationEntry>) { val category = inputData.getString(NOTIFICATION_CATEGORY_PARAMETER_KEY) ?: context.applicationInfo.loadLabel(context.packageManager).toString() val smallIcon = inputData.getInt(NOTIFICATION_SMALLICON_PARAMETER_KEY, android.R.mipmap.sym_def_app_icon) val largeIcon = inputData.getInt(NOTIFICATION_LARGEICON_PARAMETER_KEY, smallIcon) // Restrict notifications to last 3 entries.reversed().takeLast(3).forEach { entry -> makeNotification(entry, category, smallIcon, largeIcon) } } protected fun makeNotification(entry: NotificationEntry, category: String, smallIcon: Int, largeIcon: Int) { if (entry.data.startsWith("http:") or entry.data.startsWith("https:")) notificationHelper.makeUrlNotification(entry.title, entry.text, entry.data, smallIcon, ContextCompat.getDrawable(context, largeIcon)?.toBitmap(), category) else if (entry.data.startsWith("intent:")) { val intent = Intent() var urlTokenIndex = entry.data.indexOf(",") var urlPart: String? = if (urlTokenIndex >= 0) entry.data.substring(urlTokenIndex+1) else null intent.setClassName(context, entry.data.substring(7, if (urlTokenIndex >= 0) urlTokenIndex else entry.data.length)) urlPart?.let { intent.putExtra("url", urlPart) } notificationHelper.makeIntentNotification(entry.title, entry.text, intent, smallIcon, ContextCompat.getDrawable(context, largeIcon)?.toBitmap(), category) } } data class NotificationEntry(val title: String, val text: String, val data: String) }
0
Kotlin
0
0
57e47e656269a6a764285cc0d04db89bf7690db5
5,528
hofandroid
MIT License
src/main/kotlin/helpers/VMFile.kt
ChippyPlus
850,474,357
false
{"Kotlin": 104286}
package helpers import java.io.File /** * Represents a file within the virtual machine's environment. * * @property file The [File] object associated with the virtual machine file. */ data class VMFile(val file: File)
0
Kotlin
0
1
6308a3208d63f5865931a1439a3f828b28a6af8f
224
MVM
MIT License
core/src/main/java/studio/crud/feature/core/web/annotations/CrudOperations.kt
crud-studio
390,327,908
false
null
package studio.crud.feature.core.web.annotations @Target(AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS) annotation class CrudOperations( val index: Boolean = true, val show: Boolean = true, val update: Boolean = true, val create: Boolean = true, val delete: Boolean = true )
6
Kotlin
0
0
6cb1d5f7b3fc7117c9fbaaf6708ac93ae631e674
307
feature-depot
MIT License
src/commonMain/kotlin/ru/DmN/Project/core/obj/ICO.kt
DmNProject
342,525,186
false
null
package ru.DmN.Project.core.obj /** * Callable Object */ interface ICO<VM, I> : IObject { fun call(vm: VM, instance: I) }
0
Kotlin
1
2
514f3fc6c2d36f341ded5e9f835d735d02507dac
128
DmNPCore
Apache License 2.0
app/src/main/java/com/sk/outlay/data/dao/CategoryDao.kt
swapnilkadlag
438,615,490
false
null
package com.sk.outlay.data.dao import androidx.room.Dao import androidx.room.Query import com.sk.outlay.data.entities.Account import com.sk.outlay.data.entities.Category import kotlinx.coroutines.flow.Flow import java.util.* @Dao abstract class CategoryDao : BaseDao<Category> { @Query("""SELECT * FROM tblCategory""") abstract fun getCategories(): Flow<List<Category>> @Query("""SELECT * FROM tblCategory WHERE id = :id""") abstract suspend fun getCategory(id: UUID): Category }
0
Kotlin
0
1
5122273cc8830ada1eae78c87c02d447663e4d7d
498
Outlay
Apache License 2.0
app/src/main/java/com/andre_max/tiktokclone/presentation/ui/components/comment/MainComment.kt
Andre-max
291,054,765
false
null
/* * MIT License * * Copyright (c) 2021 Andre-max * * 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.andre_max.tiktokclone.presentation.ui.components.comment import androidx.constraintlayout.motion.widget.MotionLayout import androidx.lifecycle.MutableLiveData import androidx.recyclerview.widget.LinearLayoutManager import com.andre_max.tiktokclone.R import com.andre_max.tiktokclone.databinding.LargeVideoLayoutBinding import com.andre_max.tiktokclone.models.comment.Comment import com.andre_max.tiktokclone.models.video.RemoteVideo import com.andre_max.tiktokclone.repo.network.comment.CommentRepo import com.andre_max.tiktokclone.repo.network.user.UserRepo import com.andre_max.tiktokclone.utils.NumbersUtils import com.andre_max.tiktokclone.utils.ResUtils import com.andre_max.tiktokclone.utils.map.SmartAction import com.andre_max.tiktokclone.utils.map.SmartMap import com.xwray.groupie.GroupAdapter import com.xwray.groupie.GroupieViewHolder import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch class MainComment( private val binding: LargeVideoLayoutBinding, private val commentRepo: CommentRepo, private val remoteVideo: RemoteVideo, private val userRepo: UserRepo, private val scope: CoroutineScope, private val liveUserComment: MutableLiveData<String>, private val onCommentVisibilityChanged: (Boolean) -> Unit ) { private val commentsGroupAdapter = GroupAdapter<GroupieViewHolder>() val commentsSize by lazy { commentRepo.getTotalCommentsSize(remoteVideo.videoId) } val commentsMap by lazy { commentRepo.fetchComments(remoteVideo.videoId) } init { binding.commentRecyclerview.apply { layoutManager = LinearLayoutManager(context) adapter = commentsGroupAdapter } } fun init() { // Reset any previous user comment liveUserComment.value = "" setUpClickListeners() // If we have not add the observer, add it. if (!commentsMap.hasObservers()) commentsMap.observeForever(commentsMapObserver) if (!commentsSize.hasObservers()) commentsSize.observeForever(commentSizeObserver) } fun showCommentSection() { (binding.root as MotionLayout).transitionToEnd() onCommentVisibilityChanged(true) } fun hideCommentSection() { (binding.root as MotionLayout).transitionToStart() onCommentVisibilityChanged(false) } private val commentSizeObserver: (Int) -> Unit = { commentSize -> val context = binding.root.context binding.totalComments.text = context.getString(R.string.comment_size, NumbersUtils.formatCount(commentSize)) } private val commentsMapObserver: (SmartMap<String, Comment>) -> Unit = { smartMap -> when (smartMap.action) { SmartAction.Add -> { smartMap.actionValue?.let { addGroupToAdapter(it) } } SmartAction.AddAll -> { smartMap.actionMap?.values?.forEach { addGroupToAdapter(it) } } SmartAction.Remove -> { smartMap.actionKey?.let { removeGroup(smartMap.indexOf(it)) } } else -> { } } } private fun addGroupToAdapter(comment: Comment) { val videoId = remoteVideo.videoId val commentId = comment.commentId scope.launch { val eachCommentGroup = EachCommentGroup( comment = comment, isLiked = commentRepo.isCommentLiked(videoId, commentId), commentAuthor = userRepo.getUserProfile(comment.authorUid).tryData(), likeOrUnlikeComment = { scope.launch { } } ) commentsGroupAdapter.add(eachCommentGroup) } } private fun removeGroup(position: Int) { commentsGroupAdapter.removeGroupAtAdapterPosition(position) } fun setUpClickListeners() { binding.sendCommentBtn.setOnClickListener { val message = liveUserComment.value ?: "" if (userRepo.doesDeviceHaveAnAccount()) { sendComment(message) } else { // TODO: Once the button is clicked, let's show a small pop-up layout that tells him/her to sign up or login } } } private fun sendComment(message: String) { if (message.isBlank()) ResUtils.showSnackBar(binding.root, R.string.empty_comment_error) else commentRepo.sendComment(message, remoteVideo.videoId) } fun destroy() { commentsMap.removeObserver(commentsMapObserver) commentsSize.removeObserver(commentSizeObserver) } }
7
Kotlin
27
56
0dcbc62d6b7d388744c213881a8125157eaf51e2
5,796
TikTok-Clone
MIT License
src/test/kotlin/parsers/LongParserTests.kt
nathanblaubach
245,930,992
false
{"Kotlin": 40195}
package parsers import org.junit.Test class LongParserTests { private val parser = LongParser() @Test fun validStringsAreConvertedToLongs() { println(Long.MIN_VALUE) println(Long.MAX_VALUE) listOf( "-9223372036854775808", // Minimum Double Value "-9223372036854775807", // Just Above Minimum Double Value "0", // Zero "9223372036854775806", // Just Below Maximum Double Value "9223372036854775807" // Maximum Double Value ).map(parser::parse).forEach { assert(it != null) } } @Test fun invalidStringsAreConvertedToNull() { listOf( "", "Hello", "12.3", "01/01/2020", "true", "false", "-9223372036854775809", // Just Below Double Integer Value "9223372036854775808" // Just Above Double Integer Value ).map(parser::parse).forEach { assert(it == null) } } }
1
Kotlin
0
0
ca3e911ffa1be3b1d964f4d5ef4b7aec73e381ef
955
KtValid8
MIT License
src/commonTest/kotlin/ch/lettercode/kotlin/event/EventTest.kt
lettercode
612,447,119
false
null
package ch.lettercode.kotlin.event import kotlin.test.Test import kotlin.test.assertEquals class EventTest { @Test fun size() { val event = Event<Any>() event += EventHandler { } event += EventHandler { } event += EventHandler { } assertEquals(3, event.size) } @Test fun clear() { val event = Event<Any>() event += EventHandler { } event += EventHandler { } event.clear() assertEquals(0, event.size) } @Test fun iterator() { val event = Event<Any>() event += EventHandler { } event += EventHandler { } event += EventHandler { } var count = 0 for (handler in event) count++ assertEquals(3, count) } @Test fun addEventHandler() { val event = Event<Any>() event += EventHandler { } event(Any()) assertEquals(1, event.size) } @Test fun addLambdaEventHandler() { val event = Event<Any>() event += {} event(Any()) assertEquals(1, event.size) } @Test fun remove() { val event = Event<Any>() val eventHandler1 = EventHandler<Any> { } val eventHandler2 = EventHandler<Any> { } event += eventHandler1 event += eventHandler2 event -= eventHandler1 event(Any()) assertEquals(1, event.size) } @Test fun sumValues() { data class EventArgs(var value: Int) val event = Event<EventArgs>() var testee = 0 event += EventHandler { testee += it.value } event(EventArgs(1)) event(EventArgs(1)) assertEquals(2, testee) } @Test fun plusAssign_CrossInline() { data class EventArgs(var value: Int) val event = Event<EventArgs>() var testee = 0 event += { testee += it.value } event(EventArgs(1)) event(EventArgs(1)) assertEquals(2, testee) } }
0
Kotlin
0
0
dde6da7bd6cf274fe5a668640616a6b7c382c201
2,078
kotlin-event
Apache License 2.0
casty/src/main/java/pl/droidsonroids/casty/ExpandedControlsActivity.kt
l1068
585,808,470
false
null
package pl.droidsonroids.casty import android.view.Menu import com.google.android.gms.cast.framework.CastButtonFactory import com.google.android.gms.cast.framework.media.widget.ExpandedControllerActivity /** * Fullscreen media controls */ class ExpandedControlsActivity : ExpandedControllerActivity() { override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.casty_discovery, menu) CastButtonFactory.setUpMediaRouteButton(this, menu, R.id.casty_media_route_menu_item) return true } }
0
Kotlin
0
0
e8214c1d5fedc776feb1d04bfe7347b777c44e8b
589
casty
MIT License
db-objekts-core/src/main/kotlin/com/dbobjekts/codegen/configbuilders/AbstractConfigurer.kt
jaspersprengers
576,889,038
false
null
package com.dbobjekts.codegen.configbuilders import com.dbobjekts.codegen.CodeGenerator /** * Base class for all configuration builders */ abstract class AbstractConfigurer(protected val generator: CodeGenerator) { /** * Returns the parent [CodeGenerator] instance to allow for fluent syntax. * ```kotlin * CodeGenerator() * .withDataSource(AcmeDB.dataSource) * .configurePrimaryKeySequences() * [...] * .and().configureColumnTypeMapping() * [...] * .and().configureOutput() * [...] * .and().generateSourceFiles() * ``` */ fun and(): CodeGenerator = generator }
0
Kotlin
2
4
5b66aae10cae18a95f77c29ce55b11b03e53500b
719
db-objekts
Apache License 2.0
tiltak/src/test/kotlin/no/nav/amt/tiltak/deltaker/DeltakerServiceImplTest.kt
navikt
393,356,849
false
null
package no.nav.amt.tiltak.deltaker import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.mockk.mockk import no.nav.amt.tiltak.core.domain.tiltak.Deltaker import no.nav.amt.tiltak.core.domain.tiltak.DeltakerStatuser import no.nav.amt.tiltak.core.port.BrukerService import no.nav.amt.tiltak.deltaker.repositories.BrukerRepository import no.nav.amt.tiltak.deltaker.repositories.DeltakerRepository import no.nav.amt.tiltak.deltaker.repositories.DeltakerStatusRepository import no.nav.amt.tiltak.deltaker.service.DeltakerServiceImpl import no.nav.amt.tiltak.test.database.DbTestDataUtils import no.nav.amt.tiltak.test.database.SingletonPostgresContainer import no.nav.amt.tiltak.test.database.data.TestData.BRUKER_3 import no.nav.amt.tiltak.test.database.data.TestData.GJENNOMFORING_1 import no.nav.amt.tiltak.tiltak.services.BrukerServiceImpl import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.jdbc.datasource.DataSourceTransactionManager import org.springframework.transaction.support.TransactionTemplate import java.time.LocalDateTime import java.util.* class DeltakerServiceImplTest { lateinit var deltakerRepository: DeltakerRepository lateinit var deltakerStatusRepository: DeltakerStatusRepository lateinit var deltakerServiceImpl: DeltakerServiceImpl lateinit var brukerRepository: BrukerRepository lateinit var brukerService: BrukerService val dataSource = SingletonPostgresContainer.getDataSource() val jdbcTemplate = NamedParameterJdbcTemplate(dataSource) val deltakerId = UUID.randomUUID() @BeforeEach fun beforeEach() { brukerRepository = BrukerRepository(jdbcTemplate) brukerService = BrukerServiceImpl(brukerRepository, mockk(), mockk(), mockk(), mockk()) deltakerRepository = DeltakerRepository(jdbcTemplate) deltakerStatusRepository = DeltakerStatusRepository(jdbcTemplate) deltakerServiceImpl = DeltakerServiceImpl( deltakerRepository, deltakerStatusRepository, brukerService, TransactionTemplate(DataSourceTransactionManager(dataSource)) ) DbTestDataUtils.cleanAndInitDatabaseWithTestData(dataSource) } @AfterEach fun afterEach() { DbTestDataUtils.cleanDatabase(dataSource) } @Test fun `upsertDeltaker - inserter ny deltaker`() { deltakerServiceImpl.upsertDeltaker(BRUKER_3.fodselsnummer, deltaker) val nyDeltaker = deltakerRepository.get(BRUKER_3.fodselsnummer, GJENNOMFORING_1.id) nyDeltaker shouldNotBe null val statuser = deltakerStatusRepository.getStatuserForDeltaker(deltakerId) statuser shouldHaveSize 1 statuser.first().status shouldBe Deltaker.Status.DELTAR statuser.first().aktiv shouldBe true } @Test fun `upsertDeltaker - deltaker får ny status - oppdaterer status på deltaker`() { deltakerServiceImpl.upsertDeltaker(BRUKER_3.fodselsnummer, deltaker) var nyDeltaker = deltakerRepository.get(BRUKER_3.fodselsnummer, GJENNOMFORING_1.id) var statuser = deltakerStatusRepository.getStatuserForDeltaker(deltakerId) nyDeltaker shouldNotBe null statuser shouldHaveSize 1 val endretStatus = status.medNy(Deltaker.Status.HAR_SLUTTET, LocalDateTime.now()) val endretDeltaker = deltaker.copy(statuser = endretStatus) deltakerServiceImpl.upsertDeltaker(BRUKER_3.fodselsnummer, endretDeltaker) nyDeltaker = deltakerRepository.get(BRUKER_3.fodselsnummer, GJENNOMFORING_1.id) statuser = deltakerStatusRepository.getStatuserForDeltaker(deltakerId) val aktivStatus = statuser.first{ it.aktiv } nyDeltaker shouldNotBe null statuser shouldHaveSize 2 aktivStatus.status shouldBe Deltaker.Status.HAR_SLUTTET } @Test fun `upsertDeltaker - deltaker får samme status igjen - oppdaterer ikke status`() { deltakerServiceImpl.upsertDeltaker(BRUKER_3.fodselsnummer, deltaker) var nyDeltaker = deltakerRepository.get(BRUKER_3.fodselsnummer, GJENNOMFORING_1.id) var statuser = deltakerStatusRepository.getStatuserForDeltaker(deltakerId) nyDeltaker shouldNotBe null statuser shouldHaveSize 1 deltakerServiceImpl.upsertDeltaker(BRUKER_3.fodselsnummer, deltaker) nyDeltaker = deltakerRepository.get(BRUKER_3.fodselsnummer, GJENNOMFORING_1.id) statuser = deltakerStatusRepository.getStatuserForDeltaker(deltakerId) val aktivStatus = statuser.first{ it.aktiv } nyDeltaker shouldNotBe null statuser shouldHaveSize 1 aktivStatus.status shouldBe Deltaker.Status.DELTAR } @Test fun `upsertDeltaker - deltaker får samme status på nytt etter opphold - oppdaterer status`() { deltakerServiceImpl.upsertDeltaker(BRUKER_3.fodselsnummer, deltaker) var nyDeltaker = deltakerRepository.get(BRUKER_3.fodselsnummer, GJENNOMFORING_1.id) var statuser = deltakerStatusRepository.getStatuserForDeltaker(deltakerId) nyDeltaker shouldNotBe null statuser shouldHaveSize 1 val endretDeltaker = deltaker.copy(statuser = DeltakerStatuser.settAktivStatus(Deltaker.Status.HAR_SLUTTET)) deltakerServiceImpl.upsertDeltaker(BRUKER_3.fodselsnummer, endretDeltaker) nyDeltaker = deltakerRepository.get(BRUKER_3.fodselsnummer, GJENNOMFORING_1.id) statuser = deltakerStatusRepository.getStatuserForDeltaker(deltakerId) val aktivStatus = statuser.first{ it.aktiv } nyDeltaker shouldNotBe null statuser shouldHaveSize 2 aktivStatus.status shouldBe Deltaker.Status.HAR_SLUTTET deltakerServiceImpl.upsertDeltaker(BRUKER_3.fodselsnummer, deltaker.copy(statuser = DeltakerStatuser.settAktivStatus(Deltaker.Status.DELTAR))) } @Test fun `slettDeltaker - skal slette deltaker og status`() { deltakerServiceImpl.upsertDeltaker(BRUKER_3.fodselsnummer, deltaker) deltakerStatusRepository.getStatuserForDeltaker(deltakerId) shouldHaveSize 1 deltakerServiceImpl.slettDeltaker(deltakerId) deltakerRepository.get(deltakerId) shouldBe null deltakerStatusRepository.getStatuserForDeltaker(deltakerId) shouldHaveSize 0 } val status = DeltakerStatuser.settAktivStatus(Deltaker.Status.DELTAR) val deltaker = Deltaker( id = deltakerId, bruker = null, startDato = null, sluttDato = null, statuser = status, registrertDato = LocalDateTime.now(), dagerPerUke = null, prosentStilling = null, gjennomforingId = GJENNOMFORING_1.id ) }
3
Kotlin
1
2
90b2da08f224d9b05496cecc36434d95762e4cd5
6,338
amt-tiltak
MIT License
modules/core/arrow-core-data/src/main/kotlin/arrow/core/map.kt
Krishan14sharma
183,217,828
true
{"Kotlin": 2391225, "CSS": 152663, "JavaScript": 67900, "HTML": 23177, "Java": 4465, "Shell": 3043, "Ruby": 1598}
package arrow.core object MapInstances object SortedMapInstances
0
Kotlin
0
1
2b26976e1a8fbf29b7a3786074d56612440692a8
67
arrow
Apache License 2.0
09. WebData/09_00. Ex/ex01. WebView Coroutine/MainActivity.kt
JFrost-L
864,016,978
false
{"Kotlin": 201411}
package com.frost.ex01webview_coroutine import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import com.frost.ex01webview_coroutine.databinding.ActivityMainBinding import kotlinx.coroutines.* import java.io.BufferedReader import java.io.InputStream import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL import java.nio.charset.Charset class MainActivity : AppCompatActivity() { lateinit var binding:ActivityMainBinding val scope = CoroutineScope(Dispatchers.Main) //Main 스레드에서만 UI 상태 변경 가능 lateinit var requestQueue:RequestQueue override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) //initLayout() initLayout2() } private fun initLayout2() { requestQueue = Volley.newRequestQueue(this) binding.apply { button.setOnClickListener { progressBar.visibility=View.VISIBLE val stringRequest = StringRequest(//받고자 하는 타입의 request 객체 생성 Request.Method.GET, editText.text.toString(),//String 타입의 url 정보 Response.Listener {//성공시의 콜백함수 => 2번째 인자인 String 객체 그대로 들어옴 textView.text = String(it.toByteArray(Charsets.ISO_8859_1), Charsets.UTF_8) //인코딩 모드 변경해서 text에 저장 progressBar.visibility=View.GONE }, Response.ErrorListener {//실패시의 콜백함수 textView.text = it.message } ) requestQueue.add(stringRequest)//큐에 추가 } } } private fun initLayout() { binding.apply { Log.i("CheckScope", Thread.currentThread().name) // 메인 스레드에 해당 button.setOnClickListener { scope.launch {//시작 Log.i("CheckScope", Thread.currentThread().name)// 메인 스레드에 해당 progressBar.visibility = View.VISIBLE var data = "" withContext(Dispatchers.IO){//이미 await() 자동으로 갖음 data=loadNetwork(URL(editText.text.toString())) } /* CoroutineScope(Dispatchers.IO).async {//비동기식으로 코루틴 객체 생성 Log.i("CheckScope", Thread.currentThread().name) //DefaultDispacter 스레드에 해당 data=loadNetwork(URL(editText.text.toString())) }.await()//기다리라고 설정 */ textView.text = data progressBar.visibility=View.GONE } } } } fun loadNetwork(url: URL):String{ var result = "" val connect = url.openConnection() as HttpURLConnection//객체 생성 connect.connectTimeout=4000 connect.readTimeout = 1000 connect.requestMethod="GET" connect.connect() val responseCode = connect.responseCode if(responseCode==HttpURLConnection.HTTP_OK){ result = streamToString(connect.inputStream) } return result } private fun streamToString(inputStream: InputStream?): String { val bufferReader = BufferedReader(InputStreamReader(inputStream)) var line:String var result = "" try { do{ line = bufferReader.readLine() if(line!=null){ result+=line } }while(line!=null) Log.i("close", "Close") inputStream?.close() }catch(ex: Exception){ Log.e("error","읽기 실패") } return result } }
0
Kotlin
0
0
f11ef529db7e4738de521d934815857611c0f1a6
4,059
Mobile_Programming
MIT License
library/src/main/java/com/github/stevenrudenko/omnitext/OmniTextSpannableFactory.kt
StevenRudenko
309,694,387
false
null
package com.github.stevenrudenko.omnitext import android.content.Context import android.text.Spannable import android.text.SpannableString import android.text.Spanned import android.text.style.ClickableSpan import android.text.style.ImageSpan import android.view.View import androidx.annotation.VisibleForTesting import androidx.core.content.res.ResourcesCompat import com.github.stevenrudenko.omnitext.factory.SpanFactory import com.google.android.material.chip.ChipDrawable /** Used to parse and render within [Spannable]. */ class OmniTextSpannableFactory( private val context: Context, private val factories: Array<out SpanFactory> ) : Spannable.Factory() { var enabled: Boolean = true var listener: ((OmniSpan) -> Unit)? = null override fun newSpannable(source: CharSequence?): Spannable { if (!enabled) { return super.newSpannable(source) } val input = source ?: return source as Spannable val spans = search(input) val spannable = SpannableString(input) spans.forEach { val chip = createChipSpan(it) spannable.setSpan( ActionSpan(it), it.start, it.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) spannable.setSpan(chip, it.start, it.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } return spannable } private fun createChipSpan(span: OmniSpan): ImageSpan { val chip = ChipDrawable.createFromResource(context, R.xml.omni_chip) chip.text = span.text chip.chipIcon = if (span.icon > 0) ResourcesCompat.getDrawable(context.resources, span.icon, context.theme) else null chip.setBounds(0, 0, chip.intrinsicWidth, chip.intrinsicHeight) return ImageSpan(chip) } @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) fun search(text: CharSequence): Array<OmniSpan> { return filter(factories.map { it.search(text) } .reduce { acc, spans -> acc.plus(spans) }) } @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) fun filter(spans: Array<OmniSpan>): Array<OmniSpan> { return spans.filter { src -> val other = spans.filter { it.valid && src.start >= it.start && src.end <= it.end } if (other.isEmpty()) true else if (!src.valid) false else other.find { it.type < src.type } == null }.toTypedArray() } inner class ActionSpan( private val span: OmniSpan ) : ClickableSpan() { override fun onClick(v: View) { listener?.invoke(span) } } }
0
Kotlin
0
0
bf4717cb80b18b7b8aa724505aeda3f837f61f23
2,668
OmniText
Apache License 2.0
app/src/main/java/com/finderbar/jovian/viewholder/PostPhotoViewHolder.kt
finderbar
705,707,975
false
{"Kotlin": 665596, "Java": 45822}
package com.finderbar.jovian.viewholder import android.support.v4.app.FragmentManager import android.support.v7.app.AppCompatActivity import android.view.View import com.finderbar.jovian.ItemPostCallBack import com.finderbar.jovian.R import com.finderbar.jovian.adaptor.post.PhotoGridAdaptor import com.finderbar.jovian.adaptor.post.PostAdaptor import com.finderbar.jovian.databinding.ItemPostPhotoBinding import com.finderbar.jovian.fragments.post.PostTimeLinePhotoFragment import com.finderbar.jovian.models.PostImage import com.finderbar.jovian.models.Post import com.finderbar.jovian.utilities.android.SpacesItemDecoration import com.finderbar.jovian.utilities.assymetric.AsymmetricRecyclerViewAdapter import com.finderbar.jovian.utilities.assymetric.Utils import com.finderbar.jovian.utilities.photo.imageItemPresenterFor class PostPhotoViewHolder(val binding: ItemPostPhotoBinding) : PostAdaptor.ItemViewHolder(binding.root), ItemPostCallBack { fun bind(post: Post) { binding.post = post val images = getImages(post.postImages); val presenter = imageItemPresenterFor(images) val adaptor = PhotoGridAdaptor(this, post, presenter.item, presenter.maxDisplayItem, images.size) binding.recyclerGridView.setRequestedColumnCount(presenter.requestColumns) binding.recyclerGridView.isDebugging = true binding.recyclerGridView.isAllowReordering binding.recyclerGridView.requestedHorizontalSpacing = Utils.dpToPx(itemView.context, 0.0f) val dividerItemDecoration = SpacesItemDecoration(itemView.context.resources.getDimensionPixelSize(R.dimen.recycler_padding)) binding.recyclerGridView.addItemDecoration(dividerItemDecoration) binding.recyclerGridView.adapter = AsymmetricRecyclerViewAdapter(itemView.context, binding.recyclerGridView, adaptor) } private fun getImages(postImages: List<PostImage>): List<String> { val result = ArrayList<String>(); for (x in postImages.indices) { if(x >= 4) break result.add(postImages[x].url) } return result; } override fun onItemClick(view: View, position: Int, item: Post) { val manager: FragmentManager = (view.context as AppCompatActivity).supportFragmentManager val morePhotos = PostTimeLinePhotoFragment.newInstance(position, item) morePhotos.show(manager, "TimeLinePhotos") } }
0
Kotlin
0
0
fb71909023cd376fbb23ae69c0affd1c69b68bf6
2,417
finderbar-app
MIT License
kanashi-server/src/main/java/ink/anur/engine/prelog/ByteBufPreLogService.kt
anurnomeru
242,305,129
false
null
package ink.anur.engine.prelog import ink.anur.pojo.log.common.GenerationAndOffset import ink.anur.engine.StoreEngineFacadeService import ink.anur.engine.log.LogService import ink.anur.exception.LogException import ink.anur.inject.NigateBean import ink.anur.inject.NigateInject import ink.anur.inject.NigatePostConstruct import ink.anur.log.logitemset.ByteBufferLogItemSet import ink.anur.log.prelog.ByteBufPreLog import ink.anur.log.prelog.PreLogMeta import ink.anur.mutex.ReentrantReadWriteLocker import org.slf4j.LoggerFactory import java.util.concurrent.ConcurrentSkipListMap /** * Created by <NAME> on 2019/7/12 * * 负责写入预日志,并操作将预日志追加到日志中 */ @NigateBean class ByteBufPreLogService : ReentrantReadWriteLocker() { @NigateInject private lateinit var logService: LogService @NigateInject private lateinit var storeEngineFacadeService: StoreEngineFacadeService private val preLog: ConcurrentSkipListMap<Long, ByteBufPreLog> = ConcurrentSkipListMap() private val logger = LoggerFactory.getLogger(ByteBufPreLogService::class.java) /** * 当前已经提交的 offset */ private var commitOffset: GenerationAndOffset? = null /** * 预日志最后一个 offset */ private var preLogOffset: GenerationAndOffset? = null @NigatePostConstruct(dependsOn = "LogService") private fun init() { this.commitOffset = logService.getInitialGAO() this.preLogOffset = commitOffset logger.info("预日志初始化成功,预日志将由 {} 开始", commitOffset!!.toString()) } /** * 供 leader 写入使用, 仅供降级为 follower 时删除未提交的 gao */ fun cover(GAO: GenerationAndOffset) { writeLocker { commitOffset = GAO preLogOffset = GAO } } /** * 获取当前副本同步到的最新的 preLog GAO */ fun getPreLogGAO(): GenerationAndOffset { return readLockSupplierCompel { preLogOffset!! } } /** * 获取当前副本同步到的最新的 commit GAO */ fun getCommitGAO(): GenerationAndOffset { return readLockSupplierCompel { commitOffset!! } } /** * 此添加必须保证一次调用中,ByteBufferLogItemSet 所有的操作日志都在同一个世代,实际上也确实如此 */ fun append(generation: Long, byteBufferLogItemSet: ByteBufferLogItemSet) { writeLocker { /* 简单检查 */ if (generation < preLogOffset!!.generation) { logger.error("追加到预日志的日志 generation {} 小于当前预日志 generation {},追加失败!", generation, preLogOffset!!.getGeneration()) return@writeLocker } val byteBufPreLogOperated = preLog.compute(generation) { _, byteBufPreLog -> byteBufPreLog ?: ByteBufPreLog(generation) } val iterator = byteBufferLogItemSet.iterator() var lastOffset = -1L while (iterator.hasNext()) { val oao = iterator.next() val oaoOffset = oao.offset val thisGao = GenerationAndOffset(generation, oaoOffset) if (thisGao <= preLogOffset!!) { logger.error("追加到预日志的日志 offset $oaoOffset 小于当前预日志 offset ${preLogOffset!!.offset},追加失败!!") break } byteBufPreLogOperated!!.append(oao.logItem, oaoOffset) lastOffset = oaoOffset } if (lastOffset != -1L) { val before = preLogOffset preLogOffset = GenerationAndOffset(generation, lastOffset) logger.info("本地追加了预日志,由 {} 更新至 {}", before.toString(), preLogOffset.toString()) } } } /** * follower 将此 offset 往后的数据都从内存提交到本地 */ fun commit(GAO: GenerationAndOffset) { writeLocker { // 先与本地已经提交的记录做对比,只有大于本地副本提交进度时才进行commit val compareResult = GAO.compareTo(commitOffset) // 需要提交的进度小于等于preLogOffset if (compareResult <= 0) { return@writeLocker } else { val canCommit = readLockSupplierCompel { if (GAO > preLogOffset) preLogOffset else GAO } if (canCommit == commitOffset) { logger.debug("收到来自 Leader 节点的有效 commit 请求,本地预日志最大为 {} ,故可提交到 {} ,但本地已经提交此进度。", preLogOffset.toString(), canCommit!!.toString()) } else { logger.debug("收到来自 Leader 节点的有效 commit 请求,本地预日志最大为 {} ,故可提交到 {}", preLogOffset.toString(), canCommit!!.toString()) val preLogMeta = getBefore(canCommit) ?: throw LogException("有bug请注意排查!!,不应该出现这个情况") // 追加到磁盘 logService.appendForFollower(preLogMeta, canCommit.generation, preLogMeta.startOffset, preLogMeta.endOffset) // 强制刷盘 logService.activeLog().flush(preLogMeta.endOffset) logger.debug("本地预日志 commit 进度由 {} 更新至 {}", commitOffset.toString(), canCommit.toString()) commitOffset = canCommit discardBefore(canCommit) storeEngineFacadeService.coverCommittedProjectGenerationAndOffset(canCommit) } } } } /** * 获取当前这一条之前的预日志(包括这一条) */ private fun getBefore(GAO: GenerationAndOffset): PreLogMeta? { return this.readLockSupplier { val gen = GAO.generation val offset = GAO.offset val head = preLog.headMap(gen, true) if (head == null || head.size == 0) { throw LogException("获取预日志时:世代过小或者此世代还未有预日志") } val byteBufPreLog = head.firstEntry() .value byteBufPreLog.getBefore(offset) } } /** * 丢弃掉一些预日志消息(批量丢弃,包括这一条) */ private fun discardBefore(GAO: GenerationAndOffset) { this.writeLockSupplier { val gen = GAO.generation val offset = GAO.offset val head = preLog.headMap(gen, true) if (head == null || head.size == 0) { throw LogException("获取预日志时:世代过小或者此世代还未有预日志") } val byteBufPreLog = head.firstEntry() .value if (byteBufPreLog.discardBefore(offset)) preLog.remove(byteBufPreLog.generation) } } }
1
null
1
5
27db6442ef9d4abc594d7e7719a8c772f03e61b6
6,188
kanashi
MIT License
Android/app/src/main/java/com/didichuxing/doraemondemo/mc/NetMainActivity.kt
didi
144,705,602
false
{"Markdown": 26, "Ruby": 5, "Text": 5, "Ignore List": 26, "XML": 404, "OpenStep Property List": 14, "Objective-C": 804, "JSON": 140, "Objective-C++": 1, "C": 8, "Swift": 25, "HTML": 10, "JavaScript": 102, "Vue": 53, "CSS": 2, "Less": 2, "Shell": 19, "Gradle": 27, "Java Properties": 6, "Batchfile": 2, "EditorConfig": 1, "INI": 19, "Proguard": 15, "Java": 732, "Kotlin": 517, "AIDL": 2, "C++": 3, "CMake": 1, "YAML": 3, "Dart": 42, "JSON with Comments": 1}
package com.didichuxing.doraemondemo.mc import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView import com.didichuxing.doraemondemo.R import kotlinx.coroutines.* import okhttp3.* import java.io.IOException class NetMainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_net_main) } override fun onResume() { super.onResume() request() } fun request() { val httpRequest = Request.Builder() .header("User-Agent", "mc-test") .url("https://www.tianqiapi.com/free/week?appid=68852321&appsecret=BgGLDVc7") .build() val client = OkHttpClient.Builder().build() client.newCall(httpRequest).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { GlobalScope.launch(Dispatchers.Main) { val view = findViewById<TextView>(R.id.text) view.text = e.message } } override fun onResponse(call: Call, response: Response) { GlobalScope.launch(Dispatchers.Main) { val text: String? = response.body()?.string() val view = findViewById<TextView>(R.id.text) view.text = text } } }) } }
252
Java
3074
20,003
166a1a92c6fd509f6b0ae3e8dd9993f631b05709
1,483
DoKit
Apache License 2.0
build-tools/gradle-core-configuration/configuration-cache/src/main/kotlin/org/gradle/configurationcache/extensions/TaskInternalExtensions.kt
RivanParmar
526,653,590
false
null
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.configurationcache.extensions import org.gradle.api.Project import org.gradle.api.internal.GradleInternal import org.gradle.api.internal.TaskInternal import org.gradle.api.internal.project.ProjectInternal import org.gradle.internal.service.ServiceRegistry internal inline fun <reified T : Any> TaskInternal.serviceOf(): T = project.serviceOf() inline fun <reified T : Any> Project.serviceOf(): T = (this as ProjectInternal).services.get() inline fun <reified T : Any> GradleInternal.serviceOf(): T = services.get() inline fun <reified T : Any> ServiceRegistry.get(): T = this[T::class.java]!!
2,663
null
4552
17
8fb2bb1433e734aa9901184b76bc4089a02d76ca
1,254
androlabs
Apache License 2.0
src/main/day03/Day03.kt
FlorianGz
573,204,597
false
{"Kotlin": 8491}
package main.day03 import readInput fun main() { val elfBags = readInput("main/day03/day03") fun part1(): Int { return elfBags.map { val (bagPart1, bagPart2) = it.chunked(size = (it.length) / 2) bagPart1.first { bagItem -> bagPart2.contains(bagItem) } }.sumOf { it.toPriority() } } fun part2(): Int { return elfBags.chunked(3) .map { group -> val (bag1, bag2, bag3) = group bag1.first { bagItem -> bag2.contains(bagItem) && bag3.contains(bagItem) } }.sumOf { it.toPriority() } } println(part1()) println(part2()) } private fun Char.toPriority(): Int { return if (isLowerCase()) this - 'a' + 1 else this - 'A' + 27 }
0
Kotlin
0
0
58c9aa8fdec77c25a9d9945ca8e77ecd1170321b
757
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/no/nav/lydia/exceptions/AzureException.kt
navikt
444,072,054
false
null
package no.nav.lydia.exceptions class AzureException(message: String?, e: Exception) : RuntimeException(message, e)
0
Kotlin
0
2
4026bea42d89710f23d52baaab4d19d592f247da
117
lydia-api
MIT License