path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/tomclaw/drawa/util/SchedulersFactory.kt
solkin
62,579,229
false
{"Kotlin": 201724, "Java": 39209}
package com.tomclaw.drawa.util import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers interface SchedulersFactory { fun io(): Scheduler fun single(): Scheduler fun trampoline(): Scheduler fun mainThread(): Scheduler } class SchedulersFactoryImpl : SchedulersFactory { override fun io(): Scheduler { return Schedulers.io() } override fun single(): Scheduler { return Schedulers.single() } override fun trampoline(): Scheduler { return Schedulers.trampoline() } override fun mainThread(): Scheduler { return AndroidSchedulers.mainThread() } }
1
Kotlin
6
22
131f0ef2a9ea88854f18ecef2250d5396da225e2
707
drawa-android
Apache License 2.0
src/nativeTest/kotlin/io/github/krisbitney/wasmtime/wasm/MemoryTypeTest.kt
krisbitney
625,042,873
false
null
package io.github.krisbitney.wasmtime.wasm import kotlinx.cinterop.pointed import wasmtime.wasm_memorytype_limits import kotlin.test.* class MemoryTypeTest { private val simpleMemoryType = MemoryType(Limits(1u, 10u)) @Test fun testAllocateCValue() { val cMemoryType = MemoryType.allocateCValue(simpleMemoryType) assertNotNull(cMemoryType) assertNotEquals(cMemoryType.rawValue.toLong(), 0) val cLimits = wasm_memorytype_limits(cMemoryType) assertNotNull(cLimits) assertNotEquals(cLimits.rawValue.toLong(), 0) assertEquals(simpleMemoryType.limits.min, cLimits.pointed.min) assertEquals(simpleMemoryType.limits.max, cLimits.pointed.max) val memoryType = MemoryType(cMemoryType) assertEquals(simpleMemoryType.limits.min, memoryType.limits.min) assertEquals(simpleMemoryType.limits.max, memoryType.limits.max) } @Test fun testDeleteCValue() { val cMemoryType = MemoryType.allocateCValue(simpleMemoryType) assertNotNull(cMemoryType) assertNotEquals(cMemoryType.rawValue.toLong(), 0) MemoryType.deleteCValue(cMemoryType) } }
0
Kotlin
0
0
da0993556a50573f257ce157ae88faeff4d18ca4
1,173
wasmtime-kotlin
MIT License
app/src/main/java/com/fredrikbogg/android_chat_app/data/db/remote/FirebaseStorageSource.kt
dgewe
288,984,096
false
null
package com.fredrikbogg.android_chat_app.data.db.remote import android.net.Uri import com.google.android.gms.tasks.Task import com.google.firebase.storage.FirebaseStorage // Task based class FirebaseStorageSource { private val storageInstance = FirebaseStorage.getInstance() fun uploadUserImage(userID: String, bArr: ByteArray): Task<Uri> { val path = "user_photos/$userID/profile_image" val ref = storageInstance.reference.child(path) return ref.putBytes(bArr).continueWithTask { ref.downloadUrl } } }
0
null
35
87
cff2f947a4496e46cbaa750b4e3fa768ba2308f0
562
Chat-App-Android
MIT License
Android/HumanActivityRecognition/app/src/main/java/com/example/humanactivityrecognition/ui/RecognitionAdapter.kt
phuoctan4141
462,199,972
false
null
package com.example.mlapp.ui import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.example.mlapp.data.Recognition import com.example.mlapp.databinding.RecognitionItemBinding class RecognitionAdapter(private val ctx: Context) : ListAdapter<Recognition, RecognitionViewHolder>(RecognitionDiffUtil()) { /** * Inflating the ViewHolder with recognition_item layout and data binding */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecognitionViewHolder { val inflater = LayoutInflater.from(ctx) val binding = RecognitionItemBinding.inflate(inflater, parent, false) return RecognitionViewHolder(binding) } // Binding the data fields to the RecognitionViewHolder override fun onBindViewHolder(holder: RecognitionViewHolder, position: Int) { holder.bindTo(getItem(position)) } private class RecognitionDiffUtil : DiffUtil.ItemCallback<Recognition>() { override fun areItemsTheSame(oldItem: Recognition, newItem: Recognition): Boolean { return oldItem.label == newItem.label } override fun areContentsTheSame(oldItem: Recognition, newItem: Recognition): Boolean { return oldItem.confidence == newItem.confidence } } } class RecognitionViewHolder(private val binding: RecognitionItemBinding) : RecyclerView.ViewHolder(binding.root) { // Binding all the fields to the view - to see which UI element is bind to which field, check // out layout/recognition_item.xml fun bindTo(recognition: Recognition) { binding.recognitionItem = recognition binding.executePendingBindings() } }
1
null
2
8
51f119e46a16a010f34f6b27c7356177d7fdc126
1,862
A-FUSED-TFLITE-LSTM-MODEL
Apache License 2.0
tests/test-kotlin/src/test/kotlin/org/example/order/Order.kt
ebean-orm
5,793,895
false
null
package org.example.order import javax.persistence.CascadeType import javax.persistence.Entity import javax.persistence.Id import javax.persistence.ManyToOne import javax.persistence.OneToMany import javax.persistence.Table import javax.persistence.Version @Entity @Table(name = "t_order") class Order( customer: Customer, ) { @Id val id: Long = 0 @ManyToOne val customer: Customer = customer @OneToMany(mappedBy = "order", cascade = [CascadeType.ALL], orphanRemoval = true) val items: MutableList<OrderItem> = mutableListOf() @Version val version: Long = 0 }
75
Java
251
1,401
76d85adc98a77ed08db6458d34b397d287afc783
583
ebean
Apache License 2.0
java/java-tests/testSrc/com/intellij/codeInspection/ex/InspectionSchemeTest.kt
androidports
115,100,208
true
{"Java": 168074327, "Python": 25851822, "Kotlin": 6237300, "Groovy": 3448233, "HTML": 1962706, "C": 214338, "C++": 180382, "CSS": 172743, "JavaScript": 148969, "Lex": 148787, "XSLT": 113040, "Jupyter Notebook": 93222, "Shell": 60321, "NSIS": 57796, "Batchfile": 51257, "Roff": 37534, "Objective-C": 27309, "TeX": 25473, "AMPL": 20665, "TypeScript": 9469, "J": 5050, "PHP": 2699, "Makefile": 2352, "Thrift": 1846, "CoffeeScript": 1759, "CMake": 1675, "Ruby": 1217, "Perl": 962, "Smalltalk": 906, "C#": 696, "AspectJ": 182, "Visual Basic": 77, "HLSL": 57, "Erlang": 10}
/* * Copyright 2000-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 com.intellij.codeInspection.ex import com.intellij.configurationStore.SchemeManagerFactoryBase import com.intellij.openapi.application.ApplicationManager import com.intellij.testFramework.InMemoryFsRule import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.runInInitMode import com.intellij.util.readText import com.intellij.util.write import org.assertj.core.api.Assertions.assertThat import org.junit.ClassRule import org.junit.Rule import org.junit.Test internal class InspectionSchemeTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule() } @JvmField @Rule val fsRule = InMemoryFsRule() @Test fun loadSchemes() { val schemeFile = fsRule.fs.getPath("inspection/Bar.xml") val schemeData = """ <inspections profile_name="Bar" version="1.0"> <option name="myName" value="Bar" /> <inspection_tool class="Since15" enabled="true" level="ERROR" enabled_by_default="true" /> "</inspections>""".trimIndent() schemeFile.write(schemeData) val schemeManagerFactory = SchemeManagerFactoryBase.TestSchemeManagerFactory(fsRule.fs.getPath("")) val profileManager = ApplicationInspectionProfileManager(InspectionToolRegistrar.getInstance(), schemeManagerFactory, ApplicationManager.getApplication().messageBus) profileManager.forceInitProfiles(true) profileManager.initProfiles() assertThat(profileManager.profiles).hasSize(1) val scheme = profileManager.profiles.first() as InspectionProfileImpl assertThat(scheme.name).isEqualTo("Bar") runInInitMode { scheme.initInspectionTools(null) } schemeManagerFactory.save() assertThat(schemeFile.readText()).isEqualTo(schemeData) profileManager.profiles } }
6
Java
1
4
6e4f7135c5843ed93c15a9782f29e4400df8b068
2,540
intellij-community
Apache License 2.0
RoomWordSample/app/src/main/java/com/example/roomwordsample/WordRepository.kt
jirois
217,171,472
true
{"Kotlin": 396065}
package com.example.roomwordsample import androidx.lifecycle.LiveData class WordRepository(private val wordDao: WordDao) { // Used the LiveData in order to notify the observer when the data changed val allWords : LiveData<List<Word>> = wordDao.getAlphabetizedWords() suspend fun insert(word: Word){ wordDao.insert(word) } }
0
Kotlin
0
0
34f7fde40a2a857c2f17f69d5a00790f154aa19d
353
android-kotlin-fundamentals-starter-apps
Apache License 2.0
legacy/demos/demo-shared/src/commonMain/kotlin/design/ThemeSelector.kt
CLOVIS-AI
582,955,979
false
{"Kotlin": 313151, "JavaScript": 1822, "Dockerfile": 1487, "HTML": 372, "CSS": 280}
package opensavvy.decouple.demo.theming import androidx.compose.runtime.Composable import opensavvy.decouple.core.atom.ActionButton import opensavvy.decouple.core.atom.Button import opensavvy.decouple.core.atom.Text import opensavvy.decouple.core.layout.Row import opensavvy.decouple.core.layout.Screen import opensavvy.decouple.core.theme.Theme @Composable fun ThemeSelector( available: List<Theme>, recommended: List<Theme>, current: Theme, setCurrent: (Theme) -> Unit, ) = Screen("Themes") { Text( "It is often necessary to provide visual differences between instances of an application, " + "without going as far as creating a entirely new style. For example, some users may prefer white text " + "on a dark background, or you may want to adapt the colors of the application to your brand or your " + "client's." ) Text( "Themes are a set of design tokens to allow all components of the app to speak the same design " + "language, even if they are created by entirely different teams. All components work in term of “the " + "primary color” and not in term of hard-coded values. Artists and designers can edit the values of the " + "theme without needing to know programming." ) Text( "An application can embark as many themes as you deem necessary: you can create some yourself, or " + "use some procedural generation to create new themes tailored to the user on-the-fly." ) Text("This version of the documentation app is compatible with the following themes:") Row { for (theme in available) { if (theme in recommended) { ActionButton( onClick = { setCurrent(theme) }, enabled = theme != current, ) { Text(theme.name) } } else { Button( onClick = { setCurrent(theme) }, enabled = theme != current, ) { Text(theme.name) } } } } Text( "The highlighted themes are recommended by the style you're currently using. The other themes were " + "created for other styles, and may or may not look good with the current style." ) }
0
Kotlin
0
2
c00928e09c01da9754f968a54cb87daa556186f0
2,417
Decouple
Apache License 2.0
modules/feature/feature_dashboard/src/main/kotlin/kekmech/ru/feature_dashboard/items/SearchFieldItem.kt
tonykolomeytsev
203,239,594
false
null
package kekmech.ru.feature_dashboard.items import kekmech.ru.coreui.items.ClickableAdapterItem import kekmech.ru.feature_dashboard.R object SearchFieldItem class SearchFieldAdapterItem( onClickListener: (SearchFieldItem) -> Unit ) : ClickableAdapterItem<SearchFieldItem>( isType = { it is SearchFieldItem }, layoutRes = R.layout.item_search_field, onClickListener = onClickListener )
9
null
4
21
4ad7b2fe62efb956dc7f8255d35436695643d229
403
mpeiapp
MIT License
hoplite-aws/src/main/kotlin/com/sksamuel/hoplite/aws/RegionDecoder.kt
mduesterhoeft
233,792,930
true
{"Kotlin": 194619, "Shell": 126}
package com.sksamuel.hoplite.aws import arrow.core.Try import arrow.core.invalid import com.amazonaws.regions.Region import com.amazonaws.regions.Regions import com.sksamuel.hoplite.ConfigFailure import com.sksamuel.hoplite.ConfigResult import com.sksamuel.hoplite.DecoderContext import com.sksamuel.hoplite.StringNode import com.sksamuel.hoplite.Node import com.sksamuel.hoplite.arrow.toValidated import com.sksamuel.hoplite.decoder.NonNullableDecoder import kotlin.reflect.KType class RegionDecoder : NonNullableDecoder<Region> { override fun supports(type: KType): Boolean = type.classifier == Region::class override fun safeDecode(node: Node, type: KType, context: DecoderContext): ConfigResult<Region> { fun regionFromName(name: String): ConfigResult<Region> = Try { Region.getRegion(Regions.fromName(name)) } .toValidated { ConfigFailure.Generic("Cannot create region from $name") } return when (node) { is StringNode -> regionFromName(node.value) else -> ConfigFailure.DecodeError(node, type).invalid() } } }
0
null
0
0
eb2a3429c39969e559231e9d6aec769efdea94ec
1,121
hoplite
Apache License 2.0
local_libs/lib-bumblebee/src/main/kotlin/gov/cdc/hl7/bumblebee/HL7JsonTransformer.kt
CDCgov
510,836,864
false
null
package gov.cdc.hl7.bumblebee import com.google.gson.* import gov.cdc.hl7.HL7ParseUtils import gov.cdc.hl7.bumblebee.StringUtils.Companion.normalize import gov.cdc.hl7.model.HL7Hierarchy class HL7JsonTransformer(val profile: Profile, val fieldProfile: Profile, val hl7Parser: HL7ParseUtils) { companion object { val gson = GsonBuilder().serializeNulls().create() //Factory Method @JvmStatic fun getTransformerWithResource( message: String, profileFilename: String, fieldProfileFileName: String = "/DefaultFieldsProfileSimple.json" ): HL7JsonTransformer { val profContent = HL7JsonTransformer::class.java.getResource("/$profileFilename").readText() val profile: Profile = gson.fromJson(profContent, Profile::class.java) val fieldProfContent = HL7JsonTransformer::class.java.getResource(fieldProfileFileName).readText() val fieldProfile: Profile = gson.fromJson(fieldProfContent, Profile::class.java) val parser = HL7ParseUtils.getParser(message, profileFilename) return HL7JsonTransformer(profile, fieldProfile, parser) } } fun transformMessage(): JsonObject { val fullHL7 = JsonObject() val msg = hl7Parser.msgHierarchy() msg.children().foreach { processMsgSeg(it, fullHL7) } //Fix MSH-1 and 2: val msh =fullHL7.get("MSH").asJsonObject msh.addProperty("file_separator", "|") msh.addProperty("encoding_characters", "^~\\&") return fullHL7 } private fun getValueFromMessage(arrayVal: List<String>?, fieldNbr: Int, fieldIndexSkew: Int = 0): String? { return if (arrayVal!= null && arrayVal.size > (fieldNbr - fieldIndexSkew)) arrayVal[fieldNbr - fieldIndexSkew] else null } private fun processMsgSeg(seg: HL7Hierarchy, parentJson: JsonElement) { //Prepare Json Node for Segment: val segID = seg.segment().substring(0,3) val segJson = JsonObject() if (parentJson.isJsonObject) parentJson.asJsonObject.add(segID, segJson) else { val segArrayJson = JsonObject() segArrayJson.add(segID, segJson) parentJson.asJsonArray.add(segArrayJson) } //Prepare elements of this segment val segArray = seg.segment().split("|") // val fieldIndexSkew = if (segID == "MSH") 1 else 0 profile.getSegmentField(segID)?.forEach { segField -> //Add A JsonObject if max cardinality is 1, array otherwise. var fieldJsonNode = if (getCardinality(segField.cardinality) == "1") JsonObject() else { JsonArray() } segJson.add(segField.name.normalize(), fieldJsonNode) //Get the value of this field from Message.... val fieldVal = getValueFromMessage(segArray, segField.fieldNumber, if (segID == "MSH") 1 else 0) //Is this field defined with components? //For OBX-5, use OBX 2 as the data type. Everything else, use segField val dataTypeToUse = if (segID == "OBX" && segField.fieldNumber == 5) segArray[2] else segField.dataType val components = fieldProfile.getSegmentField(dataTypeToUse) val fieldRepeat = fieldVal?.split("~") if (components == null) { //No components - it's primitive, just add value! if (fieldJsonNode.isJsonObject) { segJson.addValueOrNull(fieldRepeat?.get(0), segField.name) fieldJsonNode.asJsonObject.addProperty(segField.name.normalize(), fieldRepeat?.get(0)) } else if (fieldRepeat != null && fieldRepeat[0].isNotEmpty()) { fieldRepeat.forEach { element -> fieldJsonNode.asJsonArray.add(element) } } } else { fieldRepeat?.forEach { fieldRepeatItem -> val compJsonObj = JsonObject() val compArray = fieldRepeatItem.split("^") var compHasValue:Boolean = false components.forEach { component -> val compVal = getValueFromMessage(compArray, component.fieldNumber -1 ) compHasValue = compHasValue || (!compVal.isNullOrEmpty() && compVal.replace("&", "").trim() != null) //Handle subcomponents... val subComponents = fieldProfile.getSegmentField(component.dataType) if (!subComponents.isNullOrEmpty()) { val subCompJsonObj = JsonObject() val subCompArray = compVal?.split("&") var subHasValue: Boolean = false subComponents.forEach { subComp -> val subCompVal = getValueFromMessage(subCompArray, subComp.fieldNumber - 1) subCompJsonObj.addValueOrNull(subCompVal, subComp.name) subHasValue = subHasValue || subCompVal != null } if (subHasValue) compJsonObj.add(component.name.normalize(), subCompJsonObj) else compJsonObj.add(component.name.normalize(), JsonNull.INSTANCE) } else { compJsonObj.addValueOrNull(compVal, component.name) } } if (fieldJsonNode.isJsonArray && compHasValue) fieldJsonNode.asJsonArray.add(compJsonObj) else { if (compHasValue) { segJson.add(segField.name.normalize(), compJsonObj) fieldJsonNode = compJsonObj } else segJson.add(segField.name.normalize(), JsonNull.INSTANCE) } } } //Fix empty JsonNode if no values were found. if ((fieldJsonNode.isJsonObject && fieldJsonNode.asJsonObject.size() == 0)) segJson.add(segField.name.normalize(), JsonNull.INSTANCE) } if (!seg.children().isEmpty) { val childArray = JsonArray() segJson.add("children", childArray) seg.children().foreach { childSeg -> processMsgSeg(childSeg, childArray) } } } private fun getCardinality(cardinality: String): String { val end = try { cardinality.substring(cardinality.indexOf("..")+2, cardinality.length -1) }catch (e: StringIndexOutOfBoundsException) { "UNK" } return if (end == "*") "*" else try { "${end.toInt()}" } catch (e: NumberFormatException) { "?" } } fun JsonObject.addValueOrNull(value: String?, name: String) { if (!value.isNullOrEmpty()) this.addProperty(name.normalize(), value) else this.add(name.normalize(),JsonNull.INSTANCE) } }
126
null
14
9
e719565dc2d2ce837b8c5929f155b0e2416fc44d
7,354
data-exchange-hl7
Apache License 2.0
app/src/main/java/com/example/jetpack_compose_all_in_one/ui/components/NavigationDrawerMain.kt
myofficework000
626,474,700
false
{"Kotlin": 1392414}
package com.example.jetpack_compose_all_in_one.ui.components import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.basicMarquee import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.DrawerState import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalDrawerSheet import androidx.compose.material3.ModalNavigationDrawer import androidx.compose.material3.NavigationDrawerItem import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.State import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.example.jetpack_compose_all_in_one.ui.theme.dp_16 import com.example.jetpack_compose_all_in_one.ui.theme.dp_8 import com.example.jetpack_compose_all_in_one.ui.theme.sp_32 import com.example.jetpack_compose_all_in_one.ui.theme.spaceLarge import com.example.jetpack_compose_all_in_one.ui.views.theming.ThemeSettingsRow import com.example.jetpack_compose_all_in_one.ui.views.theming.ThemeViewModel import com.example.jetpack_compose_all_in_one.utils.navigation.NavDes import com.example.jetpack_compose_all_in_one.utils.navigation.NavigationCategoryData import com.example.jetpack_compose_all_in_one.utils.navigation.NavigationDrawerData // content is most likely a Scaffold. So no padding needed. @Composable fun NavigationDrawerMain( navController: NavController, currentRoute: MutableState<NavDes>, drawerState: DrawerState, noSwiping: State<Boolean>, themeViewModel: ThemeViewModel, closeDrawerFunc: () -> Unit, content: @Composable () -> Unit ) { ModalNavigationDrawer( drawerState = drawerState, drawerContent = { ModalDrawerSheet { DrawerHeader() ScrollableColumn( Modifier.weight(1f).padding(horizontal = dp_16) ) { NavDes.drawerList.forEach { DrawerCategoryAndItem(it) { des -> des.data as NavigationDrawerData // This is for smart casting navController.navigate(des.data.route) currentRoute.value = des closeDrawerFunc() } } } ThemeSettingsRow(vm = themeViewModel, Modifier.padding(16.dp)) } }, gesturesEnabled = if (noSwiping.value) drawerState.isOpen else true ) { content() } } @OptIn(ExperimentalFoundationApi::class) @Composable private fun DrawerCategoryAndItem( item: NavDes, onItemClick: (NavDes) -> Unit ) { if (item.data is NavigationCategoryData) { ExpandableContent({ Text( item.data.displayName, Modifier.padding(ButtonDefaults.TextButtonContentPadding) .basicMarquee(), MaterialTheme.colorScheme.onSurfaceVariant ) }) { item.data.items.forEach { DrawerCategoryAndItem(it, onItemClick) } } } else { item.data as NavigationDrawerData // This is for smart casting Text( item.data.displayText, Modifier.padding(ButtonDefaults.TextButtonContentPadding) .fillMaxWidth() .basicMarquee() .clickable { onItemClick(item) }, MaterialTheme.colorScheme.onSurfaceVariant ) } } @Composable private fun DrawerHeader() { Box( modifier = Modifier .fillMaxWidth() .padding(vertical = spaceLarge), contentAlignment = Alignment.Center ) { Text(text = "Header", fontSize = sp_32) } }
9
Kotlin
9
222
4de5418608d6917b5c97fac7d868454c424daa26
4,204
Jetpack-Compose-All-in-one-Guide
MIT License
plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/completion/MavenCoordinateCompletionContributor.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.dom.model.completion import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.progress.runBlockingCancellable import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.xml.XmlTag import com.intellij.psi.xml.XmlText import com.intellij.util.xml.DomManager import com.intellij.util.xml.GenericDomValue import org.jetbrains.idea.maven.dom.converters.MavenDependencyCompletionUtil import org.jetbrains.idea.maven.dom.model.MavenDomShortArtifactCoordinates import org.jetbrains.idea.maven.dom.model.completion.insert.MavenDependencyInsertionHandler import org.jetbrains.idea.maven.onlinecompletion.model.MavenRepositoryArtifactInfo import org.jetbrains.idea.maven.utils.MavenUtil import org.jetbrains.idea.reposearch.DependencySearchService import org.jetbrains.idea.reposearch.DependencySearchService.Companion.getInstance import org.jetbrains.idea.reposearch.RepositoryArtifactData import org.jetbrains.idea.reposearch.SearchParameters import java.util.concurrent.ConcurrentHashMap import java.util.function.Consumer import java.util.function.Predicate abstract class MavenCoordinateCompletionContributor protected constructor(private val myTagId: String) : CompletionContributor() { override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) { if (parameters.completionType != CompletionType.BASIC) return val placeChecker = MavenCoordinateCompletionPlaceChecker(myTagId, parameters).checkPlace() if (placeChecker.isCorrectPlace) { val coordinates = placeChecker.coordinates!! val completionPrefix = CompletionUtil.findReferenceOrAlphanumericPrefix(parameters) val amendedResult = amendResultSet(result) runBlockingCancellable { val resultFilter = resultFilter() find(getInstance(placeChecker.project!!), coordinates, parameters) { if (resultFilter.accept(it)) { fillResults(amendedResult, coordinates, it, completionPrefix) } } fillAfter(amendedResult) } } } protected open fun resultFilter(): MavenCoordinateCompletionResultFilter = MavenCoordinateCompletionResultFilter.ACCEPT_ALL protected open fun fillResults(result: CompletionResultSet, coordinates: MavenDomShortArtifactCoordinates, item: RepositoryArtifactData, completionPrefix: String) { if (item is MavenRepositoryArtifactInfo) { fillResult(coordinates, result, item, completionPrefix) } } protected fun createSearchParameters(parameters: CompletionParameters): SearchParameters { return SearchParameters(parameters.invocationCount < 2, MavenUtil.isMavenUnitTestModeEnabled()) } protected abstract suspend fun find(service: DependencySearchService, coordinates: MavenDomShortArtifactCoordinates, parameters: CompletionParameters, consumer: Consumer<RepositoryArtifactData>) protected open fun fillAfter(result: CompletionResultSet) { } protected open fun fillResult(coordinates: MavenDomShortArtifactCoordinates, result: CompletionResultSet, item: MavenRepositoryArtifactInfo, completionPrefix: String) { val lookup: LookupElement = MavenDependencyCompletionUtil.lookupElement(item) .withInsertHandler(MavenDependencyInsertionHandler.INSTANCE) lookup.putUserData(MAVEN_COORDINATE_COMPLETION_PREFIX_KEY, completionPrefix) result.addElement(lookup) } protected open fun amendResultSet(result: CompletionResultSet): CompletionResultSet { result.restartCompletionWhenNothingMatches() return result } protected fun <T> withPredicate(consumer: Consumer<in T>, predicate: Predicate<in T>): Consumer<T> { return Consumer { it: T -> if (predicate.test(it)) { consumer.accept(it) } } } protected fun isCorrectPlace(parameters: CompletionParameters) = MavenCoordinateCompletionPlaceChecker(myTagId, parameters).checkPlace().isCorrectPlace companion object { val MAVEN_COORDINATE_COMPLETION_PREFIX_KEY: Key<String> = Key.create("MAVEN_COORDINATE_COMPLETION_PREFIX_KEY") fun trimDummy(value: String?): String { if (value == null) { return "" } return StringUtil.trim(value.replace(CompletionUtil.DUMMY_IDENTIFIER, "").replace(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED, "")) } } } interface MavenCoordinateCompletionResultFilter { fun accept(item: RepositoryArtifactData): Boolean companion object { val ACCEPT_ALL: MavenCoordinateCompletionResultFilter = object : MavenCoordinateCompletionResultFilter { override fun accept(item: RepositoryArtifactData) = true } fun uniqueProperty(property: (MavenRepositoryArtifactInfo) -> String): MavenCoordinateCompletionResultFilter { return object : MavenCoordinateCompletionResultFilter { val existing = ConcurrentHashMap<String, Boolean>() override fun accept(item: RepositoryArtifactData): Boolean { return item is MavenRepositoryArtifactInfo && null == existing.putIfAbsent(property(item), true) } } } } } internal class MavenCoordinateCompletionPlaceChecker(private val myTagId: String, private val myParameters: CompletionParameters) { private var badPlace = false var project: Project? = null private set var coordinates: MavenDomShortArtifactCoordinates? = null private set val isCorrectPlace: Boolean get() = !badPlace fun checkPlace(): MavenCoordinateCompletionPlaceChecker { if (myParameters.completionType != CompletionType.BASIC) { badPlace = true return this } val element = myParameters.position val xmlText = element.parent if (xmlText !is XmlText) { badPlace = true return this } val tagElement = xmlText.getParent() if (tagElement !is XmlTag) { badPlace = true return this } if (myTagId != tagElement.name) { badPlace = true return this } project = element.project when (myTagId) { "artifactId", "groupId", "version" -> checkPlaceForChildrenTags(tagElement) "dependency", "extension", "plugin" -> checkPlaceForParentTags(tagElement) else -> badPlace = true } return this } private fun checkPlaceForChildrenTags(tag: XmlTag) { val domElement = DomManager.getDomManager(project).getDomElement(tag) if (domElement !is GenericDomValue<*>) { badPlace = true return } val parent = domElement.getParent() if (parent is MavenDomShortArtifactCoordinates) { coordinates = parent } else { badPlace = true } } private fun checkPlaceForParentTags(tag: XmlTag) { val domElement = DomManager.getDomManager(project).getDomElement(tag) if (domElement is MavenDomShortArtifactCoordinates) { coordinates = domElement } else { badPlace = true } } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
7,469
intellij-community
Apache License 2.0
app/src/main/java/com/jpgsolution/youcongresspersonmvvm/model/data/congressPersonDetail/UltimoStatus.kt
jeremias-Pereira
480,959,206
false
{"Kotlin": 18628}
package com.jpgsolution.youcongresspersonmvvm.model.data.congressPersonDetail data class UltimoStatus( val email: String, val gabinete: Gabinete, val id: Int, val nomeEleitoral: String, val siglaPartido: String, val siglaUf: String, val urlFoto: String )
0
Kotlin
0
0
680ef98ce5032ad0485be7d03b223b3089d1eeee
284
your-congressperson-MVVM
Apache License 2.0
android/engine/src/main/java/org/smartregister/fhircore/engine/domain/model/RuleConfig.kt
opensrp
339,242,809
false
null
/* * Copyright 2021 Ona Systems, 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 org.smartregister.fhircore.engine.domain.model import kotlinx.serialization.Serializable @Serializable data class RuleConfig( val name: String, val description: String = "", val priority: Int = 1, val condition: String = "true", // Default to always execute the action val actions: List<String> )
192
null
56
56
64a55e6920cb6280cf02a0d68152d9c03266518d
920
fhircore
Apache License 2.0
library/src/main/kotlin/io/github/wax911/library/persistedquery/PersistedQueryHashCalculator.kt
AniTrend
128,179,094
false
null
package io.github.wax911.library.persistedquery import android.content.Context import io.github.wax911.library.annotation.processor.GraphProcessor import io.github.wax911.library.annotation.processor.contract.AbstractGraphProcessor import java.math.BigInteger import java.security.MessageDigest import java.util.* /** * Utility class for calculating SHA256 hashes based off of the .graphql files held in memory by * [io.github.wax911.library.annotation.processor.GraphProcessor] * * @param context A context used to obtain an instance of [GraphProcessor] */ @Deprecated( "Consider migrating to AutomaticPersistedQueryCalculator instead", ReplaceWith( "AutomaticPersistedQueryCalculator", "io.github.wax911.library.persisted.query.AutomaticPersistedQueryCalculator" ) ) class PersistedQueryHashCalculator(context: Context) { private val apqHashes: MutableMap<String, String> by lazy { HashMap<String, String>() } private val graphProcessor: AbstractGraphProcessor by lazy { GraphProcessor.getInstance(context.assets) } fun getOrCreateAPQHash(queryName: String): String? { val fileKey = "$queryName${graphProcessor.defaultExtension}" return if(apqHashes.containsKey(fileKey)){ apqHashes[fileKey] } else{ createAndStoreHash(queryName, fileKey) } } private fun createAndStoreHash(queryName: String, fileKey: String): String? { graphProcessor.logger.d(TAG, "Creating hash for $queryName") return if (graphProcessor.graphFiles.containsKey(fileKey)) { val hashOfQuery = hashOfQuery(graphProcessor.graphFiles.getValue(fileKey)) graphProcessor.logger.d(TAG, "Created ") apqHashes[fileKey] = hashOfQuery hashOfQuery } else { graphProcessor.logger.e(TAG, "The request query $fileKey could not be found!") graphProcessor.logger.e(TAG, "Current size of graphFiles -> size: ${graphProcessor.graphFiles.size}") null } } private fun hashOfQuery(query: String): String { val md = MessageDigest.getInstance(sha256Algorithm) md.update(query.toByteArray()) val digest = md.digest() return String.format("%064x", BigInteger(1, digest)) } companion object { private val TAG = PersistedQueryHashCalculator::class.java.simpleName private const val sha256Algorithm = "SHA-256" } }
0
Kotlin
13
108
c733e613dc1e0a18b571b16d7cfb474901781fa0
2,488
retrofit-graphql
Apache License 2.0
ui-tests/tst/software/aws/toolkits/jetbrains/uitests/fixtures/AwsExplorer.kt
JetBrains
223,485,227
false
null
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.uitests.fixtures import com.intellij.remoterobot.RemoteRobot import com.intellij.remoterobot.data.RemoteComponent import com.intellij.remoterobot.fixtures.CommonContainerFixture import com.intellij.remoterobot.fixtures.ComponentFixture import com.intellij.remoterobot.fixtures.FixtureName import com.intellij.remoterobot.search.locators.byXpath import com.intellij.remoterobot.stepsProcessing.step import java.time.Duration fun IdeaFrame.awsExplorer( timeout: Duration = Duration.ofSeconds(20), function: AwsExplorer.() -> Unit ) { val locator = byXpath("//div[@accessiblename='AWS Explorer Tool Window' and @class='InternalDecorator']") step("AWS explorer") { val explorer = try { find<AwsExplorer>(locator) } catch (e: Exception) { step("Open tool window") { // Click the tool window stripe find(ComponentFixture::class.java, byXpath("//div[@accessiblename='AWS Explorer' and @class='StripeButton' and @text='AWS Explorer']")).click() find<AwsExplorer>(locator, timeout) } } explorer.apply(function) } } @FixtureName("AWSExplorer") open class AwsExplorer( remoteRobot: RemoteRobot, remoteComponent: RemoteComponent ) : CommonContainerFixture(remoteRobot, remoteComponent) { private fun explorerTree() = find<JTreeFixture>(byXpath("//div[@class='Tree']")).also { it.waitUntilLoaded() } fun openExplorerActionMenu(vararg path: String) { explorerTree().rightClickPath(*path) } fun expandExplorerNode(vararg path: String) { explorerTree().expandPath(*path) explorerTree().waitUntilLoaded() } fun doubleClickExplorer(vararg nodeElements: String) { explorerTree().doubleClickPath(*nodeElements) } }
6
null
4
9
ccee3307fe58ad48f93cd780d4378c336ee20548
1,962
aws-toolkit-jetbrains
Apache License 2.0
baseutils/src/main/java/peru/android/dev/baseutils/SingleEvent.kt
Bruno125
158,170,168
true
{"Kotlin": 82012, "Java": 1123}
package peru.android.dev.baseutils class SingleEvent: Event<Any?>(null)
0
Kotlin
0
1
5b996ad482f9077c8abcf1071b38bc4fe518cd87
72
android-dev-peru-app
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/config/CfnRemediationConfigurationResourceValuePropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.config import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.config.CfnRemediationConfiguration /** * The dynamic value of the resource. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.config.*; * ResourceValueProperty resourceValueProperty = ResourceValueProperty.builder() * .value("value") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-remediationconfiguration-resourcevalue.html) */ @CdkDslMarker public class CfnRemediationConfigurationResourceValuePropertyDsl { private val cdkBuilder: CfnRemediationConfiguration.ResourceValueProperty.Builder = CfnRemediationConfiguration.ResourceValueProperty.builder() /** @param value The value is a resource ID. */ public fun `value`(`value`: String) { cdkBuilder.`value`(`value`) } public fun build(): CfnRemediationConfiguration.ResourceValueProperty = cdkBuilder.build() }
4
Kotlin
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
1,407
awscdk-dsl-kotlin
Apache License 2.0
compiler/tests-spec/testData/diagnostics/linked/expressions/type-checking-and-containment-checking-expressions/type-checking-expression/p-4/pos/1.1.kt
JetBrains
3,432,266
false
null
// FIR_IDENTICAL // !LANGUAGE: +NewInference // !DIAGNOSTICS: -USELESS_IS_CHECK USELESS_NULLABLE_CHECK -UNUSED_VALUE -UNUSED_PARAMETER -UNREACHABLE_CODE -UNUSED_VARIABLE -USELESS_NULLABLE_CHECK // SKIP_TXT /* * KOTLIN DIAGNOSTICS SPEC TEST (POSITIVE) * * SPEC VERSION: 0.1-296 * PLACE: expressions, type-checking-and-containment-checking-expressions, type-checking-expression -> paragraph 4 -> sentence 1 * RELEVANT PLACES: expressions, type-checking-and-containment-checking-expressions, type-checking-expression -> paragraph 4 -> sentence 1 * NUMBER: 1 * DESCRIPTION: Type-checking expression always has type kotlin.Boolean. * HELPERS: checkType */ // TESTCASE NUMBER: 1 fun case1() { val x = null is Nothing x checkType { check<Boolean>() } } // TESTCASE NUMBER: 2 fun case2() { ("" !is String) checkType { check<Boolean>() } } // TESTCASE NUMBER: 3 fun case3(n: Nothing) { val x = n is Nothing x checkType { check<Boolean>() } } // TESTCASE NUMBER: 4 fun case4() { val x = A() is Any? x checkType { check<Boolean>() } } class A
3
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,074
kotlin
Apache License 2.0
layout-ui/src/main/java/com/android/tools/componenttree/treetable/TreeTableDropTargetHandler.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 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 com.android.tools.componenttree.treetable import com.intellij.ui.ColorUtil import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.UIUtil import java.awt.BasicStroke import java.awt.Graphics import java.awt.Graphics2D import java.awt.Point import java.awt.Polygon import java.awt.Rectangle import java.awt.RenderingHints import java.awt.Stroke import java.awt.datatransfer.Transferable import java.awt.dnd.DropTargetDragEvent import java.awt.dnd.DropTargetDropEvent import java.awt.dnd.DropTargetEvent import java.awt.dnd.DropTargetListener import javax.swing.tree.TreePath class TreeTableDropTargetHandler(private val table: TreeTableImpl, private val getDraggedItem: () -> Any?) : DropTargetListener { private var lineColor = ColorUtil.brighter(UIUtil.getTreeSelectionBackground(true), 10) private var dashedStroke = createDashStroke() private var insertionRow = -1 private var insertionDepth = -1 private var insertionBounds: Rectangle? = null private var receiverRow = -1 private var receiverBounds: Rectangle? = null override fun dragEnter(event: DropTargetDragEvent) { updateInsertionPoint(event) } override fun dragOver(event: DropTargetDragEvent) { updateInsertionPoint(event) } override fun dropActionChanged(event: DropTargetDragEvent) { } override fun dragExit(event: DropTargetEvent) { clearInsertionPoint() } override fun drop(event: DropTargetDropEvent) { val receiver = table.getValueAt(receiverRow, 0) val item = table.getValueAt(insertionRow, 0) val insertAfterLastItemInReceiver = insertionRow - receiverRow > table.tableModel.children(receiver).size val before = if (!insertAfterLastItemInReceiver) item else null val succeeded = table.tableModel.insert(receiver, event.transferable, before) if (succeeded) { event.acceptDrop(event.dropAction) event.dropComplete(true) } clearInsertionPoint() } fun updateUI() { lineColor = ColorUtil.brighter(UIUtil.getTreeSelectionBackground(true), 10) dashedStroke = createDashStroke() } fun reset() { clearInsertionPoint() } fun paintDropTargetPosition(g: Graphics) { if (insertionRow >= 0) { val g2 = g.create() as Graphics2D try { g2.color = lineColor g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) paintReceiverRectangle(g2) paintInsertionLine(g2) paintColumnLine(g2) } finally { g2.dispose() } } } private fun createDashStroke(): Stroke = BasicStroke(JBUIScale.scale(1.0f), BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, JBUIScale.scale(10.0f), floatArrayOf(JBUIScale.scale(4f), JBUIScale.scale(4f)), 0.0f) private fun paintReceiverRectangle(g: Graphics2D) { receiverBounds?.let { val x = maxOf(0, it.x - JBUIScale.scale(2)) val maxWidth = table.columnModel.getColumn(0).width val width = minOf(maxWidth - x, it.width + JBUIScale.scale(2)) g.drawRect(x, it.y, width, it.height) } } private fun paintColumnLine(g: Graphics2D) { val x = (receiverBounds?.x ?: 0) + JBUIScale.scale(7) val y = receiverBounds?.bottom ?: 0 g.stroke = dashedStroke g.drawLine(x, y, x, insertionBounds?.bottom ?: y) } private val Rectangle.bottom: Int get() = y + height private val Rectangle.right: Int get() = x + width private fun paintInsertionLine(g: Graphics2D) { val triangle = Polygon() val indicatorSize = JBUIScale.scale(6) val x = (receiverBounds?.x ?: 0) + JBUIScale.scale(6) val y = insertionBounds?.bottom ?: 0 triangle.addPoint(x + indicatorSize, y) triangle.addPoint(x, y + indicatorSize / 2) triangle.addPoint(x, y - indicatorSize / 2) g.drawLine(x, y, insertionBounds?.right ?: x, y) g.drawPolygon(triangle) g.fillPolygon(triangle) } private fun updateInsertionPoint(event: DropTargetDragEvent) { val point = Point(event.location.x, event.location.y + table.rowHeight / 2) val column = table.columnAtPoint(point) if (column != 0) { event.acceptDrag(0) clearInsertionPoint() return } val newInsertionDepth = table.findDepthFromOffset(point.x) val newInsertionRow = table.rowAtPoint(point).takeIf { it >= 0 } ?: table.rowCount if (insertionRow != newInsertionRow || insertionDepth != newInsertionDepth) { if (findReceiver(event.transferable, newInsertionRow, newInsertionDepth)) { insertionRow = newInsertionRow insertionDepth = newInsertionDepth insertionBounds = if (!table.isEmpty) table.tree.getRowBounds(maxOf(0, insertionRow - 1)) else Rectangle(0, 0, table.columnModel.getColumn(0).width, 0) table.repaint() } else { event.acceptDrag(0) clearInsertionPoint() } } } // This allows the user to select the previous ancestor by moving // the cursor to the left only if there is some ambiguity to define where // the insertion should be. // There is an ambiguity if either the user tries to insert the component after the last row // in between a component deeper than the one on the next row: // shall we insert at the component after the last leaf or after the last leaf ancestor // -- root // |-- parent // |-- child1 // |-- child2 // .................. // |-- potential Insertion point 1 <--- // |-- potential Insertion point 2 <--- // private fun findReceiver(data: Transferable, insertionRow: Int, insertionDepth: Int): Boolean { receiverRow = -1 receiverBounds = null var item = table.model.getValueAt(insertionRow - 1, 0) ?: return false var receiver = item.takeIf { canDropInto(item, data) } var index = 0 while (index + 1 >= table.tableModel.getChildCount(item) && (receiver == null || insertionDepth < table.tableModel.computeDepth(item))) { val parent = table.tableModel.parent(item) ?: break index = table.tableModel.getIndexOfChild(parent, item) item = parent receiver = item.takeIf { canDropInto(item, data) } ?: receiver } if (receiver == null) { return false } val path = TreePath(generateSequence(item) { table.tableModel.parent(it) }.toList().asReversed().toTypedArray()) receiverRow = table.tree.getRowForPath(path) receiverBounds = table.tree.getPathBounds(path) return true } private fun canDropInto(receiver: Any, data: Transferable): Boolean = getDraggedItem()?.let { dragged -> generateSequence(receiver) { table.tableModel.parent(it) }.none { it === dragged} } ?: true && table.tableModel.canInsert(receiver, data) private fun clearInsertionPoint() { val repaint = insertionRow >= 0 insertionRow = -1 insertionDepth = -1 insertionBounds = null receiverRow = -1 receiverBounds = null if (repaint) { table.repaint() } } }
1
null
220
857
8d22f48a9233679e85e42e8a7ed78bbff2c82ddb
7,583
android
Apache License 2.0
PayPal/src/main/java/com/braintreepayments/api/paypal/PayPalPaymentAuthRequest.kt
braintree
21,631,528
false
{"Kotlin": 943673, "Java": 780759, "Shell": 282}
package com.braintreepayments.api.paypal /** * A request used to launch the continuation of the PayPal payment flow. */ sealed class PayPalPaymentAuthRequest { /** * The request was successfully created and is ready to be launched by [PayPalLauncher] */ class ReadyToLaunch(val requestParams: PayPalPaymentAuthRequestParams) : PayPalPaymentAuthRequest() /** * There was an [error] creating the request */ class Failure(val error: Exception) : PayPalPaymentAuthRequest() }
24
Kotlin
232
405
3a713b966c132dd5647bc2565c548e9d09e0be82
521
braintree_android
MIT License
paymentsheet-example/src/main/java/com/stripe/android/paymentsheet/example/samples/ui/paymentsheet/complete_flow/CompleteFlowViewState.kt
stripe
6,926,049
false
null
package com.stripe.android.paymentsheet.example.samples.ui.complete_flow import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.example.samples.model.CartState data class CompleteFlowViewState( val isProcessing: Boolean = false, val paymentInfo: PaymentInfo? = null, val cartState: CartState = CartState.default, val status: String? = null, val didComplete: Boolean = false, ) { data class PaymentInfo( val publishableKey: String, val clientSecret: String, val customerConfiguration: PaymentSheet.CustomerConfiguration?, val shouldPresent: Boolean, ) { val paymentSheetConfig: PaymentSheet.Configuration get() = PaymentSheet.Configuration( merchantDisplayName = "Example, Inc.", customer = customerConfiguration, googlePay = PaymentSheet.GooglePayConfiguration( environment = PaymentSheet.GooglePayConfiguration.Environment.Test, countryCode = "US", ), // Set `allowsDelayedPaymentMethods` to true if your business can handle payment // methods that complete payment after a delay, like SEPA Debit and Sofort. allowsDelayedPaymentMethods = true ) } }
92
null
644
1,277
174b27b5a70f75a7bc66fdcce3142f1e51d809c8
1,339
stripe-android
MIT License
mobzy-spawning/src/main/kotlin/com/mineinabyss/mobzy/spawning/WorldGuardSpawnFlags.kt
MineInAbyss
142,800,887
false
null
package com.mineinabyss.mobzy.registration import com.sk89q.worldguard.WorldGuard import com.sk89q.worldguard.protection.flags.StringFlag import com.sk89q.worldguard.protection.flags.registry.FlagConflictException object MobzyWorldguard { //TODO Make these into their own custom flags instead of StringFlag //TODO rename this to MZ_... in the WorldGuard config files :mittysweat: var MZ_SPAWN_REGIONS: StringFlag? = null var MZ_SPAWN_OVERLAP: StringFlag? = null fun registerFlags() { val registry = WorldGuard.getInstance().flagRegistry val mzSpawnRegions = registry["cm-spawns"] val mzSpawnOverlap = registry["mz-spawn-overlap"] //register MZ_SPAWN_REGIONS if (mzSpawnRegions is StringFlag) //avoid problems if registering flag that already exists MZ_SPAWN_REGIONS = mzSpawnRegions else try { val flag = StringFlag("cm-spawns", "") registry.register(flag) MZ_SPAWN_REGIONS = flag } catch (e: FlagConflictException) { e.printStackTrace() } //register MZ_SPAWN_OVERLAP if (mzSpawnOverlap is StringFlag) MZ_SPAWN_OVERLAP = mzSpawnOverlap else try { val flag = StringFlag("mz-spawn-overlap", "stack") registry.register(flag) MZ_SPAWN_OVERLAP = flag } catch (e: FlagConflictException) { e.printStackTrace() } } /*fun disablePluginSpawnsErrorMessage() { //TODO try to allow plugin spawning in WorldGuard's config automatically //onCreatureSpawn in WorldGuardEntityListener throws errors if we don't enable custom entity spawns WorldGuard.getInstance().platform.globalStateManager.get(BukkitAdapter.adapt(server.worlds.first())) .blockPluginSpawning = false }*/ }
9
null
8
43
c3b007ca794292886b3f13e607bb0fbbac46f285
1,845
Mobzy
MIT License
src/main/kotlin/unq/deportes/repository/MatchRepository.kt
Coronel-B
217,918,188
false
null
package unq.deportes.repository import org.springframework.data.repository.CrudRepository import unq.deportes.model.Match interface MatchRepository : CrudRepository<Match, Long> { }
0
Kotlin
1
0
c25915cebb358c48bae14e18aa82e707216f4707
185
deportesunq-backend
Apache License 2.0
plugins/gradle/java/testSources/importing/GradleJavaOutputParsersMessagesImportingTest.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.importing import org.assertj.core.api.Assertions.assertThat import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.testFramework.util.createBuildFile import org.jetbrains.plugins.gradle.testFramework.util.importProject import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions import org.junit.Test @Suppress("GrUnresolvedAccess") class GradleJavaOutputParsersMessagesImportingTest : GradleOutputParsersMessagesImportingTestCase() { @Test fun `test build script errors on Build`() { createSettingsFile("include 'api', 'impl', 'brokenProject' ") createBuildFile("impl") { addImplementationDependency(project(":api")) } createProjectSubFile("api/src/main/java/my/pack/Api.java", "package my.pack;\n" + "public interface Api {\n" + " @Deprecated" + " public int method();" + "}") createProjectSubFile("impl/src/main/java/my/pack/App.java", "package my.pack;\n" + "import my.pack.Api;\n" + "public class App implements Api {\n" + " public int method() { return 1; }" + "}") createProjectSubFile("brokenProject/src/main/java/my/pack/App2.java", "package my.pack;\n" + "import my.pack.Api;\n" + "public class App2 {\n" + " public int metho d() { return 1; }" + "}") importProject { subprojects { withJavaPlugin() } } assertSyncViewTree { assertNode("finished") { assertNodeWithDeprecatedGradleWarning() } } var expectedExecutionTree: String when { isGradleAtLeast("4.7") -> expectedExecutionTree = "-\n" + " -successful\n" + " :api:compileJava\n" + " :api:processResources\n" + " :api:classes\n" + " :api:jar\n" + " -:impl:compileJava\n" + " -App.java\n" + " uses or overrides a deprecated API.\n" + " :impl:processResources\n" + " :impl:classes" else -> expectedExecutionTree = "-\n" + " -successful\n" + " :api:compileJava\n" + " :api:processResources\n" + " :api:classes\n" + " :api:jar\n" + " :impl:compileJava\n" + " :impl:processResources\n" + " -App.java\n" + " uses or overrides a deprecated API.\n" + " :impl:classes" } compileModules("project.impl.main") assertBuildViewTreeSame(expectedExecutionTree) when { isGradleAtLeast("4.7") -> expectedExecutionTree = "-\n" + " -failed\n" + " -:brokenProject:compileJava\n" + " -App2.java\n" + " ';' expected\n" + " invalid method declaration; return type required" else -> expectedExecutionTree = "-\n" + " -failed\n" + " :brokenProject:compileJava\n" + " -App2.java\n" + " ';' expected\n" + " invalid method declaration; return type required" } compileModules("project.brokenProject.main") assertBuildViewTreeSame(expectedExecutionTree) } @Test fun `test compilation view tree`() { createProjectSources() importProject { withJavaPlugin() } assertSyncViewTree { assertNode("finished") { assertNodeWithDeprecatedGradleWarning() } } compileModules("project.test") assertBuildViewTreeEquals(""" |- | -successful | :compileJava | :processResources | :classes | :compileTestJava | :processTestResources | :testClasses """.trimMargin()) } @Test @TargetVersions("<5.0") fun `test unresolved dependencies errors on Build without repositories for legacy Gradle`() { createProjectSources() importProject { withJavaPlugin() addTestImplementationDependency("junit:junit:4.12") } compileModules("project.test") assertBuildViewTreeEquals(""" |- | -failed | :compileJava | :processResources | :classes | :compileTestJava | Could not resolve junit:junit:4.12 because no repositories are defined """.trimMargin()) assertBuildViewSelectedNode("Could not resolve junit:junit:4.12 because no repositories are defined", """ |Could not resolve all files for configuration ':testCompileClasspath'. |> Cannot resolve external dependency junit:junit:4.12 because no repositories are defined. | Required by: | project : | |Possible solution: | - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html | | """.trimMargin() ) } @Test @TargetVersions("5.0+") fun `test unresolved dependencies errors on Build without repositories`() { createProjectSources() importProject { withJavaPlugin() addTestImplementationDependency("junit:junit:4.12") } compileModules("project.test") assertBuildViewTreeEquals(""" |- | -failed | :compileJava | :processResources | :classes | -:compileTestJava | Could not resolve junit:junit:4.12 because no repositories are defined """.trimMargin() ) assertBuildViewSelectedNode("Could not resolve junit:junit:4.12 because no repositories are defined", """ |Execution failed for task ':compileTestJava'. |> Could not resolve all files for configuration ':testCompileClasspath'. | > Cannot resolve external dependency junit:junit:4.12 because no repositories are defined. | Required by: | project : | |Possible solution: | - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html | | """.trimMargin()) } @Test @TargetVersions("<5.0") fun `test unresolved dependencies errors on Build in offline mode for legacy Gradle`() { GradleSettings.getInstance(myProject).isOfflineWork = true createProjectSources() importProject { withJavaPlugin() withRepository { mavenRepository(MAVEN_REPOSITORY, isGradleAtLeast("6.0")) } addTestImplementationDependency("junit:junit:4.12") addTestImplementationDependency("junit:junit:99.99") } compileModules("project.test") assertBuildViewTreeEquals(""" | - | -failed | :compileJava | :processResources | :classes | :compileTestJava | Could not resolve junit:junit:99.99 """.trimMargin()) assertBuildViewSelectedNode("Could not resolve junit:junit:99.99", """|Could not resolve all files for configuration ':testCompileClasspath'. |> Could not resolve junit:junit:99.99. | Required by: | project : | > No cached version of junit:junit:99.99 available for offline mode. |> Could not resolve junit:junit:99.99. | Required by: | project : | > No cached version of junit:junit:99.99 available for offline mode. | |Possible solution: | - Disable offline mode and rerun the build | | """.trimMargin()) } @Test @TargetVersions("5.0+") fun `test unresolved dependencies errors on Build in offline mode`() { GradleSettings.getInstance(myProject).isOfflineWork = true createProjectSources() importProject { withJavaPlugin() withRepository { mavenRepository(MAVEN_REPOSITORY, isGradleAtLeast("6.0")) } addTestImplementationDependency("junit:junit:99.99") } compileModules("project.test") assertBuildViewTree { assertNode("failed") { assertNode(":compileJava") assertNode(":processResources") assertNode(":classes") assertNode(":compileTestJava") { assertNode("Could not resolve junit:junit:99.99") } } } assertBuildViewSelectedNode("Could not resolve junit:junit:99.99", """ |Execution failed for task ':compileTestJava'. |> Could not resolve all files for configuration ':testCompileClasspath'. | > Could not resolve junit:junit:99.99. | Required by: | project : | > No cached version of junit:junit:99.99 available for offline mode. | |Possible solution: | - Disable offline mode and rerun the build | | """.trimMargin()) } @Test @TargetVersions("<5.0") fun `test unresolved dependencies errors on Build for legacy Gradle`() { createProjectSources() importProject { withJavaPlugin() withRepository { mavenRepository(MAVEN_REPOSITORY, isGradleAtLeast("6.0")) } addTestImplementationDependency("junit:junit:4.12") addTestImplementationDependency("junit:junit:99.99") } compileModules("project.test") assertBuildViewTreeEquals(""" | - | -failed | :compileJava | :processResources | :classes | :compileTestJava | Could not resolve junit:junit:99.99 """.trimMargin() ) val repositoryPrefix = if (isGradleOlderThan("4.8")) " " else "-" assertBuildViewSelectedNode("Could not resolve junit:junit:99.99", """Could not resolve all files for configuration ':testCompileClasspath'. |> Could not find junit:junit:99.99. | Searched in the following locations: | $repositoryPrefix $MAVEN_REPOSITORY/junit/junit/99.99/junit-99.99.pom | $repositoryPrefix $MAVEN_REPOSITORY/junit/junit/99.99/junit-99.99.jar | Required by: | project : |> Could not find junit:junit:99.99. | Searched in the following locations: | $repositoryPrefix $MAVEN_REPOSITORY/junit/junit/99.99/junit-99.99.pom | $repositoryPrefix $MAVEN_REPOSITORY/junit/junit/99.99/junit-99.99.jar | Required by: | project : | |Possible solution: | - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html | | """.trimMargin()) } @Test @TargetVersions("5.0+") fun `test unresolved dependencies errors on Build`() { createProjectSources() importProject { withJavaPlugin() withRepository { mavenRepository(MAVEN_REPOSITORY, isGradleAtLeast("6.0")) } addTestImplementationDependency("junit:junit:4.12") addTestImplementationDependency("junit:junit:99.99") } compileModules("project.test") assertBuildViewTreeEquals(""" |- | -failed | :compileJava | :processResources | :classes | -:compileTestJava | Could not resolve junit:junit:99.99 """.trimMargin()) assertBuildViewSelectedNode("Could not resolve junit:junit:99.99", """Execution failed for task ':compileTestJava'. |> Could not resolve all files for configuration ':testCompileClasspath'. | > Could not find junit:junit:99.99. | Searched in the following locations: | - $MAVEN_REPOSITORY/junit/junit/99.99/junit-99.99.pom | - $MAVEN_REPOSITORY/junit/junit/99.99/junit-99.99.jar | Required by: | project : | > Could not find junit:junit:99.99. | Searched in the following locations: | - $MAVEN_REPOSITORY/junit/junit/99.99/junit-99.99.pom | - $MAVEN_REPOSITORY/junit/junit/99.99/junit-99.99.jar | Required by: | project : | |Possible solution: | - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html | | """.trimMargin() ) } private fun createProjectSources() { createProjectSubFile("src/main/java/my/pack/App.java", "package my.pack;\n" + "public class App {\n" + " public int method() { return 1; }\n" + "}") createProjectSubFile("src/test/java/my/pack/AppTest.java", "package my.pack;\n" + "public class AppTest {\n" + " public void testMethod() { }\n" + "}") } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
16,090
intellij-community
Apache License 2.0
ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/ServletApplicationRequest.kt
jakobkmar
323,173,348
false
null
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.servlet import io.ktor.application.* import io.ktor.http.* import io.ktor.request.* import io.ktor.server.engine.* import javax.servlet.http.* @Suppress("KDocMissingDocumentation") @EngineAPI abstract class ServletApplicationRequest( call: ApplicationCall, val servletRequest: HttpServletRequest ) : BaseApplicationRequest(call) { override val local: RequestConnectionPoint = ServletConnectionPoint(servletRequest) override val queryParameters: Parameters by lazy { servletRequest.queryString?.let { parseQueryString(it) } ?: Parameters.Empty } override val headers: Headers = ServletApplicationRequestHeaders(servletRequest) @Suppress("LeakingThis") // this is safe because we don't access any content in the request override val cookies: RequestCookies = ServletApplicationRequestCookies(servletRequest, this) }
1
null
0
7
ea35658a05cc085b97297a303a7c0de37efe0024
1,012
ktor
Apache License 2.0
src/contributors/Contributors.kt
kotlin-hands-on
189,397,412
false
null
package contributors import contributors.Contributors.LoadingStatus.CANCELED import contributors.Contributors.LoadingStatus.COMPLETED import contributors.Contributors.LoadingStatus.IN_PROGRESS import contributors.Variant.BACKGROUND import contributors.Variant.BLOCKING import contributors.Variant.CALLBACKS import contributors.Variant.CHANNELS import contributors.Variant.CONCURRENT import contributors.Variant.NOT_CANCELLABLE import contributors.Variant.PROGRESS import contributors.Variant.SUSPEND import java.awt.event.ActionListener import javax.swing.SwingUtilities import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import tasks.loadContributorsBackground import tasks.loadContributorsBlocking import tasks.loadContributorsCallbacks import tasks.loadContributorsChannels import tasks.loadContributorsConcurrent import tasks.loadContributorsNotCancellable import tasks.loadContributorsProgress import tasks.loadContributorsSuspend enum class Variant { BLOCKING, // Request1Blocking BACKGROUND, // Request2Background CALLBACKS, // Request3Callbacks SUSPEND, // Request4Coroutine CONCURRENT, // Request5Concurrent NOT_CANCELLABLE, // Request6NotCancellable PROGRESS, // Request6Progress CHANNELS // Request7Channels } interface Contributors : CoroutineScope { val job: Job override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main fun init() { // Start a new loading on 'load' click addLoadListener { saveParams() loadContributors() } // Save preferences and exit on closing the window addOnWindowClosingListener { job.cancel() saveParams() System.exit(0) } // Load stored params (user & password values) loadInitialParams() } fun loadContributors() { val (username, password, org, _) = getParams() val req = RequestData(username, password, org) clearResults() val service = createGitHubService(req.username, req.password) val startTime = System.currentTimeMillis() when (getSelectedVariant()) { BLOCKING -> { // Blocking UI thread val users = loadContributorsBlocking(service, req) updateResults(users, startTime) } BACKGROUND -> { // Blocking a background thread loadContributorsBackground(service, req) { users -> SwingUtilities.invokeLater { updateResults(users, startTime) } } } CALLBACKS -> { // Using callbacks loadContributorsCallbacks(service, req) { users -> SwingUtilities.invokeLater { updateResults(users, startTime) } } } SUSPEND -> { // Using coroutines launch { val users = loadContributorsSuspend(service, req) updateResults(users, startTime) }.setUpCancellation() } CONCURRENT -> { // Performing requests concurrently launch(Dispatchers.Default) { val users = loadContributorsConcurrent(service, req) // updateResults should be called on the main UI thread withContext(Dispatchers.Main) { updateResults(users, startTime) } }.setUpCancellation() } NOT_CANCELLABLE -> { // Performing requests in a non-cancellable way launch { val users = loadContributorsNotCancellable(service, req) updateResults(users, startTime) }.setUpCancellation() } PROGRESS -> { // Showing progress launch(Dispatchers.Default) { loadContributorsProgress(service, req) { users, completed -> withContext(Dispatchers.Main) { updateResults(users, startTime, completed) } } }.setUpCancellation() } CHANNELS -> { // Performing requests concurrently and showing progress launch(Dispatchers.Default) { loadContributorsChannels(service, req) { users, completed -> withContext(Dispatchers.Main) { updateResults(users, startTime, completed) } } }.setUpCancellation() } } } private enum class LoadingStatus { COMPLETED, CANCELED, IN_PROGRESS } private fun clearResults() { updateContributors(listOf()) updateLoadingStatus(IN_PROGRESS) setActionsStatus(newLoadingEnabled = false) } private fun updateResults( users: List<User>, startTime: Long, completed: Boolean = true ) { updateContributors(users) updateLoadingStatus(if (completed) COMPLETED else IN_PROGRESS, startTime) if (completed) { setActionsStatus(newLoadingEnabled = true) } } private fun updateLoadingStatus( status: LoadingStatus, startTime: Long? = null ) { val time = if (startTime != null) { val time = System.currentTimeMillis() - startTime "${(time / 1000)}.${time % 1000 / 100} sec" } else "" val text = "Loading status: " + when (status) { COMPLETED -> "completed in $time" IN_PROGRESS -> "in progress $time" CANCELED -> "canceled" } setLoadingStatus(text, status == IN_PROGRESS) } private fun Job.setUpCancellation() { // make active the 'cancel' button setActionsStatus(newLoadingEnabled = false, cancellationEnabled = true) val loadingJob = this // cancel the loading job if the 'cancel' button was clicked val listener = ActionListener { loadingJob.cancel() updateLoadingStatus(CANCELED) } addCancelListener(listener) // update the status and remove the listener after the loading job is completed launch { loadingJob.join() setActionsStatus(newLoadingEnabled = true) removeCancelListener(listener) } } fun loadInitialParams() { setParams(loadStoredParams()) } fun saveParams() { val params = getParams() if (params.username.isEmpty() && params.password.isEmpty()) { removeStoredParams() } else { saveParams(params) } } fun getSelectedVariant(): Variant fun updateContributors(users: List<User>) fun setLoadingStatus(text: String, iconRunning: Boolean) fun setActionsStatus(newLoadingEnabled: Boolean, cancellationEnabled: Boolean = false) fun addCancelListener(listener: ActionListener) fun removeCancelListener(listener: ActionListener) fun addLoadListener(listener: () -> Unit) fun addOnWindowClosingListener(listener: () -> Unit) fun setParams(params: Params) fun getParams(): Params }
58
null
227
241
eee89091c695b3b35993cf6611503ed04a65bcae
7,566
intro-coroutines
Apache License 2.0
core/src/commonTest/kotlin/pw/binom/base64/TestBase64DecodeAppendable.kt
caffeine-mgn
182,165,415
false
null
package pw.binom.base64 import pw.binom.asUTF8ByteArray import pw.binom.asUTF8String import pw.binom.io.ByteArrayOutputStream import kotlin.test.Test import kotlin.test.assertEquals class TestBase64DecodeAppendable { @Test fun test() { val out = ByteArrayOutputStream() val o = Base64DecodeAppendable(out) val txt = "Hello world!" println("-->${Base64.encode(txt.asUTF8ByteArray())}") o.append(Base64.encode(txt.asUTF8ByteArray())) assertEquals(txt, out.toByteArray().asUTF8String()) } @Test fun test2() { val out = ByteArrayOutputStream() Base64DecodeAppendable(out).apply { append('A') append('Z') append('a') append('z') append('0') append('9') append('+') append('/') } out.toByteArray().also { assertEquals(1, it[0]) assertEquals(-106, it[1]) assertEquals(-77, it[2]) assertEquals(-45, it[3]) assertEquals(-33, it[4]) assertEquals(-65, it[5]) } } }
7
null
2
59
580ff27a233a1384273ef15ea6c63028dc41dc01
1,137
pw.binom.io
Apache License 2.0
app/src/main/java/com/algorigo/pressuregoapp/RxActivity.kt
seosh817
414,050,200
false
{"Kotlin": 166092}
package com.algorigo.pressuregoapp import android.Manifest import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Button import androidx.recyclerview.widget.RecyclerView import com.algorigo.algorigoble.BleManager import com.algorigo.library.rx.permission.PermissionAppCompatActivity import com.algorigo.pressurego.RxPDMSDevice import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.schedulers.Schedulers class RxActivity : PermissionAppCompatActivity() { private lateinit var stateDisposable: Disposable private var scanDisposable: Disposable? = null private var devices = listOf<RxPDMSDevice>() private val deviceAdapter = DeviceAdapter(object : DeviceAdapter.Callback { override fun onConnectBtn(device: DeviceAdapter.Device) { if (device.connected) { disconnect(device.macAddress) } else { connect(device.macAddress) } } override fun onItemSelected(device: DeviceAdapter.Device) { if (device.connected) { devices.find { it.macAddress == device.macAddress }?.also { val intent = Intent(this@RxActivity, RxPDMSDeviceActivity::class.java) intent.putExtra(PDMSDeviceActivity.MAC_ADDRESS_KEY, device.macAddress) startActivity(intent) } } } }) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_scan) BleManager.init(applicationContext, BleManager.BleManagerEngine.ALGORIGO_BLE) BleManager.getInstance().bleDeviceDelegate = RxPDMSDevice.DeviceDelegate() stateDisposable = BleManager.getInstance().getConnectionStateObservable() .observeOn(AndroidSchedulers.mainThread()) .subscribe({ adjustRecycler() }, { }) findViewById<Button>(R.id.scan_btn).setOnClickListener { if (scanDisposable != null) { stopScan() } else { startScan() } } findViewById<RecyclerView>(R.id.device_recycler).adapter = deviceAdapter } override fun onPause() { super.onPause() stopScan() } override fun onDestroy() { super.onDestroy() stateDisposable.dispose() } private fun startScan() { scanDisposable = requestPermissionCompletable(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)) .andThen(BleManager.getInstance().scanObservable(5000).subscribeOn(Schedulers.io())) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { findViewById<Button>(R.id.scan_btn).text = getText(R.string.stop_scan) } .doFinally { scanDisposable = null findViewById<Button>(R.id.scan_btn).text = getText(R.string.start_scan) } .subscribe({ devices = it.mapNotNull { it as? RxPDMSDevice } adjustRecycler() }, { Log.e(LOG_TAG, "", it) }) } private fun adjustRecycler() { deviceAdapter.devices = devices.map { DeviceAdapter.Device(it.name, it.macAddress, it.connected) } deviceAdapter.notifyDataSetChanged() } private fun stopScan() { scanDisposable?.dispose() } private fun connect(macAddress: String) { devices.find { it.macAddress == macAddress }?.connectCompletable(false) ?.observeOn(AndroidSchedulers.mainThread()) ?.subscribe({ Log.e(LOG_TAG, "connect complete") }, { Log.e(LOG_TAG, "connect error", it) }) } private fun disconnect(macAddress: String) { devices.find { it.macAddress == macAddress }?.disconnect() } companion object { private val LOG_TAG = RxActivity::class.java.simpleName } }
0
null
0
0
1ee091b06a85ca738591962b05137c03452d90cc
4,161
PressureGo_Android
MIT License
app/src/main/java/com/kcteam/features/addAttendence/RouteShopListDialog.kt
DebashisINT
558,234,039
false
null
package com.demo.features.addAttendence import android.content.Context import android.os.Bundle import androidx.fragment.app.DialogFragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import android.widget.ImageView import com.demo.R import com.demo.app.AppDatabase import com.demo.app.domain.RouteShopListEntity import com.demo.widgets.AppCustomTextView /** * Created by Saikat on 22-11-2018. */ class RouteShopListDialog : DialogFragment() { private lateinit var mContext: Context private lateinit var iv_close_icon: ImageView private lateinit var rv_shop_list: RecyclerView private var routeId = "" private var isSelected = false private var adapter: RouteShopListAdapter? = null private lateinit var tv_ok_btn: AppCustomTextView companion object { private lateinit var addressUpdateClickListener: RouteShopClickLisneter fun getInstance(routeId: String, isSelected: Boolean, listener: RouteShopClickLisneter): RouteShopListDialog { val mUpdateShopAddressDialog = RouteShopListDialog() val bundle = Bundle() bundle.putString("routeId", routeId) bundle.putBoolean("isSelected", isSelected) mUpdateShopAddressDialog.arguments = bundle addressUpdateClickListener = listener return mUpdateShopAddressDialog } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) routeId = arguments?.getString("routeId").toString() isSelected = arguments?.getBoolean("isSelected")!! } override fun onAttach(context: Context) { super.onAttach(context) this.mContext = context } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { dialog?.window!!.requestFeature(Window.FEATURE_NO_TITLE) dialog?.window!!.setBackgroundDrawableResource(R.drawable.rounded_corner_white_bg) val v = inflater.inflate(R.layout.dialog_route_shop_list, container, false) //addShopData = AppDatabase.getDBInstance()!!.addShopEntryDao().getShopDetail(shopId) isCancelable = false initView(v) return v } private fun initView(v: View) { iv_close_icon = v.findViewById(R.id.iv_close_icon) tv_ok_btn = v.findViewById(R.id.tv_ok_btn) rv_shop_list = v.findViewById(R.id.rv_shop_list) rv_shop_list.layoutManager = LinearLayoutManager(mContext) val list = AppDatabase.getDBInstance()?.routeShopListDao()?.getDataRouteIdWise(routeId) as ArrayList<RouteShopListEntity> adapter = RouteShopListAdapter(mContext, list, isSelected, object : RouteShopListAdapter.OnRouteClickListener { override fun onLeaveTypeClick(leaveTypeList: RouteShopListEntity?, adapterPosition: Int) { adapter?.notifyDataSetChanged() addressUpdateClickListener.onCheckClick(leaveTypeList) } }) rv_shop_list.adapter = adapter iv_close_icon.setOnClickListener({ dismiss() }) tv_ok_btn.setOnClickListener({ dismiss() }) } interface RouteShopClickLisneter { fun onCheckClick(leaveTypeList: RouteShopListEntity?) } }
0
null
1
1
e6114824d91cba2e70623631db7cbd9b4d9690ed
3,483
NationalPlastic
Apache License 2.0
app/src/main/java/io/aayush/relabs/network/data/thread/DiscussionState.kt
theimpulson
679,298,392
false
{"Kotlin": 143534}
package io.aayush.relabs.network.data.thread import com.squareup.moshi.Json enum class DiscussionState { @Json(name = "visible") VISIBLE, @Json(name = "moderated") MODERATED, @Json(name = "deleted") DELETED }
1
Kotlin
2
73
22f5741848708c9700dd197cc5731db54d19dc8e
237
ReLabs
Apache License 2.0
app/src/main/java/com/fabian/schengenvisacalculator/ui/screens/calendar/Calendar.kt
FabianShallari
313,957,735
false
null
package com.fabian.schengenvisacalculator.ui.screens.calendar import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.Providers import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.fabian.schengenvisacalculator.ui.model.WeekData import com.fabian.schengenvisacalculator.ui.providers.AmbientStartDayOfWeek import com.fabian.schengenvisacalculator.ui.theme.SchengenCalculatorTheme import com.fabian.schengenvisacalculator.util.* import java.time.DayOfWeek import java.time.LocalDate import java.time.YearMonth import java.time.temporal.TemporalAdjusters.nextOrSame import java.time.temporal.TemporalAdjusters.previousOrSame val CELL_SIZE_DP = 48.dp @Composable fun Calendar( modifier: Modifier = Modifier, calendarDateRange: LocalDateRange, selectedDateRanges: List<LocalDateRange>, ) { val weeksData = calculateWeeksData( calendarDateRange = calendarDateRange, startDayOfWeek = AmbientStartDayOfWeek.current ) Surface( modifier = modifier .fillMaxWidth() .fillMaxHeight() ) { LazyColumn( contentPadding = PaddingValues( start = 8.dp, end = 8.dp, top = 12.dp, bottom = 12.dp ), modifier = Modifier .fillMaxWidth() .fillMaxHeight(), horizontalAlignment = Alignment.CenterHorizontally ) { itemsIndexed(items = weeksData) { index, item -> CalendarWeekItem( index = index, weekData = item, selectedDateRanges = selectedDateRanges ) } } } } // TODO: 12/4/20 This should be calculated on a background thread and be part of a ViewModel private fun calculateWeeksData( calendarDateRange: LocalDateRange, startDayOfWeek: DayOfWeek, ): List<WeekData> { val endDayOfWeek = startDayOfWeek.minus(1) val weeksData = mutableListOf<WeekData>() var startDateOfWeek = calendarDateRange.start while (startDateOfWeek.isBeforeOrEqual(calendarDateRange.endInclusive)) { val dateAtEndOfWeek = startDateOfWeek.with(nextOrSame(endDayOfWeek)) val dateAtEndOfMonth = YearMonth.of(startDateOfWeek.year, startDateOfWeek.month).atEndOfMonth() val dateAtEndOfDateRange = calendarDateRange.endInclusive // Find end date of this week // Earliest of: (day at end of week || day at end of month || day at end of date range) val endDateOfWeek = listOf(dateAtEndOfWeek, dateAtEndOfMonth, dateAtEndOfDateRange).earliest() val dayAtStartOfWeek = startDateOfWeek.with(previousOrSame(startDayOfWeek)) val dayAtEndOfWeek = endDateOfWeek.with(nextOrSame(endDayOfWeek)) weeksData.add( WeekData( firstDateOfWeek = startDateOfWeek, lastDateOfWeek = endDateOfWeek, isFirstWeekOfMonth = startDateOfWeek.dayOfMonth == 1 || startDateOfWeek.isEqual( calendarDateRange.start ), startDaysToSkip = dayAtStartOfWeek.periodInDays(startDateOfWeek).toInt(), endDaysToSkip = endDateOfWeek.periodInDays(dayAtEndOfWeek).toInt(), ) ) // start on next week startDateOfWeek = endDateOfWeek.plusDays(1) } return weeksData } @Composable private fun CalendarPreview( darkTheme: Boolean, ) { SchengenCalculatorTheme(darkTheme = darkTheme) { Providers(AmbientStartDayOfWeek provides DayOfWeek.MONDAY) { Calendar( calendarDateRange = rangeOf( startInclusive = LocalDate.of(2020, 1, 12), endInclusive = LocalDate.of(2020, 3, 21)), selectedDateRanges = listOf( rangeOf( startInclusive = LocalDate.of(2020, 1, 12), endInclusive = LocalDate.of(2020, 1, 12)), rangeOf( startInclusive = LocalDate.of(2020, 2, 1), endInclusive = LocalDate.of(2020, 2, 16) ), rangeOf( startInclusive = LocalDate.of(2020, 2, 24), endInclusive = LocalDate.of(2020, 3, 5) ) ) ) } } } @Preview("CalendarPreview - Dark", showBackground = true) @Composable private fun CalendarPreviewDark() { CalendarPreview(darkTheme = true) } @Preview("CalendarPreview - Light", showBackground = true) @Composable private fun CalendarPreviewLight() { CalendarPreview(darkTheme = false) }
0
Kotlin
0
0
228a38efc164c0a0f67af8c4d9e6f8f441391f97
5,131
schengen-visa-calculator
MIT License
mineinabyss-features/src/main/kotlin/com/mineinabyss/features/lootcrates/LootCratesListener.kt
MineInAbyss
115,279,675
false
{"Kotlin": 412052}
package com.mineinabyss.features.lootcrates import com.mineinabyss.components.lootcrates.ContainsLoot import com.mineinabyss.features.abyss import com.mineinabyss.features.helpers.di.Features import com.mineinabyss.features.lootcrates.database.LootedChests import com.mineinabyss.geary.papermc.datastore.decode import com.mineinabyss.idofront.entities.rightClicked import com.mineinabyss.idofront.messaging.error import net.kyori.adventure.text.Component import org.bukkit.Bukkit import org.bukkit.block.Chest import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.block.BlockBreakEvent import org.bukkit.event.player.PlayerInteractEvent import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.select import org.jetbrains.exposed.sql.transactions.transaction import java.time.LocalDate class LootCratesListener(val msg: LootCratesFeature.Messages) : Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) fun PlayerInteractEvent.onChestInteract() { if (!rightClicked) return val chest = clickedBlock?.state as? Chest ?: return val loot = chest.persistentDataContainer.decode<ContainsLoot>() ?: return if (!player.hasPermission(LootCratePermissions.OPEN)) { player.error(msg.noPermissionToOpen) return } val uuid = chest.location.toLootChestUUID() val lastLootDate = transaction(abyss.db) { LootedChests.select { LootedChests.playerUUID eq player.uniqueId LootedChests.chestId eq uuid }.singleOrNull()?.getOrNull(LootedChests.dateLooted) } if (lastLootDate == null) { transaction(abyss.db) { LootedChests.insert { it[playerUUID] = player.uniqueId it[chestId] = uuid it[dateLooted] = LocalDate.now() } } val table = Features.lootCrates.lootTables[loot.table] ?: run { player.error(msg.tableNotFound.format(loot.table)) return } val lootInventory = Bukkit.createInventory(null, 27, Component.text("Loot")) table.populateInventory(lootInventory) player.openInventory(lootInventory) } else { player.error(msg.alreadyLooted.format(lastLootDate)) } isCancelled = true } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) fun BlockBreakEvent.removeFromDBOnChestRemove() { val chest = block.state as? Chest ?: return val loot = chest.persistentDataContainer.decode<ContainsLoot>() ?: return transaction(abyss.db) { LootedChests.deleteWhere { chestId eq chest.location.toLootChestUUID() } } } }
13
Kotlin
26
89
c862566af077173b00e39248121e24bb3c41402a
3,021
MineInAbyss
MIT License
src/main/kotlin/com/sugarizer/view/createinstruction/CreateInstructionView.kt
llaske
101,508,477
false
{"HTML": 16270623, "Python": 11699550, "JavaScript": 159051, "Kotlin": 125711, "C++": 19170, "C": 10794, "Shell": 6864, "CSS": 2281}
package com.sugarizer.view.createinstruction import com.sugarizer.Main import com.sugarizer.listitem.ListItemSpkInstruction import com.sugarizer.utils.shared.SpkManager import com.sugarizer.view.device.cellfactory.ListItemSpkInstructionCellFactory import com.sugarizer.view.devicedetails.view.devicedetails.CreateInstructionDialog import io.reactivex.rxjavafx.schedulers.JavaFxScheduler import javafx.application.Platform import javafx.fxml.FXML import javafx.fxml.Initializable import javafx.scene.layout.StackPane import org.controlsfx.control.GridView import java.io.File import java.net.URL import java.util.* import javax.inject.Inject class CreateInstructionView : Initializable, CreateInstructionContract.View { @Inject lateinit var spkManager: SpkManager @FXML lateinit var root: StackPane @FXML lateinit var listSpk: GridView<ListItemSpkInstruction> enum class Type { APK, CLICK, LONGCLICK, SWIPE, TEXT, KEY, PUSH, DELETE, SLEEP, OPENAPP, SINGLE_APK } val presenter: CreateInstructionPresenter = CreateInstructionPresenter(this) init { Main.appComponent.inject(this) } override fun initialize(location: URL?, resources: ResourceBundle?) { listSpk.cellHeight = 150.0 listSpk.cellWidth = 150.0 listSpk.cellFactory = ListItemSpkInstructionCellFactory() var fake = ListItemSpkInstruction(File(""), presenter, true) listSpk.items.add(0, fake) spkManager.toObservable() .observeOn(JavaFxScheduler.platform()) .subscribe { (first, second) -> when (first) { SpkManager.State.CREATE -> onSpkAdded(second) SpkManager.State.MODIFY -> onSpkModified(second) SpkManager.State.DELETE -> onSpkRemoved(second) } } fake.setOnMouseClicked { CreateInstructionDialog(null).showAndWait() } } fun onSpkAdded(file: File) { val contains = listSpk.items.any { it.file.equals(file) } if (!contains) { listSpk.items.add(listSpk.items.lastIndex, ListItemSpkInstruction(file, presenter, false).onItemAdded()) } } fun onSpkRemoved(file: File) { val tmp: ListItemSpkInstruction? = listSpk.items.lastOrNull { it.file.nameWithoutExtension.equals(file.nameWithoutExtension) } tmp?.let { var fade = it.onItemRemoved() fade.setOnFinished { Platform.runLater { listSpk.items.remove(tmp) } } fade.play() } } fun onSpkModified(file: File) { val contains = listSpk.items.any { it.file.equals(file) } if (!contains) { listSpk.items.add(listSpk.items.lastIndex, ListItemSpkInstruction(file, presenter, false).onItemAdded()) } } }
2
HTML
1
1
34df1a56b68b15b6771671f87ab66586d60c514a
2,920
sugarizer-deployment-tool-desktop
Apache License 2.0
app/src/main/java/ca/on/hojat/gamenews/core/BaseViewModel.kt
hojat72elect
574,228,468
false
null
package ca.on.hojat.gamenews.core import androidx.lifecycle.ViewModel import ca.on.hojat.gamenews.core.events.Command import ca.on.hojat.gamenews.core.events.Route import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.receiveAsFlow abstract class BaseViewModel : ViewModel() { private val _commandChannel = Channel<Command>(Channel.BUFFERED) private val _routeChannel = Channel<Route>(Channel.BUFFERED) val commandFlow: Flow<Command> = _commandChannel.receiveAsFlow() val routeFlow: Flow<Route> = _routeChannel.receiveAsFlow() protected fun dispatchCommand(command: Command) { _commandChannel.trySend(command) } protected fun route(route: Route) { _routeChannel.trySend(route) } }
0
Kotlin
2
4
b1c07551e90790ee3d273bc4c0ad3a5f97f71202
791
GameHub
MIT License
app/src/main/kotlin/com/akagiyui/drive/service/impl/AnnouncementServiceImpl.kt
AkagiYui
647,653,830
false
null
package com.akagiyui.drive.service.impl import com.akagiyui.common.ResponseEnum import com.akagiyui.common.exception.CustomException import com.akagiyui.common.utils.hasText import com.akagiyui.drive.entity.Announcement import com.akagiyui.drive.model.AnnouncementFilter import com.akagiyui.drive.model.request.UpdateAnnouncementRequest import com.akagiyui.drive.repository.AnnouncementRepository import com.akagiyui.drive.service.AnnouncementService import org.springframework.data.domain.Page import org.springframework.data.domain.PageRequest import org.springframework.data.jpa.domain.Specification import org.springframework.stereotype.Service /** * 公告服务实现类 * * @author AkagiYui */ @Service class AnnouncementServiceImpl(private val announcementRepository: AnnouncementRepository) : AnnouncementService { /** * 根据id查找公告或抛出异常 * * @param id 公告id * @return 公告实体 */ private fun getAnnouncement(id: String): Announcement { return announcementRepository.findById(id).orElseThrow { CustomException(ResponseEnum.NOT_FOUND) } } override fun addAnnouncement(announcement: Announcement): Announcement { return announcementRepository.save(announcement) } override fun getAnnouncementList(all: Boolean): List<Announcement> { return if (all) announcementRepository.findAll() else announcementRepository.findAnnouncementsByEnabledIsTrue() } override fun getAnnouncementDisplayList(): List<Announcement> { return announcementRepository.findAnnouncementsByEnabledIsTrueOrderByUpdateTimeDesc() } override fun find(index: Int, size: Int, filter: AnnouncementFilter?): Page<Announcement> { val pageable = PageRequest.of(index, size) // 条件查询 val specification = Specification<Announcement> { root, _, cb -> filter?.expression?.takeIf { it.hasText() }?.let { queryString -> val likePattern = "%$queryString%" val titlePredicate = cb.like(root.get("title"), likePattern) val contentPredicate = cb.like(root.get("content"), likePattern) cb.or(titlePredicate, contentPredicate) } } return announcementRepository.findAll(specification, pageable) } override fun disable(id: String, disabled: Boolean) { val announcement = getAnnouncement(id) announcement.enabled = !disabled announcementRepository.save(announcement) } override fun delete(id: String) { val announcement = getAnnouncement(id) announcementRepository.delete(announcement) } override fun update(id: String, request: UpdateAnnouncementRequest) { val announcement = getAnnouncement(id) if (request.title.hasText()) { announcement.title = request.title!! } if (request.content.hasText()) { announcement.content = request.content } announcementRepository.save(announcement) } }
5
null
3
9
6ff345645dfa83944ca4d36c02f9fa7b2162697f
3,025
KenkoDrive
MIT License
plugins/search-everywhere-ml/semantics/src/com/intellij/searchEverywhereMl/semantics/services/ClassEmbeddingsStorage.kt
wwwjames
83,334,899
true
null
package com.intellij.searchEverywhereMl.semantics.services import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.project.getProjectCachePath import com.intellij.openapi.startup.ProjectActivity import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.* import com.intellij.searchEverywhereMl.semantics.SemanticSearchBundle import com.intellij.searchEverywhereMl.semantics.indices.DiskSynchronizedEmbeddingSearchIndex import com.intellij.searchEverywhereMl.semantics.indices.FileIndexableEntitiesProvider import com.intellij.searchEverywhereMl.semantics.indices.IndexableEntity import com.intellij.searchEverywhereMl.semantics.services.LocalArtifactsManager.Companion.SEMANTIC_SEARCH_RESOURCES_DIR import com.intellij.searchEverywhereMl.semantics.settings.SemanticSearchSettings import com.intellij.searchEverywhereMl.semantics.utils.splitIdentifierIntoTokens import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import java.io.File /** * Thread-safe service for semantic classes search. * Supports Java Kotlin classes. * Holds a state with embeddings for each available indexable item and persists it on disk after calculation. * Generates the embeddings for classes not present in the loaded state at the IDE startup event if semantic classes search is enabled. */ @Service(Service.Level.PROJECT) class ClassEmbeddingsStorage(project: Project) : FileContentBasedEmbeddingsStorage<IndexableClass>(project) { override val index = DiskSynchronizedEmbeddingSearchIndex( project.getProjectCachePath( File(SEMANTIC_SEARCH_RESOURCES_DIR) .resolve(LocalArtifactsManager.getInstance().getModelVersion()) .resolve(INDEX_DIR).toString() ) ) override val indexingTaskManager = EmbeddingIndexingTaskManager(index) override val setupTitle: String = SemanticSearchBundle.getMessage("search.everywhere.ml.semantic.classes.generation.label") override val indexMemoryWeight: Int = 1 override val indexStrongLimit = Registry.intValue("search.everywhere.ml.semantic.indexing.indexable.classes.limit") init { project.messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, ClassesSemanticSearchFileChangeListener.getInstance(project)) } override fun checkSearchEnabled() = SemanticSearchSettings.getInstance().enabledInClassesTab @RequiresBackgroundThread override fun getIndexableEntities() = collectEntities(ClassesSemanticSearchFileChangeListener.getInstance(project)) override fun traversePsiFile(file: PsiFile) = FileIndexableEntitiesProvider.extractClasses(file) companion object { private const val INDEX_DIR = "classes" fun getInstance(project: Project) = project.service<ClassEmbeddingsStorage>() } } @Suppress("unused") // Registered in the plugin's XML file class ClassSemanticSearchServiceInitializer : ProjectActivity { override suspend fun execute(project: Project) { if (SemanticSearchSettings.getInstance().enabledInClassesTab) { ClassEmbeddingsStorage.getInstance(project).prepareForSearch() } } } open class IndexableClass(override val id: String) : IndexableEntity { override val indexableRepresentation: String get() = splitIdentifierIntoTokens(id).joinToString(separator = " ") }
7
null
1
1
9d4b7c6230b668e59a1aabb2b54cb89ba840fce4
3,400
intellij-community
Apache License 2.0
library/src/main/java/com/joom/grip/commons/AnyExtensions.kt
joomcode
412,782,399
false
null
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.grip.commons internal inline fun <T : Any> given(condition: Boolean, body: () -> T): T? { return if (condition) body() else null }
1
null
1
6
b1f0a7436452079eaaf663ad283e2aa7fe04cf6d
749
grip
Apache License 2.0
app/src/main/java/com/axondragonscale/jwtauth/auth/AuthResult.kt
AxonDragonScale
497,392,129
false
{"Kotlin": 18087}
package com.axondragonscale.jwtauth.auth /** * Created by <NAME> on 28/05/22 */ sealed class AuthResult<T>(data: T? = null) { class Authorized<T>(data: T? = null): AuthResult<T>(data) class Unauthorized<T>: AuthResult<T>() class UknownError<T>: AuthResult<T>() }
0
Kotlin
0
0
4644fe7a4285859fbf171f208d178e9103e3f74c
277
JwtAuthAndroid
MIT License
compottie/src/commonMain/kotlin/io/github/alexzhirkevich/compottie/internal/animation/expressions/operations/composition/OpGetProperty.kt
alexzhirkevich
730,724,501
false
{"Kotlin": 891763, "Swift": 601, "HTML": 211}
package io.github.alexzhirkevich.compottie.internal.animation.expressions.operations.composition import io.github.alexzhirkevich.compottie.internal.AnimationState import io.github.alexzhirkevich.compottie.internal.animation.AnimatedNumber import io.github.alexzhirkevich.compottie.internal.animation.RawProperty import io.github.alexzhirkevich.compottie.internal.animation.expressions.EvaluationContext import io.github.alexzhirkevich.compottie.internal.animation.expressions.Expression internal class OpGetProperty( private val property: Expression?= null ) : OpPropertyContext() { override fun invoke( property: RawProperty<Any>, context: EvaluationContext, state: AnimationState ): RawProperty<Any> { return if (this.property != null) this.property.invoke(property, context, state) as RawProperty<*> else property } }
5
Kotlin
7
232
46b008cd7cf40a84261b20c5888359f08368016a
892
compottie
MIT License
app/src/main/java/com/kcteam/features/reimbursement/api/reimbursement_list_api/ReimbursementListRepoProvider.kt
DebashisINT
558,234,039
false
null
package com.ntcv4tracker.features.reimbursement.api.reimbursement_list_api /** * Created by Saikat on 25-01-2019. */ object ReimbursementListRepoProvider { fun getReimbursementListRepository(): ReimbursementListRepo { return ReimbursementListRepo(ReimbursementListApi.create()) } }
0
null
1
1
a9aabcf48662c76db18bcece75cae9ac961da1ed
300
NationalPlastic
Apache License 2.0
app/src/main/kotlin/com/tommyfen/jetpackexercise/TestFragment.kt
TommyFen
175,630,899
false
{"Java": 17341, "Kotlin": 5244}
package com.tommyfen.jetpackexercise import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import cn.tommyfen.jetpackexercise.databinding.FragmentTestBinding // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [TestFragment.newInstance] factory method to * create an instance of this fragment. */ class TestFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null private var _binging: FragmentTestBinding? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragmenz _binging = FragmentTestBinding.inflate(inflater, container, false) return _binging?.root } override fun onDestroyView() { super.onDestroyView() _binging = null } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment TestFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = TestFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
1
Java
1
2
42326414cea154c635515ecab76e3ea134690faa
2,158
JetpackExercise
Apache License 2.0
core-points/src/test/kotlin/io/vibrantnet/ryp/core/points/service/PointsQueueServiceTest.kt
nilscodes
769,729,247
false
{"Kotlin": 901616, "TypeScript": 887764, "Dockerfile": 8250, "Shell": 7536, "JavaScript": 1867}
package io.vibrantnet.ryp.core.points.service import io.mockk.every import io.mockk.mockk import io.mockk.verify import io.ryp.shared.model.points.PointsClaimDto import io.vibrantnet.ryp.core.points.model.DuplicatePointsClaimException import org.junit.jupiter.api.Test import org.springframework.amqp.rabbit.core.RabbitTemplate import org.springframework.dao.DataIntegrityViolationException import reactor.core.publisher.Mono import java.time.OffsetDateTime class PointsQueueServiceTest { @Test fun `sending a point claim to the queue processes correctly`() { val pointsApiService = mockk<PointsApiService>() val rabbitTemplate = mockk<RabbitTemplate>() val pointsQueueService = PointsQueueService(pointsApiService, rabbitTemplate) val pointClaim = makePointClaim() every { pointsApiService.createPointClaim(pointClaim.accountId, pointClaim.tokenId, pointClaim.claimId, pointClaim) } answers { Mono.just(pointClaim) } pointsQueueService.savePointsClaimFromQueue(pointClaim) verify(exactly = 1) { rabbitTemplate.convertAndSend("pointclaimsfulfilled", pointClaim) } } @Test fun `sending an already existing point claim to the queue is a no-operation but does not crash the queue processing`() { val pointsApiService = mockk<PointsApiService>() val rabbitTemplate = mockk<RabbitTemplate>() val pointsQueueService = PointsQueueService(pointsApiService, rabbitTemplate) val pointClaim = makePointClaim() every { pointsApiService.createPointClaim(pointClaim.accountId, pointClaim.tokenId, pointClaim.claimId, pointClaim) } answers { Mono.error(DuplicatePointsClaimException("Claim with ID ${pointClaim.claimId} already exists")) } pointsQueueService.savePointsClaimFromQueue(pointClaim) verify(exactly = 0) { rabbitTemplate.convertAndSend("pointclaimsfulfilled", any<PointsClaimDto>()) } } @Test fun `sending a point claim to the queue that has no matching token is a no-operation but does not crash the queue processing`() { val pointsApiService = mockk<PointsApiService>() val rabbitTemplate = mockk<RabbitTemplate>() val pointsQueueService = PointsQueueService(pointsApiService, rabbitTemplate) val pointClaim = makePointClaim() every { pointsApiService.createPointClaim(pointClaim.accountId, pointClaim.tokenId, pointClaim.claimId, pointClaim) } answers { Mono.error(DataIntegrityViolationException("Dunno man, this one just doesn't exist")) } pointsQueueService.savePointsClaimFromQueue(pointClaim) verify(exactly = 0) { rabbitTemplate.convertAndSend("pointclaimsfulfilled", any<PointsClaimDto>()) } } private fun makePointClaim() = PointsClaimDto( claimId = "signup-12", category = "signup", tokenId = 18, accountId = 12, points = 100, projectId = 119, claimed = false, claimTime = null, createTime = OffsetDateTime.parse("2021-01-01T00:00:00Z"), expirationTime = OffsetDateTime.parse("2025-02-01T00:00:00Z"), ) }
0
Kotlin
0
0
a03ddb79eb7a71d0c440584c758cb5600c29c15e
3,233
reach-your-people
Apache License 2.0
ospf-kotlin-framework-gantt-scheduling/gantt-scheduling-domain-produce-context/src/main/fuookami/ospf/kotlin/framework/gantt_scheduling/domain/produce/service/limits/ConsumptionQuantityMinimization.kt
fuookami
359,831,793
false
null
package fuookami.ospf.kotlin.framework.gantt_scheduling.domain.produce.service.limits import fuookami.ospf.kotlin.utils.math.* import fuookami.ospf.kotlin.utils.functional.* import fuookami.ospf.kotlin.core.frontend.variable.* import fuookami.ospf.kotlin.core.frontend.expression.monomial.* import fuookami.ospf.kotlin.core.frontend.expression.polynomial.* import fuookami.ospf.kotlin.core.frontend.expression.symbol.linear_function.* import fuookami.ospf.kotlin.core.frontend.model.mechanism.* import fuookami.ospf.kotlin.framework.gantt_scheduling.domain.task.model.* import fuookami.ospf.kotlin.framework.gantt_scheduling.domain.produce.model.* class ConsumptionQuantityMinimization<Args : GanttSchedulingShadowPriceArguments<E, A>, E : Executor, A : AssignmentPolicy<E>>( private val materials: List<Material>, private val consumption: Consumption, private val threshold: (Material) -> Flt64 = { Flt64.zero }, private val coefficient: (Material) -> Flt64 = { Flt64.one }, override val name: String = "consumption_quantity_minimization" ) : GanttSchedulingCGPipeline<Args, E, A> { override fun invoke(model: LinearMetaModel): Try { model.minimize( sum(materials.map { val thresholdValue = threshold(it) if (thresholdValue eq Flt64.zero) { coefficient(it) * consumption.quantity[it] } else { val slack = SlackFunction( UContinuous, x = LinearPolynomial(consumption.quantity[it]), threshold = LinearPolynomial(thresholdValue), name = "consumption_quantity_minimization_threshold_$it" ) model.addSymbol(slack) coefficient(it) * slack } }), "consumption quantity" ) return Ok(success) } }
0
null
0
2
ee15667db4a8d3789cb1fd3df772717971e83a31
1,938
ospf-kotlin
Apache License 2.0
app/src/main/java/com/smarttoolfactory/composecolorpicker/ui/CanvasWithTitle.kt
SmartToolFactory
468,093,233
false
{"Kotlin": 422080}
package com.smarttoolfactory.composecolorpicker.ui import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.smarttoolfactory.colorpicker.ui.Blue400 @Composable fun CanvasWithTitle( modifier: Modifier = Modifier, text: String, onDraw: DrawScope.() -> Unit ) { Column( modifier = Modifier .wrapContentWidth() ) { Text( text = text, color = Blue400, modifier = Modifier .padding(8.dp), fontSize = 18.sp, fontWeight = FontWeight.Bold ) Canvas(modifier = modifier, onDraw = onDraw) } }
0
Kotlin
6
56
a027bbadc0542494214ce59c399dcfe9cd0862ef
1,073
Compose-Color-Picker-Bundle
Apache License 2.0
sykepenger-model/src/test/kotlin/no/nav/helse/serde/migration/V236MigrereUtbetalingTilÅOverlappeMedAUUTest.kt
navikt
193,907,367
false
null
package no.nav.helse.serde.migration import org.junit.jupiter.api.Test internal class V236MigrereUtbetalingTilÅOverlappeMedAUUTest: MigrationTest(V236MigrereUtbetalingTilÅOverlappeMedAUU()) { @Test fun `strekker tilbake utbetalingsperiodeobjekt`() { assertMigration( expectedJson = "/migrations/236/expected.json", originalJson = "/migrations/236/original.json" ) } }
2
Kotlin
6
5
314d8a6e32b3dda391bcac31e0b4aeeee68f9f9b
421
helse-spleis
MIT License
shared/src/iosMain/kotlin/dev/sasikanth/rss/reader/network/IOSRssMapper.kt
msasikanth
632,826,313
false
{"Kotlin": 484129, "Swift": 5413, "Shell": 227, "Ruby": 102}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.sasikanth.rss.reader.network import com.mohamedrejeb.ksoup.html.parser.KsoupHtmlOptions import com.mohamedrejeb.ksoup.html.parser.KsoupHtmlParser import dev.sasikanth.rss.reader.models.remote.FeedPayload import dev.sasikanth.rss.reader.models.remote.PostPayload import io.github.aakira.napier.Napier import io.ktor.http.Url import io.sentry.kotlin.multiplatform.Sentry import platform.Foundation.NSDateFormatter import platform.Foundation.timeIntervalSince1970 private val offsetTimezoneDateFormatter = NSDateFormatter().apply { dateFormat = "E, d MMM yyyy HH:mm:ss Z" } private val abbrevTimezoneDateFormatter = NSDateFormatter().apply { dateFormat = "E, d MMM yyyy HH:mm:ss z" } internal fun PostPayload.Companion.mapRssPost( rssMap: Map<String, String>, hostLink: String ): PostPayload { val pubDate = rssMap["pubDate"] val link = rssMap["link"] var description = rssMap["description"] val encodedContent = rssMap["content:encoded"] var imageUrl: String? = rssMap["imageUrl"] val commentsLink: String? = rssMap["comments"] val descriptionToParse = if (encodedContent.isNullOrBlank()) { description } else { encodedContent } val contentParser = KsoupHtmlParser( handler = HtmlContentParser { if (imageUrl.isNullOrBlank()) imageUrl = it.imageUrl description = it.content.ifBlank { descriptionToParse?.trim() } }, options = KsoupHtmlOptions(decodeEntities = false) ) contentParser.parseComplete(descriptionToParse.orEmpty()) return PostPayload( title = FeedParser.cleanText(rssMap["title"])!!, link = FeedParser.cleanText(link)!!, description = FeedParser.cleanTextCompact(description).orEmpty(), imageUrl = FeedParser.safeUrl(hostLink, imageUrl), date = pubDate.rssDateStringToEpochSeconds(), commentsLink = commentsLink?.trim() ) } internal fun FeedPayload.Companion.mapRssFeed( feedUrl: String, rssMap: Map<String, String>, posts: List<PostPayload> ): FeedPayload { val link = rssMap["link"]!!.trim() val domain = Url(link) val iconUrl = FeedParser.feedIcon( if (domain.host != "localhost") domain.host else domain.pathSegments.first().split(" ").first().trim() ) return FeedPayload( name = FeedParser.cleanText(rssMap["title"])!!, homepageLink = link, link = feedUrl, description = FeedParser.cleanText(rssMap["description"])!!, icon = iconUrl, posts = posts ) } private fun String?.rssDateStringToEpochSeconds(): Long { if (this.isNullOrBlank()) return 0L val date = try { offsetTimezoneDateFormatter.dateFromString(this.trim()) } catch (e: Exception) { try { abbrevTimezoneDateFormatter.dateFromString(this.trim()) } catch (e: Exception) { Sentry.captureException(e) Napier.e("Parse date error: ${e.message}") null } } return date?.timeIntervalSince1970?.times(1000)?.toLong() ?: 0L }
4
Kotlin
20
342
eb714b64f320c83f026433317dffe06940199cd6
3,572
twine
Apache License 2.0
app/src/main/java/com/rami/koroutinesdemo/presentation/di/ViewModelFactory.kt
rami-de
214,674,311
false
null
package com.rami.koroutinesdemo.presentation.di import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton @Singleton class ViewModelFactory @Inject constructor( private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>> ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return creators[modelClass]?.get() as T } }
0
Kotlin
0
0
2b748717e49ead520bc5c4f2b247b4e7fc826f83
520
KoroutinesDemo
MIT License
fir/testData/codeInsight/handlers/gotoSuperActionHandler/properties/incorrectCode/overrideFinalPropertyInFinalClass.kt
JetBrains
278,369,660
false
null
open class A { val foo: Int = 1 } class B : A() { override val fo<caret>o: Int = 10 }
1
Kotlin
29
71
b6789690db56407ae2d6d62746fb69dc99d68c84
94
intellij-kotlin
Apache License 2.0
idea/testData/quickfix/autoImports/noImportInQualifiedExpressionNotFirst.before.Main.kt
JakeWharton
99,388,807
false
null
// "class org.jetbrains.kotlin.idea.quickfix.ImportFix" "false" // ACTION: Convert property initializer to getter // ACTION: Create class 'SomeTest' // ACTION: Rename reference // ERROR: Unresolved reference: SomeTest package testing val x = testing.<caret>SomeTest()
1
null
37
83
4383335168338df9bbbe2a63cb213a68d0858104
270
kotlin
Apache License 2.0
core/admin-api/src/main/kotlin/io/mailit/core/admin/api/type/MailMessageTypeService.kt
awelless
467,556,925
false
null
package io.mailit.core.admin.api.type import io.mailit.core.model.HtmlTemplateEngine import io.mailit.core.model.MailMessageType import io.mailit.core.model.Slice interface MailMessageTypeService { suspend fun getById(id: Long): MailMessageType suspend fun getAllSliced(page: Int, size: Int): Slice<MailMessageType> suspend fun createNewMailType(command: CreateMailMessageTypeCommand): MailMessageType suspend fun updateMailType(command: UpdateMailMessageTypeCommand): MailMessageType suspend fun deleteMailType(id: Long, force: Boolean) } data class CreateMailMessageTypeCommand( val name: String, val description: String? = null, val maxRetriesCount: Int? = null, val contentType: MailMessageContentType, val templateEngine: HtmlTemplateEngine? = null, val template: String? = null, ) data class UpdateMailMessageTypeCommand( val id: Long, val description: String?, val maxRetriesCount: Int?, val templateEngine: HtmlTemplateEngine? = null, val template: String? = null, ) enum class MailMessageContentType { PLAIN_TEXT, HTML, }
3
Kotlin
0
1
55b4e9502dba6f3a218affa2a1c96ea4e7754584
1,114
mail-it
MIT License
app/src/main/java/com/n27/elections/injection/SubcomponentsModule.kt
Narsuf
52,900,182
false
{"Kotlin": 246421}
package com.n27.elections.injection import com.n27.core.injection.CoreComponent import com.n27.regional_live.injection.RegionalLiveComponent import dagger.Module @Module( subcomponents = [ CoreComponent::class, RegionalLiveComponent::class ] ) class SubcomponentsModule
0
Kotlin
0
2
73959e069dcd7166b9095f0b94cc3d0c42873c77
296
Elections
Apache License 2.0
iteration7/music-matters/core/data/src/main/java/com/odesa/musicMatters/core/data/search/impl/SearchHistoryStoreImpl.kt
Odhiambo-Michael-Allan
740,198,682
false
{"Kotlin": 9540063}
package com.odesa.musicMatters.data.search.impl import com.odesa.musicMatters.data.playlists.impl.FileAdapter import com.odesa.musicMatters.data.search.SearchHistoryItem import com.odesa.musicMatters.data.search.SearchHistoryStore import com.odesa.musicMatters.utils.toList import org.json.JSONArray import org.json.JSONObject import java.io.File class SearchHistoryStoreImpl( searchHistoryFile: File ): SearchHistoryStore { private var fileAdapter = FileAdapter( searchHistoryFile ) override fun fetchSearchHistory() = getSavedSearchItems() override suspend fun saveSearchHistoryItem( searchHistoryItem: SearchHistoryItem ) { val savedSearchHistoryItems = getSavedSearchItems().toMutableList() savedSearchHistoryItems.add( 0, searchHistoryItem ) saveSearchItems( savedSearchHistoryItems ) } override suspend fun deleteSearchHistoryItem( searchHistoryItem: SearchHistoryItem ) { val currentlySavedSearchHistoryItems = getSavedSearchItems().toMutableList() currentlySavedSearchHistoryItems.remove( searchHistoryItem ) saveSearchItems( currentlySavedSearchHistoryItems ) } private fun getSavedSearchItems(): List<SearchHistoryItem> { val fileContents = fileAdapter.read() if ( fileContents.isEmpty() ) return emptyList() val jsonObject = JSONObject( fileContents ) if ( !jsonObject.has( SEARCH_HISTORY_ITEMS_LIST_KEY ) ) return emptyList() return jsonObject.getJSONArray( SEARCH_HISTORY_ITEMS_LIST_KEY ).toList { SearchHistoryItem.fromJSONObject( getJSONObject( it ) ) }.mapNotNull { it } } private fun saveSearchItems( searchItems: List<SearchHistoryItem> ) { val jsonObject = JSONObject().apply { put( SEARCH_HISTORY_ITEMS_LIST_KEY, JSONArray( searchItems.map { it.toJSONObject() } ) ) } fileAdapter.overwrite( jsonObject.toString() ) } } private const val SEARCH_HISTORY_ITEMS_LIST_KEY = "SEARCH_HISTORY_ITEMS_LIST_KEY"
0
Kotlin
0
3
05ad5e08002a78958ed7763e6685a0e15f635fae
2,013
music-matters
Apache License 2.0
app/src/main/java/com/kgurgul/cpuinfo/features/applications/ApplicationsFragment.kt
kamgurgul
105,620,694
false
null
/* * Copyright 2017 KG Soft * * 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.kgurgul.cpuinfo.features.applications import android.annotation.SuppressLint import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.Uri import android.os.Bundle import android.provider.Settings import android.view.* import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.ListView import androidx.fragment.app.viewModels import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import com.kgurgul.cpuinfo.R import com.kgurgul.cpuinfo.databinding.FragmentApplicationsBinding import com.kgurgul.cpuinfo.features.information.base.BaseFragment import com.kgurgul.cpuinfo.utils.DividerItemDecoration import com.kgurgul.cpuinfo.utils.Utils import com.kgurgul.cpuinfo.utils.lifecycleawarelist.ListLiveDataObserver import com.kgurgul.cpuinfo.utils.uninstallApp import com.kgurgul.cpuinfo.utils.wrappers.EventObserver import com.kgurgul.cpuinfo.widgets.swiperv.SwipeMenuRecyclerView import dagger.hilt.android.AndroidEntryPoint import java.io.File /** * Activity for apps list. * * @author kgurgul */ @AndroidEntryPoint class ApplicationsFragment : BaseFragment<FragmentApplicationsBinding>( R.layout.fragment_applications), ApplicationsAdapter.ItemClickListener { private val viewModel: ApplicationsViewModel by viewModels() private val uninstallReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { viewModel.refreshApplicationsList() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) viewModel.refreshApplicationsList() registerUninstallBroadcast() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.lifecycleOwner = viewLifecycleOwner binding.viewModel = viewModel binding.swipeRefreshLayout.setColorSchemeResources(R.color.accent, R.color.primaryDark) initObservables() setupRecyclerView() } /** * Setup for [SwipeMenuRecyclerView] */ private fun setupRecyclerView() { val applicationsAdapter = ApplicationsAdapter(viewModel.applicationList, this) viewModel.applicationList.listStatusChangeNotificator.observe(viewLifecycleOwner, ListLiveDataObserver(applicationsAdapter)) binding.recyclerView.apply { layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) adapter = applicationsAdapter addItemDecoration(DividerItemDecoration(requireContext())) } } /** * Register all fields from [ApplicationsViewModel] which should be observed */ private fun initObservables() { viewModel.shouldStartStorageServiceEvent.observe(viewLifecycleOwner, EventObserver { StorageUsageService.startService(requireContext(), viewModel.applicationList) }) } /** * Register broadcast receiver for uninstalling apps */ private fun registerUninstallBroadcast() { val intentFilter = IntentFilter() intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED) intentFilter.addDataScheme("package") requireActivity().registerReceiver(uninstallReceiver, intentFilter) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.apps_menu, menu) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.action_sorting -> { viewModel.changeAppsSorting() true } else -> super.onOptionsItemSelected(item) } /** * Try to open clicked app. In case of error show [Snackbar]. */ override fun appOpenClicked(position: Int) { val appInfo = viewModel.applicationList[position] // Block self opening if (appInfo.packageName == requireContext().packageName) { Snackbar.make(binding.mainContainer, getString(R.string.cpu_open), Snackbar.LENGTH_SHORT).show() return } val intent = requireContext().packageManager.getLaunchIntentForPackage(appInfo.packageName) if (intent != null) { try { startActivity(intent) } catch (e: Exception) { Snackbar.make(binding.mainContainer, getString(R.string.app_open), Snackbar.LENGTH_SHORT).show() } } else { Snackbar.make(binding.mainContainer, getString(R.string.app_open), Snackbar.LENGTH_SHORT).show() } } /** * Open settings activity for selected app */ override fun appSettingsClicked(position: Int) { val appInfo = viewModel.applicationList[position] val uri = Uri.fromParts("package", appInfo.packageName, null) val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, uri) startActivity(intent) } /** * Try to uninstall selected app */ override fun appUninstallClicked(position: Int) { val appInfo = viewModel.applicationList[position] if (appInfo.packageName == requireContext().packageName) { Snackbar.make(binding.mainContainer, getString(R.string.cpu_uninstall), Snackbar.LENGTH_SHORT).show() return } requireActivity().uninstallApp(appInfo.packageName) } /** * Open dialog with native lib list and open google if user taps on it */ override fun appNativeLibsClicked(nativeDir: String) { showNativeListDialog(nativeDir) } /** * Create dialog with native libraries list */ @SuppressLint("InflateParams") private fun showNativeListDialog(nativeLibsDir: String) { val builder = MaterialAlertDialogBuilder(requireContext()) val inflater = LayoutInflater.from(context) val dialogLayout = inflater.inflate(R.layout.dialog_native_libs, null) val nativeDirFile = File(nativeLibsDir) val libs = nativeDirFile.listFiles()?.map { it.name } ?: emptyList() val listView: ListView = dialogLayout.findViewById(R.id.dialog_lv) val arrayAdapter = ArrayAdapter(requireContext(), R.layout.item_native_libs, R.id.native_name_tv, libs) listView.adapter = arrayAdapter listView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> Utils.searchInGoogle(requireContext(), libs[position]) } builder.setPositiveButton(R.string.ok) { dialog, _ -> dialog.cancel() } builder.setView(dialogLayout) val alert = builder.create() alert.show() } override fun onDestroy() { requireActivity().unregisterReceiver(uninstallReceiver) super.onDestroy() } }
27
null
88
462
b987a198d0aaaa9978a80ee52ddedb6bb30fd8c8
7,843
cpu-info
Apache License 2.0
app/src/main/kotlin/jp/co/yumemi/android/codecheck/data/api/GithubApi.kt
LeoAndo
583,336,904
false
{"Kotlin": 26878}
package jp.co.yumemi.android.codecheck.data.api import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.engine.android.* import io.ktor.client.plugins.* import io.ktor.client.plugins.logging.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import jp.co.yumemi.android.codecheck.BuildConfig import jp.co.yumemi.android.codecheck.data.api.response.GithubSearchResponse import jp.co.yumemi.android.codecheck.data.api.response.toModel import jp.co.yumemi.android.codecheck.model.RepositorySummary import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json class GithubApi { private val format by lazy { Json { ignoreUnknownKeys = true } } private val httpClient: HttpClient by lazy { HttpClient(Android) { defaultRequest { url.takeFrom(URLBuilder().takeFrom(BuildConfig.GITHUB_API_DOMAIN).apply { encodedPath += url.encodedPath }) header("Accept", "application/vnd.github.v3+json") header("Authorization", "Bearer ${BuildConfig.GITHUB_ACCESS_TOKEN}") header("X-GitHub-Api-Version", "2022-11-28") } install(HttpTimeout) { requestTimeoutMillis = TIMEOUT_MILLIS connectTimeoutMillis = TIMEOUT_MILLIS socketTimeoutMillis = TIMEOUT_MILLIS } install(Logging) { logger = AppHttpLogger() level = LogLevel.BODY } expectSuccess = true } } suspend fun searchRepositories(query: String): List<RepositorySummary> { val response: HttpResponse = httpClient.get { url { path("search", "repositories") } parameter("q", query) } val data = format.decodeFromString<GithubSearchResponse>(response.body()) return data.toModel() } companion object { private const val TIMEOUT_MILLIS: Long = 30 * 1000 } }
2
Kotlin
0
1
9f4fd9856df78d9cdc696b2a90a5840bf54ca8ae
2,064
android-engineer-codecheck
Apache License 2.0
app/shared/state-machine/ui/public/src/commonMain/kotlin/build/wallet/statemachine/demo/DemoModeCodeEntryUiStateMachineImpl.kt
proto-at-block
761,306,853
false
null
package build.wallet.statemachine.demo import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import build.wallet.compose.collections.immutableListOf import build.wallet.debug.DebugOptionsService import build.wallet.f8e.demo.DemoModeF8eClient import build.wallet.statemachine.core.LoadingBodyModel import build.wallet.statemachine.core.ScreenModel import build.wallet.statemachine.core.form.FormBodyModel import build.wallet.statemachine.core.form.FormHeaderModel import build.wallet.statemachine.core.form.FormMainContentModel.TextInput import build.wallet.time.Delayer import build.wallet.time.withMinimumDelay import build.wallet.ui.model.StandardClick import build.wallet.ui.model.button.ButtonModel import build.wallet.ui.model.input.TextFieldModel import build.wallet.ui.model.toolbar.ToolbarAccessoryModel import build.wallet.ui.model.toolbar.ToolbarModel import com.github.michaelbull.result.mapBoth import kotlinx.coroutines.flow.first class DemoModeCodeEntryUiStateMachineImpl( private val demoModeF8eClient: DemoModeF8eClient, private val delayer: Delayer, private val debugOptionsService: DebugOptionsService, ) : DemoModeCodeEntryUiStateMachine { @Composable override fun model(props: DemoCodeEntryUiProps): ScreenModel { var uiState: DemoModeState by remember { mutableStateOf(DemoModeState.DemoCodeEntryIdleState) } var demoModeCode by remember { mutableStateOf("") } return when (uiState) { is DemoModeState.DemoCodeEntryIdleState -> FormBodyModel( id = DemoCodeTrackerScreenId.DEMO_MODE_CODE_ENTRY, onBack = props.onBack, onSwipeToDismiss = props.onBack, header = FormHeaderModel( headline = "Enter demo mode code" ), mainContentList = immutableListOf( TextInput( fieldModel = TextFieldModel( value = "", placeholderText = "", onValueChange = { newValue, _ -> demoModeCode = newValue }, keyboardType = TextFieldModel.KeyboardType.Uri ) ) ), primaryButton = ButtonModel( text = "Submit", isEnabled = true, onClick = StandardClick { uiState = DemoModeState.DemoCodeEntrySubmissionState }, size = ButtonModel.Size.Footer ), toolbar = ToolbarModel( leadingAccessory = ToolbarAccessoryModel.IconAccessory.CloseAccessory( onClick = props.onBack ) ) ).asModalScreen() is DemoModeState.DemoCodeEntrySubmissionState -> { LaunchedEffect("submit-demo-code") { val debugOptions = debugOptionsService.options().first() delayer.withMinimumDelay { demoModeF8eClient.initiateDemoMode( f8eEnvironment = debugOptions.f8eEnvironment, code = demoModeCode ) }.mapBoth( success = { uiState = DemoModeState.DemoCodeEntryIdleState props.onCodeSuccess() }, failure = { uiState = DemoModeState.DemoCodeEntryIdleState } ) } LoadingBodyModel( id = DemoCodeTrackerScreenId.DEMO_MODE_CODE_SUBMISSION, message = "Submitting demo mode code...", onBack = null ).asModalScreen() } } } } sealed interface DemoModeState { data object DemoCodeEntryIdleState : DemoModeState data object DemoCodeEntrySubmissionState : DemoModeState }
3
null
16
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
3,854
bitkey
MIT License
server/src/main/kotlin/vr/network/model/ModelNode.kt
tlaukkan
62,936,064
false
{"Gradle": 3, "Text": 2, "Ignore List": 1, "YAML": 1, "Markdown": 1, "Kotlin": 108, "INI": 1, "HTML": 2, "Wavefront Object": 4, "COLLADA": 1, "JavaScript": 6, "Java": 2, "JSON": 156}
package vr.network.model class ModelNode(var path: String = "") : Node() { }
0
JavaScript
0
1
4067f653eef50e93aeaa7a5171709e6eb9dee005
78
kotlin-web-vr
MIT License
identity-starter/src/main/kotlin/com/labijie/application/identity/data/pojo/dsl/OAuth2ClientDSL.kt
hongque-pro
309,874,586
false
null
@file:Suppress("RedundantVisibilityModifier") package com.labijie.application.identity.`data`.pojo.dsl import com.labijie.application.identity.`data`.OAuth2ClientTable import com.labijie.application.identity.`data`.OAuth2ClientTable.accessTokenLiveSeconds import com.labijie.application.identity.`data`.OAuth2ClientTable.additionalInformation import com.labijie.application.identity.`data`.OAuth2ClientTable.authorities import com.labijie.application.identity.`data`.OAuth2ClientTable.authorizedGrantTypes import com.labijie.application.identity.`data`.OAuth2ClientTable.autoApprove import com.labijie.application.identity.`data`.OAuth2ClientTable.clientId import com.labijie.application.identity.`data`.OAuth2ClientTable.clientSecret import com.labijie.application.identity.`data`.OAuth2ClientTable.enabled import com.labijie.application.identity.`data`.OAuth2ClientTable.redirectUrls import com.labijie.application.identity.`data`.OAuth2ClientTable.refreshTokenLiveSeconds import com.labijie.application.identity.`data`.OAuth2ClientTable.resourceIds import com.labijie.application.identity.`data`.OAuth2ClientTable.scopes import com.labijie.application.identity.`data`.pojo.OAuth2Client import java.lang.IllegalArgumentException import kotlin.Array import kotlin.Boolean import kotlin.Int import kotlin.Number import kotlin.String import kotlin.Unit import kotlin.collections.Iterable import kotlin.collections.List import kotlin.collections.isNotEmpty import kotlin.collections.toList import kotlin.reflect.KClass import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.Op import org.jetbrains.exposed.sql.Query import org.jetbrains.exposed.sql.ResultRow import org.jetbrains.exposed.sql.SqlExpressionBuilder import org.jetbrains.exposed.sql.batchInsert import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.statements.InsertStatement import org.jetbrains.exposed.sql.statements.UpdateBuilder import org.jetbrains.exposed.sql.update /** * DSL support for OAuth2ClientTable * * This class made by a code generation tool (https://github.com/hongque-pro/infra-orm). * * Don't modify these codes !! * * Origin Exposed Table: * @see com.labijie.application.identity.data.OAuth2ClientTable */ @kotlin.Suppress( "unused", "DuplicatedCode", "MemberVisibilityCanBePrivate", "RemoveRedundantQualifierName", ) public object OAuth2ClientDSL { public val OAuth2ClientTable.allColumns: Array<Column<*>> by lazy { arrayOf( clientId, resourceIds, clientSecret, scopes, authorizedGrantTypes, redirectUrls, authorities, additionalInformation, autoApprove, enabled, accessTokenLiveSeconds, refreshTokenLiveSeconds, ) } public fun parseRow(raw: ResultRow): OAuth2Client { val plain = OAuth2Client() plain.clientId = raw[clientId] plain.resourceIds = raw[resourceIds] plain.clientSecret = raw[clientSecret] plain.scopes = raw[scopes] plain.authorizedGrantTypes = raw[authorizedGrantTypes] plain.redirectUrls = raw[redirectUrls] plain.authorities = raw[authorities] plain.additionalInformation = raw[additionalInformation] plain.autoApprove = raw[autoApprove] plain.enabled = raw[enabled] plain.accessTokenLiveSeconds = raw[accessTokenLiveSeconds] plain.refreshTokenLiveSeconds = raw[refreshTokenLiveSeconds] return plain } public fun parseRowSelective(row: ResultRow): OAuth2Client { val plain = OAuth2Client() if(row.hasValue(clientId)) { plain.clientId = row[clientId] } if(row.hasValue(resourceIds)) { plain.resourceIds = row[resourceIds] } if(row.hasValue(clientSecret)) { plain.clientSecret = row[clientSecret] } if(row.hasValue(scopes)) { plain.scopes = row[scopes] } if(row.hasValue(authorizedGrantTypes)) { plain.authorizedGrantTypes = row[authorizedGrantTypes] } if(row.hasValue(redirectUrls)) { plain.redirectUrls = row[redirectUrls] } if(row.hasValue(authorities)) { plain.authorities = row[authorities] } if(row.hasValue(additionalInformation)) { plain.additionalInformation = row[additionalInformation] } if(row.hasValue(autoApprove)) { plain.autoApprove = row[autoApprove] } if(row.hasValue(enabled)) { plain.enabled = row[enabled] } if(row.hasValue(accessTokenLiveSeconds)) { plain.accessTokenLiveSeconds = row[accessTokenLiveSeconds] } if(row.hasValue(refreshTokenLiveSeconds)) { plain.refreshTokenLiveSeconds = row[refreshTokenLiveSeconds] } return plain } public fun <T> OAuth2ClientTable.getColumnType(column: Column<T>): KClass<*> = when(column) { clientId->String::class resourceIds->String::class clientSecret->String::class scopes->String::class authorizedGrantTypes->String::class redirectUrls->String::class authorities->String::class additionalInformation->String::class autoApprove->Boolean::class enabled->Boolean::class accessTokenLiveSeconds->Int::class refreshTokenLiveSeconds->Int::class else->throw IllegalArgumentException("""Unknown column <${column.name}> for 'OAuth2Client'""") } @kotlin.Suppress("UNCHECKED_CAST") public fun <T> OAuth2Client.getColumnValue(column: Column<T>): T = when(column) { OAuth2ClientTable.clientId->this.clientId as T OAuth2ClientTable.resourceIds->this.resourceIds as T OAuth2ClientTable.clientSecret->this.clientSecret as T OAuth2ClientTable.scopes->this.scopes as T OAuth2ClientTable.authorizedGrantTypes->this.authorizedGrantTypes as T OAuth2ClientTable.redirectUrls->this.redirectUrls as T OAuth2ClientTable.authorities->this.authorities as T OAuth2ClientTable.additionalInformation->this.additionalInformation as T OAuth2ClientTable.autoApprove->this.autoApprove as T OAuth2ClientTable.enabled->this.enabled as T OAuth2ClientTable.accessTokenLiveSeconds->this.accessTokenLiveSeconds as T OAuth2ClientTable.refreshTokenLiveSeconds->this.refreshTokenLiveSeconds as T else->throw IllegalArgumentException("""Unknown column <${column.name}> for 'OAuth2Client'""") } public fun assign( builder: UpdateBuilder<*>, raw: OAuth2Client, selective: Array<out Column<*>>? = null, vararg ignore: Column<*>, ) { val list = if(selective.isNullOrEmpty()) null else selective if((list == null || list.contains(clientId)) && !ignore.contains(clientId)) builder[clientId] = raw.clientId if((list == null || list.contains(resourceIds)) && !ignore.contains(resourceIds)) builder[resourceIds] = raw.resourceIds if((list == null || list.contains(clientSecret)) && !ignore.contains(clientSecret)) builder[clientSecret] = raw.clientSecret if((list == null || list.contains(scopes)) && !ignore.contains(scopes)) builder[scopes] = raw.scopes if((list == null || list.contains(authorizedGrantTypes)) && !ignore.contains(authorizedGrantTypes)) builder[authorizedGrantTypes] = raw.authorizedGrantTypes if((list == null || list.contains(redirectUrls)) && !ignore.contains(redirectUrls)) builder[redirectUrls] = raw.redirectUrls if((list == null || list.contains(authorities)) && !ignore.contains(authorities)) builder[authorities] = raw.authorities if((list == null || list.contains(additionalInformation)) && !ignore.contains(additionalInformation)) builder[additionalInformation] = raw.additionalInformation if((list == null || list.contains(autoApprove)) && !ignore.contains(autoApprove)) builder[autoApprove] = raw.autoApprove if((list == null || list.contains(enabled)) && !ignore.contains(enabled)) builder[enabled] = raw.enabled if((list == null || list.contains(accessTokenLiveSeconds)) && !ignore.contains(accessTokenLiveSeconds)) builder[accessTokenLiveSeconds] = raw.accessTokenLiveSeconds if((list == null || list.contains(refreshTokenLiveSeconds)) && !ignore.contains(refreshTokenLiveSeconds)) builder[refreshTokenLiveSeconds] = raw.refreshTokenLiveSeconds } public fun ResultRow.toOAuth2Client(vararg selective: Column<*>): OAuth2Client { if(selective.isNotEmpty()) { return parseRowSelective(this) } return parseRow(this) } public fun Iterable<ResultRow>.toOAuth2ClientList(vararg selective: Column<*>): List<OAuth2Client> = this.map { it.toOAuth2Client(*selective) } public fun OAuth2ClientTable.selectSlice(vararg selective: Column<*>): Query { val query = if(selective.isNotEmpty()) { slice(selective.toList()).selectAll() } else { selectAll() } return query } public fun UpdateBuilder<*>.setValue(raw: OAuth2Client, vararg ignore: Column<*>): Unit = assign(this, raw, ignore = ignore) public fun UpdateBuilder<*>.setValueSelective(raw: OAuth2Client, vararg selective: Column<*>): Unit = assign(this, raw, selective = selective) public fun OAuth2ClientTable.insert(raw: OAuth2Client): InsertStatement<Number> = insert { assign(it, raw) } public fun OAuth2ClientTable.batchInsert( list: Iterable<OAuth2Client>, ignoreErrors: Boolean = false, shouldReturnGeneratedValues: Boolean = false, ): List<ResultRow> { val rows = batchInsert(list, ignoreErrors, shouldReturnGeneratedValues) { entry -> assign(this, entry) } return rows } public fun OAuth2ClientTable.update( raw: OAuth2Client, selective: Array<out Column<*>>? = null, ignore: Array<out Column<*>>? = null, limit: Int? = null, `where`: SqlExpressionBuilder.() -> Op<Boolean>, ): Int = update(`where`, limit) { val ignoreColumns = ignore ?: arrayOf() assign(it, raw, selective = selective, *ignoreColumns) } public fun OAuth2ClientTable.selectMany(vararg selective: Column<*>, `where`: Query.() -> Unit): List<OAuth2Client> { val query = selectSlice(*selective) `where`.invoke(query) return query.toOAuth2ClientList(*selective) } public fun OAuth2ClientTable.selectOne(vararg selective: Column<*>, `where`: Query.() -> Unit): OAuth2Client? { val query = selectSlice(*selective) `where`.invoke(query) return query.firstOrNull()?.toOAuth2Client(*selective) } }
0
null
0
8
9e2b1f76bbb239ae9029bd27cda2d17f96b13326
10,368
application-framework
Apache License 2.0
basick/src/main/java/com/mozhimen/basick/taskk/temps/TaskKPollInfinite.kt
mozhimen
353,952,154
false
null
package com.mozhimen.basick.taskk.temps import coil.request.Disposable import com.mozhimen.basick.lintk.optin.OptInApiInit_ByLazy import com.mozhimen.basick.elemk.commons.ISuspend_Listener import com.mozhimen.basick.lintk.optin.OptInApiCall_BindLifecycle import com.mozhimen.basick.taskk.bases.BaseWakeBefDestroyTaskK import com.mozhimen.basick.utilk.android.util.et import kotlinx.coroutines.* import kotlin.coroutines.CoroutineContext @OptInApiCall_BindLifecycle @OptInApiInit_ByLazy open class TaskKPollInfinite : BaseWakeBefDestroyTaskK() { private var _pollingScope: CoroutineScope? = null override fun isActive(): Boolean = _pollingScope != null && _pollingScope!!.isActive /** * * @param intervalMillis Long 循环间隔时长 * @param context CoroutineContext * @param task SuspendFunction0<Unit> */ open fun start(intervalMillis: Long, context: CoroutineContext = Dispatchers.IO, task: /*suspend*/ ISuspend_Listener) { if (isActive()) return val scope = CoroutineScope(context) scope.launch { while (isActive) { try { task.invoke() } catch (e: Exception) { if (e is CancellationException) return@launch e.printStackTrace() e.message?.et(TAG) } delay(intervalMillis) } } _pollingScope = scope } override fun cancel() { if (!isActive()) return _pollingScope?.cancel() _pollingScope = null } }
1
null
8
118
8192372dff44185d6c61ff39958e7d61a6521305
1,585
SwiftKit
Apache License 2.0
domain/src/main/kotlin/no/nav/su/se/bakover/domain/oppdrag/KryssjekkTidslinjerOgSimulering.kt
navikt
227,366,088
false
null
package no.nav.su.se.bakover.domain.oppdrag import arrow.core.Either import arrow.core.getOrElse import arrow.core.left import arrow.core.right import no.nav.su.se.bakover.common.extensions.førsteINesteMåned import no.nav.su.se.bakover.common.sikkerLogg import no.nav.su.se.bakover.common.tid.periode.Måned import no.nav.su.se.bakover.common.tid.periode.Periode import no.nav.su.se.bakover.domain.oppdrag.simulering.SimuleringFeilet import no.nav.su.se.bakover.domain.oppdrag.utbetaling.TidslinjeForUtbetalinger import no.nav.su.se.bakover.domain.oppdrag.utbetaling.Utbetalinger import no.nav.su.se.bakover.domain.oppdrag.utbetaling.UtbetalingslinjePåTidslinje import org.slf4j.Logger import org.slf4j.LoggerFactory import økonomi.domain.simulering.Simulering data object KryssjekkTidslinjerOgSimulering { fun sjekk( log: Logger = LoggerFactory.getLogger(this::class.java), underArbeidEndringsperiode: Periode, underArbeid: Utbetaling.UtbetalingForSimulering, eksisterende: Utbetalinger, simuler: (utbetalingForSimulering: Utbetaling.UtbetalingForSimulering, periode: Periode) -> Either<SimuleringFeilet, Utbetaling.SimulertUtbetaling>, ): Either<KryssjekkAvTidslinjeOgSimuleringFeilet, Unit> { val periode = Periode.create( fraOgMed = underArbeid.tidligsteDato(), tilOgMed = underArbeid.senesteDato(), ) val simulertUtbetaling = simuler(underArbeid, periode) .getOrElse { log.error( "Feil ved kryssjekk av tidslinje og simulering, kunne ikke simulere: $it", RuntimeException("Genererer en stacktrace for enklere debugging."), ) return KryssjekkAvTidslinjeOgSimuleringFeilet.KunneIkkeSimulere(it).left() } val tidslinjeEksisterendeOgUnderArbeid = (eksisterende + underArbeid) .tidslinje() .getOrElse { log.error( "Feil ved kryssjekk av tidslinje og simulering, kunne ikke generere tidslinjer: $it", RuntimeException("Genererer en stacktrace for enklere debugging."), ) return KryssjekkAvTidslinjeOgSimuleringFeilet.KunneIkkeGenerereTidslinje.left() } sjekkTidslinjeMotSimulering( tidslinjeEksisterendeOgUnderArbeid = tidslinjeEksisterendeOgUnderArbeid, simulering = simulertUtbetaling.simulering, ).getOrElse { log.error( "Feil (${it.map { it::class.simpleName }}) ved kryssjekk av tidslinje og simulering. Se sikkerlogg for detaljer", RuntimeException("Genererer en stacktrace for enklere debugging."), ) sikkerLogg.error("Feil: $it ved kryssjekk av tidslinje: $tidslinjeEksisterendeOgUnderArbeid og simulering: ${simulertUtbetaling.simulering}") return KryssjekkAvTidslinjeOgSimuleringFeilet.KryssjekkFeilet(it.first()).left() } if (eksisterende.harUtbetalingerEtterDato(underArbeidEndringsperiode.tilOgMed)) { val rekonstruertPeriode = Periode.create( fraOgMed = underArbeidEndringsperiode.tilOgMed.førsteINesteMåned(), tilOgMed = eksisterende.maxOf { it.senesteDato() }, ) val tidslinjeUnderArbeid = underArbeid.tidslinje() val tidslinjeEksisterende = eksisterende.tidslinje().getOrElse { log.error( "Feil ved kryssjekk av tidslinje og simulering, kunne ikke generere tidslinjer: $it", RuntimeException("Genererer en stacktrace for enklere debugging."), ) return KryssjekkAvTidslinjeOgSimuleringFeilet.KunneIkkeGenerereTidslinje.left() } if (!tidslinjeUnderArbeid.ekvivalentMedInnenforPeriode(tidslinjeEksisterende, rekonstruertPeriode)) { log.error( "Feil ved kryssjekk av tidslinje og simulering. Tidslinje for ny utbetaling er ulik eksisterende. Se sikkerlogg for detaljer", RuntimeException("Genererer en stacktrace for enklere debugging."), ) sikkerLogg.error("Feil ved kryssjekk av tidslinje: Tidslinje for ny utbetaling:$tidslinjeUnderArbeid er ulik eksisterende:$tidslinjeEksisterende for rekonstruert periode:$rekonstruertPeriode") return KryssjekkAvTidslinjeOgSimuleringFeilet.RekonstruertUtbetalingsperiodeErUlikOpprinnelig.left() } } return Unit.right() } } sealed interface KryssjekkAvTidslinjeOgSimuleringFeilet { data class KryssjekkFeilet(val feil: KryssjekkFeil) : KryssjekkAvTidslinjeOgSimuleringFeilet data object RekonstruertUtbetalingsperiodeErUlikOpprinnelig : KryssjekkAvTidslinjeOgSimuleringFeilet data class KunneIkkeSimulere(val feil: SimuleringFeilet) : KryssjekkAvTidslinjeOgSimuleringFeilet data object KunneIkkeGenerereTidslinje : KryssjekkAvTidslinjeOgSimuleringFeilet } private fun sjekkTidslinjeMotSimulering( tidslinjeEksisterendeOgUnderArbeid: TidslinjeForUtbetalinger, simulering: Simulering, ): Either<List<KryssjekkFeil>, Unit> { val feil = mutableListOf<KryssjekkFeil>() if (simulering.erAlleMånederUtenUtbetaling()) { simulering.periode().also { periode -> periode.måneder().forEach { val utbetaling = tidslinjeEksisterendeOgUnderArbeid.gjeldendeForDato(it.fraOgMed)!! if (!( utbetaling is UtbetalingslinjePåTidslinje.Stans || utbetaling is UtbetalingslinjePåTidslinje.Opphør || (utbetaling is UtbetalingslinjePåTidslinje.Ny && utbetaling.beløp == 0) || (utbetaling is UtbetalingslinjePåTidslinje.Reaktivering && utbetaling.beløp == 0) ) ) { feil.add( KryssjekkFeil.KombinasjonAvSimulertTypeOgTidslinjeTypeErUgyldig( måned = it, simulertType = "IngenUtbetaling", tidslinjeType = utbetaling::class.toString(), ), ) } } } } else { simulering.hentTotalUtbetaling().forEach { månedsbeløp -> kryssjekkBeløp( måned = månedsbeløp.periode, simulertUtbetaling = månedsbeløp.beløp.sum(), beløpPåTidslinje = tidslinjeEksisterendeOgUnderArbeid.gjeldendeForDato(månedsbeløp.periode.fraOgMed)!!.beløp, ).getOrElse { feil.add(it) } } } return when (feil.isEmpty()) { true -> Unit.right() false -> feil.sorted().left() } } private fun kryssjekkBeløp( måned: Måned, simulertUtbetaling: Int, beløpPåTidslinje: Int, ): Either<KryssjekkFeil.SimulertBeløpOgTidslinjeBeløpErForskjellig, Unit> { return if (simulertUtbetaling != beløpPåTidslinje) { KryssjekkFeil.SimulertBeløpOgTidslinjeBeløpErForskjellig( måned = måned, simulertBeløp = simulertUtbetaling, tidslinjeBeløp = beløpPåTidslinje, ).left() } else { Unit.right() } }
5
Kotlin
1
1
fbeb1614c40e0f6fce631d4beb1ba25e2f78ddda
7,309
su-se-bakover
MIT License
app/src/main/java/sk/devprog/firmy/ui/screen/licenses/LicensesScreen.kt
yuraj11
637,130,066
false
{"Kotlin": 157151}
package sk.devprog.firmy.ui.screen.licenses import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import com.mikepenz.aboutlibraries.ui.compose.LibrariesContainer import sk.devprog.firmy.R import sk.devprog.firmy.ui.theme.AppTheme @OptIn(ExperimentalMaterial3Api::class) @Composable fun LicensesScreen(onBackClicked: () -> Unit) { Scaffold(topBar = { TopAppBar( title = { Text(text = stringResource(id = R.string.more_licenses_title)) }, navigationIcon = { IconButton(onClick = onBackClicked) { Icon( imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(id = R.string.top_app_bar_back) ) } } ) }) { padding -> LibrariesContainer(modifier = Modifier .padding(padding) .fillMaxSize()) } } @Preview @Composable private fun LicensesScreenPreview() { AppTheme { LicensesScreen(onBackClicked = {}) } }
0
Kotlin
0
1
bd10f991ae17fdc1830b7dd79bdda177ff880527
1,675
firmy
Apache License 2.0
app/src/main/java/com/hwinzniej/musichelper/ui/AboutPageUi.kt
Winnie0408
730,239,668
false
null
package com.hwinzniej.musichelper.ui import android.content.Intent import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Environment import android.webkit.WebView import android.widget.Toast import androidx.activity.compose.BackHandler import androidx.compose.animation.core.spring import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues 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.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.pager.PagerState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableFloatState import androidx.compose.runtime.MutableIntState import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView import androidx.compose.ui.zIndex import androidx.core.content.res.ResourcesCompat import androidx.core.graphics.drawable.toBitmap import com.alibaba.fastjson2.JSON import com.hwinzniej.musichelper.R import com.hwinzniej.musichelper.utils.MyVibrationEffect import com.hwinzniej.musichelper.utils.Tools import com.moriafly.salt.ui.RoundedColumn import com.moriafly.salt.ui.SaltTheme import com.moriafly.salt.ui.TitleBar import com.moriafly.salt.ui.UnstableSaltApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okhttp3.OkHttpClient import okhttp3.Request import java.io.File import java.util.Locale @OptIn(UnstableSaltApi::class, ExperimentalFoundationApi::class) @Composable fun AboutPageUi( settingsPageState: PagerState, showNewVersionAvailableDialog: MutableState<Boolean>, latestVersion: MutableState<String>, latestDescription: MutableState<String>, latestDownloadLink: MutableState<String>, enableHaptic: MutableState<Boolean>, language: MutableState<String>, updateFileSize: MutableFloatState, hapticStrength: MutableIntState ) { val coroutineScope = rememberCoroutineScope() val context = LocalContext.current var showLoadingProgressBar by remember { mutableStateOf(false) } var showYesNoDialog by remember { mutableStateOf(false) } var yesNoDialogTitle by remember { mutableStateOf("") } var yesNoDialogContent by remember { mutableStateOf("") } var showYesDialog by remember { mutableStateOf(false) } var yesDialogTitle by remember { mutableStateOf("") } var yesDialogContent by remember { mutableStateOf("") } var yesDialogCustomContent by remember { mutableStateOf<@Composable () -> Unit>({}) } var yesNoDialogOnConfirm by remember { mutableStateOf({}) } var yesDialogOnConfirm by remember { mutableStateOf({}) } BackHandler(enabled = settingsPageState.currentPage == 1) { coroutineScope.launch { settingsPageState.animateScrollToPage( 0, animationSpec = spring(2f) ) } } if (showYesNoDialog) { YesNoDialog( onDismiss = { showYesNoDialog = false }, onCancel = { showYesNoDialog = false }, onConfirm = { showYesNoDialog = false yesNoDialogOnConfirm() }, title = yesNoDialogTitle, content = yesNoDialogContent.ifEmpty { null }, enableHaptic = enableHaptic.value, hapticStrength = hapticStrength.intValue ) } if (showYesDialog) { YesDialog( onDismissRequest = { showYesDialog = false yesDialogOnConfirm() }, title = yesDialogTitle, content = yesDialogContent.ifEmpty { null }, fontSize = 14.sp, enableHaptic = enableHaptic.value, drawContent = yesDialogCustomContent, hapticStrength = hapticStrength.intValue ) } Column( modifier = Modifier .fillMaxSize() .background(color = SaltTheme.colors.background) ) { TitleBar( onBack = { MyVibrationEffect(context, enableHaptic.value, hapticStrength.intValue).click() coroutineScope.launch { settingsPageState.animateScrollToPage( 0, animationSpec = spring(2f) ) } }, text = stringResource(id = R.string.about_function_name), ) Box { if (showLoadingProgressBar) { LinearProgressIndicator( modifier = Modifier .fillMaxWidth() .zIndex(1f), color = SaltTheme.colors.highlight, trackColor = SaltTheme.colors.background ) } Column( modifier = Modifier .fillMaxSize() .background(color = SaltTheme.colors.background) .verticalScroll(rememberScrollState()) ) { Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.height(8.dp)) ResourcesCompat.getDrawable( context.resources, R.mipmap.ic_launcher_round, null )?.let { Image( modifier = Modifier .size(96.dp) .clip(RoundedCornerShape(12.dp)), bitmap = (it).toBitmap().asImageBitmap(), contentDescription = null ) } Spacer(modifier = Modifier.height(8.dp)) Text( text = stringResource( id = R.string.app_name ), fontSize = 19.sp, color = SaltTheme.colors.text ) Spacer(modifier = Modifier.height(8.dp)) Text( text = context.packageManager.getPackageInfo( context.packageName, 0 ).versionName, color = SaltTheme.colors.text ) Spacer(modifier = Modifier.height(4.dp)) } RoundedColumn { ItemTitle(text = stringResource(id = R.string.related_info)) if (context.packageManager.getApplicationInfo( context.packageName, 0 ).targetSdkVersion > 28 ) { Item( onClick = { yesDialogContent = "" yesDialogCustomContent = { Column( modifier = Modifier .heightIn(max = (LocalConfiguration.current.screenHeightDp / 1.8).dp) .verticalScroll(rememberScrollState()) ) { RoundedColumn { ItemTitle(text = stringResource(id = R.string.app_developer)) Text( modifier = Modifier.padding( horizontal = 16.dp, vertical = 8.dp ), text = "HWinZnieJ", color = SaltTheme.colors.text, fontSize = 14.sp ) } RoundedColumn { ItemTitle(text = stringResource(id = R.string.app_translator)) Text( modifier = Modifier.padding( horizontal = 16.dp, vertical = 8.dp ), text = "HWinZnieJ & Microsoft Copilot & DeepL Translator", color = SaltTheme.colors.text, fontSize = 14.sp ) } RoundedColumn { ItemTitle(text = stringResource(id = R.string.app_technical_supportor)) Text( modifier = Modifier.padding( horizontal = 16.dp, vertical = 8.dp ), text = "Microsoft Copilot & GitHub Copilot & OpenAI GPT-4", color = SaltTheme.colors.text, fontSize = 14.sp ) } RoundedColumn { ItemTitle(text = stringResource(id = R.string.app_special_thanks)) Text( modifier = Modifier .padding( horizontal = 16.dp, vertical = 8.dp ), text = "${ stringResource(id = R.string.coolapk) }\n叶谖儿、网恋被骗九八上单、路还要走、星辰与月、破晓px、OmegaFallen、鷄你太魅、暮雨江天、PO8的惊堂木、叁陈小洋楼、白给少年又来了、梦中之城你和TA、大帅帅帅帅逼、不良人有品大帅、大泉麻衣、zz_xmy、迷茫和乐观的小陈\n\n${ stringResource(id = R.string.qq_group) }\n过客、 、.、王八仨水、路还要走、天中HD、曾喜樂、。、ZERO、60、MATURE、Xik-、Zj、这是一个名字、唯爱、天择\uD83D\uDCAB、九江、迷雾水珠、K、七、xmy、大泉麻衣、w、Sandmい旧梦、奔跑吧,兄弟!、吔—、匿名用户、S\n\n${ stringResource( id = R.string.rank_no_order ) }", color = SaltTheme.colors.text, fontSize = 14.sp ) } } } yesDialogOnConfirm = {} yesDialogTitle = context.getString(R.string.staff) showYesDialog = true }, text = stringResource(id = R.string.staff), iconPainter = painterResource(id = R.drawable.developer), iconColor = SaltTheme.colors.text ) } Item( enabled = !showLoadingProgressBar, onClick = { coroutineScope.launch(Dispatchers.IO) { showLoadingProgressBar = true val client = OkHttpClient() var request = Request.Builder() .url("https://gitlab.com/api/v4/projects/54005438/releases/permalink/latest") .header( "PRIVATE-TOKEN", "" ) //TODO 不要提交到公开仓库!!! .get() .build() try { val response = JSON.parseObject( client.newCall(request).execute().body?.string() ) latestVersion.value = response.getString("name").replace("v", "") if (Tools().isVersionNewer( curVersion = context.packageManager.getPackageInfo( context.packageName, 0 ).versionName, newVersion = latestVersion.value ) ) { latestDescription.value = response.getString("description") latestDownloadLink.value = response.getString("description") .substring( latestDescription.value.indexOf("[app-release.apk](") + 18, latestDescription.value.indexOf("/app-release.apk)") + 16 ) latestDownloadLink.value = "https://gitlab.com/HWinZnieJ/LocalMusicHelper${latestDownloadLink.value}" request = Request.Builder() .url(latestDownloadLink.value) .head() .build() client.newCall(request).execute().header("Content-Length") ?.let { updateFileSize.floatValue = it.toFloat() } latestDescription.value = latestDescription.value.substring( 0, latestDescription.value.indexOf("\n[app-") ) showNewVersionAvailableDialog.value = true } else { withContext(Dispatchers.Main) { Toast.makeText( context, context.getString(R.string.no_update_available), Toast.LENGTH_SHORT ).show() } } } catch (e: Exception) { yesDialogCustomContent = {} yesDialogTitle = context.getString(R.string.error) yesDialogContent = "${context.getString(R.string.check_connectivity)}\n${ context.getString( R.string.error_details ) }\n- ${e.message.toString()}" yesDialogOnConfirm = {} showYesDialog = true } finally { showLoadingProgressBar = false } } }, text = stringResource(id = R.string.check_for_updates), iconPainter = painterResource(id = R.drawable.check_update), iconColor = SaltTheme.colors.text, iconPaddingValues = PaddingValues(all = 1.5.dp) ) Item( onClick = { yesDialogContent = "" yesDialogCustomContent = { val currentTheme = SaltTheme.colors.text.red Column( modifier = Modifier .heightIn( min = 0.1.dp, max = (LocalConfiguration.current.screenHeightDp / 1.8).dp ) ) { AndroidView(factory = { WebView(context) }) { webView -> val licensesHtml = if (currentTheme < 0.5f) { context.assets.open("licenses.html") .use { inputStream -> inputStream.bufferedReader().use { it.readText() } } } else { context.assets.open("licenses_dark.html") .use { inputStream -> inputStream.bufferedReader().use { it.readText() } } } webView.setBackgroundColor(0) webView.settings.javaScriptEnabled = false webView.loadDataWithBaseURL( null, licensesHtml, "text/html", "utf-8", null ) } } } yesDialogOnConfirm = { // 第一次切换语言,打开该对话框,再关闭后,会自动切换回系统语言, // 后续再进行相同操作则不会,原因未知,使用下面的方法来规避这个问题 var locale = Locale(language.value) if (language.value == "system") { locale = Resources.getSystem().configuration.locales[0] } val resources = context.resources val configuration = resources.configuration Locale.setDefault(locale) configuration.setLocale(locale) resources.updateConfiguration( configuration, resources.displayMetrics ) } yesDialogTitle = context.getString(R.string.open_source_licence) showYesDialog = true }, text = stringResource(id = R.string.open_source_licence), iconPainter = painterResource(id = R.drawable.license), iconColor = SaltTheme.colors.text ) Item( onClick = { yesNoDialogOnConfirm = { context.startActivity(Intent(Intent.ACTION_VIEW).apply { data = Uri.parse( "https://saltconv.hwinzniej.top:45999" ) }) } yesNoDialogTitle = context.getString(R.string.visit_the_link_below) yesNoDialogContent = "https://saltconv.hwinzniej.top:45999" showYesNoDialog = true }, text = stringResource(id = R.string.pc_salt_converter), iconPainter = painterResource(id = R.drawable.computer), iconColor = SaltTheme.colors.text ) Item( onClick = { yesDialogContent = "" yesDialogCustomContent = { RoundedColumn { Column( modifier = Modifier .heightIn( min = 0.1.dp, max = (LocalConfiguration.current.screenHeightDp / 1.5).dp ) .align(Alignment.CenterHorizontally) .padding(vertical = 8.dp) ) { Text( modifier = Modifier.align(Alignment.CenterHorizontally), text = stringResource(id = R.string.thank_you_very_much), color = SaltTheme.colors.text, fontSize = 15.sp ) Spacer(modifier = Modifier.height(12.dp)) Image( modifier = Modifier .clip(RoundedCornerShape(12.dp)) .size(200.dp) .clickable { val bitmap = BitmapFactory.decodeResource( context.resources, R.drawable.alipay ) try { MyVibrationEffect( context, enableHaptic.value, hapticStrength.intValue ).click() val path = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES ).absolutePath val directory = File(path) if (!directory.exists()) { directory.mkdir() } val file = File(directory, "hwinzniej_alipay.jpg") val out = file.outputStream() bitmap.compress( Bitmap.CompressFormat.JPEG, 100, out ) out.flush() out.close() context.sendBroadcast( Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file) ) ) Toast .makeText( context, context.getString(R.string.save_success), Toast.LENGTH_SHORT ) .show() } catch (_: Exception) { Toast .makeText( context, context.getString(R.string.save_failed), Toast.LENGTH_SHORT ) .show() } }, painter = painterResource(id = R.drawable.alipay), contentDescription = "" ) Spacer(modifier = Modifier.height(12.dp)) Image( modifier = Modifier .clip(RoundedCornerShape(12.dp)) .size(200.dp) .clickable { val bitmap = BitmapFactory.decodeResource( context.resources, R.drawable.wechat ) try { MyVibrationEffect( context, enableHaptic.value, hapticStrength.intValue ).click() val path = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES ).absolutePath val directory = File(path) if (!directory.exists()) { directory.mkdir() } val file = File(directory, "hwinzniej_wechat.png") val out = file.outputStream() bitmap.compress( Bitmap.CompressFormat.PNG, 100, out ) out.flush() out.close() context.sendBroadcast( Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file) ) ) Toast .makeText( context, context.getString(R.string.save_success), Toast.LENGTH_SHORT ) .show() } catch (_: Exception) { Toast .makeText( context, context.getString(R.string.save_failed), Toast.LENGTH_SHORT ) .show() } }, painter = painterResource(id = R.drawable.wechat), contentDescription = "" ) Spacer(modifier = Modifier.height(12.dp)) Text( modifier = Modifier.align(Alignment.CenterHorizontally), text = stringResource(id = R.string.save_image), color = SaltTheme.colors.text, fontSize = 12.sp ) } } } yesDialogTitle = context.getString(R.string.buy_me_a_coffee) yesDialogOnConfirm = {} showYesDialog = true }, text = stringResource(id = R.string.buy_me_a_coffee), iconPainter = painterResource(id = R.drawable.coffee), iconColor = SaltTheme.colors.text, iconPaddingValues = PaddingValues(all = 0.5.dp) ) } RoundedColumn { ItemTitle(text = stringResource(id = R.string.contact_developer)) Item( onClick = { yesNoDialogOnConfirm = { try { context.startActivity( Intent( Intent.ACTION_VIEW, Uri.parse("mqqapi://card/show_pslcard?src_type=internal&version=1&card_type=group&uin=931819834") ) ) Toast.makeText( context, context.getString(R.string.launching_app) .replace("#", "QQ"), Toast.LENGTH_SHORT ).show() } catch (e: Exception) { Toast.makeText( context, "${ context.getString(R.string.app_not_installed) .replace("#", "QQ") }, ${ context.getString(R.string.will_open_in_browser) }", Toast.LENGTH_SHORT ).show() context.startActivity( Intent( Intent.ACTION_VIEW, Uri.parse("https://qm.qq.com/q/dMPQiCYp8c") ) ) } } yesNoDialogTitle = context.getString(R.string.open_in_some_app) .replace("#", "QQ") yesNoDialogContent = "" showYesNoDialog = true }, text = stringResource(id = R.string.join_qq_group), iconPainter = painterResource(id = R.drawable.qq_group), iconPaddingValues = PaddingValues(all = 1.dp) ) Item( onClick = { yesNoDialogOnConfirm = { try { context.startActivity( Intent( Intent.ACTION_VIEW, Uri.parse("coolmarket://u/1844460") ) ) Toast.makeText( context, context.getString(R.string.launching_app).replace( "#", context.getString( R.string.coolapk ).replace("(:)|(:\\s)".toRegex(), "") ), Toast.LENGTH_SHORT ).show() } catch (e: Exception) { Toast.makeText( context, "${ context.getString(R.string.app_not_installed).replace( "#", context.getString(R.string.coolapk) .replace("(:)|(:\\s)".toRegex(), "") ) }, ${ context.getString(R.string.will_open_in_browser) }", Toast.LENGTH_SHORT ).show() context.startActivity( Intent( Intent.ACTION_VIEW, Uri.parse("http://www.coolapk.com/u/1844460") ) ) } } yesNoDialogTitle = context.getString(R.string.open_in_some_app) .replace( "#", context.getString(R.string.coolapk) .replace("(:)|(:\\s)".toRegex(), "") ) yesNoDialogContent = "" showYesNoDialog = true }, text = stringResource(id = R.string.follow_on_coolapk), iconPainter = painterResource(id = R.drawable.coolapk) ) Item( onClick = { yesNoDialogOnConfirm = { try { context.startActivity( Intent( Intent.ACTION_VIEW, Uri.parse("bilibili://space/221114757") ) ) Toast.makeText( context, context.getString(R.string.launching_app) .replace("#", "BiliBili"), Toast.LENGTH_SHORT ).show() } catch (e: Exception) { Toast.makeText( context, "${ context.getString(R.string.app_not_installed) .replace("#", "BiliBili") }, ${ context.getString(R.string.will_open_in_browser) }", Toast.LENGTH_SHORT ).show() context.startActivity( Intent( Intent.ACTION_VIEW, Uri.parse("https://space.bilibili.com/221114757") ) ) } } yesNoDialogTitle = context.getString(R.string.open_in_some_app) .replace("#", "BiliBili") yesNoDialogContent = "" showYesNoDialog = true }, text = stringResource(id = R.string.follow_on_bilibili), iconPainter = painterResource(id = R.drawable.bilibili), iconPaddingValues = PaddingValues(all = 1.dp) ) Item( onClick = { yesNoDialogOnConfirm = { context.startActivity(Intent(Intent.ACTION_VIEW).apply { data = Uri.parse( "https://github.com/Winnie0408/LocalMusicHelper" ) }) } yesNoDialogTitle = context.getString(R.string.visit_the_link_below) yesNoDialogContent = "https://github.com/Winnie0408/LocalMusicHelper" showYesNoDialog = true }, text = stringResource(id = R.string.open_source_github), sub = stringResource(id = R.string.open_source_sub), iconPainter = painterResource(id = R.drawable.github), iconColor = SaltTheme.colors.text ) Item( onClick = { yesNoDialogOnConfirm = { context.startActivity(Intent(Intent.ACTION_VIEW).apply { data = Uri.parse( "https://gitlab.com/HWinZnieJ/LocalMusicHelper" ) }) } yesNoDialogTitle = context.getString(R.string.visit_the_link_below) yesNoDialogContent = "https://gitlab.com/HWinZnieJ/LocalMusicHelper" showYesNoDialog = true }, text = stringResource(id = R.string.open_source_gitlab), sub = stringResource(id = R.string.open_source_sub), iconPainter = painterResource(id = R.drawable.gitlab), iconPaddingValues = PaddingValues(all = 1.dp) ) Item( onClick = { yesNoDialogOnConfirm = { context.startActivity(Intent(Intent.ACTION_VIEW).apply { data = Uri.parse( "https://gitee.com/winnie0408/LocalMusicHelper" ) }) } yesNoDialogTitle = context.getString(R.string.visit_the_link_below) yesNoDialogContent = "https://gitee.com/winnie0408/LocalMusicHelper" showYesNoDialog = true }, text = stringResource(id = R.string.open_source_gitee), sub = "${stringResource(id = R.string.open_source_sub)}\n${stringResource(id = R.string.temporarily_unavailable)}", iconPainter = painterResource(id = R.drawable.gitee), iconPaddingValues = PaddingValues(all = 1.dp), enabled = false ) } } } } } @Preview @Composable fun Preview1() { // AboutPageUi() }
0
null
2
98
016561a8fe6d601d4d0885fe2cc41023624806eb
45,625
LocalMusicHelper
MIT License
ok-marketplace-be-app-ktor/test/ApplicationInMemoryTest.kt
otuskotlin
323,966,359
false
null
import io.ktor.http.* import io.ktor.server.testing.* import ru.otus.otuskotlin.marketplace.backend.app.ktor.jsonConfig import ru.otus.otuskotlin.marketplace.backend.app.ktor.module import ru.otus.otuskotlin.marketplace.backend.repository.inmemory.demands.DemandRepoInMemory import ru.otus.otuskotlin.marketplace.backend.repository.inmemory.proposals.ProposalRepoInMemory import ru.otus.otuskotlin.marketplace.common.backend.models.* import ru.otus.otuskotlin.marketplace.common.kmp.RestEndpoints import ru.otus.otuskotlin.marketplace.transport.kmp.models.common.MpMessage import ru.otus.otuskotlin.marketplace.transport.kmp.models.common.MpWorkModeDto import ru.otus.otuskotlin.marketplace.transport.kmp.models.common.ResponseStatusDto import ru.otus.otuskotlin.marketplace.transport.kmp.models.demands.* import ru.otus.otuskotlin.marketplace.transport.kmp.models.proposals.MpRequestProposalOffers import ru.otus.otuskotlin.marketplace.transport.kmp.models.proposals.MpResponseProposalOffers import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.fail import kotlin.time.DurationUnit import kotlin.time.ExperimentalTime import kotlin.time.toDuration @OptIn(ExperimentalTime::class) internal class ApplicationInMemoryTest { companion object { val demand1 = MpDemandModel( id = MpDemandIdModel("test-demand-id-1"), title = "demand1", description = "Некая весьма тяжелая деталь", techDets = mutableSetOf( MpTechDetModel( param = MpTechParamModel( name = "Weight" ), value = "100", unit = MpUnitTypeModel(name = "kg") ) ) ) val demand2 = MpDemandModel( id = MpDemandIdModel("test-demand-id-2"), title = "demand2", description = "Что-то метровой высоты", techDets = mutableSetOf( MpTechDetModel( param = MpTechParamModel( name = "Height" ), value = "100", unit = MpUnitTypeModel(name = "mm") ) ) ) val demand3 = MpDemandModel( id = MpDemandIdModel("test-demand-id-3"), title = "demand3", description = "Очень длинная деталь", techDets = mutableSetOf( MpTechDetModel( param = MpTechParamModel( name = "Length" ), value = "10", unit = MpUnitTypeModel(name = "m") ) ) ) val proposal = MpProposalModel( id = MpProposalIdModel("test-proposal-id-1"), title = "DeMand" ) // создается репозитарий с начальными данными val demandRepo by lazy { DemandRepoInMemory( ttl = 15.toDuration(DurationUnit.MINUTES), initObjects = listOf(demand1, demand2, demand3) ) } val proposalRepo by lazy { ProposalRepoInMemory( ttl = 15.toDuration(DurationUnit.MINUTES), initObjects = listOf(proposal) ) } } @Test fun testRead() { withTestApplication({module(testDemandRepo = demandRepo)}) { handleRequest(HttpMethod.Post, RestEndpoints.demandRead) { val body = MpRequestDemandRead( requestId = "12345", demandId = demand1.id.id, debug = MpRequestDemandRead.Debug(mode = MpWorkModeDto.TEST) ) val format = jsonConfig val bodyString = format.encodeToString(MpMessage.serializer(), body) setBody(bodyString) addHeader("Content-Type", "application/json") }.apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Application.Json.withCharset(Charsets.UTF_8), response.contentType()) val jsonString = response.content ?: fail("Null response json") println(jsonString) val res = (jsonConfig.decodeFromString(MpMessage.serializer(), jsonString) as? MpResponseDemandRead) ?: fail("Incorrect response format") assertEquals(ResponseStatusDto.SUCCESS, res.status) assertEquals("12345", res.onRequest) assertEquals(demand1.title, res.demand?.title) assertEquals(demand1.description, res.demand?.description) assertEquals(demand1.techDets.size, res.demand?.techDets?.size) } } } @Test fun testCreate() { withTestApplication({module(testDemandRepo = demandRepo)}) { handleRequest(HttpMethod.Post, RestEndpoints.demandCreate) { val body = MpRequestDemandCreate( requestId = "12345", createData = MpDemandCreateDto( title = demand2.title, description = demand2.description, ), debug = MpRequestDemandCreate.Debug(mode = MpWorkModeDto.TEST) ) val format = jsonConfig val bodyString = format.encodeToString(MpMessage.serializer(), body) setBody(bodyString) addHeader("Content-Type", "application/json") }.apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Application.Json.withCharset(Charsets.UTF_8), response.contentType()) val jsonString = response.content ?: fail("Null response json") println(jsonString) val res = (jsonConfig.decodeFromString(MpMessage.serializer(), jsonString) as? MpResponseDemandCreate) ?: fail("Incorrect response format") assertEquals(ResponseStatusDto.SUCCESS, res.status) assertEquals("12345", res.onRequest) assertEquals(demand2.title, res.demand?.title) assertEquals(demand2.description, res.demand?.description) } } } @Test fun testUpdate() { withTestApplication({module(testDemandRepo = demandRepo)}) { handleRequest(HttpMethod.Post, RestEndpoints.demandUpdate) { val body = MpRequestDemandUpdate( requestId = "12345", updateData = MpDemandUpdateDto( id = demand3.id.id, title = demand3.title, description = demand3.description ), debug = MpRequestDemandUpdate.Debug(mode = MpWorkModeDto.TEST) ) val format = jsonConfig val bodyString = format.encodeToString(MpMessage.serializer(), body) setBody(bodyString) addHeader("Content-Type", "application/json") }.apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Application.Json.withCharset(Charsets.UTF_8), response.contentType()) val jsonString = response.content ?: fail("Null response json") println(jsonString) val res = (jsonConfig.decodeFromString(MpMessage.serializer(), jsonString) as? MpResponseDemandUpdate) ?: fail("Incorrect response format") assertEquals(ResponseStatusDto.SUCCESS, res.status) assertEquals("12345", res.onRequest) assertEquals(demand3.id.id, res.demand?.id) assertEquals(demand3.title, res.demand?.title) assertEquals(demand3.description, res.demand?.description) assertEquals(null, res.demand?.techDets) } } } @Test fun testDelete() { withTestApplication({module(testDemandRepo = demandRepo)}) { handleRequest(HttpMethod.Post, RestEndpoints.demandDelete) { val body = MpRequestDemandDelete( requestId = "12345", demandId = demand2.id.id, debug = MpRequestDemandDelete.Debug(mode = MpWorkModeDto.TEST) ) val format = jsonConfig val bodyString = format.encodeToString(MpMessage.serializer(), body) setBody(bodyString) addHeader("Content-Type", "application/json") }.apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Application.Json.withCharset(Charsets.UTF_8), response.contentType()) val jsonString = response.content ?: fail("Null response json") println(jsonString) val res = (jsonConfig.decodeFromString(MpMessage.serializer(), jsonString) as? MpResponseDemandDelete) ?: fail("Incorrect response format") assertEquals(ResponseStatusDto.SUCCESS, res.status) assertEquals("12345", res.onRequest) assertEquals(demand2.id.id, res.demand?.id) assertEquals(demand2.title, res.demand?.title) assertEquals(demand2.description, res.demand?.description) assertEquals(demand2.techDets.size, res.demand?.techDets?.size) } } } @Test fun testList() { withTestApplication({module(testDemandRepo = demandRepo)}) { handleRequest(HttpMethod.Post, RestEndpoints.demandList) { val body = MpRequestDemandList( requestId = "12345", filterData = MpDemandListFilterDto( text = "дет", offset = 0, count = 10, includeDescription = true, ), debug = MpRequestDemandList.Debug(mode = MpWorkModeDto.TEST) ) val format = jsonConfig val bodyString = format.encodeToString(MpMessage.serializer(), body) setBody(bodyString) addHeader("Content-Type", "application/json") }.apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Application.Json.withCharset(Charsets.UTF_8), response.contentType()) val jsonString = response.content ?: fail("Null response json") println(jsonString) val res = (jsonConfig.decodeFromString(MpMessage.serializer(), jsonString) as? MpResponseDemandList) ?: fail("Incorrect response format") assertEquals(ResponseStatusDto.SUCCESS, res.status) assertEquals("12345", res.onRequest) assertEquals(2, res.demands?.size) assertEquals(1, res.pageCount) } } } @Test fun testOffers() { withTestApplication({module(testDemandRepo = demandRepo, testProposalRepo = proposalRepo)}) { handleRequest(HttpMethod.Post, RestEndpoints.proposalOffers) { val body = MpRequestProposalOffers( requestId = "12345", proposalId = proposal.id.id, debug = MpRequestProposalOffers.Debug(mode = MpWorkModeDto.TEST) ) val format = jsonConfig val bodyString = format.encodeToString(MpMessage.serializer(), body) setBody(bodyString) addHeader("Content-Type", "application/json") }.apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(ContentType.Application.Json.withCharset(Charsets.UTF_8), response.contentType()) val jsonString = response.content ?: fail("Null response json") println(jsonString) val res = (jsonConfig.decodeFromString(MpMessage.serializer(), jsonString) as? MpResponseProposalOffers) ?: fail("Incorrect response format") assertEquals(ResponseStatusDto.SUCCESS, res.status) assertEquals("12345", res.onRequest) assertEquals(3, res.proposalDemands?.size) } } } }
0
Kotlin
0
1
5f52fc91b3d71397cfabd02b5abb86a69d8567a1
12,612
202012-otuskotlin-marketplace
MIT License
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/greengrass/CfnDeviceDefinitionVersion.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 142794926}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.greengrass import io.cloudshiftdev.awscdk.CfnResource import io.cloudshiftdev.awscdk.IInspectable import io.cloudshiftdev.awscdk.IResolvable import io.cloudshiftdev.awscdk.TreeInspector import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Any import kotlin.Boolean import kotlin.String import kotlin.Unit import kotlin.collections.List import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct import software.constructs.Construct as SoftwareConstructsConstruct /** * The `AWS::Greengrass::DeviceDefinitionVersion` resource represents a device definition version * for AWS IoT Greengrass . * * A device definition version contains a list of devices. * * * To create a device definition version, you must specify the ID of the device definition that you * want to associate with the version. For information about creating a device definition, see * [`AWS::Greengrass::DeviceDefinition`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-devicedefinition.html) * . * * After you create a device definition version that contains the devices you want to deploy, you * must add it to your group version. For more information, see * [`AWS::Greengrass::Group`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-group.html) * . * * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.greengrass.*; * CfnDeviceDefinitionVersion cfnDeviceDefinitionVersion = * CfnDeviceDefinitionVersion.Builder.create(this, "MyCfnDeviceDefinitionVersion") * .deviceDefinitionId("deviceDefinitionId") * .devices(List.of(DeviceProperty.builder() * .certificateArn("certificateArn") * .id("id") * .thingArn("thingArn") * // the properties below are optional * .syncShadow(false) * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-devicedefinitionversion.html) */ public open class CfnDeviceDefinitionVersion( cdkObject: software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion, ) : CfnResource(cdkObject), IInspectable { public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnDeviceDefinitionVersionProps, ) : this(software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion(scope.let(CloudshiftdevConstructsConstruct::unwrap), id, props.let(CfnDeviceDefinitionVersionProps::unwrap)) ) public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnDeviceDefinitionVersionProps.Builder.() -> Unit, ) : this(scope, id, CfnDeviceDefinitionVersionProps(props) ) /** * */ public open fun attrId(): String = unwrap(this).getAttrId() /** * The ID of the device definition associated with this version. */ public open fun deviceDefinitionId(): String = unwrap(this).getDeviceDefinitionId() /** * The ID of the device definition associated with this version. */ public open fun deviceDefinitionId(`value`: String) { unwrap(this).setDeviceDefinitionId(`value`) } /** * The devices in this version. */ public open fun devices(): Any = unwrap(this).getDevices() /** * The devices in this version. */ public open fun devices(`value`: IResolvable) { unwrap(this).setDevices(`value`.let(IResolvable::unwrap)) } /** * The devices in this version. */ public open fun devices(`value`: List<Any>) { unwrap(this).setDevices(`value`) } /** * The devices in this version. */ public open fun devices(vararg `value`: Any): Unit = devices(`value`.toList()) /** * Examines the CloudFormation resource and discloses attributes. * * @param inspector tree inspector to collect and process attributes. */ public override fun inspect(inspector: TreeInspector) { unwrap(this).inspect(inspector.let(TreeInspector::unwrap)) } /** * A fluent builder for [io.cloudshiftdev.awscdk.services.greengrass.CfnDeviceDefinitionVersion]. */ @CdkDslMarker public interface Builder { /** * The ID of the device definition associated with this version. * * This value is a GUID. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-devicedefinitionversion.html#cfn-greengrass-devicedefinitionversion-devicedefinitionid) * @param deviceDefinitionId The ID of the device definition associated with this version. */ public fun deviceDefinitionId(deviceDefinitionId: String) /** * The devices in this version. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-devicedefinitionversion.html#cfn-greengrass-devicedefinitionversion-devices) * @param devices The devices in this version. */ public fun devices(devices: IResolvable) /** * The devices in this version. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-devicedefinitionversion.html#cfn-greengrass-devicedefinitionversion-devices) * @param devices The devices in this version. */ public fun devices(devices: List<Any>) /** * The devices in this version. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-devicedefinitionversion.html#cfn-greengrass-devicedefinitionversion-devices) * @param devices The devices in this version. */ public fun devices(vararg devices: Any) } private class BuilderImpl( scope: SoftwareConstructsConstruct, id: String, ) : Builder { private val cdkBuilder: software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion.Builder = software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion.Builder.create(scope, id) /** * The ID of the device definition associated with this version. * * This value is a GUID. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-devicedefinitionversion.html#cfn-greengrass-devicedefinitionversion-devicedefinitionid) * @param deviceDefinitionId The ID of the device definition associated with this version. */ override fun deviceDefinitionId(deviceDefinitionId: String) { cdkBuilder.deviceDefinitionId(deviceDefinitionId) } /** * The devices in this version. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-devicedefinitionversion.html#cfn-greengrass-devicedefinitionversion-devices) * @param devices The devices in this version. */ override fun devices(devices: IResolvable) { cdkBuilder.devices(devices.let(IResolvable::unwrap)) } /** * The devices in this version. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-devicedefinitionversion.html#cfn-greengrass-devicedefinitionversion-devices) * @param devices The devices in this version. */ override fun devices(devices: List<Any>) { cdkBuilder.devices(devices) } /** * The devices in this version. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-devicedefinitionversion.html#cfn-greengrass-devicedefinitionversion-devices) * @param devices The devices in this version. */ override fun devices(vararg devices: Any): Unit = devices(devices.toList()) public fun build(): software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion = cdkBuilder.build() } public companion object { public val CFN_RESOURCE_TYPE_NAME: String = software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion.CFN_RESOURCE_TYPE_NAME public operator fun invoke( scope: CloudshiftdevConstructsConstruct, id: String, block: Builder.() -> Unit = {}, ): CfnDeviceDefinitionVersion { val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id) return CfnDeviceDefinitionVersion(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion): CfnDeviceDefinitionVersion = CfnDeviceDefinitionVersion(cdkObject) internal fun unwrap(wrapped: CfnDeviceDefinitionVersion): software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion = wrapped.cdkObject as software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion } /** * A device is an AWS IoT device (thing) that's added to a Greengrass group. * * Greengrass devices can communicate with the Greengrass core in the same group. For more * information, see [What Is AWS IoT Greengrass * ?](https://docs.aws.amazon.com/greengrass/v1/developerguide/what-is-gg.html) in the *Developer * Guide* . * * In an AWS CloudFormation template, the `Devices` property of the * [`AWS::Greengrass::DeviceDefinitionVersion`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-devicedefinitionversion.html) * resource contains a list of `Device` property types. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.greengrass.*; * DeviceProperty deviceProperty = DeviceProperty.builder() * .certificateArn("certificateArn") * .id("id") * .thingArn("thingArn") * // the properties below are optional * .syncShadow(false) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-devicedefinitionversion-device.html) */ public interface DeviceProperty { /** * The ARN of the device certificate for the device. * * This X.509 certificate is used to authenticate the device with AWS IoT and AWS IoT Greengrass * services. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-devicedefinitionversion-device.html#cfn-greengrass-devicedefinitionversion-device-certificatearn) */ public fun certificateArn(): String /** * A descriptive or arbitrary ID for the device. * * This value must be unique within the device definition version. Maximum length is 128 * characters with pattern `[a-zA-Z0-9:_-]+` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-devicedefinitionversion-device.html#cfn-greengrass-devicedefinitionversion-device-id) */ public fun id(): String /** * Indicates whether the device's local shadow is synced with the cloud automatically. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-devicedefinitionversion-device.html#cfn-greengrass-devicedefinitionversion-device-syncshadow) */ public fun syncShadow(): Any? = unwrap(this).getSyncShadow() /** * The Amazon Resource Name (ARN) of the device, which is an AWS IoT device (thing). * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-devicedefinitionversion-device.html#cfn-greengrass-devicedefinitionversion-device-thingarn) */ public fun thingArn(): String /** * A builder for [DeviceProperty] */ @CdkDslMarker public interface Builder { /** * @param certificateArn The ARN of the device certificate for the device. * This X.509 certificate is used to authenticate the device with AWS IoT and AWS IoT * Greengrass services. */ public fun certificateArn(certificateArn: String) /** * @param id A descriptive or arbitrary ID for the device. * This value must be unique within the device definition version. Maximum length is 128 * characters with pattern `[a-zA-Z0-9:_-]+` . */ public fun id(id: String) /** * @param syncShadow Indicates whether the device's local shadow is synced with the cloud * automatically. */ public fun syncShadow(syncShadow: Boolean) /** * @param syncShadow Indicates whether the device's local shadow is synced with the cloud * automatically. */ public fun syncShadow(syncShadow: IResolvable) /** * @param thingArn The Amazon Resource Name (ARN) of the device, which is an AWS IoT device * (thing). */ public fun thingArn(thingArn: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion.DeviceProperty.Builder = software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion.DeviceProperty.builder() /** * @param certificateArn The ARN of the device certificate for the device. * This X.509 certificate is used to authenticate the device with AWS IoT and AWS IoT * Greengrass services. */ override fun certificateArn(certificateArn: String) { cdkBuilder.certificateArn(certificateArn) } /** * @param id A descriptive or arbitrary ID for the device. * This value must be unique within the device definition version. Maximum length is 128 * characters with pattern `[a-zA-Z0-9:_-]+` . */ override fun id(id: String) { cdkBuilder.id(id) } /** * @param syncShadow Indicates whether the device's local shadow is synced with the cloud * automatically. */ override fun syncShadow(syncShadow: Boolean) { cdkBuilder.syncShadow(syncShadow) } /** * @param syncShadow Indicates whether the device's local shadow is synced with the cloud * automatically. */ override fun syncShadow(syncShadow: IResolvable) { cdkBuilder.syncShadow(syncShadow.let(IResolvable::unwrap)) } /** * @param thingArn The Amazon Resource Name (ARN) of the device, which is an AWS IoT device * (thing). */ override fun thingArn(thingArn: String) { cdkBuilder.thingArn(thingArn) } public fun build(): software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion.DeviceProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion.DeviceProperty, ) : CdkObject(cdkObject), DeviceProperty { /** * The ARN of the device certificate for the device. * * This X.509 certificate is used to authenticate the device with AWS IoT and AWS IoT * Greengrass services. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-devicedefinitionversion-device.html#cfn-greengrass-devicedefinitionversion-device-certificatearn) */ override fun certificateArn(): String = unwrap(this).getCertificateArn() /** * A descriptive or arbitrary ID for the device. * * This value must be unique within the device definition version. Maximum length is 128 * characters with pattern `[a-zA-Z0-9:_-]+` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-devicedefinitionversion-device.html#cfn-greengrass-devicedefinitionversion-device-id) */ override fun id(): String = unwrap(this).getId() /** * Indicates whether the device's local shadow is synced with the cloud automatically. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-devicedefinitionversion-device.html#cfn-greengrass-devicedefinitionversion-device-syncshadow) */ override fun syncShadow(): Any? = unwrap(this).getSyncShadow() /** * The Amazon Resource Name (ARN) of the device, which is an AWS IoT device (thing). * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-greengrass-devicedefinitionversion-device.html#cfn-greengrass-devicedefinitionversion-device-thingarn) */ override fun thingArn(): String = unwrap(this).getThingArn() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): DeviceProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion.DeviceProperty): DeviceProperty = CdkObjectWrappers.wrap(cdkObject) as? DeviceProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: DeviceProperty): software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion.DeviceProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.greengrass.CfnDeviceDefinitionVersion.DeviceProperty } } }
3
Kotlin
0
4
a18731816a3ec710bc89fb8767d2ab71cec558a6
17,957
kotlin-cdk-wrapper
Apache License 2.0
android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerButtonViewManager.kt
software-mansion
72,087,685
false
null
package com.swmansion.gesturehandler.react import android.annotation.SuppressLint import android.annotation.TargetApi import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.graphics.drawable.Drawable import android.graphics.drawable.LayerDrawable import android.graphics.drawable.PaintDrawable import android.graphics.drawable.RippleDrawable import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.RectShape import android.os.Build import android.util.TypedValue import android.view.MotionEvent import android.view.View import android.view.View.OnClickListener import android.view.ViewGroup import androidx.core.view.children import com.facebook.react.module.annotations.ReactModule import com.facebook.react.uimanager.PixelUtil import com.facebook.react.uimanager.ThemedReactContext import com.facebook.react.uimanager.ViewGroupManager import com.facebook.react.uimanager.ViewManagerDelegate import com.facebook.react.uimanager.ViewProps import com.facebook.react.uimanager.annotations.ReactProp import com.facebook.react.viewmanagers.RNGestureHandlerButtonManagerDelegate import com.facebook.react.viewmanagers.RNGestureHandlerButtonManagerInterface import com.swmansion.gesturehandler.core.NativeViewGestureHandler import com.swmansion.gesturehandler.react.RNGestureHandlerButtonViewManager.ButtonViewGroup @ReactModule(name = RNGestureHandlerButtonViewManager.REACT_CLASS) class RNGestureHandlerButtonViewManager : ViewGroupManager<ButtonViewGroup>(), RNGestureHandlerButtonManagerInterface<ButtonViewGroup> { private val mDelegate: ViewManagerDelegate<ButtonViewGroup> init { mDelegate = RNGestureHandlerButtonManagerDelegate<ButtonViewGroup, RNGestureHandlerButtonViewManager>(this) } override fun getName() = REACT_CLASS public override fun createViewInstance(context: ThemedReactContext) = ButtonViewGroup(context) @TargetApi(Build.VERSION_CODES.M) @ReactProp(name = "foreground") override fun setForeground(view: ButtonViewGroup, useDrawableOnForeground: Boolean) { view.useDrawableOnForeground = useDrawableOnForeground } @ReactProp(name = "borderless") override fun setBorderless(view: ButtonViewGroup, useBorderlessDrawable: Boolean) { view.useBorderlessDrawable = useBorderlessDrawable } @ReactProp(name = "enabled") override fun setEnabled(view: ButtonViewGroup, enabled: Boolean) { view.isEnabled = enabled } @ReactProp(name = ViewProps.BORDER_RADIUS) override fun setBorderRadius(view: ButtonViewGroup, borderRadius: Float) { view.borderRadius = borderRadius } @ReactProp(name = "rippleColor") override fun setRippleColor(view: ButtonViewGroup, rippleColor: Int?) { view.rippleColor = rippleColor } @ReactProp(name = "rippleRadius") override fun setRippleRadius(view: ButtonViewGroup, rippleRadius: Int) { view.rippleRadius = rippleRadius } @ReactProp(name = "exclusive") override fun setExclusive(view: ButtonViewGroup, exclusive: Boolean) { view.exclusive = exclusive } @ReactProp(name = "touchSoundDisabled") override fun setTouchSoundDisabled(view: ButtonViewGroup, touchSoundDisabled: Boolean) { view.isSoundEffectsEnabled = !touchSoundDisabled } override fun onAfterUpdateTransaction(view: ButtonViewGroup) { view.updateBackground() } override fun getDelegate(): ViewManagerDelegate<ButtonViewGroup>? { return mDelegate } class ButtonViewGroup(context: Context?) : ViewGroup(context), NativeViewGestureHandler.NativeViewGestureHandlerHook { // Using object because of handling null representing no value set. var rippleColor: Int? = null set(color) = withBackgroundUpdate { field = color } var rippleRadius: Int? = null set(radius) = withBackgroundUpdate { field = radius } var useDrawableOnForeground = false set(useForeground) = withBackgroundUpdate { field = useForeground } var useBorderlessDrawable = false var borderRadius = 0f set(radius) = withBackgroundUpdate { field = radius * resources.displayMetrics.density } var exclusive = true private var _backgroundColor = Color.TRANSPARENT private var needBackgroundUpdate = false private var lastEventTime = -1L private var lastAction = -1 var isTouched = false init { // we attach empty click listener to trigger tap sounds (see View#performClick()) setOnClickListener(dummyClickListener) isClickable = true isFocusable = true needBackgroundUpdate = true } private inline fun withBackgroundUpdate(block: () -> Unit) { block() needBackgroundUpdate = true } override fun setBackgroundColor(color: Int) = withBackgroundUpdate { _backgroundColor = color } override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { if (super.onInterceptTouchEvent(ev)) { return true } // We call `onTouchEvent` and wait until button changes state to `pressed`, if it's pressed // we return true so that the gesture handler can activate. onTouchEvent(ev) return isPressed } /** * Buttons in RN are wrapped in NativeViewGestureHandler which manages * calling onTouchEvent after activation of the handler. Problem is, in order to verify that * underlying button implementation is interested in receiving touches we have to call onTouchEvent * and check if button is pressed. * * This leads to invoking onTouchEvent twice which isn't idempotent in View - it calls OnClickListener * and plays sound effect if OnClickListener was set. * * To mitigate this behavior we use lastEventTime and lastAction variables to check that we already handled * the event in [onInterceptTouchEvent]. We assume here that different events * will have different event times or actions. * Events with same event time can occur on some devices for different actions. * (e.g. move and up in one gesture; move and cancel) * * Reference: * [com.swmansion.gesturehandler.NativeViewGestureHandler.onHandle] */ @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { if (event.action == MotionEvent.ACTION_CANCEL) { tryFreeingResponder() } val eventTime = event.eventTime val action = event.action // always true when lastEventTime or lastAction have default value (-1) if (lastEventTime != eventTime || lastAction != action) { lastEventTime = eventTime lastAction = action return super.onTouchEvent(event) } return false } fun updateBackground() { if (!needBackgroundUpdate) { return } needBackgroundUpdate = false if (_backgroundColor == Color.TRANSPARENT) { // reset background background = null } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // reset foreground foreground = null } val selectable = createSelectableDrawable() if (borderRadius != 0f) { // Radius-connected lines below ought to be considered // as a temporary solution. It do not allow to set // different radius on each corner. However, I suppose it's fairly // fine for button-related use cases. // Therefore it might be used as long as: // 1. ReactViewManager is not a generic class with a possibility to handle another ViewGroup // 2. There's no way to force native behavior of ReactViewGroup's superclass's onTouchEvent if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && selectable is RippleDrawable) { val mask = PaintDrawable(Color.WHITE) mask.setCornerRadius(borderRadius) selectable.setDrawableByLayerId(android.R.id.mask, mask) } } if (useDrawableOnForeground && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { foreground = selectable if (_backgroundColor != Color.TRANSPARENT) { setBackgroundColor(_backgroundColor) } } else if (_backgroundColor == Color.TRANSPARENT && rippleColor == null) { background = selectable } else { val colorDrawable = PaintDrawable(_backgroundColor) if (borderRadius != 0f) { colorDrawable.setCornerRadius(borderRadius) } val layerDrawable = LayerDrawable(if (selectable != null) arrayOf(colorDrawable, selectable) else arrayOf(colorDrawable)) background = layerDrawable } } private fun createSelectableDrawable(): Drawable? { // TODO: remove once support for RN 0.63 is dropped, since 0.64 minSdkVersion is 21 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { context.theme.resolveAttribute(android.R.attr.selectableItemBackground, resolveOutValue, true) @Suppress("Deprecation") return resources.getDrawable(resolveOutValue.resourceId) } // Since Android 13, alpha channel in RippleDrawable is clamped between [128, 255] // see https://github.com/aosp-mirror/platform_frameworks_base/blob/c1bd0480261460584753508327ca8a0c6fc80758/graphics/java/android/graphics/drawable/RippleDrawable.java#L1012 if (rippleColor == Color.TRANSPARENT && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { return null } val states = arrayOf(intArrayOf(android.R.attr.state_enabled)) val rippleRadius = rippleRadius val colorStateList = if (rippleColor != null) { val colors = intArrayOf(rippleColor!!) ColorStateList(states, colors) } else { // if rippleColor is null, reapply the default color context.theme.resolveAttribute(android.R.attr.colorControlHighlight, resolveOutValue, true) val colors = intArrayOf(resolveOutValue.data) ColorStateList(states, colors) } val drawable = RippleDrawable( colorStateList, null, if (useBorderlessDrawable) null else ShapeDrawable(RectShape()) ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && rippleRadius != null) { drawable.radius = PixelUtil.toPixelFromDIP(rippleRadius.toFloat()).toInt() } return drawable } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { // No-op } override fun drawableHotspotChanged(x: Float, y: Float) { if (touchResponder == null || touchResponder === this) { super.drawableHotspotChanged(x, y) } } override fun canBegin(): Boolean { val isResponder = tryGrabbingResponder() if (isResponder) { isTouched = true } return isResponder } override fun afterGestureEnd(event: MotionEvent) { tryFreeingResponder() isTouched = false } private fun tryFreeingResponder() { if (touchResponder === this) { touchResponder = null soundResponder = this } } private fun tryGrabbingResponder(): Boolean { if (isChildTouched()) { return false } if (touchResponder == null) { touchResponder = this return true } return if (exclusive) { touchResponder === this } else { !(touchResponder?.exclusive ?: false) } } private fun isChildTouched(children: Sequence<View> = this.children): Boolean { for (child in children) { if (child is ButtonViewGroup && (child.isTouched || child.isPressed)) { return true } else if (child is ViewGroup) { if (isChildTouched(child.children)) { return true } } } return false } override fun performClick(): Boolean { // don't preform click when a child button is pressed (mainly to prevent sound effect of // a parent button from playing) return if (!isChildTouched() && soundResponder == this) { tryFreeingResponder() soundResponder = null super.performClick() } else { false } } override fun setPressed(pressed: Boolean) { // there is a possibility of this method being called before NativeViewGestureHandler has // opportunity to call canStart, in that case we need to grab responder in case the gesture // will activate // when canStart is called eventually, tryGrabbingResponder will return true if the button // already is a responder if (pressed) { if (tryGrabbingResponder()) { soundResponder = this } } // button can be pressed alongside other button if both are non-exclusive and it doesn't have // any pressed children (to prevent pressing the parent when children is pressed). val canBePressedAlongsideOther = !exclusive && touchResponder?.exclusive != true && !isChildTouched() if (!pressed || touchResponder === this || canBePressedAlongsideOther) { // we set pressed state only for current responder or any non-exclusive button when responder // is null or non-exclusive, assuming it doesn't have pressed children isTouched = pressed super.setPressed(pressed) } if (!pressed && touchResponder === this) { // if the responder is no longer pressed we release button responder isTouched = false } } override fun dispatchDrawableHotspotChanged(x: Float, y: Float) { // No-op // by default Viewgroup would pass hotspot change events } companion object { var resolveOutValue = TypedValue() var touchResponder: ButtonViewGroup? = null var soundResponder: ButtonViewGroup? = null var dummyClickListener = OnClickListener { } } } companion object { const val REACT_CLASS = "RNGestureHandlerButton" } }
95
null
980
6,098
da9eed867ff09633c506fc9ad08634eaf707cbdb
13,979
react-native-gesture-handler
MIT License
data/src/main/java/dev/seabat/android/hellobottomnavi/data/repository/QiitaArticlesRepository.kt
seabat
614,867,401
false
null
package dev.seabat.android.hellobottomnavi.data.repository import dev.seabat.android.hellobottomnavi.data.BuildConfig import dev.seabat.android.hellobottomnavi.data.datasource.qiita.QiitaApiService import dev.seabat.android.hellobottomnavi.data.datasource.qiita.QiitaExceptionConverter import dev.seabat.android.hellobottomnavi.data.datasource.qiita.model.QiitaArticle import dev.seabat.android.hellobottomnavi.domain.entity.QiitaArticleEntity import dev.seabat.android.hellobottomnavi.domain.entity.QiitaArticleListEntity import dev.seabat.android.hellobottomnavi.domain.exception.HelloException import dev.seabat.android.hellobottomnavi.domain.repository.QiitaArticlesRepositoryContract import java.lang.Exception import java.text.SimpleDateFormat import java.util.Locale import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class QiitaArticlesRepository(private val endpoint: QiitaApiService) : QiitaArticlesRepositoryContract { override suspend fun fetchItems(query: String?): QiitaArticleListEntity? { // NOTE: 同期方式の場合はメインスレッド以外で通信する必要あり return withContext(Dispatchers.IO) { val response = try { // 同期方式で HTTP 通信を行う endpoint.getItems( token = "Bearer ${BuildConfig.QIITA_TOKEN}", page = "1", per_page = "100", query = query ?: "created:>2023-04-01" ).execute() } catch (e: Exception) { // 通信自体が失敗した場合 val exception = HelloException.convertTo(e as Throwable) throw exception } if (response.isSuccessful) { val responseBody = response.body() val totalCount = response.headers().get("Total-Count") val entityList = convertToEntity(responseBody, totalCount?.toInt()) entityList } else { val exception = QiitaExceptionConverter.convertTo( response.code(), response.errorBody()?.string() ) throw exception } } } private fun convertToEntity( articles: Array<QiitaArticle>?, totalCount: Int? ): QiitaArticleListEntity? = articles?.let { nonNullArticles -> QiitaArticleListEntity( nonNullArticles.map { QiitaArticleEntity( totalCount = totalCount, createdAt = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.JAPAN).parse( it.createdAt )!!, // NOTE: LocalDateTime#parse は Android O 以降で使用可能 title = it.title, url = it.url, ) } as ArrayList<QiitaArticleEntity> ) } }
0
Kotlin
0
0
b4c5afa9609ef0e07e36593b8545d9ab093c33ea
2,852
hello-bottom-navigation
Apache License 2.0
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/PaintBrushArrowDown.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.filled import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Filled.PaintBrushArrowDown: ImageVector get() { if (_paintBrushArrowDown != null) { return _paintBrushArrowDown!! } _paintBrushArrowDown = fluentIcon(name = "Filled.PaintBrushArrowDown") { fluentPath { moveTo(10.0f, 4.0f) arcToRelative(2.0f, 2.0f, 0.0f, true, true, 4.0f, 0.0f) verticalLineToRelative(3.5f) horizontalLineToRelative(2.75f) curveToRelative(1.24f, 0.0f, 2.25f, 1.0f, 2.25f, 2.25f) verticalLineToRelative(1.75f) lineTo(5.09f, 11.5f) curveToRelative(0.01f, -0.72f, 0.0f, -1.35f, -0.02f, -1.87f) arcTo(2.06f, 2.06f, 0.0f, false, true, 7.11f, 7.5f) lineTo(10.0f, 7.5f) lineTo(10.0f, 4.0f) close() moveTo(5.04f, 13.0f) lineTo(19.0f, 13.0f) verticalLineToRelative(1.15f) arcToRelative(1.74f, 1.74f, 0.0f, false, false, -2.45f, 1.6f) verticalLineToRelative(2.44f) arcToRelative(1.75f, 1.75f, 0.0f, false, false, -2.04f, 2.8f) lineTo(15.53f, 22.0f) horizontalLineToRelative(-4.98f) curveToRelative(0.17f, -0.38f, 0.36f, -0.87f, 0.54f, -1.39f) arcToRelative(9.53f, 9.53f, 0.0f, false, false, 0.41f, -1.84f) verticalLineToRelative(-0.02f) arcToRelative(0.75f, 0.75f, 0.0f, true, false, -1.5f, 0.03f) lineToRelative(-0.04f, 0.23f) curveToRelative(-0.04f, 0.23f, -0.12f, 0.6f, -0.3f, 1.13f) arcTo(16.83f, 16.83f, 0.0f, false, true, 8.91f, 22.0f) lineTo(7.57f, 22.0f) lineToRelative(0.4f, -0.93f) curveToRelative(0.4f, -0.97f, 0.88f, -2.23f, 1.02f, -3.21f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -1.48f, -0.22f) curveToRelative(-0.11f, 0.77f, -0.51f, 1.88f, -0.92f, 2.85f) arcTo(32.38f, 32.38f, 0.0f, false, true, 5.91f, 22.0f) lineTo(3.75f, 22.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.63f, -1.16f) curveToRelative(0.95f, -1.46f, 1.47f, -3.58f, 1.73f, -5.73f) curveToRelative(0.1f, -0.72f, 0.15f, -1.43f, 0.19f, -2.11f) close() moveTo(15.22f, 19.22f) curveToRelative(0.3f, -0.3f, 0.77f, -0.3f, 1.06f, 0.0f) lineToRelative(1.27f, 1.27f) verticalLineToRelative(-4.74f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 1.5f, 0.0f) verticalLineToRelative(4.64f) lineToRelative(1.17f, -1.17f) arcToRelative(0.75f, 0.75f, 0.0f, true, true, 1.06f, 1.06f) lineToRelative(-2.5f, 2.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.06f, 0.0f) lineToRelative(-2.5f, -2.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, -1.06f) close() } } return _paintBrushArrowDown!! } private var _paintBrushArrowDown: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
3,487
compose-fluent-ui
Apache License 2.0
app/src/main/java/com/kirakishou/photoexchange/helper/database/entity/GalleryPhotoEntity.kt
K1rakishou
109,590,033
false
null
package com.kirakishou.photoexchange.helper.database.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.kirakishou.photoexchange.helper.database.entity.GalleryPhotoEntity.Companion.TABLE_NAME @Entity(tableName = TABLE_NAME) class GalleryPhotoEntity( @PrimaryKey @ColumnInfo(name = PHOTO_NAME_COLUMN) var photoName: String = "", @ColumnInfo(name = LON_COLUMN) var lon: Double = -1.0, @ColumnInfo(name = LAT_COLUMN) var lat: Double = -1.0, @ColumnInfo(name = UPLOADED_ON_COLUMN) var uploadedOn: Long = 0L, @ColumnInfo(name = INSERTED_ON_COLUMN, index = true) var insertedOn: Long = 0L ) { fun isEmpty(): Boolean { return photoName == "" } companion object { fun empty(): GalleryPhotoEntity { return GalleryPhotoEntity() } fun create( photoName: String, lon: Double, lat: Double, uploadedOn: Long, insertedOn: Long ): GalleryPhotoEntity { return GalleryPhotoEntity( photoName, lon, lat, uploadedOn, insertedOn ) } const val TABLE_NAME = "GALLERY_PHOTOS" const val PHOTO_NAME_COLUMN = "PHOTO_NAME" const val LON_COLUMN = "LON" const val LAT_COLUMN = "LAT" const val UPLOADED_ON_COLUMN = "UPLOADED_ON" const val INSERTED_ON_COLUMN = "INSERTED_ON" } }
0
Kotlin
1
4
15f67029376a98353a01b5523dfb42d183a26bf2
1,383
photoexchange-android
Do What The F*ck You Want To Public License
compiler/testData/diagnostics/tests/evaluate/unaryMinusIndependentExpType.kt
JakeWharton
99,388,807
false
null
val p1: Int = -1 val p2: Long = -1 val p3: Byte = -1 val p4: Short = -1 val lp1: Int = <!INITIALIZER_TYPE_MISMATCH!>-1111111111111111111<!> val lp2: Long = -1111111111111111111 val lp3: Byte = <!INITIALIZER_TYPE_MISMATCH!>-1111111111111111111<!> val lp4: Short = <!INITIALIZER_TYPE_MISMATCH!>-1111111111111111111<!> val l1: Long = -1.toLong() val l2: Byte = <!INITIALIZER_TYPE_MISMATCH!>-1.toLong()<!> val l3: Int = <!INITIALIZER_TYPE_MISMATCH!>-1.toLong()<!> val l4: Short = <!INITIALIZER_TYPE_MISMATCH!>-1.toLong()<!> val b1: Byte = -1.toByte() val b2: Int = -1.toByte() val b3: Long = -1.toByte() val b4: Short = -1.toByte() val i1: Byte = -1.toInt() val i2: Int = -1.toInt() val i3: Long = -1.toInt() val i4: Short = -1.toInt() val s1: Byte = -1.toShort() val s2: Int = -1.toShort() val s3: Long = -1.toShort() val s4: Short = -1.toShort()
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
849
kotlin
Apache License 2.0
backend/service-import/src/jvmMain/kotlin/dev/johnoreilly/confetti/backend/import/Sessionize.kt
joreilly
436,024,503
false
null
package dev.johnoreilly.confetti.backend.import import dev.johnoreilly.confetti.backend.datastore.* import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.atTime import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import net.mbonnin.bare.graphql.* import kotlin.time.Duration.Companion.hours object Sessionize { private val droidConLondon2022 = "https://sessionize.com/api/v2/qi0g29hw/view/All" private val kotlinConf2023 = "https://sessionize.com/api/v2/rje6khfn/view/All" private val androidMakers2023 = "https://sessionize.com/api/v2/72i2tw4v/view/All" data class SessionizeData( val rooms: List<DRoom>, val sessions: List<DSession>, val speakers: List<DSpeaker>, ) suspend fun importDroidConLondon2022(): Int { return writeData( getData(droidConLondon2022), config = DConfig( id = ConferenceId.DroidConLondon2022.id, name = "droidcon London", timeZone = "Europe/London" ), venue = DVenue( id = "main", name = "Business Design Center", address = "52 Upper St, London N1 0QH, United Kingdom", description = mapOf( "en" to "Cool venue", "fr" to "Venue fraiche", ), latitude = 51.5342463, longitude = -0.1068864, imageUrl = "https://london.droidcon.com/wp-content/uploads/sites/3/2022/07/Venue2-1.png", floorPlanUrl = null ) ) } suspend fun importKotlinConf2023(): Int { return writeData( getData(kotlinConf2023).let { it.copy(sessions = it.sessions.filter { it.start.date.dayOfMonth != 12 }) }, config = DConfig( id = ConferenceId.KotlinConf2023.id, name = "KotlinConf 2023", timeZone = "Europe/Amsterdam" ), venue = DVenue( id = "main", name = "Business Design Center", address = "52 Upper St, London N1 0QH, United Kingdom", description = mapOf( "en" to "Cool venue", "fr" to "Venue fraiche", ), latitude = 51.5342463, longitude = -0.1068864, imageUrl = "https://london.droidcon.com/wp-content/uploads/sites/3/2022/07/Venue2-1.png", floorPlanUrl = null ) ) } private suspend fun getLinks(id: String): List<DLink> { val data = getJsonUrl("https://raw.githubusercontent.com/paug/AndroidMakersBackend/main/service-graphql/src/main/resources/links.json") return data.asMap.get(id)?.asList.orEmpty() .map { DLink( it.asMap.get("type").asString, it.asMap.get("url").asString ) } } suspend fun importAndroidMakers2023(): Int { return writeData( getData(androidMakers2023, ::getLinks), config = DConfig( id = ConferenceId.AndroidMakers2023.id, name = "Android Makers by droidcon", timeZone = "Europe/Paris", days = listOf(LocalDate(2023, 4, 27), LocalDate(2023, 4, 28)) ), venue = DVenue( id = "main", name = "<NAME>", address = "Av. de la République, 92120 Montrouge", description = mapOf( "en" to "Cool venue", "fr" to "Venue fraiche", ), latitude = 48.8188958, longitude = 2.3193016, imageUrl = "https://www.beffroidemontrouge.com/wp-content/uploads/2019/09/moebius-1.jpg", floorPlanUrl = null ), partnerGroups = partnerGroups("https://raw.githubusercontent.com/paug/AndroidMakersApp/ce800d6eefa4f83d34690161637d7f98918ee4a3/data/sponsors.json") ) } private fun writeData( sessionizeData: SessionizeData, config: DConfig, venue: DVenue, partnerGroups: List<DPartnerGroup> = emptyList() ): Int { return DataStore().write( sessions = sessionizeData.sessions.sortedBy { it.start }, rooms = sessionizeData.rooms, speakers = sessionizeData.speakers, partnerGroups = partnerGroups, config = config, venues = listOf(venue) ) } private suspend fun getData(url: String, linksFor: suspend ((String) -> List<DLink>) = { emptyList() }): SessionizeData { val data = getJsonUrl(url) val categories = data.asMap["categories"].asList.map { it.asMap } .flatMap { it["items"].asList }.map { it.asMap }.map { it["id"] to it["name"] }.toMap() val sessions = data.asMap["sessions"].asList.map { it.asMap }.mapNotNull { if (it.get("startsAt") == null || it.get("endsAt") == null) { /** * Guard against sessions that are not scheduled. */ return@mapNotNull null } DSession( id = it.get("id").asString, type = if (it.get("isServiceSession").cast()) "service" else "talk", title = it.get("title").asString, description = it.get("description")?.asString, language = "en-US", start = it.get("startsAt").asString.let { LocalDateTime.parse(it) }, end = it.get("endsAt").asString.let { LocalDateTime.parse(it) }, complexity = null, feedbackId = null, tags = it.get("categoryItems").asList.mapNotNull { categoryId -> categories.get(categoryId)?.asString }, rooms = listOf(it.get("roomId").toString()), speakers = it.get("speakers").asList.map { it.asString }, shortDescription = null, links = linksFor(it.get("id").asString), ) } var rooms = data.asMap["rooms"].asList.map { it.asMap }.map { DRoom( id = it.get("id").toString(), name = it.get("name").asString ) } if (rooms.isEmpty()) { rooms = sessions.flatMap { it.rooms }.distinct().map { DRoom(id = it, name = it) } } val speakers = data.asMap["speakers"].asList.map { it.asMap }.map { DSpeaker( id = it.get("id").asString, name = it.get("fullName").asString, photoUrl = it.get("profilePicture")?.asString, bio = it.get("bio")?.asString, tagline = it.get("tagLine")?.asString, city = null, company = null, companyLogoUrl = null, links = it.get("links").asList.map { it.asMap }.map { DLink( key = it.get("linkType").asString, url = it.get("url").asString ) } ) } return SessionizeData( rooms = rooms, sessions = sessions, speakers = speakers ) } }
37
Kotlin
44
443
039c4aadd82f7029df027a6332a4743a4470dbc8
7,646
Confetti
Apache License 2.0
modules/theme/src/commonMain/kotlin/io/imrekaszab/eaplayers/theme/AppTheme.kt
kaszabimre
853,228,340
false
null
package io.imrekaszab.eaplayers.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.text.selection.LocalTextSelectionColors import androidx.compose.material3.ColorScheme import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.LocalRippleConfiguration import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.ReadOnlyComposable @OptIn(ExperimentalMaterial3Api::class) @Composable fun AppTheme( dimens: AppDimens = AppTheme.dimens, shapes: AppShapes = AppShapes(AppTheme.dimens), darkTheme: Boolean = isSystemInDarkTheme(), // Flag to toggle between light and dark themes colors: AppColors = AppColors(), colorScheme: ColorScheme = getColorScheme(darkTheme = darkTheme), typography: AppTypography = AppTypography( AppTheme.dimens, colorScheme, fontFamily = getDefaultFontFamily() ), content: @Composable () -> Unit ) { CompositionLocalProvider( LocalAppColors provides colors, LocalAppDimens provides dimens, LocalAppTypography provides typography, LocalAppShapes provides shapes, LocalRippleConfiguration provides AppRippleTheme.getAppRippleTheme(), ) { MaterialTheme(colorScheme = debugColors()) { CompositionLocalProvider( LocalTextStyle provides AppTheme.typography.body.medium, LocalRippleConfiguration provides AppRippleTheme.getAppRippleTheme(), LocalAppShapes provides AppShapes(dimens), LocalTextSelectionColors provides appTextSelectionColors() ) { content() } } } } object AppTheme { val colors: AppColors @Composable @ReadOnlyComposable get() = LocalAppColors.current val dimens: AppDimens @Composable @ReadOnlyComposable get() = LocalAppDimens.current val typography: AppTypography @Composable @ReadOnlyComposable get() = LocalAppTypography.current // Dynamically generate the ColorScheme from the current AppColors val colorScheme: ColorScheme @Composable @ReadOnlyComposable get() = if (isSystemInDarkTheme()) { getDarkColors(LocalAppColors.current) } else { getLightColors(LocalAppColors.current) } val shapes: AppShapes @Composable @ReadOnlyComposable get() = LocalAppShapes.current }
3
null
2
2
85b56abea8531a2ace9aaa76e9508ab3ef64ad7f
2,684
EAPlayers
Apache License 2.0
app/src/main/java/ua/blackwind/limbushelper/domain/party/model/Party.kt
BlackW1ndCoding
609,364,983
false
null
package ua.blackwind.limbushelper.domain.party.model const val DEFAULT_PARTY_ID = 1 data class Party( val id: Int, val name: String, val sinners: List<PartySinner> ) fun Party.getAllIdentities() = sinners.map { it.identities }.flatten().map { it.identity } fun Party.getAllActiveIdentities() = sinners.map { it.identities }.flatten().filter { it.isActive } fun Party.getAllEgo() = sinners.map { it.ego }.flatten()
7
Kotlin
2
3
f832ec78af5bfca6f7e092d4e4f640b93983f393
429
limbus_helper
MIT License
app/src/main/java/me/ranko/autodark/ui/MainActivity.kt
0ranko0P
208,796,965
false
null
package me.ranko.autodark.ui import android.content.Intent import android.content.res.ColorStateList import android.os.Bundle import android.view.View import android.view.WindowManager import androidx.databinding.DataBindingUtil import androidx.databinding.Observable import androidx.databinding.ObservableField import androidx.fragment.app.FragmentManager import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.preference.PreferenceFragmentCompat import com.google.android.material.appbar.CollapsingToolbarLayout import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.snackbar.Snackbar import me.ranko.autodark.R import me.ranko.autodark.databinding.ActivityMainBinding class MainActivity : BaseListActivity(), FragmentManager.OnBackStackChangedListener { private lateinit var viewModel: MainViewModel private lateinit var binding: ActivityMainBinding private var restrictedDialog: BottomSheetDialog? = null private val summaryTextListener = object : Observable.OnPropertyChangedCallback() { override fun onPropertyChanged(sender: Observable, propertyId: Int) { val summary = (sender as ObservableField<*>).get() showSummary(summary as MainViewModel.Companion.Summary) } } override fun onCreate(savedInstanceState: Bundle?) { binding = DataBindingUtil.setContentView(this, R.layout.activity_main) binding.lifecycleOwner = this viewModel = ViewModelProvider(this, MainViewModel.Companion.Factory(application)) .get(MainViewModel::class.java) binding.viewModel = viewModel super.onCreate(savedInstanceState) viewModel.summaryText.addOnPropertyChangedCallback(summaryTextListener) viewModel.requirePermission.observe(this, Observer { required -> if (!required) return@Observer // ignore consumed signal // Show permission UI now PermissionActivity.startWithAnimationForResult(binding.fab, this) viewModel.onRequirePermissionConsumed() }) if (isLandScape) { val collapsingToolbar = binding.appbar.findViewById<CollapsingToolbarLayout>(R.id.collapsingToolbar)!! val transparent = ColorStateList.valueOf(getColor(android.R.color.transparent)) collapsingToolbar.setExpandedTitleTextColor(transparent) window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS) } supportFragmentManager.addOnBackStackChangedListener(this) if (savedInstanceState == null) { val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.container, MainFragment()) transaction.commit() } } override fun onResumeFragments() { super.onResumeFragments() viewModel.getDelayedSummary()?.run { // delayed summary exists, show summary showSummary(this) } // check on resume // so user won't ignore the receiver problem restrictedDialog = viewModel.getRestrictedDialog(this) restrictedDialog?.show() } private fun showSummary(summary: MainViewModel.Companion.Summary) { Snackbar.make(binding.coordinatorRoot, summary.message, Snackbar.LENGTH_LONG) .setAction(summary.actionStr, summary.action) .show() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == PermissionActivity.REQUEST_CODE_PERMISSION) { viewModel.onSecurePermissionResult(PermissionViewModel.checkSecurePermission(this)) } else { super.onActivityResult(requestCode, resultCode, data) } } override fun onBackStackChanged() { val frag = supportFragmentManager.findFragmentById(R.id.container) as PreferenceFragmentCompat frag.listView.apply { setPadding(paddingLeft, paddingTop, paddingRight, bottomNavHeight) if (clipToPadding) clipToPadding = false } } override fun getRootView(): View = binding.coordinatorRoot override fun getListView(): View? = null override fun getAppbar(): View? = null override fun applyInsetsToListPadding(top: Int, bottom: Int) { onBackStackChanged() } override fun onStop() { restrictedDialog?.run { if (isShowing) dismiss() } super.onStop() } override fun onDestroy() { viewModel.summaryText.removeOnPropertyChangedCallback(summaryTextListener) supportFragmentManager.removeOnBackStackChangedListener(this) super.onDestroy() } }
2
Kotlin
4
53
5a5b47014b38e5b461c5329a4387882b956c1f28
4,744
AutoDark
MIT License
api/src/test/kotlin/org/jetbrains/kotlinx/dl/api/core/activation/LishtActivationTest.kt
JetBrains
249,948,572
false
null
/* * Copyright 2020 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. */ package org.jetbrains.kotlinx.dl.api.core.activation import org.junit.jupiter.api.Test internal class LishtActivationTest : ActivationTest() { @Test fun apply() { val input = floatArrayOf(Float.NEGATIVE_INFINITY, -5f, -0.5f, 1f, 1.2f, 2f, 3f, Float.POSITIVE_INFINITY) val expected = floatArrayOf( Float.POSITIVE_INFINITY, 4.999546f, 0.23105858f, 0.7615942f, 1.0003856f, 1.9280552f, 2.9851642f, Float.POSITIVE_INFINITY ) assertActivationFunction(LishtActivation(), input, expected) } }
81
null
79
806
efaa1ebdf7bf9a131826d3ded42e1eb178e4fd19
846
KotlinDL
Apache License 2.0
data/src/main/java/com/ribsky/data/service/offline/article/ArticlesDatabase.kt
nexy791
607,748,138
false
{"Kotlin": 844377, "Java": 316}
package com.ribsky.data.service.offline.article import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.ribsky.data.converters.Converters import com.ribsky.data.model.ArticleApiModel @TypeConverters(Converters::class) @Database(entities = [ArticleApiModel::class], version = 1, exportSchema = false) abstract class ArticlesDatabase : RoomDatabase() { abstract val dao: ArticlesDao companion object { const val DATABASE_NAME = "articles_database" } }
0
Kotlin
0
17
aa23106d2e167906066f433ff758a4b6ad1e5e4e
528
dymka
Apache License 2.0
rt/support/src/main/kotlin/LoggerReporting.kt
yandex
570,094,802
false
null
/* * Copyright 2022 Yandex LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yandex.yatagan.rt.support import com.yandex.yatagan.validation.RichString /** * An implementation of [DynamicValidationDelegate.ReportingDelegate], which is backed by a [logger]. * * @param logger a logger to use for printing messages. * @param useAnsiColor if `true`, then messages will be colored using ANSI control sequences. * Makes sense to use if the [logger] prints to a terminal or any other tool with ANSI-sequence support. * `false` means the output is plain string. */ class LoggerReporting( private val logger: Logger, private val useAnsiColor: Boolean = false, ): DynamicValidationDelegate.ReportingDelegate { override fun reportError(message: RichString) = report(message, "error") override fun reportWarning(message: RichString) = report(message, "warning") private fun report(message: RichString, messageKind: String) { val text = if (useAnsiColor) message.toAnsiEscapedString() else message.toString() logger.log("$messageKind: $text") } }
17
Kotlin
6
170
33418e21a7c6374bbe7b52b73b36781f99b27d25
1,613
yatagan
Apache License 2.0
app/src/main/java/com/example/flixterapp/Article.kt
tpatel29
857,178,041
false
{"Kotlin": 26559}
package com.codepath.articlesearch import android.support.annotation.Keep import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Keep @Serializable data class SearchNewsResponse( @SerialName("response") val response: BaseResponse? ) @Keep @Serializable data class BaseResponse( @SerialName("docs") val docs: List<Article>? ) @Keep @Serializable data class Article( @SerialName("abstract") val abstract: String?, @SerialName("byline") val byline: Byline?, @SerialName("headline") val headline: HeadLine?, @SerialName("multimedia") val multimedia: List<MultiMedia>?, ): java.io.Serializable { val mediaImageUrl = "https://www.nytimes.com/${multimedia?.firstOrNull { it.url != null }?.url ?: ""}" } @Keep @Serializable data class HeadLine( @SerialName("main") val main: String ) : java.io.Serializable @Keep @Serializable data class Byline( @SerialName("original") val original: String? = null ) : java.io.Serializable @Keep @Serializable data class MultiMedia( @SerialName("url") val url: String? ) : java.io.Serializable
1
Kotlin
1
0
f8902b8b24514bc24a003135da615c6f8a571ece
1,130
Lab4Real
MIT License
src/main/kotlin/no/nav/familie/ks/sak/api/dto/KorrigertEtterbetalingRequestDto.kt
navikt
533,308,075
false
{"Kotlin": 3728348, "Gherkin": 186833, "Shell": 1839, "Dockerfile": 467}
package no.nav.familie.ks.sak.api.dto import no.nav.familie.ks.sak.kjerne.korrigertetterbetaling.KorrigertEtterbetaling import no.nav.familie.ks.sak.kjerne.korrigertetterbetaling.KorrigertEtterbetalingÅrsak import java.time.LocalDateTime data class KorrigertEtterbetalingRequestDto( val årsak: KorrigertEtterbetalingÅrsak, val begrunnelse: String?, val beløp: Int, ) data class KorrigertEtterbetalingResponsDto( val id: Long, val årsak: KorrigertEtterbetalingÅrsak, val begrunnelse: String?, val opprettetTidspunkt: LocalDateTime, val beløp: Int, val aktiv: Boolean, ) fun KorrigertEtterbetaling.tilKorrigertEtterbetalingResponsDto(): KorrigertEtterbetalingResponsDto = KorrigertEtterbetalingResponsDto( id = id, årsak = årsak, begrunnelse = begrunnelse, opprettetTidspunkt = opprettetTidspunkt, beløp = beløp, aktiv = aktiv, )
3
Kotlin
1
2
c39fb12189c468a433ca2920b1aa0f5509b23d54
924
familie-ks-sak
MIT License
app/src/main/java/com/udayy/android/utils/CustomInputDialog.kt
premchand-verma
382,544,390
false
null
package com.udayy.android.utils import android.app.Activity import android.app.Dialog import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.view.View import android.view.ViewGroup import android.view.Window import android.widget.Button import android.widget.EditText import android.widget.Toast import com.udayy.android.interfaces.OnLocationFileSelected import kotlinx.android.synthetic.main.dialog_location_name.* import com.udayy.android.R /** * Created by premchand. */ class CustomInputDialog(ctx: Activity?, selectedListener: OnLocationFileSelected) { init { createProgressDialog(ctx, selectedListener) } var dialog: Dialog? = null private fun createProgressDialog(ctx: Activity?, selectedListener: OnLocationFileSelected) { dialog = Dialog(ctx!!, R.style.Theme_Transparent) val window = dialog!!.window window!!.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) dialog!!.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) dialog!!.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog!!.setContentView(R.layout.dialog_location_name) dialog!!.setCanceledOnTouchOutside(false) dialog!!.setCancelable(true) dialog!!.btn_ok.setOnClickListener{ if(dialog!!.et_file.text.toString().trim().isEmpty()){ Toast.makeText(ctx, "Please enter folder.", Toast.LENGTH_SHORT).show() }else if(dialog!!.et_file_name.text.toString().trim().isEmpty()){ Toast.makeText(ctx, "Please enter file name.", Toast.LENGTH_SHORT).show() }else{ selectedListener.onLocationFileSelected(dialog!!.et_file.text.toString(), dialog!!.et_file_name.text.toString()) dismissDialog() } } } fun showDialog() { dialog!!.show() } fun dismissDialog() { dialog!!.dismiss() } }
0
Kotlin
0
0
5cd5396ba3df092a449bbbfb4fae7f8d96890eaf
1,981
udayy
Apache License 2.0
src/main/kotlin/other/MinAlgorithm.kt
DmitryTsyvtsyn
418,166,620
false
{"Kotlin": 228861}
package other import java.lang.IllegalArgumentException /** * * Algorithm for finding the minimum value from a list * */ class MinAlgorithm { fun <T : Comparable<T>> compute(items: List<T>) : T { if (items.isEmpty()) { throw IllegalArgumentException("items list is empty!") } var min = items[0] for (i in 1 until items.size) { if (min > items[i]) { min = items[i] } } return min } fun <T : Comparable<T>> computeRecursive(items: List<T>) : T { if (items.isEmpty()) { throw IllegalArgumentException("items list is empty!") } if (items.size == 1) { return items.first() } val first = items.first() val others = items.subList(1, items.size) val min = computeRecursive(others) return if (first < min) first else min } }
0
Kotlin
135
788
1f89f062a056e24cc289ffdd0c6e23cadf8df887
931
Kotlin-Algorithms-and-Design-Patterns
MIT License
next/kmp/browser/src/commonMain/kotlin/org/dweb_browser/browser/BrowserI18nResource.kt
BioforestChain
594,577,896
false
{"Kotlin": 2719211, "TypeScript": 733573, "Swift": 350492, "Vue": 150380, "SCSS": 39016, "Objective-C": 17350, "HTML": 13200, "Shell": 11193, "JavaScript": 3998, "CSS": 818}
package org.dweb_browser.browser import org.dweb_browser.core.help.types.MMID import org.dweb_browser.helper.compose.Language import org.dweb_browser.helper.compose.OneParamI18nResource import org.dweb_browser.helper.compose.SimpleI18nResource object BrowserI18nResource { val application_name = SimpleI18nResource(Language.ZH to "Dweb Browser", Language.EN to "Dweb Browser") val dialog_title_webview_upgrade = SimpleI18nResource(Language.ZH to "更新提示", Language.EN to "Update tip") class WebViewVersions(var currentVersion: String, var requiredVersion: String) val dialog_text_webview_upgrade = OneParamI18nResource( { WebViewVersions("", "") }, Language.ZH to { "当前系统中的 Android System Webview 版本过低 ($currentVersion),所安装扩展软件可能无法正确运行。\n如果遇到此类情况,请优先将 Android System Webview 版本更新至 $requiredVersion 以上再重试。" }, Language.EN to { "The Android System Webview version in the current system is too low ($currentVersion), and the installed extension software may not run correctly.\nIf you encounter this situation, please upgrade the Android System Webview version to $requiredVersion or above and try again. " }, ) val dialog_confirm_webview_upgrade = SimpleI18nResource(Language.ZH to "确定", Language.ZH to "Confirm") val dialog_dismiss_webview_upgrade = SimpleI18nResource(Language.ZH to "帮助文档", Language.ZH to "Help") val install_tab_download = SimpleI18nResource(Language.ZH to "下载", Language.EN to "DownLoad") val install_tab_file = SimpleI18nResource(Language.ZH to "文件", Language.EN to "File") val install_button_install = SimpleI18nResource(Language.ZH to "安装", Language.EN to "Install") val install_button_update = SimpleI18nResource(Language.ZH to "升级", Language.EN to "Upgrade") val install_button_downloading = SimpleI18nResource(Language.ZH to "下载中", Language.EN to "Downloading") val install_button_paused = SimpleI18nResource(Language.ZH to "暂停", Language.EN to "Pause") val install_button_installing = SimpleI18nResource(Language.ZH to "安装中", Language.EN to "Installing") val install_button_open = SimpleI18nResource(Language.ZH to "打开", Language.EN to "Open") val install_button_lower = SimpleI18nResource(Language.ZH to "版本降级", Language.EN to "Downgrade") val install_button_retry = SimpleI18nResource(Language.ZH to "重载失效资源", Language.EN to "Retry") val install_button_retry2 = SimpleI18nResource(Language.ZH to "重试", Language.EN to "Retry") val install_button_incompatible = SimpleI18nResource( Language.ZH to "软件不兼容", Language.EN to "Software Incompatible" ) val install_button_jump_home = SimpleI18nResource( Language.ZH to "打开来源页", Language.EN to "Go to Referring Page" ) val install_tooltip_warning = SimpleI18nResource(Language.ZH to "警告", Language.EN to "WARING") val install_tooltip_lower_version_tip = SimpleI18nResource( Language.ZH to "该目标版本低于当前已安装的版本,确定要进行降级安装吗?", Language.EN to "The target version is lower than the currently installed version. Are you sure you want to downgrade?" ) val install_tooltip_install_lower_action = SimpleI18nResource( Language.ZH to "降级安装", Language.EN to "Downgrade and install" ) val no_download_links = SimpleI18nResource( Language.ZH to "暂无下载数据", Language.EN to "There are no download links yet", ) val no_apps_data = SimpleI18nResource( Language.ZH to "没有应用数据", Language.EN to "There are no Apps", ) val unzip_title_no = SimpleI18nResource(Language.ZH to "编号", Language.EN to "No") val unzip_title_url = SimpleI18nResource(Language.ZH to "下载链接", Language.EN to "Download Link") val unzip_title_createTime = SimpleI18nResource(Language.ZH to "创建时间", Language.EN to "Create Time") val unzip_title_originMmid = SimpleI18nResource(Language.ZH to "下载来源", Language.EN to "Download App") val unzip_title_originUrl = SimpleI18nResource(Language.ZH to "数据来源", Language.EN to "Data Source") val unzip_title_mime = SimpleI18nResource(Language.ZH to "文件类型", Language.EN to "Mime") val button_name_confirm = SimpleI18nResource(Language.ZH to "确定", Language.EN to "Confirm") val button_name_cancel = SimpleI18nResource(Language.ZH to "取消", Language.EN to "Cancel") val top_bar_title_install = SimpleI18nResource(Language.ZH to "应用列表", Language.EN to "Application Manage") val top_bar_title_download = SimpleI18nResource(Language.ZH to "下载列表", Language.EN to "All Downloads") val top_bar_title_down_detail = SimpleI18nResource(Language.ZH to "下载详情", Language.EN to "Download Detail") val time_today = SimpleI18nResource(Language.ZH to "今天", Language.EN to "Today") val time_yesterday = SimpleI18nResource(Language.ZH to "昨天", Language.EN to "Yesterday") val privacy_title = SimpleI18nResource(Language.ZH to "温馨提示", Language.EN to "Tips") val privacy_content = SimpleI18nResource( Language.ZH to "欢迎使用 Dweb Browser,在您使用的时候,需要连接网络,产生的流量费用请咨询当地运营商。\n在使用 Dweb Browser 前,请认真阅读《隐私协议》。您需要同意并接受全部条款后再开始使用该软件。", Language.EN to "Welcome to Dweb Browser. Please note that an internet connection is required for use. Please consult your local operator for any data charges that may apply.\nBefore using Dweb Browser, please carefully read the 'Privacy Policy'. You must agree to and accept all terms and conditions before using the software." ) val privacy_policy = SimpleI18nResource(Language.ZH to "《隐私协议》", Language.EN to "'Privacy Policy'") val privacy_content_deny = SimpleI18nResource( Language.ZH to "本产品需要同意相关协议后才能使用哦", Language.EN to "This product can only be used after agreeing to the relevant agreement" ) val privacy_button_refuse = SimpleI18nResource(Language.ZH to "不同意", Language.EN to "Refuse") val privacy_button_agree = SimpleI18nResource(Language.ZH to "同意", Language.EN to "Agree") val privacy_button_exit = SimpleI18nResource(Language.ZH to "退出", Language.EN to "Exit") val privacy_button_i_know = SimpleI18nResource(Language.ZH to "已知晓", Language.EN to "I Know") val browser_short_name = SimpleI18nResource(Language.ZH to "浏览器", Language.EN to "Browser") val browser_search_engine = SimpleI18nResource(Language.ZH to "搜索引擎", Language.EN to "Search Engine") val browser_search_local = SimpleI18nResource(Language.ZH to "本地资源", Language.EN to "Local Resource") val browser_search_title = SimpleI18nResource(Language.ZH to "搜索", Language.EN to "Search") val browser_search_hint = SimpleI18nResource(Language.ZH to "搜索或输入网址", Language.EN to "Search or Input Website") val browser_empty_list = SimpleI18nResource(Language.ZH to "暂无数据", Language.EN to "No Data") val browser_bookmark_edit_dialog_title = SimpleI18nResource(Language.ZH to "编辑书签", Language.EN to "Edit Bookmark") val browser_search_noFound = SimpleI18nResource( Language.ZH to "未检索到符合关键字的本地资源", Language.EN to "No local resource matching the keyword was retrieved" ) val browser_bookmark_title = SimpleI18nResource(Language.ZH to "书签标题", Language.EN to "Bookmark Title") val browser_bookmark_url = SimpleI18nResource(Language.ZH to "链接地址", Language.EN to "Bookmark Url") val browser_add_bookmark = SimpleI18nResource(Language.ZH to "添加书签", Language.EN to "Add Bookmark") val browser_remove_bookmark = SimpleI18nResource(Language.ZH to "移除书签", Language.EN to "Remove Bookmark") val browser_options_share = SimpleI18nResource(Language.ZH to "分享", Language.EN to "Share") val browser_options_noTrace = SimpleI18nResource(Language.ZH to "无痕浏览", Language.EN to "NoTrace") val browser_options_privacy = SimpleI18nResource(Language.ZH to "隐私政策", Language.EN to "Privacy Policy") val browser_menu_scanner = SimpleI18nResource(Language.ZH to "扫一扫", Language.EN to "Scan") val browser_menu_add_to_desktop = SimpleI18nResource(Language.ZH to "添加到桌面", Language.EN to "Add To Desktop") val browser_multi_count = SimpleI18nResource(Language.ZH to "个标签页", Language.EN to "tabs") val browser_multi_done = SimpleI18nResource(Language.ZH to "完成", Language.EN to "Done") val search_short_name = SimpleI18nResource(Language.ZH to "搜索引擎", Language.EN to "Search") val toast_message_add_bookmark = SimpleI18nResource(Language.ZH to "添加书签成功", Language.EN to "Add Bookmark Success") val toast_message_remove_bookmark = SimpleI18nResource(Language.ZH to "移除书签成功", Language.EN to "Remove Bookmark Success") val toast_message_update_bookmark = SimpleI18nResource(Language.ZH to "修改书签成功", Language.EN to "Change Bookmark Success") val toast_message_add_desk_success = SimpleI18nResource(Language.ZH to "添加到桌面成功", Language.EN to "Add to Desktop Success") val toast_message_add_desk_exist = SimpleI18nResource( Language.ZH to "桌面已存在该链接", Language.EN to "Desktop Already Exist The Link" ) val toast_message_download_unzip_fail = SimpleI18nResource(Language.ZH to "安装失败", Language.EN to "Installed Fail") val toast_message_download_download_fail = SimpleI18nResource(Language.ZH to "下载失败", Language.EN to "Download Fail") val toast_message_download_downloading = SimpleI18nResource(Language.ZH to "正在下载中...", Language.EN to "Downloading...") object JMM { val tab_detail = SimpleI18nResource(Language.ZH to "详情", Language.EN to "Detail") val tab_intro = SimpleI18nResource(Language.ZH to "介绍", Language.EN to "Introduction") val tab_param = SimpleI18nResource(Language.ZH to "参数", Language.EN to "Parameter") val short_name = SimpleI18nResource(Language.ZH to "模块管理", Language.EN to "Module Manager") val history_tab_installed = SimpleI18nResource(Language.ZH to "已安装", Language.EN to "Installed") val history_tab_uninstalled = SimpleI18nResource(Language.ZH to "未安装", Language.EN to "No Install") val install_mmid = SimpleI18nResource(Language.ZH to "唯一标识", Language.EN to "id") val install_version = SimpleI18nResource(Language.ZH to "版本", Language.EN to "version") val install_introduction = SimpleI18nResource(Language.ZH to "应用介绍", Language.EN to "Introduction") val install_update_log = SimpleI18nResource(Language.ZH to "更新日志", Language.EN to "Update Log") val install_info = SimpleI18nResource(Language.ZH to "信息", Language.EN to "Info") val install_info_dev = SimpleI18nResource(Language.ZH to "开发者", Language.EN to "Developer") val install_info_size = SimpleI18nResource(Language.ZH to "应用大小", Language.EN to "App Size") val install_info_type = SimpleI18nResource(Language.ZH to "类别", Language.EN to "Type") val install_info_language = SimpleI18nResource(Language.ZH to "语言", Language.EN to "Language") val install_info_age = SimpleI18nResource(Language.ZH to "年龄", Language.EN to "Age") val install_info_copyright = SimpleI18nResource(Language.ZH to "版权", Language.EN to "CopyRight") val install_info_homepage = SimpleI18nResource(Language.ZH to "应用主页", Language.EN to "Home Page") val history_details = SimpleI18nResource(Language.ZH to "详情", Language.EN to "Details") val history_uninstall = SimpleI18nResource(Language.ZH to "卸载", Language.EN to "Uninstall") val url_invalid = SimpleI18nResource( Language.ZH to "网址已失效,请前往官网进行安装!", Language.EN to "The website is no longer valid, please go to the official website to install!" ) } object JsMM { class CanNotSupportTargetParams( var appName: String = "", var appId: MMID = "", var currentVersion: Int = -1, var minTarget: Int = -1, var maxTarget: Int = -1, ) val canNotSupportMinTarget = OneParamI18nResource({ CanNotSupportTargetParams() }, Language.ZH to { "应用:$appName($appId) 与容器版本不匹配,当前版本:${currentVersion},应用最低要求:${minTarget}" }, Language.EN to { "App: $appName($appId) is incompatible with the container version. Current version: ${currentVersion}, app minimum requirement: ${minTarget}." }) val canNotSupportMaxTarget = OneParamI18nResource({ CanNotSupportTargetParams() }, Language.ZH to { "应用:$appName($appId) 与容器版本不匹配,当前版本:${currentVersion},应用最高兼容到:${maxTarget}" }, Language.EN to { "App: $appName($appId) is incompatible with the container version. Current version: ${currentVersion}, app maximum compatibility: ${maxTarget}." }) } val download_shore_name = SimpleI18nResource(Language.ZH to "下载管理", Language.EN to "Download Manager") val dialog_version_title = SimpleI18nResource( Language.ZH to "版本更新", Language.EN to "Version Upgrade" ) val dialog_downloading_title = SimpleI18nResource( Language.ZH to "下载中...", Language.EN to "Downloading..." ) val dialog_install_title = SimpleI18nResource( Language.ZH to "安装提醒", Language.EN to "Install Reminder" ) val dialog_upgrade_description = SimpleI18nResource( Language.ZH to "发现新版本,请及时更新!", Language.EN to "Find a new version, please update!" ) val dialog_install_description = SimpleI18nResource( Language.ZH to "安装应用需要授权,请移步授权,再尝试!", Language.EN to "Authorization is required to install the application, please move to authorization and try again!" ) val dialog_upgrade_button_upgrade = SimpleI18nResource( Language.ZH to "升级", Language.EN to "Upgrade" ) val dialog_upgrade_button_delay = SimpleI18nResource( Language.ZH to "推迟", Language.EN to "Defer" ) val dialog_upgrade_button_background = SimpleI18nResource( Language.ZH to "后台下载", Language.EN to "Background" ) val dialog_upgrade_button_setting = SimpleI18nResource( Language.ZH to "设置", Language.EN to "Setting" ) object Home { val page_title = SimpleI18nResource(Language.ZH to "起始页", Language.EN to "Home Page") val search_error = SimpleI18nResource( Language.ZH to "没有与您搜索相关的数据!", Language.EN to "No data relevant to your search!" ) } object Web { val page_title = SimpleI18nResource(Language.ZH to "网页", Language.EN to "Web") } object Bookmark { val page_title = SimpleI18nResource(Language.ZH to "书签", Language.EN to "Bookmark") val tip_edit = SimpleI18nResource( Language.ZH to "点击书签可以进行修改", Language.EN to "You can edit in dialog by tap bookmark" ) } object History { val page_title = SimpleI18nResource(Language.ZH to "历史记录", Language.EN to "History Record") } object Engine { val page_title = SimpleI18nResource(Language.ZH to "搜索引擎", Language.EN to "Engines") val status_enable = SimpleI18nResource(Language.ZH to "开启", Language.EN to "Enable") val status_disable = SimpleI18nResource(Language.ZH to "关闭", Language.EN to "Disable") } object Download { val page_title = SimpleI18nResource(Language.ZH to "下载内容", Language.EN to "Downloads") val page_title_manage = SimpleI18nResource(Language.ZH to "下载管理", Language.EN to "Download Manager") val unknownSize = SimpleI18nResource(Language.ZH to "未知", Language.EN to "unknown") val dialog_download_title = SimpleI18nResource( Language.ZH to "下载文件", Language.EN to "Download File" ) val dialog_retry_title = SimpleI18nResource( Language.ZH to "是否重新下载文件?", Language.EN to "Do you want to re-download the file?" ) val dialog_retry_message = SimpleI18nResource( Language.ZH to "您想再次下载 %s ((%s)) 吗?", Language.EN to "Would you like to download %s ((%s)) again?" ) val dialog_confirm = SimpleI18nResource( Language.ZH to "再次下载", Language.EN to "Download Again" ) val dialog_cancel = SimpleI18nResource( Language.ZH to "取消", Language.EN to "Cancel" ) val button_title_init = SimpleI18nResource( Language.ZH to "下载", Language.EN to "Download" ) val button_title_resume = SimpleI18nResource( Language.ZH to "继续", Language.EN to "Resume" ) val button_title_pause = SimpleI18nResource( Language.ZH to "暂停", Language.EN to "Pause" ) val button_title_install = SimpleI18nResource( Language.ZH to "安装", Language.EN to "Install" ) val button_title_open = SimpleI18nResource( Language.ZH to "打开", Language.EN to "Open" ) val sheet_download_tip_cancel = SimpleI18nResource( Language.ZH to "取消", Language.EN to "Cancel" ) val sheet_download_tip_continue = SimpleI18nResource( Language.ZH to "继续下载", Language.EN to "Continue" ) val sheet_download_tip_reload = SimpleI18nResource( Language.ZH to "重新下载", Language.EN to "Re-Download" ) val tip_empty = SimpleI18nResource( Language.ZH to "暂无下载任务和记录", Language.EN to "No Download Tasks And Records" ) val dropdown_delete = SimpleI18nResource(Language.ZH to "删除", Language.EN to "Delete") val dropdown_share = SimpleI18nResource(Language.ZH to "分享", Language.EN to "Share") val dropdown_rename = SimpleI18nResource(Language.ZH to "重命名", Language.EN to "Rename") val chip_all = SimpleI18nResource(Language.ZH to "所有", Language.EN to "All") val chip_image = SimpleI18nResource(Language.ZH to "图片", Language.EN to "Photo") val chip_video = SimpleI18nResource(Language.ZH to "视频", Language.EN to "Video") val chip_audio = SimpleI18nResource(Language.ZH to "音频", Language.EN to "Audio") val chip_doc = SimpleI18nResource(Language.ZH to "文档", Language.EN to "Documents") val chip_package = SimpleI18nResource(Language.ZH to "压缩包", Language.EN to "Archives") val chip_other = SimpleI18nResource(Language.ZH to "其它", Language.EN to "Other") } object Setting { val page_title = SimpleI18nResource(Language.ZH to "设置", Language.EN to "Setting") } object QRCode { val short_name = SimpleI18nResource(Language.ZH to "二维码", Language.EN to "QR Code") val toast_mismatching = SimpleI18nResource( Language.ZH to "无法解析的数据 -> %s", Language.EN to "no support data -> %s" ) val permission_tip_camera_title = SimpleI18nResource( Language.ZH to "相机权限使用说明", Language.EN to "Camera Permission Instructions" ) val permission_tip_camera_message = SimpleI18nResource( Language.ZH to "DwebBrowser正在向您获取“相机”权限,同意后,将用于为您提供扫描二维码服务", Language.EN to "DwebBrowser is asking you for \"Camera\" permissions, and if you agree, it will be used to provide you with scanning QR code services" ) val permission_denied = SimpleI18nResource( Language.ZH to "获取“相机”权限失败,无法提供扫码服务", Language.EN to "Failed to obtain the Camera permission and cannot provide the code scanning service" ) val recognizing = SimpleI18nResource( Language.ZH to "正在识别中...", Language.EN to "Recognizing..." ) val confirm = SimpleI18nResource( Language.ZH to "确定", Language.EN to "Confirm" ) val photo_album = SimpleI18nResource( Language.ZH to "相册", Language.EN to "Album" ) } object IconDescription { val verified = SimpleI18nResource( Language.ZH to "已认证", Language.EN to "Verified" ) val unverified = SimpleI18nResource( Language.ZH to "未认证", Language.EN to "Unverified" ) } object Desktop { val quit = SimpleI18nResource( Language.ZH to "退出", Language.EN to "Close" ) val detail = SimpleI18nResource( Language.ZH to "详情", Language.EN to "Detail" ) val delete = SimpleI18nResource( Language.ZH to "删除", Language.EN to "Delete" ) val share = SimpleI18nResource( Language.ZH to "分享", Language.EN to "Share" ) } }
57
Kotlin
4
11
b9b39e294badbb02eeb3a3a6d1851fd5105bd09f
19,432
dweb_browser
MIT License
runtime/src/commonMain/kotlin/com/asyncant/io/MessageReceiver.kt
asyncant
363,257,201
false
{"Kotlin": 18781}
package com.asyncant.io internal interface MessageReceiver { fun append(data: ByteArray, size: Int) fun completed(): Boolean }
0
Kotlin
1
2
1c029f79b2b2c6e2c15580f60fd7e65f59c9d6ef
131
aws-lambda-kotlin-runtime
MIT License
src/main/java/com/cumulocity/client/api/TokensApi.kt
SoftwareAG
525,378,320
false
{"Kotlin": 776057}
// Copyright (c) 2014-2023 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. // Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. package com.cumulocity.client.api import retrofit2.converter.scalars.ScalarsConverterFactory import retrofit2.converter.gson.ExtendedGsonConverterFactory import retrofit2.Retrofit import retrofit2.Call import retrofit2.http.POST import retrofit2.http.Body import retrofit2.http.Header import retrofit2.http.Query import retrofit2.http.Headers import okhttp3.OkHttpClient import retrofit2.converter.gson.ReadOnlyProperties import com.cumulocity.client.model.NotificationTokenClaims import com.cumulocity.client.model.NotificationToken import com.cumulocity.client.model.NotificationSubscriptionResult /** * In order to receive subscribed notifications, a consumer application or microservice must obtain an authorization token that provides proof that the holder is allowed to receive subscribed notifications. */ interface TokensApi { companion object Factory { fun create(baseUrl: String): TokensApi { return create(baseUrl, null) } fun create(baseUrl: String, clientBuilder: OkHttpClient.Builder?): TokensApi { val retrofitBuilder = retrofit().baseUrl(baseUrl) if (clientBuilder != null) { retrofitBuilder.client(clientBuilder.build()) } return retrofitBuilder.build().create(TokensApi::class.java) } fun retrofit(): Retrofit.Builder{ return Retrofit.Builder() .addConverterFactory(ExtendedGsonConverterFactory()) .addConverterFactory(ScalarsConverterFactory.create()) } } /** * Create a notification token * * Create a new JWT (JSON web token) access token which can be used to establish a successful WebSocket connection to read a sequence of notifications. * * In general, each request to obtain an access token consists of: * * * The subscriber name which the client wishes to be identified with. * * The subscription name. This value must be associated with a subscription that's already been created and in essence, the obtained token will give the ability to read notifications for the subscription that is specified here. * * The token expiration duration. * * * ##### Required roles * * ROLE_NOTIFICATION_2_ADMIN * * ##### Response Codes * * The following table gives an overview of the possible response codes and their meanings: * * * HTTP 200 A notification token was created. * * HTTP 401 Authentication information is missing or invalid. * * HTTP 403 Not enough permissions/roles to perform this operation. * * HTTP 422 Unprocessable Entity – invalid payload. * * @param body * @param xCumulocityProcessingMode * Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers(*["Content-Type:application/json", "Accept:application/vnd.com.nsn.cumulocity.error+json, application/json"]) @POST("/notification2/token") fun createToken( @Body body: NotificationTokenClaims, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<NotificationToken> /** * Unsubscribe a subscriber * * Unsubscribe a notification subscriber using the notification token. * * Once a subscription is made, notifications will be kept until they are consumed by all subscribers who have previously connected to the subscription. For non-volatile subscriptions, this can result in notifications remaining in storage if never consumed by the application.They will be deleted if a tenant is deleted. It can take up considerable space in permanent storage for high-frequency notification sources. Therefore, we recommend you to unsubscribe a subscriber that will never run again. * * ##### Response Codes * * The following table gives an overview of the possible response codes and their meanings: * * * HTTP 200 The notification subscription was deleted or is scheduled for deletion. * * HTTP 401 Authentication information is missing or invalid. * * @param xCumulocityProcessingMode * Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. * @param token * Subscriptions associated with this token will be removed. */ @Headers("Accept:application/vnd.com.nsn.cumulocity.error+json, application/json") @POST("/notification2/unsubscribe") fun unsubscribeSubscriber( @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null, @Query("token") token: String ): Call<NotificationSubscriptionResult> }
1
Kotlin
1
3
b9e366de1d8d21fa479a42497d45a4efa4de2268
4,789
cumulocity-clients-kotlin
Apache License 2.0
core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraXCameraUseCase.kt
google
591,101,391
false
{"Kotlin": 640681, "C++": 2189, "CMake": 1010, "Shell": 724}
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.jetpackcamera.core.camera import android.app.Application import android.content.ContentResolver import android.content.ContentValues import android.net.Uri import android.os.Environment import android.provider.MediaStore import android.util.Log import androidx.camera.core.CameraInfo import androidx.camera.core.CameraSelector import androidx.camera.core.DynamicRange as CXDynamicRange import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCapture.OutputFileOptions import androidx.camera.core.ImageCaptureException import androidx.camera.core.SurfaceRequest import androidx.camera.core.takePicture import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.lifecycle.awaitInstance import androidx.camera.video.Recorder import com.google.jetpackcamera.settings.SettableConstraintsRepository import com.google.jetpackcamera.settings.model.AspectRatio import com.google.jetpackcamera.settings.model.CameraAppSettings import com.google.jetpackcamera.settings.model.CameraConstraints import com.google.jetpackcamera.settings.model.CaptureMode import com.google.jetpackcamera.settings.model.ConcurrentCameraMode import com.google.jetpackcamera.settings.model.DeviceRotation import com.google.jetpackcamera.settings.model.DynamicRange import com.google.jetpackcamera.settings.model.FlashMode import com.google.jetpackcamera.settings.model.ImageOutputFormat import com.google.jetpackcamera.settings.model.LensFacing import com.google.jetpackcamera.settings.model.LowLightBoost import com.google.jetpackcamera.settings.model.Stabilization import com.google.jetpackcamera.settings.model.SupportedStabilizationMode import com.google.jetpackcamera.settings.model.SystemConstraints import dagger.hilt.android.scopes.ViewModelScoped import java.io.FileNotFoundException import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale import javax.inject.Inject import kotlin.properties.Delegates import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.trySendBlocking import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update private const val TAG = "CameraXCameraUseCase" const val TARGET_FPS_AUTO = 0 const val TARGET_FPS_15 = 15 const val TARGET_FPS_30 = 30 const val TARGET_FPS_60 = 60 /** * CameraX based implementation for [CameraUseCase] */ @ViewModelScoped class CameraXCameraUseCase @Inject constructor( private val application: Application, private val defaultDispatcher: CoroutineDispatcher, private val constraintsRepository: SettableConstraintsRepository ) : CameraUseCase { private lateinit var cameraProvider: ProcessCameraProvider private var imageCaptureUseCase: ImageCapture? = null private lateinit var systemConstraints: SystemConstraints private var useCaseMode by Delegates.notNull<CameraUseCase.UseCaseMode>() private val screenFlashEvents: Channel<CameraUseCase.ScreenFlashEvent> = Channel(capacity = Channel.UNLIMITED) private val focusMeteringEvents = Channel<CameraEvent.FocusMeteringEvent>(capacity = Channel.CONFLATED) private val videoCaptureControlEvents = Channel<VideoCaptureControlEvent>() private val currentSettings = MutableStateFlow<CameraAppSettings?>(null) // Could be improved by setting initial value only when camera is initialized private val _currentCameraState = MutableStateFlow(CameraState()) override fun getCurrentCameraState(): StateFlow<CameraState> = _currentCameraState.asStateFlow() private val _surfaceRequest = MutableStateFlow<SurfaceRequest?>(null) override fun getSurfaceRequest(): StateFlow<SurfaceRequest?> = _surfaceRequest.asStateFlow() override suspend fun initialize( cameraAppSettings: CameraAppSettings, useCaseMode: CameraUseCase.UseCaseMode ) { this.useCaseMode = useCaseMode cameraProvider = ProcessCameraProvider.awaitInstance(application) // updates values for available cameras val availableCameraLenses = listOf( LensFacing.FRONT, LensFacing.BACK ).filter { cameraProvider.hasCamera(it.toCameraSelector()) } // Build and update the system constraints systemConstraints = SystemConstraints( availableLenses = availableCameraLenses, concurrentCamerasSupported = cameraProvider.availableConcurrentCameraInfos.any { it.map { cameraInfo -> cameraInfo.cameraSelector.toAppLensFacing() } .toSet() == setOf(LensFacing.FRONT, LensFacing.BACK) }, perLensConstraints = buildMap { val availableCameraInfos = cameraProvider.availableCameraInfos for (lensFacing in availableCameraLenses) { val selector = lensFacing.toCameraSelector() selector.filter(availableCameraInfos).firstOrNull()?.let { camInfo -> val supportedDynamicRanges = Recorder.getVideoCapabilities(camInfo).supportedDynamicRanges .mapNotNull(CXDynamicRange::toSupportedAppDynamicRange) .toSet() val supportedStabilizationModes = buildSet { if (camInfo.isPreviewStabilizationSupported) { add(SupportedStabilizationMode.ON) } if (camInfo.isVideoStabilizationSupported) { add(SupportedStabilizationMode.HIGH_QUALITY) } } val supportedFixedFrameRates = camInfo.filterSupportedFixedFrameRates(FIXED_FRAME_RATES) val supportedImageFormats = camInfo.supportedImageFormats val hasFlashUnit = camInfo.hasFlashUnit() put( lensFacing, CameraConstraints( supportedStabilizationModes = supportedStabilizationModes, supportedFixedFrameRates = supportedFixedFrameRates, supportedDynamicRanges = supportedDynamicRanges, supportedImageFormatsMap = mapOf( // Only JPEG is supported in single-stream mode, since // single-stream mode uses CameraEffect, which does not support // Ultra HDR now. Pair(CaptureMode.SINGLE_STREAM, setOf(ImageOutputFormat.JPEG)), Pair(CaptureMode.MULTI_STREAM, supportedImageFormats) ), hasFlashUnit = hasFlashUnit ) ) } } } ) constraintsRepository.updateSystemConstraints(systemConstraints) currentSettings.value = cameraAppSettings .tryApplyDynamicRangeConstraints() .tryApplyAspectRatioForExternalCapture(this.useCaseMode) .tryApplyImageFormatConstraints() .tryApplyFrameRateConstraints() .tryApplyStabilizationConstraints() .tryApplyConcurrentCameraModeConstraints() } override suspend fun runCamera() = coroutineScope { Log.d(TAG, "runCamera") val transientSettings = MutableStateFlow<TransientSessionSettings?>(null) currentSettings .filterNotNull() .map { currentCameraSettings -> transientSettings.value = TransientSessionSettings( audioMuted = currentCameraSettings.audioMuted, deviceRotation = currentCameraSettings.deviceRotation, flashMode = currentCameraSettings.flashMode, zoomScale = currentCameraSettings.zoomScale ) when (currentCameraSettings.concurrentCameraMode) { ConcurrentCameraMode.OFF -> { val cameraSelector = when (currentCameraSettings.cameraLensFacing) { LensFacing.FRONT -> CameraSelector.DEFAULT_FRONT_CAMERA LensFacing.BACK -> CameraSelector.DEFAULT_BACK_CAMERA } PerpetualSessionSettings.SingleCamera( cameraInfo = cameraProvider.getCameraInfo(cameraSelector), aspectRatio = currentCameraSettings.aspectRatio, captureMode = currentCameraSettings.captureMode, targetFrameRate = currentCameraSettings.targetFrameRate, stabilizePreviewMode = currentCameraSettings.previewStabilization, stabilizeVideoMode = currentCameraSettings.videoCaptureStabilization, dynamicRange = currentCameraSettings.dynamicRange, imageFormat = currentCameraSettings.imageFormat ) } ConcurrentCameraMode.DUAL -> { val primaryFacing = currentCameraSettings.cameraLensFacing val secondaryFacing = primaryFacing.flip() cameraProvider.availableConcurrentCameraInfos.firstNotNullOf { var primaryCameraInfo: CameraInfo? = null var secondaryCameraInfo: CameraInfo? = null it.forEach { cameraInfo -> if (cameraInfo.appLensFacing == primaryFacing) { primaryCameraInfo = cameraInfo } else if (cameraInfo.appLensFacing == secondaryFacing) { secondaryCameraInfo = cameraInfo } } primaryCameraInfo?.let { nonNullPrimary -> secondaryCameraInfo?.let { nonNullSecondary -> PerpetualSessionSettings.ConcurrentCamera( primaryCameraInfo = nonNullPrimary, secondaryCameraInfo = nonNullSecondary, aspectRatio = currentCameraSettings.aspectRatio ) } } } } } }.distinctUntilChanged() .collectLatest { sessionSettings -> coroutineScope { with( CameraSessionContext( context = application, cameraProvider = cameraProvider, backgroundDispatcher = defaultDispatcher, screenFlashEvents = screenFlashEvents, focusMeteringEvents = focusMeteringEvents, videoCaptureControlEvents = videoCaptureControlEvents, currentCameraState = _currentCameraState, surfaceRequests = _surfaceRequest, transientSettings = transientSettings ) ) { try { when (sessionSettings) { is PerpetualSessionSettings.SingleCamera -> runSingleCameraSession( sessionSettings, useCaseMode = useCaseMode ) { imageCapture -> imageCaptureUseCase = imageCapture } is PerpetualSessionSettings.ConcurrentCamera -> runConcurrentCameraSession( sessionSettings, useCaseMode = CameraUseCase.UseCaseMode.VIDEO_ONLY ) } } finally { // TODO(tm): This shouldn't be necessary. Cancellation of the // coroutineScope by collectLatest should cause this to // occur naturally. cameraProvider.unbindAll() } } } } } override suspend fun takePicture(onCaptureStarted: (() -> Unit)) { if (imageCaptureUseCase == null) { throw RuntimeException("Attempted take picture with null imageCapture use case") } try { val imageProxy = imageCaptureUseCase!!.takePicture(onCaptureStarted) Log.d(TAG, "onCaptureSuccess") imageProxy.close() } catch (exception: Exception) { Log.d(TAG, "takePicture onError: $exception") throw exception } } // TODO(b/319733374): Return bitmap for external mediastore capture without URI override suspend fun takePicture( onCaptureStarted: (() -> Unit), contentResolver: ContentResolver, imageCaptureUri: Uri?, ignoreUri: Boolean ): ImageCapture.OutputFileResults { if (imageCaptureUseCase == null) { throw RuntimeException("Attempted take picture with null imageCapture use case") } val eligibleContentValues = getEligibleContentValues() val outputFileOptions: OutputFileOptions if (ignoreUri) { val formatter = SimpleDateFormat( "yyyy-MM-dd-HH-mm-ss-SSS", Locale.US ) val filename = "JCA-${formatter.format(Calendar.getInstance().time)}.jpg" val contentValues = ContentValues() contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename) contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg") outputFileOptions = OutputFileOptions.Builder( contentResolver, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues ).build() } else if (imageCaptureUri == null) { val e = RuntimeException("Null Uri is provided.") Log.d(TAG, "takePicture onError: $e") throw e } else { try { val outputStream = contentResolver.openOutputStream(imageCaptureUri) if (outputStream != null) { outputFileOptions = OutputFileOptions.Builder( contentResolver.openOutputStream(imageCaptureUri)!! ).build() } else { val e = RuntimeException("Provider recently crashed.") Log.d(TAG, "takePicture onError: $e") throw e } } catch (e: FileNotFoundException) { Log.d(TAG, "takePicture onError: $e") throw e } } try { val outputFileResults = imageCaptureUseCase!!.takePicture( outputFileOptions, onCaptureStarted ) val relativePath = eligibleContentValues.getAsString(MediaStore.Images.Media.RELATIVE_PATH) val displayName = eligibleContentValues.getAsString( MediaStore.Images.Media.DISPLAY_NAME ) Log.d(TAG, "Saved image to $relativePath/$displayName") return outputFileResults } catch (exception: ImageCaptureException) { Log.d(TAG, "takePicture onError: $exception") throw exception } } private fun getEligibleContentValues(): ContentValues { val eligibleContentValues = ContentValues() eligibleContentValues.put( MediaStore.Images.Media.DISPLAY_NAME, Calendar.getInstance().time.toString() ) eligibleContentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg") eligibleContentValues.put( MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES ) return eligibleContentValues } override suspend fun startVideoRecording( videoCaptureUri: Uri?, shouldUseUri: Boolean, onVideoRecord: (CameraUseCase.OnVideoRecordEvent) -> Unit ) { if (shouldUseUri && videoCaptureUri == null) { val e = RuntimeException("Null Uri is provided.") Log.d(TAG, "takePicture onError: $e") throw e } videoCaptureControlEvents.send( VideoCaptureControlEvent.StartRecordingEvent( videoCaptureUri, shouldUseUri, onVideoRecord ) ) } override fun stopVideoRecording() { videoCaptureControlEvents.trySendBlocking(VideoCaptureControlEvent.StopRecordingEvent) } override fun setZoomScale(scale: Float) { currentSettings.update { old -> old?.copy(zoomScale = scale) } } // Sets the camera to the designated lensFacing direction override suspend fun setLensFacing(lensFacing: LensFacing) { currentSettings.update { old -> if (systemConstraints.availableLenses.contains(lensFacing)) { old?.copy(cameraLensFacing = lensFacing) ?.tryApplyDynamicRangeConstraints() ?.tryApplyImageFormatConstraints() } else { old } } } private fun CameraAppSettings.tryApplyDynamicRangeConstraints(): CameraAppSettings { return systemConstraints.perLensConstraints[cameraLensFacing]?.let { constraints -> with(constraints.supportedDynamicRanges) { val newDynamicRange = if (contains(dynamicRange)) { dynamicRange } else { DynamicRange.SDR } [email protected]( dynamicRange = newDynamicRange ) } } ?: this } private fun CameraAppSettings.tryApplyAspectRatioForExternalCapture( useCaseMode: CameraUseCase.UseCaseMode ): CameraAppSettings { return when (useCaseMode) { CameraUseCase.UseCaseMode.STANDARD -> this CameraUseCase.UseCaseMode.IMAGE_ONLY -> this.copy(aspectRatio = AspectRatio.THREE_FOUR) CameraUseCase.UseCaseMode.VIDEO_ONLY -> this.copy(aspectRatio = AspectRatio.NINE_SIXTEEN) } } private fun CameraAppSettings.tryApplyImageFormatConstraints(): CameraAppSettings { return systemConstraints.perLensConstraints[cameraLensFacing]?.let { constraints -> with(constraints.supportedImageFormatsMap[captureMode]) { val newImageFormat = if (this != null && contains(imageFormat)) { imageFormat } else { ImageOutputFormat.JPEG } [email protected]( imageFormat = newImageFormat ) } } ?: this } private fun CameraAppSettings.tryApplyFrameRateConstraints(): CameraAppSettings { return systemConstraints.perLensConstraints[cameraLensFacing]?.let { constraints -> with(constraints.supportedFixedFrameRates) { val newTargetFrameRate = if (contains(targetFrameRate)) { targetFrameRate } else { TARGET_FPS_AUTO } [email protected]( targetFrameRate = newTargetFrameRate ) } } ?: this } private fun CameraAppSettings.tryApplyStabilizationConstraints(): CameraAppSettings { return systemConstraints.perLensConstraints[cameraLensFacing]?.let { constraints -> with(constraints.supportedStabilizationModes) { val newVideoStabilization = if (contains(SupportedStabilizationMode.HIGH_QUALITY) && (targetFrameRate != TARGET_FPS_60) ) { // unlike shouldVideoBeStabilized, doesn't check value of previewStabilization videoCaptureStabilization } else { Stabilization.UNDEFINED } val newPreviewStabilization = if (contains(SupportedStabilizationMode.ON) && (targetFrameRate in setOf(TARGET_FPS_AUTO, TARGET_FPS_30)) ) { previewStabilization } else { Stabilization.UNDEFINED } [email protected]( previewStabilization = newPreviewStabilization, videoCaptureStabilization = newVideoStabilization ) } } ?: this } private fun CameraAppSettings.tryApplyConcurrentCameraModeConstraints(): CameraAppSettings = when (concurrentCameraMode) { ConcurrentCameraMode.OFF -> this else -> if (systemConstraints.concurrentCamerasSupported) { copy( targetFrameRate = TARGET_FPS_AUTO, previewStabilization = Stabilization.OFF, videoCaptureStabilization = Stabilization.OFF, dynamicRange = DynamicRange.SDR, captureMode = CaptureMode.MULTI_STREAM ) } else { copy(concurrentCameraMode = ConcurrentCameraMode.OFF) } } override suspend fun tapToFocus(x: Float, y: Float) { focusMeteringEvents.send(CameraEvent.FocusMeteringEvent(x, y)) } override fun getScreenFlashEvents() = screenFlashEvents override fun getCurrentSettings() = currentSettings.asStateFlow() override fun setFlashMode(flashMode: FlashMode) { currentSettings.update { old -> old?.copy(flashMode = flashMode) } } override fun isScreenFlashEnabled() = imageCaptureUseCase?.flashMode == ImageCapture.FLASH_MODE_SCREEN && imageCaptureUseCase?.screenFlash != null override suspend fun setAspectRatio(aspectRatio: AspectRatio) { currentSettings.update { old -> old?.copy(aspectRatio = aspectRatio) } } override suspend fun setCaptureMode(captureMode: CaptureMode) { currentSettings.update { old -> old?.copy(captureMode = captureMode) ?.tryApplyImageFormatConstraints() ?.tryApplyConcurrentCameraModeConstraints() } } override suspend fun setDynamicRange(dynamicRange: DynamicRange) { currentSettings.update { old -> old?.copy(dynamicRange = dynamicRange) ?.tryApplyConcurrentCameraModeConstraints() } } override fun setDeviceRotation(deviceRotation: DeviceRotation) { currentSettings.update { old -> old?.copy(deviceRotation = deviceRotation) } } override suspend fun setConcurrentCameraMode(concurrentCameraMode: ConcurrentCameraMode) { currentSettings.update { old -> old?.copy(concurrentCameraMode = concurrentCameraMode) ?.tryApplyConcurrentCameraModeConstraints() } } override suspend fun setImageFormat(imageFormat: ImageOutputFormat) { currentSettings.update { old -> old?.copy(imageFormat = imageFormat) } } override suspend fun setPreviewStabilization(previewStabilization: Stabilization) { currentSettings.update { old -> old?.copy( previewStabilization = previewStabilization )?.tryApplyStabilizationConstraints() ?.tryApplyConcurrentCameraModeConstraints() } } override suspend fun setVideoCaptureStabilization(videoCaptureStabilization: Stabilization) { currentSettings.update { old -> old?.copy( videoCaptureStabilization = videoCaptureStabilization )?.tryApplyStabilizationConstraints() ?.tryApplyConcurrentCameraModeConstraints() } } override suspend fun setTargetFrameRate(targetFrameRate: Int) { currentSettings.update { old -> old?.copy(targetFrameRate = targetFrameRate)?.tryApplyFrameRateConstraints() ?.tryApplyConcurrentCameraModeConstraints() } } override suspend fun setLowLightBoost(lowLightBoost: LowLightBoost) { currentSettings.update { old -> old?.copy(lowLightBoost = lowLightBoost) } } override suspend fun setAudioMuted(isAudioMuted: Boolean) { currentSettings.update { old -> old?.copy(audioMuted = isAudioMuted) } } companion object { private val FIXED_FRAME_RATES = setOf(TARGET_FPS_15, TARGET_FPS_30, TARGET_FPS_60) } }
39
Kotlin
26
141
f79336788a80bf2d7e35393bde6470db3ea548e7
26,771
jetpack-camera-app
Apache License 2.0
idea/testData/quickfix/createFromUsage/createSecondaryConstructor/noParametersImplicitSuperCall.kt
JakeWharton
99,388,807
true
null
// "Create secondary constructor" "true" open class Base() class Creation { constructor(f: Int) } val v = Creation(<caret>)
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
128
kotlin
Apache License 2.0
app/src/main/java/com/herscher/swiftlydemo/MainActivity.kt
markherscher
392,020,007
false
null
package com.herscher.swiftlydemo import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.herscher.swiftlydemo.specials.SpecialsListFragment class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (savedInstanceState == null) { supportFragmentManager .beginTransaction() .replace(R.id.container, SpecialsListFragment.newInstance()) .commit() } } }
0
Kotlin
0
0
680324f1e8736489ac8357cc41002882fbd2f438
595
ManagerSpecialDemo
Apache License 2.0
telegram/src/main/kotlin/com/github/kotlintelegrambot/entities/ChosenInlineResult.kt
kotlin-telegram-bot
121,235,631
false
{"Kotlin": 618749}
package com.github.kotlintelegrambot.entities import com.google.gson.annotations.SerializedName as Name data class ChosenInlineResult( @Name("result_id") val resultId: String, val from: User, val location: Location? = null, @Name("inline_message_id") val inlineMessageId: String? = null, val query: String )
67
Kotlin
161
794
18013912c6a8c395b6491c2323a8f5eb7288b4f5
330
kotlin-telegram-bot
Apache License 2.0
platform/platform-impl/src/com/intellij/ide/plugins/marketplace/MarketplacePluginDownloadService.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.plugins.marketplace import com.fasterxml.jackson.databind.ObjectMapper import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.PluginInstaller import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.util.PathUtil import com.intellij.util.io.HttpRequests import com.intellij.util.io.exists import com.jetbrains.plugin.blockmap.core.BlockMap import com.jetbrains.plugin.blockmap.core.FileHash import org.jetbrains.annotations.ApiStatus import java.io.* import java.net.URLConnection import java.nio.file.Path import java.nio.file.Paths import java.util.zip.ZipInputStream private val LOG = Logger.getInstance(MarketplacePluginDownloadService::class.java) private const val BLOCKMAP_ZIP_SUFFIX = ".blockmap.zip" private const val BLOCKMAP_FILENAME = "blockmap.json" private const val HASH_FILENAME_SUFFIX = ".hash.json" private const val FILENAME = "filename=" private const val MAXIMUM_DOWNLOAD_PERCENT = 0.65 // 100% = 1.0 @ApiStatus.Internal open class MarketplacePluginDownloadService { companion object { @JvmStatic @Throws(IOException::class) fun getPluginTempFile(): File { val pluginsTemp = File(PathManager.getPluginTempPath()) if (!pluginsTemp.exists() && !pluginsTemp.mkdirs()) { throw IOException(IdeBundle.message("error.cannot.create.temp.dir", pluginsTemp)) } return FileUtil.createTempFile(pluginsTemp, "plugin_", "_download", true, false) } @JvmStatic fun renameFileToZipRoot(zip: File): File { val newName = "${PluginInstaller.rootEntryName(zip.toPath())}.zip" val newZip = File("${zip.parent}/$newName") if (newZip.exists()) { FileUtil.delete(newZip) } FileUtil.rename(zip, newName) return newZip } } private val objectMapper by lazy { ObjectMapper() } @Throws(IOException::class) open fun downloadPlugin(pluginUrl: String, indicator: ProgressIndicator): File { val file = getPluginTempFile() return HttpRequests.request(pluginUrl).gzip(false).productNameAsUserAgent().connect( HttpRequests.RequestProcessor { request: HttpRequests.Request -> request.saveToFile(file, indicator) val pluginFileUrl = getPluginFileUrl(request.connection) if (pluginFileUrl.endsWith(".zip")) { renameFileToZipRoot(file) } else { val contentDisposition: String? = request.connection.getHeaderField("Content-Disposition") val url = request.connection.url.toString() guessPluginFile(contentDisposition, url, file, pluginUrl) } }) } @Throws(IOException::class) fun downloadPluginViaBlockMap(pluginUrl: String, prevPlugin: Path, indicator: ProgressIndicator): File { val prevPluginArchive = getPrevPluginArchive(prevPlugin) if (!prevPluginArchive.exists()) { LOG.info(IdeBundle.message("error.file.not.found.message", prevPluginArchive.toString())) return downloadPlugin(pluginUrl, indicator) } val (pluginFileUrl, guessFileParameters) = getPluginFileUrlAndGuessFileParameters(pluginUrl) val blockMapFileUrl = "$pluginFileUrl$BLOCKMAP_ZIP_SUFFIX" val pluginHashFileUrl = "$pluginFileUrl$HASH_FILENAME_SUFFIX" try { val newBlockMap = HttpRequests.request(blockMapFileUrl).productNameAsUserAgent().connect { request -> request.inputStream.use { input -> getBlockMapFromZip(input) } } LOG.info("Plugin's blockmap file downloaded") val newPluginHash = HttpRequests.request(pluginHashFileUrl).productNameAsUserAgent().connect { request -> request.inputStream.reader().buffered().use { input -> objectMapper.readValue(input.readText(), FileHash::class.java) } } LOG.info("Plugin's hash file downloaded") val oldBlockMap = FileInputStream(prevPluginArchive.toFile()).use { input -> BlockMap(input, newBlockMap.algorithm, newBlockMap.minSize, newBlockMap.maxSize, newBlockMap.normalSize) } val downloadPercent = downloadPercent(oldBlockMap, newBlockMap) LOG.info("Plugin's download percent is = %.2f".format(downloadPercent * 100)) if (downloadPercent > MAXIMUM_DOWNLOAD_PERCENT) { LOG.info(IdeBundle.message("too.large.download.size")) return downloadPlugin(pluginFileUrl, indicator) } val file = getPluginTempFile() val merger = PluginChunkMerger(prevPluginArchive.toFile(), oldBlockMap, newBlockMap, indicator) FileOutputStream(file).use { output -> merger.merge(output, PluginChunkDataSource(oldBlockMap, newBlockMap, pluginFileUrl)) } val curFileHash = FileInputStream(file).use { input -> FileHash(input, newPluginHash.algorithm) } if (curFileHash != newPluginHash) { LOG.info(IdeBundle.message("hashes.doesnt.match")) return downloadPlugin(pluginFileUrl, indicator) } return if (pluginFileUrl.endsWith(".zip")) { renameFileToZipRoot(file) } else { guessPluginFile(guessFileParameters.contentDisposition, guessFileParameters.url, file, pluginUrl) } } catch (e: Exception) { LOG.info(IdeBundle.message("error.download.plugin.via.blockmap"), e) return downloadPlugin(pluginFileUrl, indicator) } } @Throws(IOException::class) private fun getBlockMapFromZip(input: InputStream): BlockMap { return input.buffered().use { source -> ZipInputStream(source).use { zip -> var entry = zip.nextEntry while (entry.name != BLOCKMAP_FILENAME && entry.name != null) entry = zip.nextEntry if (entry.name == BLOCKMAP_FILENAME) { // there is must only one entry otherwise we can't properly // read entry because we don't know it size (entry.size returns -1) objectMapper.readValue(zip.readBytes(), BlockMap::class.java) } else { throw IOException("There is no entry $BLOCKMAP_FILENAME") } } } } } private fun guessPluginFile(contentDisposition: String?, url: String, file: File, pluginUrl: String): File { val fileName: String = guessFileName(contentDisposition, url, file, pluginUrl) val newFile = File(file.parentFile, fileName) FileUtil.rename(file, newFile) return newFile } @Throws(IOException::class) private fun guessFileName(contentDisposition: String?, usedURL: String, file: File, pluginUrl: String): String { var fileName: String? = null LOG.debug("header: $contentDisposition") if (contentDisposition != null && contentDisposition.contains(FILENAME)) { val startIdx = contentDisposition.indexOf(FILENAME) val endIdx = contentDisposition.indexOf(';', startIdx) fileName = contentDisposition.substring(startIdx + FILENAME.length, if (endIdx > 0) endIdx else contentDisposition.length) if (StringUtil.startsWithChar(fileName, '\"') && StringUtil.endsWithChar(fileName, '\"')) { fileName = fileName.substring(1, fileName.length - 1) } } if (fileName == null) { // try to find a filename in an URL LOG.debug("url: $usedURL") fileName = usedURL.substring(usedURL.lastIndexOf('/') + 1) if (fileName.isEmpty() || fileName.contains("?")) { fileName = pluginUrl.substring(pluginUrl.lastIndexOf('/') + 1) } } if (!PathUtil.isValidFileName(fileName)) { LOG.debug("fileName: $fileName") FileUtil.delete(file) throw IOException("Invalid filename returned by a server") } return fileName } private fun downloadPercent(oldBlockMap: BlockMap, newBlockMap: BlockMap): Double { val oldSet = oldBlockMap.chunks.toSet() val newChunks = newBlockMap.chunks.filter { chunk -> !oldSet.contains(chunk) } return newChunks.sumBy { chunk -> chunk.length }.toDouble() / newBlockMap.chunks.sumBy { chunk -> chunk.length }.toDouble() } private fun getPluginFileUrl(connection: URLConnection): String { val url = connection.url val port = url.port return if (port == -1) { "${url.protocol}://${url.host}${url.path}" } else { "${url.protocol}://${url.host}:${port}${url.path}" } } private data class GuessFileParameters(val contentDisposition: String?, val url: String) private fun getPluginFileUrlAndGuessFileParameters(pluginUrl: String): Pair<String, GuessFileParameters> { return HttpRequests.request(pluginUrl).productNameAsUserAgent().connect { request -> val connection = request.connection Pair(getPluginFileUrl(connection), GuessFileParameters(connection.getHeaderField("Content-Disposition"), connection.url.toString())) } } private fun getPrevPluginArchive(prevPlugin: Path): Path { val suffix = if (prevPlugin.endsWith(".jar")) "" else ".zip" return Paths.get(PathManager.getPluginTempPath()).resolve("${prevPlugin.fileName}$suffix") }
233
null
4912
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
9,128
intellij-community
Apache License 2.0
android/app/src/main/java/com/algorand/android/ui/register/BackupPassphraseFragment.kt
perawallet
364,359,642
false
null
/* * Copyright 2022 Pera Wallet, LDA * 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.algorand.android.ui.register import android.os.Bundle import android.view.View import androidx.fragment.app.viewModels import androidx.navigation.fragment.navArgs import com.algorand.algosdk.sdk.Sdk import com.algorand.android.R import com.algorand.android.core.DaggerBaseFragment import com.algorand.android.customviews.toolbar.buttoncontainer.model.TextButton import com.algorand.android.databinding.FragmentBackupPassphraseBinding import com.algorand.android.models.Account import com.algorand.android.models.FragmentConfiguration import com.algorand.android.models.ToolbarConfiguration import com.algorand.android.ui.register.BackupPassphraseFragmentDirections.Companion.actionBackupPassphraseFragmentToBackupPassphraseAccountNameNavigation import com.algorand.android.utils.disableScreenCapture import com.algorand.android.utils.enableScreenCapture import com.algorand.android.utils.viewbinding.viewBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class BackupPassphraseFragment : DaggerBaseFragment(R.layout.fragment_backup_passphrase) { private val toolbarConfiguration = ToolbarConfiguration( startIconResId = R.drawable.ic_left_arrow, startIconClick = ::navBack, backgroundColor = R.color.tertiary_background ) override val fragmentConfiguration = FragmentConfiguration( toolbarConfiguration = toolbarConfiguration ) private val binding by viewBinding(FragmentBackupPassphraseBinding::bind) private val backupPassphraseViewModel: BackupPassphraseViewModel by viewModels() private val args: BackupPassphraseFragmentArgs by navArgs() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) customizeToolbar() setupPassphrase() binding.nextButton.setOnClickListener { onNextClick() } } private fun customizeToolbar() { if (args.accountCreation != null) { getAppToolbar()?.setEndButton(button = TextButton(R.string.skip, onClick = ::onSkipClick)) } } override fun onResume() { super.onResume() activity?.disableScreenCapture() } override fun onStop() { super.onStop() if (view?.hasWindowFocus() == true) { activity?.enableScreenCapture() } } private fun setupPassphrase() { val secretKey = (args.accountCreation?.tempAccount?.detail as? Account.Detail.Standard)?.secretKey ?: backupPassphraseViewModel.getAccountSecretKey(args.publicKeyOfAccountToBackup) secretKey?.let { try { val mnemonic = Sdk.mnemonicFromPrivateKey(it) ?: throw Exception("Mnemonic cannot be null.") binding.passphraseBoxView.setPassphrases(mnemonic) } catch (exception: Exception) { navBack() } } ?: run { navBack() } } private fun onNextClick() { navToPassphraseValidaitonFragment() } private fun onSkipClick() { navToBackupPassphraseAccountNameNavigation() } private fun navToPassphraseValidaitonFragment() { backupPassphraseViewModel.logOnboardingNextClickEvent() nav( BackupPassphraseFragmentDirections.actionBackupPassphraseFragmentToPassphraseValidationFragment( args.publicKeyOfAccountToBackup, args.accountCreation ) ) } private fun navToBackupPassphraseAccountNameNavigation() { backupPassphraseViewModel.logOnboardingNextClickEvent() args.accountCreation?.let { accountCreation -> nav(actionBackupPassphraseFragmentToBackupPassphraseAccountNameNavigation(accountCreation)) } } }
23
null
64
181
92fc77f73fa4105de82d5e87b03c1e67600a57c0
4,357
pera-wallet
Apache License 2.0
library/src/commonMain/kotlin/com/befrvnk/knotion/objects/block/Bookmark.kt
befrvnk
672,042,674
false
null
package com.befrvnk.knotion.objects.block import com.befrvnk.knotion.objects.other.Parent import com.befrvnk.knotion.objects.richtext.RichText import com.befrvnk.knotion.objects.user.User import kotlinx.datetime.Instant import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonNames @OptIn(ExperimentalSerializationApi::class) @Serializable @SerialName("bookmark") data class Bookmark( override val id: String, override val parent: Parent, @JsonNames("created_time") override val createdTime: Instant, @JsonNames("created_by") override val createdBy: User, @JsonNames("last_edited_time") override val lastEditedTime: Instant, @JsonNames("last_edited_by") override val lastEditedBy: User, override val archived: Boolean, @JsonNames("has_children") override val hasChildren: Boolean, val bookmark: BookmarkDetails, ) : Block() { @Serializable data class BookmarkDetails( val caption: List<RichText>, val url: String, ) }
2
Kotlin
0
0
9ada5a7c5b38aedd53abe3aa58dfd999795c8e89
1,126
knotion
MIT License
src/main/kotlin/kt/kotlinalgs/app/graph/PathsWithSum.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.graph import java.util.* /* Achtung: Immer map etc. zurücksetzen!! BC: from root, cur element .. test cases! */ Solution().test() /* 10 15,5 17,7,2 18,8,3,1 alt.. store complete sum in set<Int> 10, 15, 17, 18 .. check at each node if (set.contains(runningSum - k)) -> incr. count sums = Map number to #number count start at root rec pathsWithSum(root: Node<T>, sum: Int, sums: MutableMap<Int, Int>, int runningSum) ctr = 0 sums.addOrIncrease(runningSum + root.value) // start new path or continue path(s) check if value == sum -> ctr++ if (set.contains(node.value - k)) -> ctr += sums[..] (count) return ctr + pathsWithSum(root.left,..) + pathsWithSum(root.right,..) + 1,-1, 8 .. 1,0,8 -> 2 1,-2,8 .. 1,-1,7 -> 1 */ class Solution { fun test() { println("test") val root = Node(10) root.left = Node(5) root.left?.left = Node(3) root.left?.left?.left = Node(3) root.left?.left?.right = Node(-2) root.left?.right = Node(1) root.left?.right?.right = Node(2) root.right = Node(-3) root.right?.right = Node(11) val tree = BinarySearchTree() println(tree.pathsWithSum(root, 3)) println(tree.pathsWithSum(root, 4)) println(tree.pathsWithSum(root, 8)) println(tree.pathsWithSum(root, 10)) } } data class Node( val value: Int, var left: Node? = null, var right: Node? = null ) class BinarySearchTree { fun pathsWithSum(root: Node, sum: Int): Int { val sums: MutableMap<Int, Int> = mutableMapOf() return pathsWithSumRec(root, sum, sums, 0) } private fun pathsWithSumRec( root: Node?, // 3 targetSum: Int, // 8 sums: MutableMap<Int, Int>, // [10:1, 15:1, 18:1] runningSum: Int) : Int { // 15 if (root == null) return 0 /* 1,-1, 8 RS .. 1,0,8 -> 2 1,-2,8 RS .. 1,-1,7 -> 1 */ val newSum = runningSum + root.value val searchedSum = newSum - targetSum var paths = if(newSum == targetSum) 1 else 0 sums[searchedSum]?.let { count -> // covers also case if (root.value == targetSum) /* e.g. with targetSum == 8 at index 2: 1,-2,8 RS .. 1,-1,7 -> 1 rs - ts = 7 - 8 = -1 */ paths += count } addOrIncrease(sums, newSum) paths += pathsWithSumRec(root.left, targetSum, sums, newSum) paths += pathsWithSumRec(root.right, targetSum, sums, newSum) // Achtung: Immer zurücksetzen!! removeOrDecrease(sums, newSum) return paths } private fun addOrIncrease(sums: MutableMap<Int, Int>, value: Int) { val oldCount = sums.getOrDefault(value, 0) sums[value] = oldCount + 1 } private fun removeOrDecrease(sums: MutableMap<Int, Int>, value: Int) { val oldCount = sums.getOrDefault(value, 0) if (oldCount > 1) sums[value] = oldCount - 1 else sums.remove(value) } }
1
null
1
1
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
3,130
KotlinAlgs
MIT License
paymentsheet/src/test/java/com/stripe/android/paymentsheet/addresselement/AutocompleteViewModelTest.kt
stripe
6,926,049
false
null
package com.stripe.android.paymentsheet.addresselement import android.app.Application import android.text.SpannableString import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.addresselement.analytics.AddressLauncherEventReporter import com.stripe.android.ui.core.elements.autocomplete.PlacesClientProxy import com.stripe.android.ui.core.elements.autocomplete.model.AutocompletePrediction import com.stripe.android.ui.core.elements.autocomplete.model.FetchPlaceResponse import com.stripe.android.ui.core.elements.autocomplete.model.FindAutocompletePredictionsResponse import com.stripe.android.ui.core.elements.autocomplete.model.Place import com.stripe.android.uicore.elements.TextFieldIcon import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.stub import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner import kotlin.test.AfterTest import kotlin.test.BeforeTest @RunWith(RobolectricTestRunner::class) class AutocompleteViewModelTest { private val args = mock<AddressElementActivityContract.Args>() private val navigator = mock<AddressElementNavigator>() private val application = ApplicationProvider.getApplicationContext<Application>() private val mockClient = mock<PlacesClientProxy>() private val mockEventReporter = mock<AddressLauncherEventReporter>() private fun createViewModel() = AutocompleteViewModel( args, navigator, mockClient, AutocompleteViewModel.Args( "US" ), mockEventReporter, application ) @BeforeTest fun setUp() { Dispatchers.setMain(UnconfinedTestDispatcher()) } @AfterTest fun tearDown() { Dispatchers.resetMain() } @Test fun `selectPrediction emits successful result`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel() val fetchPlaceResponse = Result.success( FetchPlaceResponse( Place( listOf() ) ) ) val expectedResult = Result.success( AddressDetails( address = PaymentSheet.Address( city = null, country = null, line1 = "", line2 = null, postalCode = null, state = null ) ) ) whenever(mockClient.fetchPlace(any())).thenReturn(fetchPlaceResponse) viewModel.selectPrediction( AutocompletePrediction( SpannableString("primaryText"), SpannableString("secondaryText"), "placeId" ) ) assertThat(viewModel.loading.value).isEqualTo(false) assertThat(viewModel.addressResult.value) .isEqualTo(expectedResult) verify(navigator).setResult(anyOrNull(), eq(expectedResult.getOrNull())) verify(navigator).onBack() } @Test fun `selectPrediction emits failure result`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel() val exception = Exception("fake exception") val result = Result.failure<FetchPlaceResponse>(exception) mockClient.stub { onBlocking { fetchPlace(any()) }.thenReturn(result) } viewModel.selectPrediction( AutocompletePrediction( SpannableString("primaryText"), SpannableString("secondaryText"), "placeId" ) ) assertThat(viewModel.loading.value).isEqualTo(false) assertThat(viewModel.addressResult.value) .isEqualTo(Result.failure<FetchPlaceResponse>(exception)) verify(navigator).setResult(anyOrNull(), eq(null)) verify(navigator).onBack() } @Test fun `onEnterAddressManually sets the current address and navigates back`() = runTest(UnconfinedTestDispatcher()) { whenever(mockClient.findAutocompletePredictions(any(), any(), any())).thenReturn( Result.success( FindAutocompletePredictionsResponse( listOf( AutocompletePrediction( primaryText = SpannableString("primaryText"), secondaryText = SpannableString("secondaryText"), placeId = "placeId", ) ) ) ) ) val viewModel = createViewModel() val expectedResult = Result.success( AddressDetails( address = PaymentSheet.Address( line1 = "Some query" ) ) ) viewModel.textFieldController.onRawValueChange("Some query") viewModel.onEnterAddressManually() verify(navigator).setResult(anyOrNull(), eq(expectedResult.getOrNull())) verify(navigator).onBack() } @Test fun `onEnterAddressManually navigates back with empty address`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel() val expectedResult = Result.success( AddressDetails( address = PaymentSheet.Address( line1 = "" ) ) ) viewModel.onEnterAddressManually() verify(navigator).setResult(anyOrNull(), eq(expectedResult.getOrNull())) verify(navigator).onBack() } @Test fun `when user presses clear text field is cleared`() = runTest { val viewModel = createViewModel() val trailingIcon = viewModel.textFieldController.trailingIcon (trailingIcon.value as? TextFieldIcon.Trailing)?.onClick?.invoke() assertThat(viewModel.textFieldController.rawFieldValue.value).isEqualTo("") } @Test fun `when query is valid then search is triggered with delay`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel() viewModel.textFieldController.onRawValueChange("Some valid query") whenever(mockClient.findAutocompletePredictions(any(), any(), any())).thenReturn( Result.success( FindAutocompletePredictionsResponse( listOf( AutocompletePrediction( SpannableString("primaryText"), SpannableString("secondaryText"), "placeId" ) ) ) ) ) // Advance past search debounce delay advanceTimeBy(AutocompleteViewModel.SEARCH_DEBOUNCE_MS + 1) assertThat(viewModel.predictions.value?.size).isEqualTo(1) } @Test fun `when query is invalid then search is not triggered`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel() viewModel.textFieldController.onRawValueChange("a") // Advance past search debounce delay advanceTimeBy(AutocompleteViewModel.SEARCH_DEBOUNCE_MS + 1) assertThat(viewModel.predictions.value?.size).isEqualTo(null) } @Test fun `when address is empty trailing icon is null`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel() viewModel.textFieldController.onRawValueChange("") assertThat(viewModel.textFieldController.trailingIcon.value).isNull() viewModel.textFieldController.onRawValueChange("a") assertThat(viewModel.textFieldController.trailingIcon.value).isNotNull() } @Test fun `when query is not empty then return line1 on back`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel() viewModel.textFieldController.onRawValueChange("a") viewModel.onBackPressed() verify(viewModel.navigator).setResult( eq(AddressDetails.KEY), eq(AddressDetails(address = PaymentSheet.Address(line1 = "a"))) ) } @Test fun `when query is empty then do nothing on back`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel() viewModel.textFieldController.onRawValueChange("") viewModel.onBackPressed() verify(viewModel.navigator, never()).setResult(any(), any()) } @Test fun `initializing ViewModel emits onShow event`() { createViewModel() verify(mockEventReporter).onShow(eq("US")) } @Test fun `clearQuery clears textfield and predictions`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel() viewModel.textFieldController.onRawValueChange("Some valid query") whenever(mockClient.findAutocompletePredictions(any(), any(), any())).thenReturn( Result.success( FindAutocompletePredictionsResponse( listOf( AutocompletePrediction( SpannableString("primaryText"), SpannableString("secondaryText"), "placeId" ) ) ) ) ) // Advance past search debounce delay advanceTimeBy(AutocompleteViewModel.SEARCH_DEBOUNCE_MS + 1) assertThat(viewModel.predictions.value?.size).isEqualTo(1) viewModel.clearQuery() assertThat(viewModel.predictions.value).isEqualTo(null) assertThat(viewModel.textFieldController.rawFieldValue.value).isEqualTo("") } }
88
null
644
1,277
174b27b5a70f75a7bc66fdcce3142f1e51d809c8
10,288
stripe-android
MIT License
2016-08-11-WebViewJavascriptInterafce/src/main/kotlin/tech/thdev/webviewjavascriptinterface/view/main/KotlinFragment.kt
mgkim9
141,031,406
false
null
package tech.thdev.webviewjavascriptinterface.view.main import android.content.Context import android.os.Bundle import android.text.TextUtils import android.view.View import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import android.webkit.WebSettings import android.webkit.WebView import android.widget.EditText import android.widget.Toast import tech.thdev.kotlin_example_01.base.view.BaseFragment import tech.thdev.webviewjavascriptinterface.R import tech.thdev.webviewjavascriptinterface.util.hideKeyboard import tech.thdev.webviewjavascriptinterface.view.main.presenter.KotlinContract import tech.thdev.webviewjavascriptinterface.webkit.CustomWebChromeClient import tech.thdev.webviewjavascriptinterface.webkit.CustomWebViewClient import tech.thdev.webviewjavascriptinterface.webkit.KtWebView /** * Created by Tae-hwan on 8/11/16. */ class KotlinFragment(var url: String = ""): BaseFragment<KotlinContract.Presenter>(), KotlinContract.View { override fun getLayout(): Int = R.layout.fragment_kotlin private val etUrl by lazy { activity.findViewById(R.id.et_url) as EditText } private val webView by lazy { view?.findViewById(R.id.web_view) as KtWebView } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initView() } private fun initView() { etUrl.setOnEditorActionListener { textView, i, keyEvent -> if (i == EditorInfo.IME_ACTION_GO) { var url = etUrl.text.toString() if (TextUtils.isEmpty(url)) { url = this.url } webView.loadUrl(url) context.hideKeyboard(etUrl) } true } webView.setWebChromeClient(CustomWebChromeClient(activity)) webView.setWebViewClient(CustomWebViewClient(presenter)) webView.init() webView.addJavascriptInterface(presenter?.getOnCustomJavaScriptListener(), "WebViewTest") WebSettings.MIXED_CONTENT_ALWAYS_ALLOW etUrl.setText(url) webView.loadUrl(url) } override fun updateKeyword(keyword: String?) { Toast.makeText(context, keyword, Toast.LENGTH_SHORT).show() } override fun changeUrl(url: String?) { url?.let { webView.loadUrl(url) } } override fun updateUrl(url: String?) { etUrl.setText(url) } override fun hideKeyboard() { val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(webView.windowToken, 0) } }
0
null
0
1
e7c88e1b4f84e54510b49004db41dbe72df39a09
2,706
Android-BlogExample
Apache License 2.0
src/test/kotlin/ru/qiwi/devops/mission/control/platform/kubernetes/KubernetesConfig.kt
qiwi
329,911,226
false
null
package ru.qiwi.devops.mission.control.platform.kubernetes import ru.qiwi.devops.mission.control.platform.configuration.TestConfig import java.time.Duration data class KubernetesConfig( val defaultCluster: String?, val waitForEventMs: Long, val generating: GeneratingConfig, val clusters: List<ClusterConfig> ) { val waitForEvent = Duration.ofMillis(waitForEventMs) } data class GeneratingConfig( val namespace: String, val namePrefix: String ) data class ClusterConfig( val name: String, val host: String, val token: String ) val TestConfig.kubernetes: KubernetesConfig get() = load("kubernetes")
1
Kotlin
1
1
a5b4a1dc716841bbf0439fa309e3a2b85bbeb1d3
646
k8s-mission-control
MIT License
src/main/kotlin/ch/unil/pafanalysis/analysis/steps/summary_stat/AsyncSummaryStatRunner.kt
UNIL-PAF
419,229,519
false
null
package ch.unil.pafanalysis.analysis.steps.summary_stat import ch.unil.pafanalysis.analysis.model.AnalysisStep import ch.unil.pafanalysis.analysis.steps.CommonStep import ch.unil.pafanalysis.common.ReadTableData import ch.unil.pafanalysis.common.SummaryStatComputation import org.springframework.scheduling.annotation.Async import org.springframework.stereotype.Service @Service class AsyncSummaryStatRunner() : CommonStep() { private val readTableData = ReadTableData() @Async fun runAsync(oldStepId: Int, newStep: AnalysisStep?) { val funToRun: () -> AnalysisStep? = { val params = gson.fromJson(newStep?.parameters, SummaryStatParams().javaClass) val normRes = transformTable( newStep, params ) newStep?.copy( results = gson.toJson(normRes) ) } tryToRun(funToRun, newStep) } fun transformTable( step: AnalysisStep?, params: SummaryStatParams, ): SummaryStat? { val expDetails = step?.columnInfo?.columnMapping?.experimentDetails val intCol = params.intCol ?: step?.columnInfo?.columnMapping?.intCol val table = readTableData.getTable(getOutputRoot() + step?.resultTablePath, step?.commonResult?.headers) val (headers, ints) = readTableData.getDoubleMatrix(table, intCol, expDetails) val summaryStatComp = SummaryStatComputation() return summaryStatComp.getSummaryStat(ints, headers, expDetails) } }
0
Kotlin
0
0
ab2cdaaa4b36cd8c7cc0ae91b196162a9fea41c1
1,535
paf-analysis-backend
MIT License
generator/src/commonTest/kotlin/maryk/generator/kotlin/GenerateKotlinForIndexedEnumTest.kt
marykdb
290,454,412
false
{"Kotlin": 3292487, "JavaScript": 1004}
package maryk.generator.kotlin import maryk.test.models.Option import kotlin.test.Test import kotlin.test.assertEquals val generatedKotlinForIndexedEnum = """ package maryk.test.models import maryk.core.properties.enum.IndexedEnumDefinition import maryk.core.properties.enum.IndexedEnumImpl sealed class Option( index: UInt, alternativeNames: Set<String>? = null ) : IndexedEnumImpl<Option>(index, alternativeNames) { object V1: Option(1u) object V2: Option(2u, setOf("VERSION2")) object V3: Option(3u, setOf("VERSION3")) class UnknownOption(index: UInt, override val name: String): Option(index) companion object : IndexedEnumDefinition<Option>( Option::class, values = { arrayOf(V1, V2, V3) }, reservedIndices = listOf(4u), reservedNames = listOf("V4"), unknownCreator = ::UnknownOption ) } """.trimIndent() class GenerateKotlinForIndexedEnumTest { @Test fun generateKotlinForOption() { val output = buildString { Option.generateKotlin("maryk.test.models") { append(it) } } assertEquals(generatedKotlinForIndexedEnum, output) } }
1
Kotlin
1
8
1da24fb090889aaf712592bcdb34876cb502f13a
1,188
maryk
Apache License 2.0
app/src/main/java/com/example/kotlinglang/b_estruturaDados/reverseStringTeste.kt
johnnymeneses
527,025,619
false
{"Kotlin": 101138}
package b_estruturaDados //import org.junit.Assert //import org.junit.Test class reverseStringTeste { // @Test // fun reverseUsingSB() { // Assert.assertEquals("ynnhoJ", reverseUsingSB("Johnny")) // } // // @Test // fun reverseStringLoop() { // Assert.assertEquals("seseneM", reverseUsingLoop("Meneses")) // // } } fun reverseUsingSB(str: String): String { return StringBuilder(str).reverse().toString() } fun reverseUsingLoop(str: String): String { var phrase = StringBuilder() var i = str.length - 1 while (i >= 0) { phrase.append(str[i])//metodo para adicionar dentro da variavel str i-- } return phrase.toString() }
0
Kotlin
0
0
81adfdad80400ece05a66d49dc7aeea7d107a68b
703
kotlin-lang
MIT License
app/src/main/java/com/destr/financehelper/data/datasource/cloud/JsonMapDeserializer.kt
DESTROYED
252,989,159
false
null
package com.destr.financehelper.data.datasource.cloud import com.destr.financehelper.data.datasource.cloud.response.PairDetail import com.google.gson.* import java.lang.reflect.Type class JsonMapDeserializer : JsonDeserializer<Map<String, PairDetail>> { override fun deserialize( json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext? ): Map<String, PairDetail> { val result: MutableMap<String, PairDetail> = HashMap() val parentAsObject: JsonObject? = json?.asJsonObject parentAsObject?.entrySet()?.let { for ((key, value) in it) { result[key] = Gson().fromJson(value, PairDetail::class.java) } } return result } }
0
Kotlin
0
0
8fa90bc008aff86cb682d8ca414acf705d54d15c
752
ExmoFinanceHelper
Apache License 2.0
idea/testData/intentions/toInfixCall/doubleFunctionCall.kt
staltz
38,581,975
true
{"Java": 15450397, "Kotlin": 8578737, "JavaScript": 176060, "HTML": 22810, "Lex": 17327, "Protocol Buffer": 13024, "ANTLR": 9689, "CSS": 9431, "Shell": 3931, "IDL": 3257, "Groovy": 3010, "Batchfile": 2831}
fun foo(x: Int) { (x.<caret>times(1)).div(2) }
0
Java
0
1
80074c71fa925a1c7173e3fffeea4cdc5872460f
51
kotlin
Apache License 2.0