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
src/main/java/uk/gov/justice/digital/hmpps/whereabouts/dto/AppointmentDtos.kt
ministryofjustice
141,123,113
false
{"Gradle Kotlin DSL": 4, "YAML": 14, "JSON": 26, "Dockerfile": 1, "INI": 5, "Shell": 4, "Text": 2, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "Markdown": 3, "SQL": 64, "Kotlin": 224, "Java": 24, "Public Key": 1, "XML": 1, "Java Properties": 10}
package uk.gov.justice.digital.hmpps.whereabouts.dto import com.fasterxml.jackson.annotation.JsonInclude import io.swagger.annotations.ApiModel import io.swagger.annotations.ApiModelProperty import uk.gov.justice.digital.hmpps.whereabouts.model.HearingType import uk.gov.justice.digital.hmpps.whereabouts.model.RepeatPeriod import java.time.LocalDateTime @JsonInclude(JsonInclude.Include.NON_NULL) data class CourtLocationsResponse(val courtLocations: List<String>? = emptyList()) @JsonInclude(JsonInclude.Include.NON_NULL) data class VideoLinkAppointmentsResponse(val appointments: List<VideoLinkAppointmentDto>? = emptyList()) data class CreateBookingAppointment( val appointmentType: String, val locationId: Long, val comment: String? = null, val startTime: String, val endTime: String, val repeat: Repeat? = null, ) @ApiModel(description = "The data required to create an appointment") data class CreateAppointmentSpecification( @ApiModelProperty(required = true, value = "The offender booking id") val bookingId: Long, @ApiModelProperty(required = true, value = "The location id of where the appointment will take place") val locationId: Long, @ApiModelProperty(required = true, value = "Appointment type") val appointmentType: String, @ApiModelProperty(value = "Additional information") val comment: String? = null, @ApiModelProperty( value = "The date and time the appointment is scheduled for", ) val startTime: LocalDateTime, @ApiModelProperty( value = "The estimated date time the appointment will end", ) val endTime: LocalDateTime? = null, @ApiModelProperty(value = "Describes how many times this appointment is to be repeated") val repeat: Repeat? = null, ) data class CreatePrisonAppointment( val appointmentDefaults: AppointmentDefaults, val appointments: List<Appointment>, val repeat: Repeat?, ) data class AppointmentDefaults( val appointmentType: String, val comment: String? = null, val startTime: LocalDateTime, val endTime: LocalDateTime?, val locationId: Long, ) data class Appointment( val bookingId: Long, val comment: String? = null, val startTime: LocalDateTime, val endTime: LocalDateTime?, ) @ApiModel(description = "Describes how many times this appointment is to be repeated") data class Repeat( @ApiModelProperty( required = true, value = "Repeat period", example = "Daily", allowableValues = "Weekly,Daily,Weekday,Monthly,Fortnightly", ) val repeatPeriod: RepeatPeriod, @ApiModelProperty(required = true, value = "Specifies the amount of times the repeat period will be applied") val count: Long, ) @ApiModel(description = "The data related to a single appointment.") data class AppointmentDto( @ApiModelProperty(required = true, value = "The event Id associated with this appointment") val id: Long, @ApiModelProperty(required = true, value = "The Id of the agency where the appointment is", example = "MDI") val agencyId: String, @ApiModelProperty(required = true, value = "The Id of the location to be used for this appointment") val locationId: Long, @ApiModelProperty(required = true, value = "The code for the type of appointment this is", example = "INTERV") val appointmentTypeCode: String, @ApiModelProperty(required = true, value = "The NOMS Id of the offender who this appointment is for") val offenderNo: String? = null, @ApiModelProperty(required = true, value = "When the appointment is scheduled to start") val startTime: LocalDateTime, @ApiModelProperty(required = false, value = "When the appointment is scheduled to end") val endTime: LocalDateTime?, @ApiModelProperty(required = false, value = "Created by user id") val createUserId: String? = null, @ApiModelProperty(required = false, value = "Additional information regarding the appointment") val comment: String? = null, ) @ApiModel(description = "The data related to a single appointment.") data class AppointmentSearchDto( @ApiModelProperty(required = true, value = "The event Id associated with this appointment") val id: Long, @ApiModelProperty(required = true, value = "The Id of the agency where the appointment is", example = "MDI") val agencyId: String, @ApiModelProperty(required = true, value = "The Id of the location to be used for this appointment") val locationId: Long, @ApiModelProperty(required = true, value = "The description of the location") val locationDescription: String, @ApiModelProperty(required = true, value = "The code for the type of appointment this is", example = "INTERV") val appointmentTypeCode: String, @ApiModelProperty(required = true, value = "The description of the appointment type") val appointmentTypeDescription: String, @ApiModelProperty(required = true, value = "The NOMS Id of the offender who this appointment is for") val offenderNo: String, @ApiModelProperty(required = true, value = "Offender first name") val firstName: String, @ApiModelProperty(required = true, value = "Offender last name") val lastName: String, @ApiModelProperty(required = true, value = "When the appointment is scheduled to start") val startTime: LocalDateTime, @ApiModelProperty(required = false, value = "When the appointment is scheduled to end") val endTime: LocalDateTime?, @ApiModelProperty(required = true, value = "The name of the user who created this appointment", example = "ASMITH") val createUserId: String, ) @ApiModel(description = "Video link appointment booking") data class VideoLinkBookingDto( @ApiModelProperty(required = true, value = "id of the video link appointment booking") val id: Long, @ApiModelProperty(required = true, value = "Main appointment") val main: VideoLinkAppointmentDto, @ApiModelProperty(required = false, value = "Pre appointment") val pre: VideoLinkAppointmentDto? = null, @ApiModelProperty(required = false, value = "Post appointment") val post: VideoLinkAppointmentDto? = null, ) @ApiModel(description = "Video link appointment details") data class VideoLinkAppointmentDto( @ApiModelProperty(value = "Court appointment id", example = "1") val id: Long, @ApiModelProperty(value = "Offender booking id", example = "1") val bookingId: Long, @ApiModelProperty(value = "Appointment id, maps to nomis event id", example = "1") val appointmentId: Long, @ApiModelProperty(value = "Video link booking id. This is the same for any related pre, post and main appointments", example = "1") val videoLinkBookingId: Long, @ApiModelProperty(value = "The id of the main appointment for the related video link booking") val mainAppointmentId: Long? = null, @ApiModelProperty( value = "The name of the court that requires the appointment", example = "York Crown Court", ) val court: String, @ApiModelProperty( value = "The identifier of the court that requires the appointment. If present this will be one of the identifier values from the courts register service.", example = "CMBGMC", ) val courtId: String?, @ApiModelProperty(value = "Type of court hearing", example = "MAIN, PRE , POST") val hearingType: HearingType, @ApiModelProperty(value = "Username of the appointment creator", example = "john1") val createdByUsername: String?, @ApiModelProperty(value = "Determines if the appointment was made by the court") val madeByTheCourt: Boolean? = true, @ApiModelProperty(value = "When the appointment is scheduled to start", example = "2020-12-23T10:00") val startTime: LocalDateTime? = null, @ApiModelProperty(value = "When the appointment is scheduled to end", example = "2020-12-24T10:00") val endTime: LocalDateTime? = null, @ApiModelProperty(value = "The location id of where the appointment will take place") val locationId: Long? = null, ) @ApiModel(description = "Recurring appointment") data class RecurringAppointmentDto( @ApiModelProperty(value = "Recurring appointment sequence id", example = "1") val id: Long, @ApiModelProperty( required = true, value = "Repeat period", example = "Daily", allowableValues = "Weekly,Daily,Weekday,Monthly,Fortnightly", ) val repeatPeriod: RepeatPeriod, @ApiModelProperty(required = true, value = "Specifies the amount of times the repeat period will be applied") val count: Long, @ApiModelProperty(value = "The start time of the first appointment in the sequence", example = "2020-12-23T10:00") val startTime: LocalDateTime, ) @ApiModel(description = "Appointment details, linking video link bookings and recurring appointments") data class AppointmentDetailsDto( @ApiModelProperty(required = true, value = "Appointment details pulled from NOMIS") val appointment: AppointmentDto, @ApiModelProperty(required = false, value = "Video link booking details") val videoLinkBooking: VideoLinkBookingDto? = null, @ApiModelProperty(required = false, value = "Recurring appointment details") val recurring: RecurringAppointmentDto? = null, ) data class Event( val eventId: Long, val agencyId: String, val eventLocationId: Long, val startTime: LocalDateTime, val endTime: LocalDateTime, ) @ApiModel(description = "The details of an appointment that has just been created") data class CreatedAppointmentDetailsDto( @ApiModelProperty(value = "The id of the appointment that was created.", example = "123456") val appointmentEventId: Long, @ApiModelProperty( required = true, value = "The Booking id of the offender for whom the appointment was created.", example = "123456", ) val bookingId: Long, @ApiModelProperty(value = "The start time of the appointment.", example = "2018-12-31T23:50") val startTime: LocalDateTime, @ApiModelProperty(value = "The end time of the appointment.", example = "2018-12-31T23:59") val endTime: LocalDateTime? = null, @ApiModelProperty(value = "The scheduled event subType", example = "ACTI") val appointmentType: String, @ApiModelProperty( value = "The identifier of the appointments' Location. The location must be situated in the requestor's case load.", example = "25", ) val locationId: Long, )
4
Kotlin
1
1
f5db01777f2ba042af38fbdad42783186a7494ef
10,128
whereabouts-api
Apache License 2.0
dokka-subprojects/analysis-kotlin-descriptors-ide/src/main/kotlin/org/jetbrains/dokka/analysis/kotlin/descriptors/ide/IdeAnalysisContextCreator.kt
Kotlin
21,763,603
false
{"Text": 4, "Gradle Kotlin DSL": 231, "Java Properties": 41, "Markdown": 102, "Shell": 12, "Ignore List": 10, "Batchfile": 9, "Git Attributes": 2, "JSON": 12, "Kotlin": 1142, "TOML": 2, "YAML": 12, "HTML": 145, "SVG": 85, "CSS": 36, "Gradle": 15, "Java": 22, "JavaScript": 28, "Diff": 3, "XML": 13, "INI": 1, "Maven POM": 2, "JAR Manifest": 1, "JSON with Comments": 1, "TSX": 7, "SCSS": 3, "Fluent": 3, "FreeMarker": 2}
/* * Copyright 2014-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package org.jetbrains.dokka.analysis.kotlin.descriptors.compiler import com.intellij.mock.MockProject import org.jetbrains.dokka.InternalDokkaApi import org.jetbrains.dokka.analysis.kotlin.descriptors.compiler.configuration.AnalysisContext import org.jetbrains.dokka.analysis.kotlin.descriptors.compiler.configuration.AnalysisEnvironment import org.jetbrains.kotlin.analyzer.ResolverForModule import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.descriptors.ModuleDescriptor @InternalDokkaApi public interface AnalysisContextCreator { public fun create( project: MockProject, moduleDescriptor: ModuleDescriptor, moduleResolver: ResolverForModule, kotlinEnvironment: KotlinCoreEnvironment, analysisEnvironment: AnalysisEnvironment, ): AnalysisContext }
1
null
1
1
09437c33bae16dd6432129db7b5706577103d3ba
955
dokka
Apache License 2.0
constraint-programming/src/main/java/org/optaplanner/examples/cloudbalancing/solver/move/factory/CloudComputerChangeMoveFactory.kt
xmlking
58,849,015
false
null
/* * Copyright 2010 Red Hat, Inc. and/or its affiliates. * * 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.optaplanner.examples.cloudbalancing.solver.move.factory import java.util.ArrayList import org.optaplanner.core.impl.heuristic.move.Move import org.optaplanner.core.impl.heuristic.selector.move.factory.MoveListFactory import org.optaplanner.examples.cloudbalancing.domain.CloudBalance import org.optaplanner.examples.cloudbalancing.domain.CloudComputer import org.optaplanner.examples.cloudbalancing.domain.CloudProcess import org.optaplanner.examples.cloudbalancing.solver.move.CloudComputerChangeMove class CloudComputerChangeMoveFactory : MoveListFactory<CloudBalance> { override fun createMoveList(cloudBalance: CloudBalance): List<Move> { val moveList = ArrayList<Move>() val cloudComputerList = cloudBalance.computerList for (cloudProcess in cloudBalance.processList!!) { for (cloudComputer in cloudComputerList!!) { moveList.add(CloudComputerChangeMove(cloudProcess, cloudComputer)) } } return moveList } }
1
null
1
12
ce35b7b7e6fcaa9a48d1545c0dc5fd878e05bb1e
1,640
ml-experiments
MIT License
Problems/Algorithms/1020. Number Enclaves/NumberEnclaves.kt
xuedong
189,745,542
false
{"Text": 1, "Ignore List": 1, "Markdown": 1, "Python": 498, "Kotlin": 443, "Java": 343, "Go": 55, "C++": 150, "Rust": 141, "Ruby": 2, "Dart": 1, "Erlang": 1, "Racket": 1, "Elixir": 1, "Scala": 2, "C": 2, "JavaScript": 22, "C#": 2, "Shell": 2, "SQL": 34, "JSON": 1, "Swift": 1, "TSX": 1}
class Solution { fun numEnclaves(grid: Array<IntArray>): Int { val n = grid.size val m = grid[0].size val visited = Array(n) { BooleanArray(m) { false } } val neighbors = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0)) var ans = 0 for (i in 0..n-1) { for (j in 0..m-1) { if (!visited[i][j] && grid[i][j] == 1) { var flag = false var count = 0 val queue = ArrayDeque<IntArray>() queue.add(intArrayOf(i, j)) while (!queue.isEmpty()) { for (k in 0..queue.size-1) { val curr = queue.removeLast() val row = curr[0] val col = curr[1] count++ visited[row][col] = true for (neighbor in neighbors) { val r = row + neighbor[0] val c = col + neighbor[1] if (r < 0 || r >= n || c < 0 || c >= m) { flag = true continue } if (grid[r][c] == 0 || visited[r][c]) continue visited[r][c] = true queue.add(intArrayOf(r, c)) } } } if (!flag) { ans += count } } } } return ans } }
0
Kotlin
0
1
64e27269784b1a31258677ab03da00f341c2fa98
1,897
leet-code
MIT License
component-toolkit/src/commonMain/kotlin/com/pablichj/templato/component/core/drawer/DrawerComponent.kt
pablichjenkov
135,388,611
false
null
package com.pablichj.templato.component.core.drawer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.DrawerValue import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import com.pablichj.templato.component.core.router.DeepLinkResult import com.pablichj.templato.component.core.stack.BackStack import com.pablichj.templato.component.platform.DiContainer import com.pablichj.templato.component.core.* import com.pablichj.templato.component.core.processBackstackEvent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch open class DrawerComponent( private val config: Config, private var diContainer: DiContainer ) : Component(), NavigationComponent, DrawerNavigationComponent { final override val backStack = BackStack<Component>() override var navItems: MutableList<NavItem> = mutableListOf() override var selectedIndex: Int = 0 override var childComponents: MutableList<Component> = mutableListOf() override var activeComponent: MutableState<Component?> = mutableStateOf(null) private val coroutineScope = CoroutineScope(diContainer.dispatchers.main) val navigationDrawerState = NavigationDrawerState( coroutineScope, DrawerHeaderState( title = "A Drawer Header Title", description = "Some description or leave it blank", imageUri = "", style = config.drawerHeaderStyle ), emptyList() ) init { coroutineScope.launch { navigationDrawerState.navItemClickFlow.collect { navItemClick -> backStack.push(navItemClick.component) } } backStack.eventListener = { event -> val stackTransition = processBackstackEvent(event) processBackstackTransition(stackTransition) } } // region: ComponentLifecycle override fun start() { super.start() if (activeComponent.value == null) { println("$clazz::start(). Pushing selectedIndex = $selectedIndex, children.size = ${childComponents.size}") if (childComponents.isNotEmpty()) { backStack.push(childComponents[selectedIndex]) } else { println("$clazz::start() with childComponents empty") } } else { println("$clazz::start() with activeNodeState = ${activeComponent.value?.clazz}") activeComponent.value?.start() } } override fun stop() { super.stop() println("$clazz::stop()") activeComponent.value?.stop() } override fun handleBackPressed() { println("$clazz::handleBackPressed, backStack.size = ${backStack.size()}") if (backStack.size() > 1) { backStack.pop() } else { // We delegate the back event when the stack has 1 element and not 0. The reason is, if // we pop all the way to zero the stack empty view will be show for a fraction of // milliseconds and this creates an undesirable effect. delegateBackPressedToParent() } } // endregion // region: IDrawerComponent override fun open() { println("$clazz::open") navigationDrawerState.setDrawerState(DrawerValue.Open) } override fun close() { println("$clazz::close") navigationDrawerState.setDrawerState(DrawerValue.Closed) } // endregion // region: NavigatorItems override fun getComponent(): Component { return this } override fun onSelectNavItem(selectedIndex: Int, navItems: MutableList<NavItem>) { val navItemsDeco = navItems.map { it.toNavItemDeco() } navigationDrawerState.navItemsDeco = navItemsDeco navigationDrawerState.selectNavItemDeco(navItemsDeco[selectedIndex]) if (getComponent().lifecycleState == ComponentLifecycleState.Started) { backStack.push(childComponents[selectedIndex]) } } override fun updateSelectedNavItem(newTop: Component) { getNavItemFromComponent(newTop).let { println("$clazz::updateSelectedNavItem(), selectedIndex = $it") navigationDrawerState.selectNavItemDeco(it.toNavItemDeco()) selectedIndex = childComponents.indexOf(newTop) } } override fun onDestroyChildComponent(component: Component) { if (component.lifecycleState == ComponentLifecycleState.Started) { component.stop() component.destroy() } else { component.destroy() } } // endregion // region: DeepLink override fun getDeepLinkSubscribedList(): List<Component> { return childComponents } override fun onDeepLinkNavigation(matchingComponent: Component): DeepLinkResult { println("$clazz.onDeepLinkMatch() matchingNode = ${matchingComponent.clazz}") backStack.push(matchingComponent) return DeepLinkResult.Success } // endregion // region Drawer rendering fun setDrawerComponentView( drawerComponentView: @Composable DrawerComponent.( modifier: Modifier, childComponent: Component ) -> Unit ) { this.drawerComponentView = drawerComponentView } private var drawerComponentView: @Composable DrawerComponent.( modifier: Modifier, childComponent: Component ) -> Unit = DefaultDrawerComponentView @Composable override fun Content(modifier: Modifier) { println( """$clazz.Composing() stack.size = ${backStack.size()} |lifecycleState = ${lifecycleState} """ ) //Box { val activeComponentCopy = activeComponent.value if (activeComponentCopy != null) { drawerComponentView(modifier, activeComponentCopy) } else { Text( modifier = Modifier .fillMaxSize(), //.align(Alignment.Center), text = "$clazz Empty Stack, Please add some children", textAlign = TextAlign.Center ) } //} } // endregion class Config( var drawerHeaderStyle: DrawerHeaderStyle ) companion object { val DefaultConfig = Config( DrawerHeaderStyle() ) val DefaultDrawerComponentView: @Composable DrawerComponent.( modifier: Modifier, childComponent: Component ) -> Unit = { modifier, childComponent -> NavigationDrawer( modifier = modifier, navigationDrawerState = navigationDrawerState ) { childComponent.Content(Modifier) } } } }
0
Kotlin
0
24
3816574c0b67fd4fc8dd749aab4af1b4f9362451
7,009
component-toolkit
The Unlicense
SKIE/kotlin-compiler/core/src/commonMain/kotlin/co/touchlab/skie/sir/element/SirVisibility.kt
touchlab
685,579,240
false
{"Kotlin": 1363716, "Swift": 25254, "Shell": 763}
package co.touchlab.skie.sir.element enum class SirVisibility { Public, PublicButHidden, PublicButReplaced, Internal, Private, Removed, } fun SirVisibility.toSwiftVisibility(): SirVisibility = when (this) { SirVisibility.Public, SirVisibility.PublicButHidden, SirVisibility.PublicButReplaced, -> SirVisibility.Public SirVisibility.Internal -> SirVisibility.Internal SirVisibility.Private -> SirVisibility.Private SirVisibility.Removed -> SirVisibility.Removed } val SirVisibility.isAccessibleFromOtherModules: Boolean get() = when (toSwiftVisibility()) { SirVisibility.Public -> true else -> false } val SirDeclaration.isExported: Boolean get() = visibility.isAccessibleFromOtherModules val SirVisibility.isAccessible: Boolean get() = when (toSwiftVisibility()) { SirVisibility.Private, SirVisibility.Removed -> false else -> true } val SirDeclaration.isAccessible: Boolean get() = visibility.isAccessible val SirVisibility.isRemoved: Boolean get() = when (this) { SirVisibility.Removed -> true else -> false } val SirDeclaration.isRemoved: Boolean get() = visibility.isRemoved || parent == SirDeclarationParent.None
4
Kotlin
7
566
b745d1617f3ce6ca95be3a09a96f5cadff1f4f45
1,262
SKIE
Apache License 2.0
app/src/main/java/com/example/vinilosgrupo3/models/CollectorAlbums.kt
ChristianBorrasTorres
549,053,538
false
{"Kotlin": 88802, "Java": 9447}
package com.example.vinilosgrupo3.models data class CollectorAlbums ( val id: Int, val price: Int, val status: String ) enum class Status { Active, Inactive }
0
Kotlin
1
0
859235ed0c65f284987fe805d47b5eb185f52f6e
177
aplicaciones-moviles
MIT License
src/test/kotlin/com/github/jwt/fixture/JwtFixture.kt
earlgrey02
728,482,511
false
{"Kotlin": 18656}
package com.github.jwt.fixture import com.github.jwt.security.DefaultJwtAuthentication import com.github.jwt.security.JwtAuthentication import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.authority.SimpleGrantedAuthority val SECRET = (1..100).map { ('a'..'z').random() }.joinToString("") const val ACCESS_TOKEN_EXPIRE = 1L const val REFRESH_TOKEN_EXPIRE = 10L const val ID = "id" val ROLES = setOf(SimpleGrantedAuthority("USER")) const val INVALID_TOKEN = "invalid_token" fun createDefaultJwtAuthentication( id: String = ID, roles: Set<GrantedAuthority> = ROLES, ): JwtAuthentication = DefaultJwtAuthentication( id = id, roles = roles )
0
Kotlin
0
0
4e341e0f93f63a22392013008a7f3623153ee5d5
719
JWT
MIT License
android-interview-project-master/app/src/test/java/com/servicenow/exercise_kotlin/ExampleUnitTestKt.kt
hemandroid
239,246,366
false
{"Text": 1, "Ignore List": 3, "Markdown": 2, "Gradle": 3, "Shell": 2, "Java Properties": 2, "Batchfile": 1, "Proguard": 1, "Java": 2, "Kotlin": 15, "XML": 18}
package com.servicenow.exercise_kotlin import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTestKt { @Test fun additionIsCorrect() { assertEquals(4, 2 + 2) } }
0
Kotlin
0
0
5eca7dc70ddfa7cd4af42014d8ca94745ec023fd
356
service_now_assignment
MIT License
test/src/main/kotlin/top/bettercode/summer/test/DefaultTestAuthenticationService.kt
top-bettercode
387,652,015
false
{"Kotlin": 2939064, "Java": 24119, "JavaScript": 22541, "CSS": 22336, "HTML": 15833}
package top.bettercode.summer.test import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import top.bettercode.summer.security.authorization.UserDetailsAuthenticationToken import top.bettercode.summer.security.userdetails.ScopeUserDetailsService /** * * @author <NAME> */ class DefaultTestAuthenticationService(private val userDetailsService: UserDetailsService) : TestAuthenticationService { override fun loadAuthentication(scope: String, username: String) { val userDetails: UserDetails = if (userDetailsService is ScopeUserDetailsService) { userDetailsService.loadUserByScopeAndUsername(scope, username) } else { userDetailsService.loadUserByUsername(username) } SecurityContextHolder.getContext().authentication = UserDetailsAuthenticationToken(userDetails) } }
0
Kotlin
0
1
da096b3c592335e25869d9ff2cdb91c2551c794c
990
summer
Apache License 2.0
build-logic/src/main/kotlin/dokkabuild/utils/downloadKotlinStdlibJvmSources.kt
Kotlin
21,763,603
false
{"Kotlin": 4076594, "CSS": 63880, "JavaScript": 39656, "TypeScript": 16774, "SCSS": 8881, "HTML": 6860, "FreeMarker": 4120, "Shell": 3948, "Java": 1147}
/* * Copyright 2014-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package dokkabuild.utils import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.api.attributes.Category.CATEGORY_ATTRIBUTE import org.gradle.api.attributes.Category.DOCUMENTATION import org.gradle.api.attributes.DocsType.DOCS_TYPE_ATTRIBUTE import org.gradle.api.attributes.DocsType.SOURCES import org.gradle.api.attributes.Usage.JAVA_RUNTIME import org.gradle.api.attributes.Usage.USAGE_ATTRIBUTE import org.gradle.api.file.ArchiveOperations import org.gradle.api.provider.Provider import org.gradle.api.tasks.Sync import org.gradle.kotlin.dsl.* import org.gradle.kotlin.dsl.support.serviceOf import java.io.File /** * Download and unpack Kotlin stdlib JVM source code. * * @returns the directory containing the unpacked sources. */ fun downloadKotlinStdlibJvmSources(project: Project): Provider<File> { val kotlinStdlibJvmSources: Configuration by project.configurations.creating { description = "kotlin-stdlib JVM source code." declarable() withDependencies { add(project.dependencies.run { create(kotlin("stdlib")) }) } } val kotlinStdlibJvmSourcesResolver: Configuration by project.configurations.creating { description = "Resolver for ${kotlinStdlibJvmSources.name}." resolvable() isTransitive = false extendsFrom(kotlinStdlibJvmSources) attributes { attribute(USAGE_ATTRIBUTE, project.objects.named(JAVA_RUNTIME)) attribute(CATEGORY_ATTRIBUTE, project.objects.named(DOCUMENTATION)) attribute(DOCS_TYPE_ATTRIBUTE, project.objects.named(SOURCES)) } } val downloadKotlinStdlibSources by project.tasks.registering(Sync::class) { description = "Download and unpacks kotlin-stdlib JVM source code." val archives = project.serviceOf<ArchiveOperations>() val unpackedJvmSources = kotlinStdlibJvmSourcesResolver.incoming.artifacts.resolvedArtifacts.map { artifacts -> artifacts.map { archives.zipTree(it.file) } } from(unpackedJvmSources) into(temporaryDir) } return downloadKotlinStdlibSources.map { it.destinationDir } }
671
Kotlin
409
3,434
ec28b78ee5b137ee989cd0203ef108b2a2ac4811
2,325
dokka
Apache License 2.0
src/main/kotlin/com/fintecsystems/xs2a/java/models/api/connections/AccountSelection.kt
FinTecSystems
399,112,589
false
null
package com.fintecsystems.xs2a.java.models.api.connections import com.squareup.moshi.Json /** * Mode of account selection. If \"all\" is given, all available accounts from this bankconnection will be used. If \"single\"/\"multi\" is given, the customer can pick single/multiple accounts from this connection which will be used. * Values: all,multi,single */ enum class AccountSelection(var value: String) { @Json(name = "all") ALL("all"), @Json(name = "multi") MULTI("multi"), @Json(name = "single") SINGLE("single"); override fun toString() = value }
0
Kotlin
3
3
295a09292035aeeb288c2cef3f92a28b65f4ae87
587
xs2a-java
MIT License
src/main/kotlin/jp/ac/osaka_u/sdl/nil/usecase/preprocess/python/PythonPreprocess.kt
kusumotolab
295,970,504
false
{"Gradle Kotlin DSL": 2, "Markdown": 4, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "INI": 1, "Python": 1, "Kotlin": 51, "Java": 19, "C++": 1, "C#": 1, "ANTLR": 5}
package jp.ac.osaka_u.sdl.nil.usecase.preprocess.python import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.kotlin.toFlowable import jp.ac.osaka_u.sdl.nil.NILConfig import jp.ac.osaka_u.sdl.nil.entity.CodeBlock import jp.ac.osaka_u.sdl.nil.usecase.preprocess.Preprocess import java.io.File class PythonPreprocess(private val config: NILConfig) : Preprocess(config.threads) { override fun collectSourceFiles(dir: File): Flowable<File> = dir.walk() .filter { it.isFile && it.toString().endsWith(".py") } .toFlowable() override fun collectBlocks(srcFile: File): Flowable<CodeBlock> = Flowable.just(srcFile) .flatMap(PythonTransformer(config)::extractBlocks) }
0
Java
3
13
d43a91e9a5ebef9d20c900046c9d6aa2b3b03b95
737
NIL
MIT License
rv-itemtype/src/main/java/me/reezy/cosmo/rv/itemtype/utility.kt
czy1121
533,686,296
false
null
package me.reezy.cosmo.rv.itemtype import android.content.Context import android.content.ContextWrapper import android.view.View import androidx.annotation.LayoutRes import androidx.annotation.RestrictTo import androidx.core.app.ComponentActivity import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.lifecycle.LifecycleOwner inline fun <reified Item, reified V> viewType(subtype: Int = 0): ItemType<Item, ViewHolder<V>> where V: View, V: ItemView<Item> { return ViewItemType(Item::class.java, V::class.java, subtype) { holder, item -> holder.view.bind(item) } } inline fun <reified Item> layoutType(@LayoutRes layoutResId: Int, subtype: Int = 0, noinline binder: (ItemHolder, Item) -> Unit): ItemType<Item, ItemHolder> { return LayoutItemType(Item::class.java, layoutResId, subtype, binder) } inline fun <reified Item> bindingType(@LayoutRes layoutResId: Int, subtype: Int = 0, noinline onClick: ((ItemHolder, Item) -> Unit)? = null): ItemType<Item, ItemHolder> { return LayoutItemType(Item::class.java, layoutResId, subtype) { holder, item -> onClick?.let { holder.itemView.setOnClickListener { onClick(holder, item) } } DataBindingUtil.bind<ViewDataBinding>(holder.itemView)?.let { it.setVariable(LayoutItemType.brItem, item) if (it.lifecycleOwner == null) { it.lifecycleOwner = holder.itemView.getLifecycleOwner() } } } } @RestrictTo(RestrictTo.Scope.LIBRARY) @PublishedApi internal fun View.getLifecycleOwner(): LifecycleOwner { if (this is LifecycleOwner) return this var obj: Context? = context do { if (obj is ComponentActivity) return obj obj = if (obj is ContextWrapper) obj.baseContext else null } while (obj != null) throw Exception("can not find LifecycleOwner") }
1
Kotlin
0
0
20f7f8693a737667398fe2f22339ed0ef61ff3ee
1,921
rv
Apache License 2.0
gradle-tooling/studio-gradle-tooling-impl/src/com/android/ide/gradle/model/builder/LegacyAndroidGradlePluginPropertiesModelBuilder.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ide.gradle.model.builder import com.android.ide.gradle.model.LegacyAndroidGradlePluginProperties import com.android.ide.gradle.model.LegacyAndroidGradlePluginPropertiesModelParameters import com.android.ide.gradle.model.builder.LegacyAndroidGradlePluginPropertiesModelBuilder.VariantCollectionProvider.AndroidTest import com.android.ide.gradle.model.builder.LegacyAndroidGradlePluginPropertiesModelBuilder.VariantCollectionProvider.ApplicationVariant import com.android.ide.gradle.model.builder.LegacyAndroidGradlePluginPropertiesModelBuilder.VariantCollectionProvider.DynamicFeature import com.android.ide.gradle.model.builder.LegacyAndroidGradlePluginPropertiesModelBuilder.VariantCollectionProvider.InstantAppFeature import com.android.ide.gradle.model.builder.LegacyAndroidGradlePluginPropertiesModelBuilder.VariantCollectionProvider.LibraryVariant import com.android.ide.gradle.model.impl.LegacyAndroidGradlePluginPropertiesImpl import org.gradle.api.DomainObjectSet import org.gradle.api.Project import org.gradle.tooling.provider.model.ParameterizedToolingModelBuilder import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry import java.lang.reflect.Method import java.util.concurrent.ConcurrentHashMap /** * An injected Gradle tooling model builder to fetch information from legacy versions of the Android Gradle plugin * * In particular, the Application ID and namespaces from AGP versions that don't report it directly in the model. * * This model should not be requested when AGP >= 7.4 is used, as the information is held directly in the model. */ class LegacyAndroidGradlePluginPropertiesModelBuilder(private val pluginType: PluginType) : ParameterizedToolingModelBuilder<LegacyAndroidGradlePluginPropertiesModelParameters> { override fun getParameterType(): Class<LegacyAndroidGradlePluginPropertiesModelParameters> = LegacyAndroidGradlePluginPropertiesModelParameters::class.java override fun canBuild(modelName: String): Boolean { return modelName == LegacyAndroidGradlePluginProperties::class.java.name } override fun buildAll(modelName: String, project: Project): Nothing = error("parameter required") override fun buildAll(modelName: String, parameters: LegacyAndroidGradlePluginPropertiesModelParameters, project: Project): LegacyAndroidGradlePluginProperties { check (modelName == LegacyAndroidGradlePluginProperties::class.java.name) { "Only valid model is ${LegacyAndroidGradlePluginProperties::class.java.name}" } val problems = mutableListOf<Exception>() val applicationIdMap = fetchApplicationIds(parameters, project, problems) val (namespace, androidTestNamespace) = fetchNamespace(parameters, project, problems) return LegacyAndroidGradlePluginPropertiesImpl(applicationIdMap, namespace, androidTestNamespace, problems) } private fun fetchApplicationIds(parameters: LegacyAndroidGradlePluginPropertiesModelParameters, project: Project, problems: MutableList<Exception>): Map<String, String> { if (!parameters.componentToApplicationIdMap) return mapOf() val extension = project.extensions.findByName("android") ?: return mapOf() val applicationIdMap = mutableMapOf<String, String>() for (variantCollectionProvider: VariantCollectionProvider in pluginType.variantCollectionProviders(extension)) { if (!variantCollectionProvider.providesApplicationId) continue val container = variantCollectionProvider.variants for (variant in container) { val componentName = variant.invokeMethod<String>("getName") val applicationId = variant.javaClass.getMethodCached("getApplicationId").runCatching { getOrThrow().invoke(variant) as String }.getOrElse { problems += RuntimeException( "Failed to read applicationId for ${componentName}.\n" + "Setting the application ID to the output of a task in the variant api is not supported", it ) null } ?: continue applicationIdMap[componentName] = applicationId } } return applicationIdMap } // This only applies to AGP 4.2 and below private fun fetchNamespace(parameters: LegacyAndroidGradlePluginPropertiesModelParameters, project: Project, problems: MutableList<Exception>): Pair<String?, String?> { if (!parameters.namespace) return Pair(null, null) val extension = project.extensions.findByName("android") ?: return Pair(null, null) var namespace : String? = null var androidTestNamespace : String? = null try { for (variantCollectionProvider in pluginType.variantCollectionProviders(extension)) { val container = variantCollectionProvider.variants for (variant in container) { // Use getGenerateBuildConfigProvider if possible to avoid triggering a user-visible deprecation warning, // but fall back to getGenerateBuildConfig if getGenerateBuildConfigProvider is not present val generateBuildConfigTask = variant.invokeMethodIfPresent<Any?>("getGenerateBuildConfigProvider")?.invokeMethod("get") ?: variant.invokeMethod<Any?>("getGenerateBuildConfig") ?: continue val namespaceObject = generateBuildConfigTask.invokeMethod<Any?>("getBuildConfigPackageName") ?: continue // This changed type from String to Property<String>, handle both. val componentNamespace = if (namespaceObject is String) namespaceObject else namespaceObject.invokeMethod("get") as String if (variantCollectionProvider.isMain) { namespace = componentNamespace } else { // In some versions of AGP the android test namespace depends on the application ID, which means that this can, // at least in theory, vary per variant. For the purpose of this model, just return one of the values. androidTestNamespace = componentNamespace } if (namespace != null && androidTestNamespace != null) { break } } } } catch (e: Exception) { problems += RuntimeException("Failed to fetch namespace", e) } return Pair(namespace, androidTestNamespace) } sealed class VariantCollectionProvider(private val extensionObject: Any, private val getterName: String, val isMain: Boolean, val providesApplicationId: Boolean) { class ApplicationVariant(extensionObject: Any): VariantCollectionProvider(extensionObject, getterName = "getApplicationVariants", isMain = true, providesApplicationId = true) class LibraryVariant(extensionObject: Any): VariantCollectionProvider(extensionObject, getterName = "getLibraryVariants", isMain = true, providesApplicationId = false) // Don't get main application IDs from dynamic features (see comment on com.android.builder.model.v2.ide.AndroidArtifact.applicationId) class DynamicFeature(extensionObject: Any): VariantCollectionProvider(extensionObject, getterName = "getApplicationVariants", isMain = true, providesApplicationId = false) // Only return the main application ID for base features (equivalent to apps in the new dynamic feature world) class InstantAppFeature(extensionObject: Any, isBaseFeature: Boolean): VariantCollectionProvider(extensionObject, getterName = "getFeatureVariants", isMain = true, providesApplicationId = isBaseFeature) class AndroidTest(extensionObject: Any): VariantCollectionProvider(extensionObject, getterName = "getTestVariants", isMain = false, providesApplicationId = true) val variants: DomainObjectSet<*> get() = extensionObject.invokeMethod(getterName) } enum class PluginType(val variantCollectionProviders: (Any) -> Set<VariantCollectionProvider>) { APPLICATION({ setOf(ApplicationVariant(it), AndroidTest(it)) }), LIBRARY({ setOf(LibraryVariant(it), AndroidTest(it)) }), TEST({ setOf(ApplicationVariant(it)) }), DYNAMIC_FEATURE({ setOf(DynamicFeature(it), AndroidTest(it)) }), INSTANT_APP_FEATURE({ setOf(InstantAppFeature(it, it.invokeMethod<Boolean?>("getBaseFeature") == true), AndroidTest(it)) } ), } companion object { private data class MethodCacheKey(val clazz: Class<*>, val methodName: String) private val methodCache: MutableMap<MethodCacheKey, Result<Method>> = ConcurrentHashMap() private fun Class<*>.getMethodCached(name: String) = methodCache.computeIfAbsent(MethodCacheKey(this, name)) { key -> runCatching { key.clazz.getMethod(key.methodName) } } internal fun <T> Any.invokeMethod(methodName: String): T { @Suppress("UNCHECKED_CAST") return javaClass.getMethodCached(methodName).getOrThrow().invoke(this) as T } private fun <T> Any.invokeMethodIfPresent(methodName: String): T? { @Suppress("UNCHECKED_CAST") return javaClass.getMethodCached(methodName).getOrNull()?.invoke(this) as T? } fun maybeRegister(project: Project, registry: ToolingModelBuilderRegistry) { project.pluginManager.withPlugin("com.android.application") { register(registry, PluginType.APPLICATION) } project.pluginManager.withPlugin("com.android.library") { register(registry, PluginType.LIBRARY) } project.pluginManager.withPlugin("com.android.dynamic-feature") { register(registry, PluginType.DYNAMIC_FEATURE) } project.pluginManager.withPlugin("com.android.feature") { register(registry, PluginType.INSTANT_APP_FEATURE) } project.pluginManager.withPlugin("com.android.test") { register(registry, PluginType.TEST) } } private fun register(registry: ToolingModelBuilderRegistry, pluginType: PluginType) { registry.register(LegacyAndroidGradlePluginPropertiesModelBuilder(pluginType)) } } }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
10,305
android
Apache License 2.0
textUtilsLib-kotlin/src/main/java/com/shuyu/textutillib/model/TopicModel.kt
CarGuo
73,381,327
false
null
package com.shuyu.textutillib.model import java.io.Serializable /** * 话题model * Created by guoshuyu on 2017/8/16. */ class TopicModel: Serializable { /** * 话题名字内部不能有#和空格 */ var topicName: String = "" var topicId: String = "" constructor() constructor(topicName: String, topicId: String) { this.topicName = topicName this.topicId = topicId } override fun toString(): String = this.topicName }
13
Java
100
692
c37d6543e401cab80d6d290fb8072bdc2c65cf8b
455
GSYRickText
MIT License
integration-tests/common/src/test/kotlin/me/tatarka/inject/test/InjectFunctionTest.kt
evant
194,859,139
false
null
package me.tatarka.inject.test import assertk.assertThat import assertk.assertions.isEqualTo import me.tatarka.inject.annotations.Component import me.tatarka.inject.annotations.Inject import me.tatarka.inject.test.module.externalFunction import kotlin.test.Test @Component abstract class FunctionInjectionComponent { abstract val bar: bar abstract val externalFunction: externalFunction } typealias F = String typealias foo = (F) -> String @Inject fun foo(dep: Foo, arg: F): String = arg typealias bar = () -> String @Inject fun bar(foo: foo): String = foo("test") typealias receiverFun = String.(arg: NamedFoo) -> String @Inject fun String.receiverFun(dep: Foo, arg: NamedFoo): String = this @Component abstract class ReceiverFunctionInjectionComponent { abstract val receiverFun: receiverFun } class InjectFunctionTest { @Test fun generates_a_component_that_provides_a_function() { val component = FunctionInjectionComponent::class.create() assertThat(component.bar()).isEqualTo("test") assertThat(component.externalFunction()).isEqualTo("external") } @Test fun generates_a_component_that_provides_a_function_with_receiver() { val component = ReceiverFunctionInjectionComponent::class.create() assertThat(with(component) { "test".receiverFun(NamedFoo("arg")) }).isEqualTo("test") } }
9
Kotlin
42
853
e29da6d82ba37b1ae19b35266eb537a0fb15273b
1,377
kotlin-inject
Apache License 2.0
src/main/kotlin/astar/Grid.kt
nebaughman
398,690,227
false
null
package astar import kotlin.math.abs import kotlin.math.max import kotlin.math.min @JsName("GridNode") class GridNode( val x: Int, val y: Int, ): Node { override fun toString() = "GridNode[$x,$y]" override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as GridNode if (x != other.x) return false if (y != other.y) return false return true } override fun hashCode(): Int { var result = x result = 31 * result + y return result } } @JsName("GridMap") class GridMap( val lonW: Int, val latH: Int, ): Graph { // TODO: factor Graph impl out of GridMap itself? /** * Diagonal distance heuristic * https://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#heuristics-for-grid-maps */ override fun heuristic(from: Node, goal: Node): Int { val a = from as GridNode val b = goal as GridNode val dx = abs(a.x - b.x) val dy = abs(a.y - b.y) return (dx + dy) - min(dx, dy) // step weights of 1 } override fun neighbors(node: Node): List<Node> { val n = node as GridNode val minX = max(0, n.x - 1) val minY = max(0, n.y - 1) val maxX = min(lonW - 1, n.x + 1) val maxY = min(latH - 1, n.y + 1) val list = mutableListOf<Node>() for (x in minX..maxX) { for (y in minY..maxY) { val gn = GridNode(x,y) // TODO: use existing instance if x,y tracked in map if (n != gn && !isWall(gn)) list.add(gn) } } return list } private val wallNodes = ArrayList<GridNode>() // Set would be better, but for JS @JsName("walls") val walls get(): List<GridNode> = wallNodes fun addWall(x: Int, y: Int) = apply { addWall(GridNode(x,y)) } @JsName("addWall") fun addWall(node: GridNode) { if (!isWall(node)) wallNodes.add(node) } @JsName("removeWall") fun removeWall(node: GridNode) { wallNodes.remove(node) } @JsName("toggleWall") fun toggleWall(node: GridNode) { if (isWall(node)) removeWall(node) else addWall(node) } @JsName("isWall") fun isWall(node: GridNode) = wallNodes.contains(node) } // TODO: instead, use Kotlin Serialization (JSON or ProtoBuf) /** * Helper to export/parse GridMap to/from string form. * Do not use this for persistent long-lived data; format may change. * Only use for current runtime transforms. * * Specific use case is to post data to/from Service Worker process. * Not using JSON because it's much more verbose than needed. * Could integrate with respective classes, but separating serialization. */ @JsName("GridParser") object GridParser { @JsName("exportGridMap") fun export(grid: GridMap): String { val list = mutableListOf(grid.lonW, grid.latH) grid.walls.forEach { list.add(it.x); list.add(it.y) } return list.joinToString(",") } @JsName("parseGridMap") fun parseGridMap(str: String): GridMap { val list = str.split(',').toMutableList() val grid = GridMap(list.removeFirst().toInt(), list.removeFirst().toInt()) while (list.isNotEmpty()) { grid.addWall(list.removeFirst().toInt(), list.removeFirst().toInt()) } return grid } @JsName("exportGridNode") fun export(node: GridNode) = "${node.x},${node.y}" @JsName("parseGridNode") fun parseGridNode(str: String) = str.split(',').let { GridNode(it.first().toInt(), it.last().toInt()) } /* fun <T:Any> parse(str: String, type: KClass<T>): T = when (type) { GridMap::class -> parseGridMap(str) as T GridNode::class -> parseGridNode(str) as T else -> throw IllegalArgumentException("Unsupported type $type") } */ }
0
Kotlin
0
0
4074ed52380e0eb12d2ed5084ed854fe7d0a1e1d
3,670
astar-kotlin-js
MIT License
mynlp/src/main/java/com/mayabot/nlp/segment/lexer/perceptron/PerceptronSegmentDefinition.kt
mayabot
113,726,044
false
null
package com.mayabot.nlp.segment.lexer.perceptron import com.mayabot.nlp.common.FastStringBuilder import com.mayabot.nlp.common.utils.CharNormUtils import com.mayabot.nlp.perceptron.EvaluateFunction import com.mayabot.nlp.perceptron.PerceptronDefinition import com.mayabot.nlp.perceptron.PerceptronModel import com.mayabot.nlp.perceptron.segmentEvaluateFunction class PerceptronSegmentDefinition : PerceptronDefinition<Char, CharArray> { override fun labels(): Array<String> { return arrayOf("B", "M", "E", "S") } override fun parseAnnotateText(text: String): List<Pair<Char, String>> { return text.splitToSequence("﹍") .flatMap { word -> when (word.length) { 0 -> emptyList() 1 -> listOf(word[0] to "S") 2 -> listOf(word[0] to "B", word[1] to "E") 3 -> listOf(word[0] to "B", word[1] to "M", word[2] to "E") 4 -> listOf(word[0] to "B", word[1] to "M", word[2] to "M", word[3] to "E") 5 -> listOf(word[0] to "B", word[1] to "M", word[2] to "M", word[3] to "M", word[4] to "E") else -> { val list = ArrayList<Pair<Char, String>>(word.length) list += word[0] to "B" for (i in 1 until word.length - 1) { list += word[i] to "M" } list += word[0] to "E" list.toList() } }.asSequence() }.toList() } override fun featureMaxSize() = 4 override fun featureFunction(sentence: CharArray, size: Int, position: Int, buffer: FastStringBuilder, emit: () -> Unit) { val CHAR_NULL = '\u0000' val lastIndex = size - position - 1 val pre2Char = if (position > 1) sentence[position - 2] else CHAR_NULL val preChar = if (position > 0) sentence[position - 1] else CHAR_NULL val curChar = sentence[position] val nextChar = if (lastIndex > 0) sentence[position + 1] else CHAR_NULL val next2Char = if (lastIndex > 1) sentence[position + 2] else CHAR_NULL buffer.clear() buffer.set2(curChar, '2') emit() if (position > 0) { buffer.clear() buffer.set2(preChar, '1') emit() buffer.clear() buffer.set4(preChar, '/', curChar, '5') emit() if (position > 1) { buffer.clear() buffer.set4(pre2Char, '/', preChar, '4') emit() } } if (lastIndex > 0) { buffer.clear() buffer.set2(nextChar, '3') emit() buffer.clear() buffer.set4(curChar, '/', nextChar, '6') emit() if (lastIndex > 1) { buffer.clear() buffer.set4(nextChar, '/', next2Char, '7') emit() } } } override fun inputList2InputSeq(list: List<Char>): CharArray { return list.toCharArray() } override fun evaluateFunction(perceptron: PerceptronModel): EvaluateFunction? { val app = PerceptronSegment(perceptron) return segmentEvaluateFunction({ app.decode(it)},"﹍",true) } override fun preProcessInputSequence(input: CharArray): CharArray { CharNormUtils.convert(input) return input } }
18
null
90
668
b980da3a6f9cdcb83e0800f6cab50656df94a22a
3,597
mynlp
MIT License
compose-mds/src/main/java/ch/sbb/compose_mds/sbbicons/medium/FilterMedium.kt
SchweizerischeBundesbahnen
853,290,161
false
{"Kotlin": 6728512}
package ch.sbb.compose_mds.sbbicons.medium import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import ch.sbb.compose_mds.sbbicons.MediumGroup public val MediumGroup.FilterMedium: ImageVector get() { if (_filterMedium != null) { return _filterMedium!! } _filterMedium = Builder(name = "FilterMedium", defaultWidth = 36.0.dp, defaultHeight = 36.0.dp, viewportWidth = 36.0f, viewportHeight = 36.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(5.663f, 7.75f) horizontalLineToRelative(24.674f) lineToRelative(-0.707f, 0.825f) lineToRelative(-8.88f, 10.36f) lineTo(20.75f, 29.75f) horizontalLineToRelative(-5.5f) lineTo(15.25f, 18.935f) lineTo(6.37f, 8.575f) close() moveTo(7.837f, 8.75f) lineTo(16.13f, 18.424f) lineTo(16.25f, 18.564f) lineTo(16.25f, 28.75f) horizontalLineToRelative(3.5f) lineTo(19.75f, 18.565f) lineToRelative(0.12f, -0.14f) lineToRelative(8.293f, -9.675f) close() } } .build() return _filterMedium!! } private var _filterMedium: ImageVector? = null
0
Kotlin
0
1
090a66a40e1e5a44d4da6209659287a68cae835d
1,981
mds-android-compose
MIT License
samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt
cioro
104,315,482
true
{"Kotlin": 3774628, "Java": 186286, "Groovy": 28824, "Shell": 320, "Batchfile": 106}
package net.corda.notarydemo import net.corda.cordform.CordformContext import net.corda.cordform.CordformDefinition import net.corda.cordform.CordformNode import net.corda.core.identity.CordaX500Name import net.corda.core.internal.div import net.corda.core.internal.stream import net.corda.core.internal.toTypedArray import net.corda.core.utilities.NetworkHostAndPort import net.corda.nodeapi.ServiceInfo import net.corda.node.services.transactions.BFTNonValidatingNotaryService import net.corda.node.services.transactions.minCorrectReplicas import net.corda.node.utilities.ServiceIdentityGenerator import net.corda.testing.ALICE import net.corda.testing.BOB import net.corda.testing.internal.demorun.* fun main(args: Array<String>) = BFTNotaryCordform.runNodes() private val clusterSize = 4 // Minimum size that tolerates a faulty replica. private val notaryNames = createNotaryNames(clusterSize) object BFTNotaryCordform : CordformDefinition("build" / "notary-demo-nodes", notaryNames[0].toString()) { private val clusterName = CordaX500Name(organisation = "BFT", locality = "Zurich", country = "CH") private val advertisedService = ServiceInfo(BFTNonValidatingNotaryService.type, clusterName) init { node { name(ALICE.name) p2pPort(10002) rpcPort(10003) rpcUsers(notaryDemoUser) } node { name(BOB.name) p2pPort(10005) rpcPort(10006) } val clusterAddresses = (0 until clusterSize).stream().mapToObj { NetworkHostAndPort("localhost", 11000 + it * 10) }.toTypedArray() fun notaryNode(replicaId: Int, configure: CordformNode.() -> Unit) = node { name(notaryNames[replicaId]) advertisedServices(advertisedService) notaryClusterAddresses(*clusterAddresses) bftReplicaId(replicaId) configure() } notaryNode(0) { p2pPort(10009) rpcPort(10010) } notaryNode(1) { p2pPort(10013) rpcPort(10014) } notaryNode(2) { p2pPort(10017) rpcPort(10018) } notaryNode(3) { p2pPort(10021) rpcPort(10022) } } override fun setup(context: CordformContext) { ServiceIdentityGenerator.generateToDisk(notaryNames.map(CordaX500Name::toString).map(context::baseDirectory), advertisedService.type.id, clusterName, minCorrectReplicas(clusterSize)) } }
0
Kotlin
0
0
002c6c46876c5ac5c3732e0406bf8edc4b1586f7
2,518
corda
Apache License 2.0
api/src/main/java/com/getcode/model/CurrencyRate.kt
code-payments
723,049,264
false
{"Kotlin": 1160980, "C": 198685, "C++": 83029, "Java": 51811, "CMake": 2594, "JavaScript": 1912, "Ruby": 1714, "Shell": 1706}
package com.getcode.model import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class CurrencyRate( @PrimaryKey val id: String, val rate: Double )
3
Kotlin
6
9
89fdff60a9ae1716d1a65e12b0dc725901422bba
175
code-android-app
MIT License
app/src/test/kotlin/com/mgaetan89/showsrage/adapter/LogsAdapter_GetItemCountTest.kt
id-ks
107,322,013
true
{"Kotlin": 763835, "Shell": 374}
package com.mgaetan89.showsrage.adapter import com.mgaetan89.showsrage.model.LogEntry import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class LogsAdapter_GetItemCountTest(val logs: List<LogEntry>, val itemCount: Int) { private lateinit var adapter: LogsAdapter @Before fun before() { this.adapter = LogsAdapter(this.logs) } @Test fun getItemCount() { assertThat(this.adapter.itemCount).isEqualTo(this.itemCount) } companion object { @JvmStatic @Parameterized.Parameters fun data(): Collection<Array<Any>> { return listOf( arrayOf(emptyList<Any>(), 0), arrayOf(listOf(LogEntry()), 1), arrayOf(listOf(LogEntry(), LogEntry(), LogEntry()), 3) ) } } }
0
Kotlin
0
0
8b32e27b8e468f13b942313a80761569a61f4f05
968
ShowsRage
Apache License 2.0
kask-repo-test/src/commonMain/kotlin/com/nao4j/otus/kask/repo/test/QuestionRepositoryMock.kt
nao4j
634,960,070
false
{"Kotlin": 183328}
package com.nao4j.otus.kask.repo.test import com.nao4j.otus.kask.common.repo.DbQuestionIdRequest import com.nao4j.otus.kask.common.repo.DbQuestionRequest import com.nao4j.otus.kask.common.repo.DbQuestionResponse import com.nao4j.otus.kask.common.repo.QuestionRepository class QuestionRepositoryMock( private val invokeCreateQuestion: (DbQuestionRequest) -> DbQuestionResponse = { DbQuestionResponse.MOCK_SUCCESS_EMPTY }, private val invokeReadQuestion: (DbQuestionIdRequest) -> DbQuestionResponse = { DbQuestionResponse.MOCK_SUCCESS_EMPTY }, private val invokeUpdateQuestion: (DbQuestionRequest) -> DbQuestionResponse = { DbQuestionResponse.MOCK_SUCCESS_EMPTY }, private val invokeDeleteQuestion: (DbQuestionIdRequest) -> DbQuestionResponse = { DbQuestionResponse.MOCK_SUCCESS_EMPTY } ): QuestionRepository { override suspend fun create(request: DbQuestionRequest): DbQuestionResponse = invokeCreateQuestion(request) override suspend fun read(request: DbQuestionIdRequest): DbQuestionResponse = invokeReadQuestion(request) override suspend fun update(request: DbQuestionRequest): DbQuestionResponse = invokeUpdateQuestion(request) override suspend fun delete(request: DbQuestionIdRequest): DbQuestionResponse = invokeDeleteQuestion(request) }
0
Kotlin
0
0
d8e81b1bcf3b0e8badeffd5f35dd67c8645853da
1,313
kotlin-backend-developer-professional-otus
MIT License
src/main/kotlin/io/Vsqx.kt
yukinsnow
302,052,124
true
{"Kotlin": 176568, "CSS": 1679, "JavaScript": 491, "HTML": 445}
package io import exception.IllegalFileException import external.Resources import model.DEFAULT_LYRIC import model.ExportNotification import model.ExportResult import model.Format import model.ImportWarning import model.Note import model.Project import model.Tempo import model.TickCounter import model.TimeSignature import model.Track import org.w3c.dom.Document import org.w3c.dom.Element import org.w3c.dom.XMLDocument import org.w3c.dom.parsing.DOMParser import org.w3c.dom.parsing.XMLSerializer import org.w3c.files.Blob import org.w3c.files.BlobPropertyBag import org.w3c.files.File import util.clone import util.getElementListByTagName import util.getSingleElementByTagName import util.getSingleElementByTagNameOrNull import util.innerValue import util.innerValueOrNull import util.insertAfterThis import util.nameWithoutExtension import util.readText import util.setSingleChildValue import kotlin.dom.clear import kotlin.math.max object Vsqx { suspend fun parse(file: File): Project { val text = file.readText() return when { text.contains("xmlns=\"http://www.yamaha.co.jp/vocaloid/schema/vsq3/\"") -> parse(file, text, TagNames.VSQ3) text.contains("xmlns=\"http://www.yamaha.co.jp/vocaloid/schema/vsq4/\"") -> parse(file, text, TagNames.VSQ4) else -> throw IllegalFileException.UnknownVsqVersion() } } private fun parse(file: File, textRead: String, tagNames: TagNames): Project { val warnings = mutableListOf<ImportWarning>() val projectName = file.nameWithoutExtension val parser = DOMParser() val document = parser.parseFromString(textRead, "text/xml") as XMLDocument val root = document.documentElement ?: throw IllegalFileException.XmlRootNotFound() val masterTrack = root.getSingleElementByTagName(tagNames.masterTrack) val preMeasureNode = masterTrack.getSingleElementByTagName(tagNames.preMeasure) val measurePrefix = try { preMeasureNode.innerValue.toInt() } catch (t: Throwable) { throw IllegalFileException.XmlElementValueIllegal(tagNames.preMeasure) } val (tickPrefix, timeSignatures) = parseTimeSignatures(masterTrack, tagNames, measurePrefix, warnings) val tempos = parseTempos(masterTrack, tagNames, tickPrefix, warnings) val tracks = root.getElementListByTagName(tagNames.vsTrack).mapIndexed { index, element -> parseTrack(element, index, tagNames, tickPrefix) } return Project( format = Format.VSQX, inputFiles = listOf(file), name = projectName, tracks = tracks, timeSignatures = timeSignatures, tempos = tempos, measurePrefix = measurePrefix, importWarnings = warnings ) } private fun parseTimeSignatures( masterTrack: Element, tagNames: TagNames, measurePrefix: Int, warnings: MutableList<ImportWarning> ): Pair<Long, List<TimeSignature>> { val rawTimeSignatures = masterTrack.getElementListByTagName(tagNames.timeSig, allowEmpty = false) .mapNotNull { val posMes = it.getSingleElementByTagNameOrNull(tagNames.posMes)?.innerValueOrNull?.toIntOrNull() ?: return@mapNotNull null val nume = it.getSingleElementByTagNameOrNull(tagNames.nume)?.innerValueOrNull?.toIntOrNull() ?: return@mapNotNull null val denomi = it.getSingleElementByTagNameOrNull(tagNames.denomi)?.innerValueOrNull?.toIntOrNull() ?: return@mapNotNull null TimeSignature( measurePosition = posMes, numerator = nume, denominator = denomi ) } .let { if (it.isEmpty()) { warnings.add(ImportWarning.TimeSignatureNotFound) listOf(TimeSignature.default) } else it } // Calculate before time signatures are cleaned up val tickPrefix = getTickPrefix(rawTimeSignatures, measurePrefix) val timeSignatures = rawTimeSignatures .map { it.copy(measurePosition = it.measurePosition - measurePrefix) } .toMutableList() // Delete all time signatures inside prefix, add apply the last as the first val firstTimeSignatureIndex = timeSignatures .last { it.measurePosition <= 0 } .let { timeSignatures.indexOf(it) } repeat(firstTimeSignatureIndex) { val removed = timeSignatures.removeAt(0) warnings.add(ImportWarning.TimeSignatureIgnoredInPreMeasure(removed)) } timeSignatures[0] = timeSignatures[0].copy(measurePosition = 0) return tickPrefix to timeSignatures.toList() } private fun getTickPrefix(timeSignatures: List<TimeSignature>, measurePrefix: Int): Long { val counter = TickCounter() timeSignatures .filter { it.measurePosition < measurePrefix } .forEach { counter.goToMeasure(it) } counter.goToMeasure(measurePrefix) return counter.tick } private fun parseTempos( masterTrack: Element, tagNames: TagNames, tickPrefix: Long, warnings: MutableList<ImportWarning> ): List<Tempo> { val tempos = masterTrack.getElementListByTagName(tagNames.tempo, allowEmpty = false) .mapNotNull { val posTick = it.getSingleElementByTagNameOrNull(tagNames.posTick)?.innerValueOrNull?.toLongOrNull() ?: return@mapNotNull null val bpm = it.getSingleElementByTagNameOrNull(tagNames.bpm)?.innerValueOrNull?.toDoubleOrNull() ?.let { bpm -> bpm / BPM_RATE } ?: return@mapNotNull null Tempo( tickPosition = posTick - tickPrefix, bpm = bpm ) } .let { if (it.isEmpty()) { warnings.add(ImportWarning.TempoNotFound) listOf(Tempo.default) } else it } .toMutableList() // Delete all tempo tags inside prefix, add apply the last as the first val firstTempoIndex = tempos .last { it.tickPosition <= 0 } .let { tempos.indexOf(it) } repeat(firstTempoIndex) { val removed = tempos.removeAt(0) warnings.add(ImportWarning.TempoIgnoredInPreMeasure(removed)) } tempos[0] = tempos[0].copy(tickPosition = 0) return tempos.toList() } private fun parseTrack(trackNode: Element, id: Int, tagNames: TagNames, tickPrefix: Long): Track { val trackName = trackNode.getSingleElementByTagNameOrNull(tagNames.trackName)?.innerValueOrNull ?: "Track ${id + 1}" val notes = trackNode.getElementListByTagName(tagNames.musicalPart) .flatMap { partNode -> val tickOffset = partNode.getSingleElementByTagName(tagNames.posTick).innerValue.toLong() - tickPrefix partNode.getElementListByTagName(tagNames.note).map { tickOffset to it } } .mapIndexed { index, (tickOffset, noteNode) -> val key = noteNode.getSingleElementByTagName(tagNames.noteNum).innerValue.toInt() val tickOn = noteNode.getSingleElementByTagName(tagNames.posTick).innerValue.toLong() val length = noteNode.getSingleElementByTagName(tagNames.duration).innerValue.toLong() val lyric = noteNode.getSingleElementByTagNameOrNull(tagNames.lyric)?.innerValueOrNull ?: DEFAULT_LYRIC Note( id = index, key = key, tickOn = tickOn + tickOffset, tickOff = tickOn + tickOffset + length, lyric = lyric ) } return Track( id = id, name = trackName, notes = notes ).validateNotes() } fun generate(project: Project): ExportResult { val document = generateContent(project) val serializer = XMLSerializer() val content = serializer.serializeToString(document) val blob = Blob(arrayOf(content), BlobPropertyBag("application/octet-stream")) val name = project.name + Format.VSQX.extension return ExportResult(blob, name, listOf(ExportNotification.PhonemeResetRequiredV4)) } private fun generateContent(project: Project): Document { val text = Resources.vsqxTemplate val tagNames = TagNames.VSQ4 val parser = DOMParser() val document = parser.parseFromString(text, "text/xml") as XMLDocument val root = requireNotNull(document.documentElement) val mixer = root.getSingleElementByTagName(tagNames.mixer) val masterTrack = root.getSingleElementByTagName(tagNames.masterTrack) val measurePrefix = max(project.measurePrefix, MIN_MEASURE_OFFSET) masterTrack.setSingleChildValue(tagNames.preMeasure, measurePrefix) val tickPrefix = project.timeSignatures.first().ticksInMeasure * measurePrefix.toLong() setupTempoNodes(masterTrack, tagNames, project.tempos, tickPrefix) setupTimeSignatureNodes(masterTrack, tagNames, project.timeSignatures, measurePrefix) val emptyTrack = root.getSingleElementByTagName(tagNames.vsTrack) val emptyUnit = mixer.getSingleElementByTagName(tagNames.vsUnit) var track = emptyTrack var unit = emptyUnit for (trackIndex in project.tracks.indices) { val newTrack = generateNewTrackNode(emptyTrack, tagNames, trackIndex, project, tickPrefix, document) track.insertAfterThis(newTrack) track = newTrack val newUnit = emptyUnit.clone() newUnit.setSingleChildValue(tagNames.trackNum, trackIndex) unit.insertAfterThis(newUnit) unit = newUnit } root.removeChild(emptyTrack) mixer.removeChild(emptyUnit) return document } private fun setupTempoNodes( masterTrack: Element, tagNames: TagNames, models: List<Tempo>, tickPrefix: Long ) { val empty = masterTrack.getSingleElementByTagName(tagNames.tempo) var previous = empty previous.setSingleChildValue(tagNames.bpm, (models.first().bpm * BPM_RATE).toInt()) models.drop(1).forEach { val model = if (it.tickPosition == 0L) it else it.copy(tickPosition = it.tickPosition + tickPrefix) val new = empty.clone() new.setSingleChildValue(tagNames.posTick, model.tickPosition) new.setSingleChildValue(tagNames.bpm, (model.bpm * BPM_RATE).toInt()) previous.insertAfterThis(new) previous = new } } private fun setupTimeSignatureNodes( masterTrack: Element, tagNames: TagNames, models: List<TimeSignature>, measurePrefix: Int ) { val empty = masterTrack.getSingleElementByTagName(tagNames.timeSig) var previous = empty previous.setSingleChildValue(tagNames.nume, models.first().numerator) previous.setSingleChildValue(tagNames.denomi, models.first().denominator) models.drop(1).forEach { val model = if (it.measurePosition == 0) it else it.copy(measurePosition = it.measurePosition + measurePrefix) val new = empty.clone() new.setSingleChildValue(tagNames.posMes, model.measurePosition) new.setSingleChildValue(tagNames.nume, model.numerator) new.setSingleChildValue(tagNames.denomi, model.denominator) previous.insertAfterThis(new) previous = new } } private fun generateNewTrackNode( emptyTrack: Element, tagNames: TagNames, trackIndex: Int, project: Project, tickPrefix: Long, document: XMLDocument ): Element { val trackModel = project.tracks[trackIndex] val newTrack = emptyTrack.clone() newTrack.setSingleChildValue(tagNames.trackNum, trackIndex) newTrack.setSingleChildValue(tagNames.trackName, trackModel.name) val part = newTrack.getSingleElementByTagName(tagNames.musicalPart) part.setSingleChildValue(tagNames.posTick, tickPrefix) part.setSingleChildValue(tagNames.playTime, trackModel.notes.lastOrNull()?.tickOff ?: 0) val emptyNote = part.getSingleElementByTagName(tagNames.note) var note = emptyNote trackModel.notes .map { model -> generateNewNote(emptyNote, tagNames, model, document) } .forEach { newNote -> note.insertAfterThis(newNote) note = newNote } part.removeChild(emptyNote) if (trackModel.notes.isEmpty()) { newTrack.removeChild(part) } return newTrack } private fun generateNewNote( emptyNote: Element, tagNames: TagNames, model: Note, document: XMLDocument ): Element { val newNote = emptyNote.clone() newNote.setSingleChildValue(tagNames.posTick, model.tickOn) newNote.setSingleChildValue(tagNames.duration, model.length) newNote.setSingleChildValue(tagNames.noteNum, model.key) newNote.getSingleElementByTagName(tagNames.lyric).also { it.clear() val lyricCData = document.createCDATASection(model.lyric) it.appendChild(lyricCData) } return newNote } private const val BPM_RATE = 100.0 private const val MIN_MEASURE_OFFSET = 1 private enum class TagNames( val masterTrack: String = "masterTrack", val preMeasure: String = "preMeasure", val timeSig: String = "timeSig", val posMes: String = "posMes", val nume: String = "nume", val denomi: String = "denomi", val tempo: String = "tempo", val posTick: String = "posTick", val bpm: String = "bpm", val vsTrack: String = "vsTrack", val trackName: String = "trackName", val musicalPart: String = "musicalPart", val note: String = "note", val duration: String = "durTick", val noteNum: String = "noteNum", val lyric: String = "lyric", val mixer: String = "mixer", val vsUnit: String = "vsUnit", val trackNum: String = "vsTrackNo", val playTime: String = "playTime" ) { VSQ3, VSQ4( posMes = "m", nume = "nu", denomi = "de", posTick = "t", bpm = "v", trackName = "name", musicalPart = "vsPart", duration = "dur", noteNum = "n", lyric = "y", trackNum = "tNo" ) } }
0
Kotlin
0
1
439073496530b5326ae860f96886a4c337cc1622
15,248
utaformatix3
Apache License 2.0
sample-android/src/main/java/tv/abema/fragfit/FlagfitSampleComponent.kt
abema
312,185,075
false
null
package tv.abema.fragfit import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.material3.Text import androidx.compose.runtime.Composable @Composable fun FragfitSampleComponent(sampleFlagService: SampleFlagService) { val awesomeWipFeatureEnabled = sampleFlagService.awesomeWipFeatureEnabled() val awesomeExperimentFeatureEnabled = sampleFlagService.awesomeExperimentFeatureEnabled() val awesomeOpsFeatureEnabled = sampleFlagService.awesomeOpsFeatureEnabled() val awesomePermissionFutureEnabled = sampleFlagService.awesomePermissionFeatureEnabled() val awesomeDebugFutureEnabled = sampleFlagService.awesomeDebugFeatureEnabled() val wipText = if (awesomeWipFeatureEnabled) "New Function" else "Previous function" val experimentText = if (awesomeExperimentFeatureEnabled) "New Function" else "Previous function" val opsText = if (awesomeOpsFeatureEnabled) "New Function" else "Previous function" val permissionText = if (awesomePermissionFutureEnabled) "New Function" else "Previous function" val debugText = if (awesomeDebugFutureEnabled) "New Function" else "Previous function" Column( verticalArrangement = Arrangement.Center ) { Text(text = "Work in progress: $wipText") Text(text = "Experiment: $experimentText") Text(text = "Ops: $opsText") Text(text = "Permission: $permissionText") Text(text = "Debug: $debugText") } }
5
Kotlin
2
93
a956d4e2be81bbae9e45121c3ee5bab31d5bab55
1,451
flagfit
Apache License 2.0
app/src/main/java/com/example/meals/data/repository/RemoteMainRepository.kt
Amrjyniat
554,786,277
false
null
package com.example.meals.data.repository import com.example.meals.data.network.modules.responses.MealResp.Companion.toMeal import com.example.meals.data.network.modules.responses.MealResp.Companion.toMeals import com.example.meals.data.network.ApiError import com.example.meals.data.network.ApiLoading import com.example.meals.data.network.ApiSuccess import com.example.meals.data.network.MealsService import com.example.meals.utils.loadingResultFlow import javax.inject.Inject import javax.inject.Singleton @Singleton class RemoteMainRepository @Inject constructor( private val service: MealsService ) : MainRepository { override fun loadMeals() = loadingResultFlow { when (val realResult = service.getMeals()) { is ApiSuccess -> ApiSuccess(realResult.data.listMealResp.toMeals()) is ApiError -> ApiError(realResult.code, realResult.message.orEmpty()) else -> ApiLoading() } } override fun loadMealDetails(mealName: String) = loadingResultFlow { when (val realResult = service.getMealDetails(mealName)) { is ApiSuccess -> ApiSuccess(realResult.data.listMealResp.first().toMeal()) is ApiError -> ApiError(realResult.code, realResult.message.orEmpty()) else -> ApiLoading() } } }
0
Kotlin
0
4
a3600dc99cf87647dd2e50cf4cee759c850a2b91
1,308
Meals
Apache License 2.0
app/src/main/java/com/mynasmah/mykamus/data/model/Kamus.kt
anas-abdrahman
457,363,344
false
{"Java": 144379, "Kotlin": 107907}
package com.mynasmah.mykamus.data.model /** * Created by NASMAH on 8/24/2017. */ class Kamus { var id : Int = 0 var arab_0 : String? = null var arab_1 : String? = null var arab_2 : String? = null var melayu : String? = null var english : String? = null override fun hashCode(): Int { val prime = 31 val result = 1 return prime * result + id } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false if (javaClass != other.javaClass) return false val check = other as Kamus? return id == check!!.id } override fun toString(): String { return "Kamus [id=$id, arab_1=$arab_1, arab_2=$arab_2, melayu=$melayu, english=$english]" } }
0
Java
0
0
a0f5b56d52bb41b9e3847172b5528e7555ad9159
893
mykamus
MIT License
src/jvmTest/kotlin/mu/KotlinLoggingTest.kt
MicroUtils
62,350,009
false
null
package mu import org.junit.Assert.assertEquals import org.junit.Test import org.slf4j.LoggerFactory private val logger = KotlinLogging.logger { } private val loggerFromSlf4j = KotlinLogging.logger(LoggerFactory.getLogger("mu.slf4jLogger")) private val loggerFromSlf4jExtension = LoggerFactory.getLogger("mu.slf4jLoggerExtension").toKLogger() class ForKotlinLoggingTest { val loggerInClass = KotlinLogging.logger { } companion object { val loggerInCompanion = KotlinLogging.logger { } } } class KotlinLoggingTest { @Test fun testLoggerName() { assertEquals("mu.KotlinLoggingTest", logger.name) assertEquals("mu.ForKotlinLoggingTest", ForKotlinLoggingTest().loggerInClass.name) assertEquals("mu.ForKotlinLoggingTest", ForKotlinLoggingTest.loggerInCompanion.name) assertEquals("mu.slf4jLogger", loggerFromSlf4j.name) assertEquals("mu.slf4jLoggerExtension", loggerFromSlf4jExtension.name) } }
17
Kotlin
76
1,648
07c705c8ac4f4e918829b4d126616b486e82f7fa
968
kotlin-logging
Apache License 2.0
android/src/main/java/tk/zwander/android/AndrolibAndroid.kt
zacharee
321,827,284
false
null
package tk.zwander.android import android.content.Context import brut.androlib.Androlib import brut.androlib.ApkOptions class AndrolibAndroid : Androlib { private val context: Context constructor(context: Context) : super(AndrolibResourcesAndroid(context)) { this.context = context } constructor(context: Context, options: ApkOptions) : super(options, AndrolibResourcesAndroid(context)) { this.context = context } }
0
null
0
9
d1a3e349be2e55be9e6bad8e5972713533ec2df5
455
Apktool
Apache License 2.0
Careium/app/src/main/java/com/example/careium/core/database/authentication/Auth.kt
KAN-Team
461,661,370
false
null
package com.example.careium.core.database.authentication import com.google.firebase.auth.FirebaseAuth abstract class Auth : Thread() { protected var authInstance: FirebaseAuth = FirebaseAuth.getInstance() protected lateinit var authViewModel: AuthViewModel abstract override fun run() }
14
Jupyter Notebook
3
13
e1a7aa43c85bff78d0ee1e64bb2ad94d94208f27
302
Careium-AI
Apache License 2.0
src/main/kotlin/br/com/zup/lucasmiguins/pix/consulta/Filtro.kt
miguins
385,259,217
true
{"Kotlin": 84040, "Smarty": 2172, "Dockerfile": 171}
package br.com.zup.lucasmiguins.pix.consulta import br.com.zup.lucasmiguins.integration.bcb.BancoCentralClient import br.com.zup.lucasmiguins.pix.ChavePixRepository import br.com.zup.lucasmiguins.pix.exceptions.ChavePixClienteNaoEncontradaException import br.com.zup.lucasmiguins.shared.validation.ValidUUID import io.micronaut.core.annotation.Introspected import io.micronaut.http.HttpStatus import java.util.* import javax.validation.constraints.NotBlank import javax.validation.constraints.Size @Introspected sealed class Filtro { abstract fun filtra(repository: ChavePixRepository, bcbClient: BancoCentralClient): ChavePixInfo @Introspected data class PorPixId( @field:NotBlank @field:ValidUUID val clienteId: String, @field:NotBlank @field:ValidUUID val pixId: String, ) : Filtro() { fun pixIdAsUuid() = UUID.fromString(pixId) fun clienteIdAsUuid() = UUID.fromString(clienteId) override fun filtra(repository: ChavePixRepository, bcbClient: BancoCentralClient): ChavePixInfo { return repository.findById(pixIdAsUuid()) .filter { it.pertenceAo(clienteIdAsUuid()) } .map(ChavePixInfo::of) .orElseThrow { ChavePixClienteNaoEncontradaException("Chave Pix não encontrada") } } } @Introspected data class PorChave(@field:NotBlank @Size(max = 77) val chave: String) : Filtro() { override fun filtra(repository: ChavePixRepository, bcbClient: BancoCentralClient): ChavePixInfo { return repository.findByChave(chave) .map(ChavePixInfo::of) .orElseGet { val response = bcbClient.consultaPorChave(chave) when (response.status) { HttpStatus.OK -> response.body()?.toModel() else -> throw ChavePixClienteNaoEncontradaException("Chave Pix não encontrada") } } } } @Introspected class Invalido() : Filtro() { override fun filtra(repository: ChavePixRepository, bcbClient: BancoCentralClient): ChavePixInfo { throw IllegalArgumentException("Chave Pix inválida ou não informada") } } }
0
Kotlin
0
0
40b9662f4983c779a2cc88a4914e6f7e9eb1287c
2,247
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
domain/src/main/java/com/dsm/dms/domain/repository/NoticeRepository.kt
DSM-DMS
203,186,000
false
null
package com.dsm.dms.domain.repository import com.dsm.dms.domain.entity.Notice import com.dsm.dms.domain.entity.Point import io.reactivex.Single interface NoticeRepository { fun getRemoteNotice(): Single<List<Notice>> fun getLocalNotice(): List<Notice>? fun saveLocalNotice(vararg notice: Notice) fun deleteLocalNotice(id: Int) }
0
Kotlin
2
14
ae7de227cee270d22a72a4f59090bff07c43f019
353
DMS-Android-V4
MIT License
app/src/main/java/com/kiwilss/lxkj/mvpretrofit/ui/home/HomeFg.kt
KiWiLss
195,376,668
false
null
/** * Copyright (C), 2017-2019, XXX有限公司 * FileName: HomeFg * Author: kiwilss * Date: 2019-06-24 17:41 * Description: {DESCRIPTION} * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ package com.kiwilss.lxkj.mvpretrofit.ui.home import android.arch.lifecycle.Observer import android.support.v4.content.ContextCompat import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.LinearLayoutManager import android.view.View import android.view.ViewGroup import com.alibaba.fastjson.JSON import com.blankj.utilcode.util.LogUtils import com.chad.library.adapter.base.BaseQuickAdapter import com.kiwilss.lxkj.mvpretrofit.R import com.kiwilss.lxkj.mvpretrofit.base.PagerLazyFragment import com.kiwilss.lxkj.mvpretrofit.config.* import com.kiwilss.lxkj.mvpretrofit.ui.login.LoginActivity import com.kiwilss.lxkj.mvpretrofit.ui.webview.WebViewActivity import com.kiwilss.lxkj.mvpretrofit.utils.GlideImageLoader import com.kiwilss.lxkj.mvpretrofit.utils.toastS import com.kiwilss.lxkj.mylibrary.bus.LiveDataBus import com.kiwilss.lxkj.mylibrary.core.dp2px import com.kiwilss.lxkj.mylibrary.core.sp import com.kiwilss.lxkj.mylibrary.core.startActivity import com.youth.banner.Banner import com.youth.banner.BannerConfig import kotlinx.android.synthetic.main.fragment_home.* /** *@FileName: HomeFg *@author : <NAME> * @e-mail : <EMAIL> * @time : 2019-06-24 * @desc : {DESCRIPTION} */ class HomeFg: PagerLazyFragment<HomePresenter>() ,BaseQuickAdapter.RequestLoadMoreListener,SwipeRefreshLayout.OnRefreshListener{ override fun getErrorKey(): String { return KEY_HOME_FG_ERROR } /** * 刷新监听 */ override fun onRefresh() { //上拉限制 mAdapter.setEnableLoadMore(false) mCurrentPage = 0 mPresenter.getHomeArticles(mCurrentPage) } private var isLogin = false /** * 加载更多监听 */ override fun onLoadMoreRequested() { if (mCurrentPage < mPageCount){ srl_fg_home_refresh.isEnabled = false mCurrentPage ++ //initData()//不想显示对话框,可以直接调用获取数据方法 mPresenter.getHomeArticles(mCurrentPage) }else{ mAdapter.loadMoreEnd() } } private var mCurrentPage = 0 //private val banner by lazy { com.youth.banner.Banner(activity) } private val mTitleList = mutableListOf<String>() private val mUrlList = mutableListOf<String>() private val mImaglList = mutableListOf<String>() private val mAdapter by lazy { HomeFgAdapter() } override fun initPresenter(): HomePresenter = HomePresenter() override fun getLayoutId(): Int = R.layout.fragment_home override fun initData() { showLoadingDiloag() mPresenter.getHomeArticles(mCurrentPage) //获取轮播图 mPresenter.getHomeFgBanner() } override fun initInterface() { initAdapter() //获取请求的数据 getAricleData() //刷新设置 //刷新图标设置 srl_fg_home_refresh.setColorSchemeColors(ContextCompat.getColor(context!!, R.color.colorPrimary)) //刷新监听 srl_fg_home_refresh.setOnRefreshListener(this) //监听是否刷新界面 isRefreshInterface() //收藏结果 getAddCollectResult() //监听是否滚动到顶部 isScrollToTop() } private fun isScrollToTop() { LiveDataBus.with<Boolean>(KEY_HOME_TOP + "0").observe(this, Observer { it?.run { if (this){ scrollToTop() } } }) } /** * 滚到顶 */ private fun scrollToTop(){ rv_fg_home_list?.run { val layoutManager: LinearLayoutManager = this.layoutManager as LinearLayoutManager if (layoutManager.findFirstVisibleItemPosition() > 20){ scrollToPosition(0)//直接滚动到顶 }else{ smoothScrollToPosition(0)//模拟滚动到顶 } } } private fun getAddCollectResult() { //加入收藏结果 LiveDataBus.with<Any>(KEY_HOME_FG_COLLECT).observe(this, Observer { LogUtils.e(JSON.toJSONString(it)) dismissLoadingDiloag() LogUtils.e("cancel--$mAddPosition") // toast("已加入收藏") toastS("已加入收藏") //处理界面 val itemBean = mAdapter.data[mAddPosition] itemBean.collect = true mAdapter.setData(mAddPosition,itemBean) }) //取消收藏结果 LiveDataBus.with<Any>(KEY_HOME_FG_CANCEL).observe(this, Observer { dismissLoadingDiloag() LogUtils.e("cancel--$mCancelPosition") //toast("已取消收藏") toastS("已取消收藏") //处理界面 val itemBean = mAdapter.data[mCancelPosition] itemBean.collect = false mAdapter.setData(mCancelPosition,itemBean) //mAdapter.notifyItemRangeChanged(mCancelPosition,1) }) } private fun isRefreshInterface() { LiveDataBus.with<Boolean>(KEY_HOME_IS_REFRESH).observe(this, Observer { if (it!!){//刷新界面 onRefresh() } }) } var mPageCount = 0 private fun getAricleData() { LiveDataBus.with<HomeBean>(KEY_HOME_ARTICLE).observe(this, Observer { dismissLoadingDiloag() it?.run { mPageCount = pageCount LogUtils.e("mpage=$mPageCount+pagecount=$pageCount") if (mCurrentPage == 0){ mAdapter.replaceData(datas) }else{ mAdapter.addData(datas) } } mAdapter.loadMoreComplete() srl_fg_home_refresh.isRefreshing = false mAdapter.setEnableLoadMore(true) srl_fg_home_refresh.isEnabled = true }) //获取轮播图数据 LiveDataBus.with<List<HomeBanner>>(KEY_HOME_BANNER).observe(this, Observer { it?.run { forEach { mTitleList.add(it.title) mImaglList.add(it.imagePath) mUrlList.add(it.url) } banner!!.setImageLoader(GlideImageLoader()) .setImages(mImaglList) .setBannerTitles(mTitleList) .setIndicatorGravity(BannerConfig.RIGHT) .setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE) .setDelayTime(3000).setOnBannerListener { //点击进入网页 startActivity<WebViewActivity>(bundle = arrayOf( "url" to mUrlList[it], "title" to mTitleList[it], "id" to this[it].id )) } banner!!.start() } }) } var banner: Banner? = null var mAddPosition = 0 var mCancelPosition = 0 private fun initAdapter() { rv_fg_home_list.run { layoutManager = LinearLayoutManager(context) adapter = mAdapter } //设置预加载 mAdapter.setPreLoadNumber(5) //加头 //mAdapter.addHeaderView(banner) val headerView = layoutInflater.inflate(R.layout.header_fg_home, null) banner = headerView.findViewById<View>(R.id.banner_header_fg_home_banner) as Banner mAdapter.addHeaderView(headerView) mAdapter.setOnLoadMoreListener(this,rv_fg_home_list) //点击事件 mAdapter.setOnItemClickListener { adapter, view, position -> //点击进入网页 startActivity<WebViewActivity>(bundle = arrayOf( "url" to mAdapter.data[position].link, "title" to mAdapter.data[position].title, "id" to mAdapter.data[position].id )) } //收藏监听 mAdapter.setOnItemChildClickListener { adapter, view, position -> //判断是否登录 LogUtils.e("$isLogin---") isLogin = context!!.sp().getBoolean(Constant.SP_IS_LOGIN,false) if (isLogin){ //调用收藏,判断是否已经收藏 val homeData = mAdapter.data[position] val id = homeData.id showLoadingDiloag(LOADING_HINT) if (homeData.collect) {//已经收藏 //调用取消收藏 mCancelPosition = position mPresenter.cancelCollect(id) }else{//没有收藏 mAddPosition = position mPresenter.collectArticle(id) } }else{ startActivity<LoginActivity>() } } } private fun initBanner() { banner?.run { layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, banner!!.dp2px(200f)) setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE) setImageLoader(GlideImageLoader()) //banner 点击 setOnBannerListener { position -> run { // val intent = Intent(activity, BrowserNormalActivity::class.java) // intent.putExtra(BrowserNormalActivity.URL, bannerUrls[position]) // startActivity(intent) } } } } override fun onStart() { super.onStart() banner?.run { startAutoPlay() } } override fun onStop() { super.onStop() banner?.run { stopAutoPlay() } } }
0
Kotlin
0
4
3a956c81a31f9ae8b18bd6540596301d581a89ae
9,646
WanAndroid
Apache License 2.0
src/Day04.kt
joshpierce
573,265,121
false
{"Kotlin": 46425}
import java.io.File fun main() { // read the lines from the file var lines: List<String> = File("Day04.txt").readLines() // read out our section pairs into arrays var sectionPairs: List<MutableList<List<Int>>> = lines.map outer@ { var sectionPair: MutableList<List<Int>> = it.split(",").map inner@ { var section: List<Int> = (it.split("-")[0].toInt()..it.split("-")[1].toInt()).toList() return@inner section }.toMutableList() sectionPair.sortByDescending { it.size } return@outer sectionPair } var fullyEncapsulated = sectionPairs.filter { return@filter it[0][0] <= it[1][0] && it[0][it[0].size - 1] >= it[1][it[1].size - 1] } println("The number of fully encapsulated sections is: " + fullyEncapsulated.size.toString()) var overlapping = sectionPairs.filter { return@filter it[0].intersect(it[1]).count() > 0 } println("The number of overlapping sections is: " + overlapping.size.toString()) }
0
Kotlin
0
1
fd5414c3ab919913ed0cd961348c8644db0330f4
1,035
advent-of-code-22
Apache License 2.0
common/build/generated/sources/schemaCode/kotlin/main/io/portone/sdk/server/schemas/IssueCashReceiptCustomerInput.kt
portone-io
809,427,199
false
{"Kotlin": 385115, "Java": 331}
package io.portone.sdk.server.schemas import kotlin.String import kotlinx.serialization.Serializable /** * 현금영수증 발급 시 고객 관련 입력 정보 */ @Serializable public data class IssueCashReceiptCustomerInput( /** * 고객 식별값 */ public val identityNumber: String, /** * 이름 */ public val name: String? = null, /** * 이메일 */ public val email: String? = null, /** * 전화번호 */ public val phoneNumber: String? = null, )
0
Kotlin
0
2
506e194123552bb5be7939fb72ee8c0a625c04e6
439
server-sdk-jvm
MIT License
module/module-tpa/src/main/kotlin/ink/work/taboopublicwork/module/tpa/command/TpDenyCommand.kt
FxRayHughes
723,338,144
false
{"Kotlin": 115771}
package ink.work.taboopublicwork.module.tpa.command import ink.work.taboopublicwork.api.ICommand import ink.work.taboopublicwork.module.tpa.ModuleTpa import ink.work.taboopublicwork.module.tpa.ModuleTpa.sendLang import ink.work.taboopublicwork.module.tpa.TpaPlayerData import ink.work.taboopublicwork.module.tpa.TpaPlayerData.isTimeout import ink.work.taboopublicwork.utils.evalKether import org.bukkit.Bukkit import org.bukkit.entity.Player import taboolib.common.LifeCycle import taboolib.common.platform.Awake import taboolib.common.platform.command.CommandBody import taboolib.common.platform.command.CommandHeader import taboolib.common.platform.command.mainCommand @CommandHeader("tpdeny", aliases = ["tpno"], description = "传送", permission = "taboopublicwork.command.tpa") object TpDenyCommand : ICommand { override val command: String = "tpdeny" @Awake(LifeCycle.LOAD) fun init() { register(ModuleTpa) } @CommandBody val main = mainCommand { execute<Player> { sender, _, _ -> val playerName = TpaPlayerData.getAsked.computeIfAbsent(sender) { arrayListOf() }.lastOrNull { Bukkit.getPlayerExact(it)?.isTimeout(sender.name) == false } ?: return@execute sender.sendLang("module-tpa-ask-timeout-any") sender.denyTp(playerName) } dynamic("player") { suggestion<Player>(uncheck = true) { sender, _ -> TpaPlayerData.getAsked.computeIfAbsent(sender) { arrayListOf() }.filter { Bukkit.getPlayerExact(it)?.isTimeout(sender.name) == false } } execute<Player> { sender, context, _ -> val playerName = context["player"] val sentPlayer = Bukkit.getPlayerExact(playerName) ?: return@execute sender.sendLang("module-tpa-target-not-online", playerName) if (sentPlayer.isTimeout(sender.name)) { sender.sendLang("module-tpa-ask-timeout", playerName) return@execute } sender.denyTp(playerName) } } } private fun Player.denyTp(player: String) { val sentPlayer = Bukkit.getPlayerExact(player)!! this.sendLang("module-tpa-deny-target", player) sentPlayer.sendLang("module-tpa-deny-player", this.name) ModuleTpa.config.getString("actions.deny.self", "")!!.evalKether(this, mapOf("target" to sentPlayer.name)).thenRun { ModuleTpa.config.getString("actions.deny.sent", "")!!.evalKether(sentPlayer, mapOf("target" to this.name)) } TpaPlayerData.askTimeout[sentPlayer]!!.timeout.remove(this.name) TpaPlayerData.getAsked[this]!!.remove(player) } }
0
Kotlin
3
6
8a87ef1d2818ffbc24a7dc73bfa7b95358be0695
2,772
TabooPublicWork
Creative Commons Zero v1.0 Universal
compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/ExtraTypeCheckers.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.analysis.checkers import org.jetbrains.kotlin.fir.analysis.checkers.extended.PlatformClassMappedToKotlinTypeRefChecker import org.jetbrains.kotlin.fir.analysis.checkers.extended.RedundantNullableChecker import org.jetbrains.kotlin.fir.analysis.checkers.type.* object ExtendedTypeCheckers : TypeCheckers() { override val typeRefCheckers: Set<FirTypeRefChecker> = setOf( RedundantNullableChecker, PlatformClassMappedToKotlinTypeRefChecker ) }
184
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
709
kotlin
Apache License 2.0
lib/src/main/kotlin/com/lemonappdev/konsist/core/provider/KoParentProviderCore.kt
LemonAppDev
621,181,534
false
null
package com.lemonappdev.konsist.core.provider import com.lemonappdev.konsist.api.declaration.KoParentDeclaration import com.lemonappdev.konsist.api.provider.KoParentProvider internal interface KoParentProviderCore : KoParentProvider, KoParentClassProviderCore, KoParentInterfaceProviderCore, KoBaseProviderCore { override val parents: List<KoParentDeclaration> get() = listOfNotNull(parentClass as? KoParentDeclaration) + parentInterfaces override val numParents: Int get() = parents.size override fun hasParents(vararg names: String): Boolean = when { names.isEmpty() -> hasParentClass() || hasParentInterfaces() else -> names.all { hasParentClass(it) || hasParentInterfaces(it) } } }
4
Kotlin
1
71
c3cf91622bab1938fecbc96c119cbbb70e372451
754
konsist
Apache License 2.0
url-gen/src/main/kotlin/com/cloudinary/transformation/Shadow.kt
baraka-gini
266,517,520
true
{"Kotlin": 589400, "Java": 7089}
package com.cloudinary.transformation import com.cloudinary.transformation.effect.innerEffectAction import com.cloudinary.util.cldRanged class Shadow(private val action: Action) : Action by action { class Builder : TransformationComponentBuilder { private var strength: Any? = null private var color: Color? = null private var x: Any? = null private var y: Any? = null fun strength(strength: Any) = apply { this.strength = strength } fun strength(strength: Int) = apply { this.strength = strength } fun color(color: Color?) = apply { this.color = color } fun x(x: Any) = apply { this.x = x } fun y(y: Any) = apply { this.y = y } fun x(x: Int) = apply { this.x = x } fun y(y: Int) = apply { this.y = y } override fun build(): Shadow { val values = listOfNotNull(strength?.cldRanged(0, 100)) val params = listOfNotNull(color?.cldAsColor(), x?.cldAsX(), y?.cldAsY()) return Shadow(innerEffectAction("shadow", *((values + params).toTypedArray()))) } } }
0
Kotlin
0
0
4eedf1de1b7d784dff7232aa108f6a363364f205
1,104
cloudinary_kotlin
MIT License
src/main/kotlin/com/cognifide/gradle/aem/pkg/deploy/PackageBuildResponse.kt
balim
159,712,475
true
{"Kotlin": 276673, "Shell": 5207, "Java": 1813, "Batchfile": 233}
package com.cognifide.gradle.aem.pkg.deploy import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.databind.ObjectMapper @JsonIgnoreProperties(ignoreUnknown = true) class PackageBuildResponse private constructor() { var isSuccess: Boolean = false lateinit var msg: String lateinit var path: String companion object { fun fromJson(json: String): PackageBuildResponse { return ObjectMapper().readValue(json, PackageBuildResponse::class.java) } } }
0
Kotlin
0
0
598abf349278473441a8965be31e4d68ccbeebc5
537
gradle-aem-plugin
Apache License 2.0
app/src/main/java/io/github/rsookram/rss/data/RssService.kt
rsookram
420,735,022
false
{"Kotlin": 39051, "Shell": 66}
package io.github.rsookram.rss.data import io.github.rsookram.rss.data.parser.RssFeed import retrofit2.http.GET import retrofit2.http.Url /** * Retrofit interface to fetch a single RSS feed. */ interface RssService { @GET suspend fun feed(@Url url: String): RssFeed }
0
Kotlin
0
0
5cd0b1ae65f92acfb388fa84a92778cc8c7c92c4
277
rss
Apache License 2.0
src/main/kotlin/no/nav/klage/clients/KlageDittnavPdfgenClient.kt
navikt
253,461,869
false
{"Kotlin": 203257, "Dockerfile": 134}
package no.nav.klage.clients import no.nav.klage.domain.PDFInput import no.nav.klage.util.getLogger import org.springframework.http.MediaType import org.springframework.stereotype.Component import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.bodyToMono @Component class KlageDittnavPdfgenClient( private val klageDittnavPdfgenWebClient: WebClient, ) { companion object { @Suppress("JAVA_CLASS_ON_COMPANION") private val logger = getLogger(javaClass.enclosingClass) } fun getKlageAnkePDF(input: PDFInput): ByteArray { logger.debug("Creating PDF for ${input.type}.") return klageDittnavPdfgenWebClient.post() .uri { it.path("/klageanke").build() } .contentType(MediaType.APPLICATION_JSON) .bodyValue(input) .retrieve() .bodyToMono<ByteArray>() .block() ?: throw RuntimeException("PDF could not be generated") } fun getEttersendelsePDF(input: PDFInput): ByteArray { logger.debug("Creating PDF for ettersendelse for ${input.type}") return klageDittnavPdfgenWebClient.post() .uri { it.path("/ettersendelse").build() } .contentType(MediaType.APPLICATION_JSON) .bodyValue(input) .retrieve() .bodyToMono<ByteArray>() .block() ?: throw RuntimeException("PDF could not be generated") } }
2
Kotlin
1
0
49a424aa08e4df4b3cc978f89d349c3c24783651
1,472
klage-dittnav-api
MIT License
app/src/main/java/com/da_chelimo/ig_clone/utils/LoginUtils.kt
DaChelimo
770,580,458
false
{"Kotlin": 134079}
package com.da_chelimo.ig_clone.utils import androidx.core.text.isDigitsOnly fun verifyEmailIsValid(email: String): Boolean = email.isNotBlank() && email.endsWith("@gmail.com") fun verifyPassword(password: String) = password.length >= 6 && !password.isDigitsOnly() // && password.contains(Regex("a-z")) fun verifyNumberIsValid(number: String): Boolean = number.isDigitsOnly() && number.length == 10 fun verifyCodeLength(code: String) = code.length == 6 fun validateUserName(userName: String) = if (userName.isBlank() || userName.isEmpty()) "Enter a valid username" else if (userName.isInDataBase()) "Username $userName is already taken" else null private fun String.isInDataBase(): Boolean { return false }
0
Kotlin
0
0
01c429657c8cc404f7a3d112fdd69fdaa49f4af6
753
Instagram-Clone
MIT License
app/src/main/java/com/example/novelfever/core/sourceutils/WebViewInterceptor.kt
yukinpb
822,620,915
false
{"Kotlin": 107244}
package com.example.novelfever.core.sourceutils import android.annotation.SuppressLint import android.content.Context import android.webkit.WebSettings import android.webkit.WebView import okhttp3.Headers import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit abstract class WebViewInterceptor(private val context: Context) : Interceptor { private val initWebView by lazy { try { WebSettings.getDefaultUserAgent(context) } catch (_: Exception) { } } abstract fun shouldIntercept(response: Response): Boolean abstract fun intercept(chain: Interceptor.Chain, request: Request, response: Response): Response override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val response = chain.proceed(request) if (!shouldIntercept(response)) { return response } initWebView return intercept(chain, request, response) } fun parseHeaders(headers: Headers): Map<String, String> { return headers .filter { (name, value) -> isRequestHeaderSafe(name, value) } .groupBy(keySelector = { (name, _) -> name }) { (_, value) -> value } .mapValues { it.value.getOrNull(0).orEmpty() } } fun CountDownLatch.awaitFor30Seconds() { await(30, TimeUnit.SECONDS) } @SuppressLint("SetJavaScriptEnabled") fun createWebView(request: Request): WebView { return WebView(context).apply { with(settings) { javaScriptEnabled = true domStorageEnabled = true databaseEnabled = true useWideViewPort = true loadWithOverviewMode = true cacheMode = WebSettings.LOAD_DEFAULT } settings.userAgentString = request.header("User-Agent") } } } private fun isRequestHeaderSafe(_name: String, _value: String): Boolean { val name = _name.lowercase(Locale.ENGLISH) val value = _value.lowercase(Locale.ENGLISH) if (name in unsafeHeaderNames || name.startsWith("proxy-")) return false if (name == "connection" && value == "upgrade") return false return true } private val unsafeHeaderNames = listOf( "content-length", "host", "trailer", "te", "upgrade", "cookie2", "keep-alive", "transfer-encoding", "set-cookie" )
0
Kotlin
0
0
84051536ab24025799b04a02207fe53bbaab9686
2,552
NovelFever
MIT License
app/src/main/java/com/mindinventory/hiltarchitecturesample/ui/adapter/UsersAdapter.kt
Mindinventory
302,571,107
false
null
package com.mindinventory.hiltarchitecturesample.ui.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import coil.load import coil.transform.CircleCropTransformation import com.mindinventory.hiltarchitecturesample.R import com.mindinventory.hiltarchitecturesample.data.entity.User import kotlinx.android.synthetic.main.row_user.view.* class UsersAdapter : RecyclerView.Adapter<UsersAdapter.ViewHolder>() { private val users = ArrayList<User>() fun updateItems(users : ArrayList<User>?, isClearAll:Boolean = true) { users?.let { if (isClearAll) { this.users.clear() } this.users.addAll(it) notifyDataSetChanged() } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.row_user, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { users[position].let { holder.itemView.tvUser.text = it.name?.getFullName() holder.itemView.tvEmail.text = it.email holder.itemView.ivUser.load(it.picture?.thumbnail) { crossfade(true) placeholder(R.drawable.ic_user) transformations(CircleCropTransformation()) } } } override fun getItemCount(): Int { return users.size } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) }
0
Kotlin
1
9
0e88dcecbd28fb7c4559f5974eec97013d8fcff5
1,649
Hilt-Architecture-Sample
MIT License
MultiModuleApp2/module1/src/main/java/com/github/yamamotoj/module1/package03/Foo00391.kt
yamamotoj
163,851,411
false
{"Text": 1, "Ignore List": 30, "Markdown": 1, "Gradle": 34, "Java Properties": 11, "Shell": 6, "Batchfile": 6, "Proguard": 22, "Kotlin": 36021, "XML": 93, "INI": 1, "Java": 32, "Python": 2}
package com.github.yamamotoj.module1.package03 class Foo00391 { fun method0() { Foo00390().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
0
Kotlin
0
9
2a771697dfebca9201f6df5ef8441578b5102641
347
android_multi_module_experiment
Apache License 2.0
felles/src/main/kotlin/no/nav/helsearbeidsgiver/felles/Arbeidsforhold.kt
navikt
495,713,363
false
{"Kotlin": 1215265, "PLpgSQL": 153, "Dockerfile": 68}
@file:UseSerializers(LocalDateSerializer::class, LocalDateTimeSerializer::class) package no.nav.helsearbeidsgiver.felles import kotlinx.serialization.Serializable import kotlinx.serialization.UseSerializers import no.nav.helsearbeidsgiver.utils.json.serializer.LocalDateSerializer import no.nav.helsearbeidsgiver.utils.json.serializer.LocalDateTimeSerializer import java.time.LocalDate import java.time.LocalDateTime @Serializable data class Arbeidsforhold( val arbeidsgiver: Arbeidsgiver, val ansettelsesperiode: Ansettelsesperiode, val registrert: LocalDateTime ) @Serializable data class Ansettelsesperiode( val periode: PeriodeNullable ) @Serializable data class Arbeidsgiver( val type: String, val organisasjonsnummer: String? ) @Serializable data class PeriodeNullable( val fom: LocalDate?, val tom: LocalDate? = null )
2
Kotlin
0
2
d7d47418b3e70fff37e103a8c39632399569c121
864
helsearbeidsgiver-inntektsmelding
MIT License
data/src/main/java/com/trian/data/model/Kurs.kt
triandamai
419,006,471
false
{"Kotlin": 577545}
package com.trian.data.model data class Kurs( var IDR:Double?=14000.0, var USD:Double?=1.0 )
27
Kotlin
1
2
07635e10d2310dc168c24da02c698c529590f18e
102
Kopra.id
Apache License 2.0
app/src/test/java/br/com/joaovq/mydailypet/pet/data/localdatasource/PetLocalDataSourceImplTest.kt
joaovq
650,739,082
false
{"Kotlin": 326547, "Ruby": 1076}
package br.com.joaovq.mydailypet.pet.data.localdatasource import br.com.joaovq.core.data.localdatasource.LocalDataSource import br.com.joaovq.data.local.dao.PetDao import br.com.joaovq.model.PetDto import br.com.joaovq.mydailypet.testutil.TestUtilPet import io.mockk.MockKAnnotations import io.mockk.coEvery import io.mockk.coVerifyAll import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.junit4.MockKRule import io.mockk.verify import io.mockk.verifyAll import junit.framework.TestCase.assertEquals import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Rule import org.junit.Test class PetLocalDataSourceImplTest { @get:Rule val mockkRule = MockKRule(this) private lateinit var localDataSource: LocalDataSource<PetDto> @MockK private lateinit var petDao: PetDao private lateinit var petDto: br.com.joaovq.model.PetDto @Before fun setUp() { MockKAnnotations.init(this) localDataSource = br.com.joaovq.localdatasource.PetLocalDataSourceImpl(petDao) petDto = TestUtilPet.petDto } @Test fun `GIVEN nothing WHEN get all THEN empty flow`() { every { petDao.getAll() } returns emptyFlow() val flow = localDataSource.getAll() verify { petDao.getAll() } assertEquals(emptyFlow<List<br.com.joaovq.model.PetDto>>(), flow) verifyAll { petDao.getAll() } } @Test @Throws(Exception::class) fun `GIVEN throws Exception WHEN get all THEN empty flow`() { every { petDao.getAll() } throws Exception() val flow = localDataSource.getAll() verify { petDao.getAll() } assertEquals(emptyFlow<List<br.com.joaovq.model.PetDto>>(), flow) verifyAll { petDao.getAll() } } @OptIn(ExperimentalCoroutinesApi::class) @Test fun `GIVEN petDto WHEN update THEN Unit`() = runTest(UnconfinedTestDispatcher()) { coEvery { petDao.updatePet(petDto = petDto) } returns Unit assertEquals(Unit, localDataSource.update(petDto)) coVerifyAll { petDao.updatePet(petDto) } } @OptIn(ExperimentalCoroutinesApi::class) @Test fun `GIVEN petDto WHEN insert THEN Unit`() = runTest(UnconfinedTestDispatcher()) { coEvery { petDao.insertPet(petDto = petDto) } returns Unit assertEquals(Unit, localDataSource.insert(petDto)) coVerifyAll { petDao.insertPet(petDto) } } @OptIn(ExperimentalCoroutinesApi::class) @Test @Throws(Exception::class) fun `GIVEN petDto WHEN insert THEN throws exception`() = runTest { coEvery { petDao.insertPet(petDto = petDto) } throws Exception() localDataSource.insert(petDto) coVerifyAll { petDao.insertPet(petDto) } } @OptIn(ExperimentalCoroutinesApi::class) @Test fun `GIVEN petDto WHEN delete THEN Unit`() = runTest(UnconfinedTestDispatcher()) { coEvery { petDao.deletePet(petDto = petDto) } returns Unit assertEquals(Unit, localDataSource.delete(petDto)) coVerifyAll { petDao.deletePet(petDto) } } }
1
Kotlin
0
0
ce80c4b481c996fc02c0f22689954edf8154d588
3,219
MyDailyPet
MIT License
testkit-truth/src/main/kotlin/com/autonomousapps/kit/truth/BuildResultSubject.kt
autonomousapps
217,134,508
false
null
package com.autonomousapps.kit.truth import com.autonomousapps.kit.truth.BuildTaskListSubject.Companion.buildTaskList import com.autonomousapps.kit.truth.BuildTaskSubject.Companion.buildTasks import com.google.common.truth.Fact.simpleFact import com.google.common.truth.FailureMetadata import com.google.common.truth.IterableSubject import com.google.common.truth.StringSubject import com.google.common.truth.Subject import com.google.common.truth.Subject.Factory import com.google.common.truth.Truth.assertAbout import org.gradle.testkit.runner.BuildResult import org.gradle.testkit.runner.TaskOutcome public class BuildResultSubject private constructor( failureMetadata: FailureMetadata, private val actual: BuildResult? ) : Subject(failureMetadata, actual) { public companion object { private val BUILD_RESULT_SUBJECT_FACTORY: Factory<BuildResultSubject, BuildResult> = Factory { metadata, actual -> BuildResultSubject(metadata, actual) } @JvmStatic public fun buildResults(): Factory<BuildResultSubject, BuildResult> = BUILD_RESULT_SUBJECT_FACTORY @JvmStatic public fun assertThat(actual: BuildResult?): BuildResultSubject { return assertAbout(buildResults()).that(actual) } } public fun output(): StringSubject { if (actual == null) { failWithActual(simpleFact("build result was null")) } return check("getOutput()").that(actual!!.output) } public fun task(name: String): BuildTaskSubject { if (actual == null) { failWithActual(simpleFact("build result was null")) } return check("task(%s)", name).about(buildTasks()).that(actual!!.task(name)) } public fun getTasks(): BuildTaskListSubject { if (actual == null) { failWithActual(simpleFact("build result was null")) } return check("getTasks()").about(buildTaskList()).that(actual!!.tasks) } public fun tasks(outcome: TaskOutcome): BuildTaskListSubject { if (actual == null) { failWithActual(simpleFact("build result was null")) } return check("tasks(%s)", outcome).about(buildTaskList()).that(actual!!.tasks(outcome)) } public fun taskPaths(outcome: TaskOutcome): IterableSubject { if (actual == null) { failWithActual(simpleFact("build result was null")) } return check("taskPaths(%s)", outcome).that(actual!!.taskPaths(outcome)) } }
82
null
55
910
da02a56a0b7a00a26876cdaa29321f8376bf7099
2,354
dependency-analysis-android-gradle-plugin
Apache License 2.0
core/src/main/kotlin/splitties/wff/group/Group.kt
Splitties
704,439,760
false
{"Kotlin": 234744}
@file:Suppress("PackageDirectoryMismatch") package splitties.wff import kotlinx.html.TagConsumer import kotlinx.html.attributesMapOf import kotlinx.html.visit import splitties.wff.attr.ContainerAttrs /** * A Group is a container for other elements. Child elements are rendered relative to the position, size, angle, and color of the group. * * [AndroidX doc](https://developer.android.com/training/wearables/wff/group/group) */ @WffTagMarker inline fun SupportsGroup.group( name: String = "null", x: Int = 0, y: Int = 0, width: Int = this.width, height: Int = this.height, id: String? = null, pivotX: Float = .5f, pivotY: Float = .5f, angle: Float = 0f, alpha: UByte = 0xFFu, scaleX: Float = 1f, scaleY: Float = 1f, renderMode: RenderMode = RenderMode.SOURCE, tintColor: Color? = null, crossinline block: GROUP.() -> Unit ): Unit = GROUP( initialAttributes = attributesMapOf( "name", name, "x", x.toString(), "y", y.toString(), "width", width.toString(), "height", height.toString(), "id", id, "pivotX", pivotX.takeUnless { it == .5f }?.toString(), "pivotY", pivotY.takeUnless { it == .5f }?.toString(), "angle", angle.takeUnless { it == 0f }?.toString(), "alpha", alpha.takeUnless { it == 0xFFu.toUByte() }?.toString(), "scaleX", scaleX.takeUnless { it == 1f }?.toString(), "scaleY", scaleY.takeUnless { it == 1f }?.toString(), "renderMode", renderMode.xmlValue(), "tintColor", tintColor?.xmlValue(), ), consumer = consumer ).visit(block) class GROUP( initialAttributes: Map<String, String>, override val consumer: TagConsumer<*> ) : XMLTag( tagName = "Group", consumer = consumer, initialAttributes = initialAttributes, namespace = null, inlineTag = false, emptyTag = false ), SupportsGroup, SupportsConditions, SupportsClock, SupportsPart, SupportsGyro, Transformable, SupportsLaunch, SupportsLocalization, SupportsVariants, SupportsBooleanConfiguration, SupportsListConfiguration { override val width: Int get() = w() override val height: Int get() = h() override val attrs = ContainerAttrs() }
4
Kotlin
3
3
e1d4fcb30bc16ce857cd31508a376987446d95f1
2,235
WffDsl
Apache License 2.0
app/src/main/java/com/dantes/backstack/MainActivityRouter.kt
vol4arrra
155,413,913
false
{"Kotlin": 31667}
package com.dantes.backstack interface MainActivityRouter { fun openIdeasFragment(isBack: Boolean = false) fun openTimeFragment() fun openFavoritesFragment() fun openAboutFragment() fun openMoreFragment() fun openListFragment() fun openItemFragment(itemText: String) }
0
Kotlin
0
0
f63dd3537c352667d2f9d4e3aec24cd87503cbb9
305
lrt-fragments-back-stack
Apache License 2.0
wow-core/src/main/kotlin/me/ahoo/wow/modeling/command/AggregateProcessorFactory.kt
Ahoo-Wang
628,167,080
false
null
/* * Copyright [2021-present] [<NAME> <<EMAIL>> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.wow.modeling.command import me.ahoo.wow.api.modeling.AggregateId import me.ahoo.wow.modeling.matedata.AggregateMetadata import me.ahoo.wow.modeling.state.StateAggregateFactory import me.ahoo.wow.modeling.state.StateAggregateRepository interface AggregateProcessorFactory { fun <C : Any, S : Any> create( aggregateId: AggregateId, aggregateMetadata: AggregateMetadata<C, S> ): AggregateProcessor<C> } class RetryableAggregateProcessorFactory( private val stateAggregateFactory: StateAggregateFactory, private val stateAggregateRepository: StateAggregateRepository, private val commandAggregateFactory: CommandAggregateFactory ) : AggregateProcessorFactory { override fun <C : Any, S : Any> create( aggregateId: AggregateId, aggregateMetadata: AggregateMetadata<C, S> ): AggregateProcessor<C> { return RetryableAggregateProcessor( aggregateId = aggregateId, aggregateMetadata = aggregateMetadata, aggregateFactory = stateAggregateFactory, stateAggregateRepository = stateAggregateRepository, commandAggregateFactory = commandAggregateFactory, ) } }
6
null
10
98
eed438bab2ae009edf3a1db03396de402885c681
1,847
Wow
Apache License 2.0
library/src/main/java/ru/yoomoney/sdk/kassa/payments/contract/Contract.kt
yoomoney
140,608,545
false
null
/* * The MIT License (MIT) * Copyright © 2021 NBCO YooMoney LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the “Software”), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package ru.yoomoney.sdk.kassa.payments.contract import ru.yoomoney.sdk.kassa.payments.checkoutParameters.SavePaymentMethod import ru.yoomoney.sdk.kassa.payments.model.AbstractWallet import ru.yoomoney.sdk.kassa.payments.model.BankCardPaymentOption import ru.yoomoney.sdk.kassa.payments.model.Confirmation import ru.yoomoney.sdk.kassa.payments.model.GooglePay import ru.yoomoney.sdk.kassa.payments.model.LinkedCard import ru.yoomoney.sdk.kassa.payments.model.PaymentIdCscConfirmation import ru.yoomoney.sdk.kassa.payments.model.PaymentInstrumentBankCard import ru.yoomoney.sdk.kassa.payments.model.PaymentOption import ru.yoomoney.sdk.kassa.payments.model.PaymentOptionInfo import ru.yoomoney.sdk.kassa.payments.model.SavePaymentMethodOptionTexts import ru.yoomoney.sdk.kassa.payments.model.SberBank import ru.yoomoney.sdk.kassa.payments.model.Wallet import ru.yoomoney.sdk.kassa.payments.payment.selectOption.SelectedPaymentMethodOutputModel import ru.yoomoney.sdk.kassa.payments.payment.tokenize.TokenizeInputModel internal sealed class ContractInfo { abstract val paymentOption: PaymentOption data class WalletContractInfo( override val paymentOption: Wallet, val walletUserAuthName: String?, val walletUserAvatarUrl: String?, val showAllowWalletLinking: Boolean, val allowWalletLinking: Boolean ): ContractInfo() data class WalletLinkedCardContractInfo( override val paymentOption: LinkedCard, val showAllowWalletLinking: Boolean, val allowWalletLinking: Boolean ): ContractInfo() data class PaymentIdCscConfirmationContractInfo( override val paymentOption: PaymentIdCscConfirmation, val allowWalletLinking: Boolean ): ContractInfo() data class NewBankCardContractInfo( override val paymentOption: BankCardPaymentOption ): ContractInfo() data class LinkedBankCardContractInfo( override val paymentOption: BankCardPaymentOption, val instrument: PaymentInstrumentBankCard ): ContractInfo() data class AbstractWalletContractInfo( override val paymentOption: AbstractWallet ): ContractInfo() data class GooglePayContractInfo( override val paymentOption: GooglePay ): ContractInfo() data class SberBankContractInfo( override val paymentOption: SberBank, val userPhoneNumber: String? ): ContractInfo() } internal object Contract { sealed class State { object Loading : State() { override fun toString() = "State.Loading" } data class Error(val error: Throwable) : State() data class Content( val shopTitle: CharSequence, val shopSubtitle: CharSequence, val isSinglePaymentMethod: Boolean, val shouldSavePaymentMethod: Boolean, val shouldSavePaymentInstrument: Boolean, val savePaymentMethod: SavePaymentMethod, val contractInfo: ContractInfo, val confirmation: Confirmation, val isSplitPayment: Boolean, val customerId: String?, val savePaymentMethodOptionTexts: SavePaymentMethodOptionTexts, val userAgreementUrl: String ) : State() data class GooglePay( val content: Content, val paymentOptionId: Int ) : State() } sealed class Action { object Load : Action() data class LoadContractFailed(val error: Throwable) : Action() data class LoadContractSuccess(val outputModel: SelectedPaymentMethodOutputModel) : Action() data class Tokenize(val paymentOptionInfo: PaymentOptionInfo? = null): Action() data class TokenizePaymentInstrument(val instrument: PaymentInstrumentBankCard, val csc: String?): Action() object TokenizeCancelled: Action() { override fun toString() = "Action.TokenizeCancelled" } object RestartProcess: Action() { override fun toString() = "Action.RestartProcess" } data class ChangeSavePaymentMethod(val savePaymentMethod: Boolean): Action() data class ChangeAllowWalletLinking(val isAllowed: Boolean): Action() object Logout: Action() object LogoutSuccessful: Action() object GooglePayCancelled: Action() } sealed class Effect { object RestartProcess: Effect() { override fun toString() = "Effect.RestartProcess" } object CancelProcess: Effect() { override fun toString() = "Effect.CancelProcess" } data class ShowTokenize(val tokenizeInputModel: TokenizeInputModel): Effect() { override fun toString() = "Effect.ShowTokenize" } data class StartGooglePay( val content: State.Content, val paymentOptionId: Int ) : Effect() } }
9
null
21
35
421619230cce92280641ea943c5ecb00f3dd8827
6,026
yookassa-android-sdk
MIT License
json-schema-validator/src/test/kotlin/io/openapiprocessor/jsonschema/validator/PendingSpec.kt
openapi-processor
418,185,783
false
{"Java": 629502, "Kotlin": 243428, "Just": 441}
/* * Copyright 2022 https://github.com/openapi-processor/openapi-parser * PDX-License-Identifier: Apache-2.0 */ package io.openapiprocessor.jsonschema.validator import io.kotest.core.annotation.Ignored import io.kotest.core.spec.style.FreeSpec import io.openapiprocessor.jsonschema.schema.Format import io.openapiprocessor.jsonschema.schema.SchemaVersion import io.openapiprocessor.jsonschema.validator.support.draftSpec @Ignored class PendingSpec : FreeSpec({ // val settings = ValidatorSettingsDefaults.draft4() // val settings = ValidatorSettingsDefaults.draft7() // val settings = ValidatorSettingsDefaults.draft201909() val settings = ValidatorSettingsDefaults.draft202012() settings.enableFormats(*Format.values()) // settings.version = SchemaVersion.Draft4 // settings.version = SchemaVersion.Draft6 // settings.version = SchemaVersion.Draft7 // settings.version = SchemaVersion.Draft201909 settings.version = SchemaVersion.Draft202012 include( draftSpec( "/suites/pending", settings, // draft4Extras // draft6Extras // draft7Extras // draft201909Extras draft202012Extras ) ) })
15
Java
1
12
0de835f5035117816d919f3c382488b4ecd9e616
1,198
openapi-parser
Apache License 2.0
app/src/main/java/com/hellguy39/hellnotes/android_features/AndroidAlarmScheduler.kt
HellGuy39
572,830,054
false
null
package com.hellguy39.hellnotes.android_features import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent import com.hellguy39.hellnotes.broadcast.ReminderReceiver import com.hellguy39.hellnotes.core.domain.system_features.AlarmScheduler import com.hellguy39.hellnotes.core.model.repository.local.database.Reminder import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject class AndroidAlarmScheduler @Inject constructor( @ApplicationContext private val context: Context ) : AlarmScheduler { private val alarmManager = context.getSystemService(AlarmManager::class.java) override fun scheduleAlarm(reminder: Reminder) { alarmManager.setExactAndAllowWhileIdle( ALARM_TYPE, reminder.triggerDate, reminder.createAlarmPendingIntent() ) } override fun cancelAlarm(reminder: Reminder) { alarmManager.cancel( reminder.createAlarmPendingIntent() ) } private fun Reminder.createAlarmPendingIntent(): PendingIntent { return PendingIntent.getBroadcast( context, hashCode(), Intent(context, ReminderReceiver::class.java).apply { putExtra(ALARM_REMINDER_ID, id) putExtra(ALARM_MESSAGE, message) putExtra(ALARM_NOTE_ID, noteId) }, PENDING_INTENT_FLAGS ) } companion object { private const val ALARM_TYPE = AlarmManager.RTC_WAKEUP private const val PENDING_INTENT_FLAGS = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE const val ALARM_REMINDER_ID = "reminder_id" const val ALARM_MESSAGE = "alarm_message" const val ALARM_NOTE_ID = "note_id" } }
1
Kotlin
0
9
548d59c0f641df6e1f3ddd9c220904631ca5351b
1,847
HellNotes
Apache License 2.0
app/src/main/java/com/lyj/pinstagram/extension/lang/StringExtension.kt
banziha104
389,872,729
false
null
package com.lyj.pinstagram.extension.lang fun String.bearerToken() = "Bearer $this"
1
Kotlin
1
3
9d8d6015b5333eb3d2bc07ffbebe2638af2f42ac
84
pinstagram_android
MIT License
app/src/test/java/com/ozantopuz/dicetask/data/remote/entity/ReleaseResponse.kt
ozantopuz
436,359,167
false
{"Kotlin": 65581}
package com.ozantopuz.dicetask.data.remote.entity fun getReleaseResponse() = ReleaseResponse( disambiguation = "", id = "f32fab67-77dd-3937-addc-9062e28e4c37", title = "Thriller", primaryTypeId = "f529b476-6e62-324f-b0aa-1f3e33d313fc", primaryType = "Album", firstReleaseDate = "1982-11-30" )
0
Kotlin
0
0
956ac995e222c2432416d3acbb9b863ca67261c4
318
DiceTask
MIT License
app/src/main/java/mustafaozhan/github/com/mycurrencies/base/preferences/BasePreferences.kt
hirenpatel868
242,063,783
true
{"Kotlin": 119920}
package mustafaozhan.github.com.mycurrencies.base.preferences import android.content.Context import com.squareup.moshi.Moshi import mustafaozhan.github.com.mycurrencies.app.CCCApplication /** * Created by <NAME> on 7/10/18 at 9:42 PM on Arch Linux wit Love <3. */ @Suppress("SameParameterValue") abstract class BasePreferences { protected abstract val preferencesName: String protected abstract val moshi: Moshi private val preferences get() = CCCApplication.instance .getSharedPreferences(preferencesName, Context.MODE_PRIVATE) private val editor get() = preferences.edit() protected fun getStringEntry(key: String, defaultValue: String) = preferences .getString(key, defaultValue) ?: defaultValue protected fun setStringEntry(key: String, value: String) = editor .putString(key, value) .commit() protected fun setBooleanEntry(key: String, value: Boolean) = editor .putBoolean(key, value) .commit() protected fun getBooleanEntry(key: String, defaultValue: Boolean = false) = preferences .getBoolean(key, defaultValue) }
0
null
0
0
9709b27913f89b5368bcaddca83a13d69a6b3ded
1,140
androidCCC
Apache License 2.0
Notifications/app/src/main/java/com/example/notifications/MainActivity.kt
TannerGabriel
163,828,907
false
{"TypeScript": 58521, "Kotlin": 23779, "Vue": 11728, "JavaScript": 6110, "HTML": 1993, "Dockerfile": 270, "CSS": 181, "Shell": 58}
package com.example.notifications import android.app.Notification.VISIBILITY_PUBLIC import android.os.Build import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v4.app.NotificationCompat import android.support.v4.app.NotificationManagerCompat import kotlinx.android.synthetic.main.activity_main.* import android.R.attr.name import android.annotation.SuppressLint import android.annotation.TargetApi import android.app.Notification.VISIBILITY_PRIVATE import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import android.os.HandlerThread import android.support.annotation.RequiresApi import android.widget.RemoteViews class MainActivity : AppCompatActivity() { private val CHANNEL_ID = "CHANNEL_ID" @SuppressLint("NewApi") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) createNotificationChannel() default_notification_btn.setOnClickListener { createNormalNotification() } head_up_notification_btn.setOnClickListener { createHeadsUpNotification() } lock_screen_notification_btn.setOnClickListener { createLockScreenNotification() } notification_badged.setOnClickListener { createBadgedNotification() } notification_click_action_btn.setOnClickListener { createNotificationWithClickAction() } notification_action_button_btn.setOnClickListener { createNotificationWithActionButtons() } expandable_notification.setOnClickListener { createExpandableNotification() } progress_bar_notification.setOnClickListener { createProgressBarNotification() } group_notification.setOnClickListener { createGroupNotification() } custom_notification.setOnClickListener { createCustomNotification() } } // Creates a standard notification fun createNormalNotification(){ val builder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("Normal Notification") .setContentText("Really great content for this notification") .setPriority(NotificationCompat.PRIORITY_DEFAULT) createNotification(0, builder) } // Creates a headup notification fun createHeadsUpNotification(){ val builder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("Heads up notification") .setContentText("Really great content for this notification") .setPriority(NotificationCompat.PRIORITY_HIGH) if (Build.VERSION.SDK_INT >= 21) builder.setVibrate(LongArray(0)) createNotification(1, builder) } // Create a notification which will be visible on the lockscreen @RequiresApi(Build.VERSION_CODES.LOLLIPOP) fun createLockScreenNotification(){ val publicBuilder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("Alternative notification") .setPriority(NotificationCompat.PRIORITY_HIGH) .setVisibility(VISIBILITY_PUBLIC) val builder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("Lock screen Notification") .setContentText("Really great content for this notification") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setVisibility(VISIBILITY_PRIVATE) .setPublicVersion(publicBuilder.build()) createNotification(2, builder) } // Create a notification which shows a badged on newer android versions fun createBadgedNotification(){ val builder = NotificationCompat.Builder(this@MainActivity, CHANNEL_ID) .setContentTitle("Badged Notification") .setContentText("New badged notification") .setSmallIcon(R.drawable.notification_icon) .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL) createNotification(3, builder) } // Create a notification with a click event fun createNotificationWithClickAction(){ val intent = Intent(this, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0) val builder = NotificationCompat.Builder(this@MainActivity, CHANNEL_ID) .setContentTitle("Notification with click action") .setContentText("New notification with great click action") .setSmallIcon(R.drawable.notification_icon) .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL) .setContentIntent(pendingIntent) .setAutoCancel(true) createNotification(4, builder) } // Create a notification with an action button fun createNotificationWithActionButtons(){ val intent = Intent(this, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0) val builder = NotificationCompat.Builder(this@MainActivity, CHANNEL_ID) .setContentTitle("Notification with click action") .setContentText("New notification with great click action") .setSmallIcon(R.drawable.notification_icon) .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL) .addAction(R.drawable.notification_icon, "Open Activity", pendingIntent) createNotification(5, builder) } // Create a notification that can be expanded for more information fun createExpandableNotification(){ val bitmap = BitmapFactory.decodeResource(resources, R.drawable.notification_icon) val builder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("Simple expandable notification") .setContentText("Simple notification that can be expended ") .setLargeIcon(bitmap) .setStyle(NotificationCompat.BigPictureStyle() .bigPicture(bitmap) .bigLargeIcon(null)) /* Add large text .setStyle(NotificationCompat.BigTextStyle() .bigText("Some great big text") */ createNotification(6, builder) } // Create a notification with a simple progress bar fun createProgressBarNotification(){ val builder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("Simple progress bar notification") .setContentText("Simple notification with a progress bar ") // Progress values val PROGRESS_MAX = 100 val PROGRESS_CURRENT = 0 NotificationManagerCompat.from(this).apply { // Sets the initial progress to 0 builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false) notify(7 , builder.build()) for(i in 0 until 100){ builder.setProgress(PROGRESS_MAX, i, false) HandlerThread.sleep(100) } // Updates the notification when the progress is done builder.setContentText("Download complete") .setProgress(0, 0, false) notify(7, builder.build()) } } val GROUP_KEY = "com.android.example.KEY" // Create a simple group notification fun createGroupNotification(){ val groupBuilderOne = NotificationCompat.Builder(this@MainActivity, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("Simple group notification") .setContentText("Simple notification group") .setGroup(GROUP_KEY) val groupBuilderTwo = NotificationCompat.Builder(this@MainActivity, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("Second simple group notification") .setContentText("Simple notification group") .setGroup(GROUP_KEY) // For older versions than 7.0 val summaryNotification = NotificationCompat.Builder(this@MainActivity, CHANNEL_ID) .setContentTitle("Notification group summary") .setContentText("Notification group summary") .setSmallIcon(R.drawable.notification_icon) .setGroup(GROUP_KEY) .setGroupSummary(true) createNotification(8, groupBuilderOne) createNotification(9, groupBuilderTwo) createNotification(10, summaryNotification) } fun createCustomNotification(){ // Get the layouts to use in the custom notification val notificationLayout = RemoteViews(packageName, R.layout.custom_notification_layout) val notificationLayoutExpanded = RemoteViews(packageName, R.layout.custom_notification_expended_layout) notificationLayout.setTextViewText(R.id.notification_title, "Title") notificationLayout.setTextViewText(R.id.notification_info, "Expand for more information") // Apply the layouts to the notification val customNotification = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setStyle(NotificationCompat.DecoratedCustomViewStyle()) .setCustomContentView(notificationLayout) .setCustomBigContentView(notificationLayoutExpanded) createNotification(11, customNotification) } // Creates the notification and displays it fun createNotification(id: Int, builder: NotificationCompat.Builder){ with(NotificationManagerCompat.from(this)) { notify(id, builder.build()) } } // Create the notification channel private fun createNotificationChannel() { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = "Channel" val descriptionText = "Simple channel example" val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(CHANNEL_ID, name, importance).apply { description = descriptionText //setShowBadge(false) } // Register the channel with the system val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } }
5
TypeScript
178
174
dabc03ab4c75f5e1d0f90ad65bfd7d22e297fcd6
11,318
Blog
MIT License
src/Day02.kt
arisaksen
573,116,584
false
{"Kotlin": 42887}
import Outcome.* import org.assertj.core.api.Assertions.assertThat enum class Opponent(val char: Char) { ROCK('A'), PAPER('B'), SCISSORS('C') } enum class Response(val char: Char) { ROCK('X'), PAPER('Y'), SCISSORS('Z') } enum class Outcome { LOSE, DRAW, WIN } val responseScore: Map<Response, Int> = mapOf(Response.ROCK to 1, Response.PAPER to 2, Response.SCISSORS to 3) val outcomeScore: Map<Outcome, Int> = mapOf(LOSE to 0, DRAW to 3, WIN to 6) /** val (a, _, c) = "X Z" Allow you to deconstruct string to char * operator fun String.component1() = this[0] * operator fun String.component2() = this[1] * operator fun String.component3() = this[1] * val (opponent, _, choice) = "X Z" * */ fun main() { fun part1(rounds: List<String>): Int { var totalScore: Int = 0 rounds.forEach { totalScore += responseScore[response(it)] ?: 0 val outcome = opponentChoice(it).outcome(response(it)) totalScore += outcomeScore[outcome] ?: 0 println("$it - ${opponentChoice(it)} ${response(it)} - ${responseScore[response(it)]} ${outcomeScore[outcome]} $outcome totalscore: $totalScore") } return totalScore } fun part2(rounds: List<String>): Int { var totalScore: Int = 0 rounds.forEach { val outcome = response(it).fixedOutcome() val fixedResponse = fixResponse(opponentChoice(it), response(it).fixedOutcome()) print("${it.last()} -> ${response(it).fixedOutcome()} - ${response(it)} -> $fixedResponse") println(" ====> $it - ${opponentChoice(it)} $fixedResponse - ${responseScore[fixedResponse]} ${outcomeScore[outcome]} $outcome totalscore: $totalScore") totalScore += responseScore[fixedResponse] ?: 0 totalScore += outcomeScore[outcome] ?: 0 } return totalScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") assertThat(part1(testInput)).isEqualTo(15) assertThat(part2(testInput)).isEqualTo(12) val input = readInput("Day02") println("totalscore: " + part1(input)) println("totalscore: " + part2(input)) } private fun Opponent.outcome(response: Response): Outcome = when (this) { Opponent.ROCK -> { when (response) { Response.ROCK -> DRAW Response.PAPER -> WIN Response.SCISSORS -> LOSE } } Opponent.PAPER -> { when (response) { Response.ROCK -> LOSE Response.PAPER -> DRAW Response.SCISSORS -> WIN } } Opponent.SCISSORS -> { when (response) { Response.ROCK -> WIN Response.PAPER -> LOSE Response.SCISSORS -> DRAW } } } fun opponentChoice(input: String): Opponent = when (input.first()) { Opponent.ROCK.char -> Opponent.ROCK Opponent.PAPER.char -> Opponent.PAPER else -> Opponent.SCISSORS } fun response(input: String): Response = when (input.last()) { Response.ROCK.char -> Response.ROCK Response.PAPER.char -> Response.PAPER else -> Response.SCISSORS } // part2 fun Response.fixedOutcome(): Outcome = when (this) { Response.ROCK -> LOSE Response.PAPER -> DRAW Response.SCISSORS -> WIN } fun fixResponse(opponent: Opponent, desiredOutcome: Outcome): Response = when (opponent) { Opponent.ROCK -> { when (desiredOutcome) { WIN -> Response.PAPER DRAW -> Response.ROCK LOSE -> Response.SCISSORS } } Opponent.PAPER -> { when (desiredOutcome) { WIN -> Response.SCISSORS DRAW -> Response.PAPER LOSE -> Response.ROCK } } Opponent.SCISSORS -> { when (desiredOutcome) { WIN -> Response.ROCK DRAW -> Response.SCISSORS LOSE -> Response.PAPER } } }
0
Kotlin
0
0
85da7e06b3355f2aa92847280c6cb334578c2463
4,178
aoc-2022-kotlin
Apache License 2.0
ContextMenu/src/main/java/com/sedo/contextmenu/utils/extensions/RecycleViewExtension.kt
saadabusham
340,050,587
false
null
package com.sedo.contextmenu.utils.extensions import androidx.databinding.BindingAdapter import androidx.recyclerview.widget.RecyclerView import com.sedo.contextmenu.ui.base.BaseBindingRecyclerViewAdapter fun RecyclerView?.setOnItemClickListener( onItemClickListener: BaseBindingRecyclerViewAdapter.OnItemClickListener? ) { this?.adapter?.let { if (this.adapter is BaseBindingRecyclerViewAdapter<*>) { (adapter as BaseBindingRecyclerViewAdapter<*>).itemClickListener = onItemClickListener } } }
0
Kotlin
0
0
444fdaa476672f973bf04c21e103f0bc623bd455
537
ContextMenu
Apache License 2.0
src/main/kotlin/pw/stamina/pubsub4k/StandardEventBus.kt
staminadevelopment
166,087,289
false
{"Kotlin": 72457}
/* * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pw.stamina.pubsub4k import pw.stamina.pubsub4k.publish.Publisher import pw.stamina.pubsub4k.publish.PublisherRegistry import pw.stamina.pubsub4k.subscribe.CancellableMessageHandler import pw.stamina.pubsub4k.subscribe.MessageHandler import pw.stamina.pubsub4k.subscribe.Subscription import pw.stamina.pubsub4k.subscribe.SubscriptionRegistry class StandardEventBus( private val subscriptions: SubscriptionRegistry, private val publishers: PublisherRegistry ) : EventBus { override fun addSubscription(subscription: Subscription<*>) { if (subscriptions.register(subscription)) { publishers.addSubscriptionToPublishers(subscription) } } override fun removeSubscription(subscription: Subscription<*>) { if (subscriptions.unregister(subscription)) { publishers.removeSubscriptionFromPublishers(subscription) } } override fun removeAllSubscriptions(subscriber: MessageSubscriber) { val unregisteredSubscriptions = subscriptions.unregisterAll(subscriber) unregisteredSubscriptions.forEach { publishers.removeSubscriptionFromPublishers(it) } } override fun <T : Any> on(topic: Topic<T>, subscriber: MessageSubscriber, handler: MessageHandler<T>) { addSubscription(Subscription(topic, subscriber, handler)) } override fun <T : Any> cancellableOn( topic: Topic<T>, subscriber: MessageSubscriber, handler: CancellableMessageHandler<T> ) { val subscription = Subscription(topic, subscriber, handler) handler.cancel = { removeSubscription(subscription) } addSubscription(subscription) } override fun <T : Any> getPublisher(topic: Topic<T>): Publisher<T> { return publishers.findOrCreatePublisher(topic, subscriptions::findSubscriptionsForTopic) } }
3
Kotlin
0
7
6b1ce35872f4513a51cf80b2e9a1265144761703
2,461
pubsub4k
Apache License 2.0
plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/psi/UastFakeDescriptorLightMethod.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin.psi import com.intellij.psi.* import com.intellij.psi.impl.light.LightModifierList import com.intellij.psi.impl.light.LightParameterListBuilder import com.intellij.psi.impl.light.LightReferenceListBuilder import com.intellij.psi.impl.light.LightTypeParameterBuilder import org.jetbrains.kotlin.analysis.api.types.KtTypeMappingMode import org.jetbrains.kotlin.analysis.api.types.KtTypeNullability import org.jetbrains.kotlin.asJava.classes.toLightAnnotation import org.jetbrains.kotlin.asJava.elements.KotlinLightTypeParameterListBuilder import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.types.typeUtil.TypeNullability import org.jetbrains.kotlin.types.typeUtil.nullability import org.jetbrains.kotlin.utils.SmartSet import org.jetbrains.uast.UastLazyPart import org.jetbrains.uast.getOrBuild import org.jetbrains.uast.kotlin.PsiTypeConversionConfiguration import org.jetbrains.uast.kotlin.TypeOwnerKind import org.jetbrains.uast.kotlin.toPsiType internal class UastFakeDescriptorLightMethod( private val originalDescriptor: SimpleFunctionDescriptor, private val containingClass: PsiClass, context: KtElement, ) : UastFakeDescriptorLightMethodBase<SimpleFunctionDescriptor>(originalDescriptor, containingClass, context) { private val buildTypeParameterListPart = UastLazyPart<PsiTypeParameterList>() private val paramsListPart = UastLazyPart<PsiParameterList>() private val _buildTypeParameterList: PsiTypeParameterList get() = buildTypeParameterListPart.getOrBuild { KotlinLightTypeParameterListBuilder(this).also { paramList -> for ((i, p) in originalDescriptor.typeParameters.withIndex()) { paramList.addParameter( object : LightTypeParameterBuilder( p.name.identifier, this, i ) { private val myExtendsListPart = UastLazyPart<LightReferenceListBuilder>() override fun getExtendsList(): LightReferenceListBuilder { return myExtendsListPart.getOrBuild { super.getExtendsList().apply { for (bound in p.upperBounds) { val psiType = bound.toPsiType( this@UastFakeDescriptorLightMethod, [email protected], PsiTypeConversionConfiguration(TypeOwnerKind.DECLARATION) ) (psiType as? PsiClassType)?.let { addReference(it) } } } } } } ) } } } override fun getTypeParameterList(): PsiTypeParameterList = _buildTypeParameterList private val paramsList: PsiParameterList get() = paramsListPart.getOrBuild { object : LightParameterListBuilder(containingClass.manager, containingClass.language) { override fun getParent(): PsiElement = this@UastFakeDescriptorLightMethod override fun getContainingFile(): PsiFile = parent.containingFile init { val parameterList = this originalDescriptor.extensionReceiverParameter?.let { receiver -> this.addParameter( UastDescriptorLightParameterBase( "\$this\$${originalDescriptor.name.identifier}", receiver.type.toPsiType( this@UastFakeDescriptorLightMethod, [email protected], PsiTypeConversionConfiguration(TypeOwnerKind.DECLARATION) ), parameterList, receiver ) ) } for (p in originalDescriptor.valueParameters) { this.addParameter( UastDescriptorLightParameter( p.name.identifier, p.type.toPsiType( this@UastFakeDescriptorLightMethod, [email protected], PsiTypeConversionConfiguration( TypeOwnerKind.DECLARATION, typeMappingMode = KtTypeMappingMode.VALUE_PARAMETER ) ), parameterList, p ) ) } if (isSuspendFunction()) { this.addParameter( UastDescriptorLightSuspendContinuationParameter.create( this@UastFakeDescriptorLightMethod, originalDescriptor, [email protected] ) ) } } } } override fun getParameterList(): PsiParameterList = paramsList } internal abstract class UastFakeDescriptorLightMethodBase<T : CallableMemberDescriptor>( protected val original: T, containingClass: PsiClass, protected val context: KtElement, ) : UastFakeLightMethodBase( containingClass.manager, containingClass.language, original.name.identifier, LightParameterListBuilder(containingClass.manager, containingClass.language), LightModifierList(containingClass.manager), containingClass ) { init { if (original.dispatchReceiverParameter == null) { addModifier(PsiModifier.STATIC) } } private val returnTypePart = UastLazyPart<PsiType?>() override fun isSuspendFunction(): Boolean { return (original as? FunctionDescriptor)?.isSuspend == true } override fun isUnitFunction(): Boolean { return original is FunctionDescriptor && _returnType == PsiTypes.voidType() } override fun computeNullability(): KtTypeNullability? { if (isSuspendFunction()) { // suspend fun returns Any?, which is mapped to @Nullable java.lang.Object return KtTypeNullability.NULLABLE } return when (original.returnType?.nullability()) { null -> null TypeNullability.NOT_NULL -> KtTypeNullability.NON_NULLABLE TypeNullability.NULLABLE -> KtTypeNullability.NULLABLE else -> KtTypeNullability.UNKNOWN } } override fun computeAnnotations(annotations: SmartSet<PsiAnnotation>) { original.annotations.mapTo(annotations) { annoDescriptor -> annoDescriptor.toLightAnnotation(this) } } override fun isConstructor(): Boolean { return original is ConstructorDescriptor } private val _returnType: PsiType? get() = returnTypePart.getOrBuild { if (isSuspendFunction()) { // suspend fun returns Any?, which is mapped to @Nullable java.lang.Object return@getOrBuild PsiType.getJavaLangObject(context.manager, context.resolveScope) } original.returnType?.toPsiType( this, context, PsiTypeConversionConfiguration( TypeOwnerKind.DECLARATION, typeMappingMode = KtTypeMappingMode.RETURN_TYPE ) ) } override fun getReturnType(): PsiType? { return _returnType } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as UastFakeDescriptorLightMethodBase<*> return original == other.original } override fun hashCode(): Int = original.hashCode() }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
9,052
intellij-community
Apache License 2.0
core/src/main/kotlin/sibyl/commands/SibylCommand.kt
NikkyAI
154,854,088
false
null
package sibyl.commands import sibyl.api.ApiMessage import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.core.PrintHelpMessage import com.github.ajalt.clikt.core.context import com.github.ajalt.clikt.output.CliktConsole import com.github.ajalt.clikt.parameters.options.eagerOption import kotlinx.coroutines.channels.SendChannel import mu.KotlinLogging import sibyl.core.HelpCommand abstract class SibylCommand( help: String = "", epilog: String = "", name: String? = null, invokeWithoutSubcommand: Boolean = true, printHelpOnEmptyArgs: Boolean = false, helpTags: Map<String, String> = emptyMap(), allowMultipleSubcommands: Boolean = false, treatUnknownOptionsAsArgs: Boolean = false ) : CliktCommand( help = help, epilog = epilog, name = name, invokeWithoutSubcommand = invokeWithoutSubcommand, printHelpOnEmptyArgs = printHelpOnEmptyArgs, helpTags = helpTags, autoCompleteEnvvar = null, allowMultipleSubcommands = allowMultipleSubcommands, treatUnknownOptionsAsArgs = treatUnknownOptionsAsArgs ) { companion object { private val logger = KotlinLogging.logger {} } private lateinit var messageContext: ApiMessage val causeMessage: ApiMessage get() = (currentContext.findRoot().command as? SibylCommand)?.messageContext ?: messageContext ?: error("cannot find message context") // private lateinit var sendChannelContext: SendChannel<ApiMessage> // @Deprecated("try not to send messages this way ?") // val sendChannel: SendChannel<ApiMessage> // get() = // (currentContext.findRoot().command as? SibylCommand)?.sendChannelContext ?: sendChannelContext // ?: error("cannot find sendchannel") init { eagerOption("-H", "--HELP", hidden = true) { logger.info { "setting verbose" } (currentContext.helpFormatter as ShortHelpFormatter).verbose = true throw PrintHelpMessage(this@SibylCommand) } eagerOption("-h", "--help", help = "shows command usage") { throw PrintHelpMessage(this@SibylCommand) } } internal fun exec( commandPrefix: String, message: ApiMessage, // sendMessage: SendChannel<ApiMessage>, customConsole: CliktConsole ) { context { console = customConsole helpFormatter = ShortHelpFormatter(verbose = false) } messageContext = message // sendChannelContext = sendMessage val argv = message.text.substringAfter(commandPrefix + commandName).shellSplit() logger.info { "executing: $commandPrefix$commandName $argv" } parse(argv) } }
0
Kotlin
0
2
847c05289ae987e996ac5b7f866b74e836833e73
2,741
Sibyl
MIT License
app/src/main/java/com/czterysery/ledcontroller/data/socket/SocketManager.kt
tmaxxdd
230,282,033
false
null
package com.czterysery.ledcontroller.data.socket import android.bluetooth.BluetoothAdapter import com.czterysery.ledcontroller.data.model.ConnectionState import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.subjects.BehaviorSubject import io.reactivex.rxjava3.subjects.PublishSubject interface SocketManager { val connectionState: BehaviorSubject<ConnectionState> val messagePublisher: PublishSubject<String> fun connect(address: String, btAdapter: BluetoothAdapter): Completable fun disconnect(): Completable fun writeMessage(message: String): Completable }
0
Kotlin
1
0
19647c669125a25c5df56870f34d08cd71eefcd4
650
LEDController
MIT License
vgscheckout/src/main/java/com/verygoodsecurity/vgscheckout/networking/UrlExtension.kt
verygoodsecurity
371,054,567
false
null
package com.verygoodsecurity.vgscheckout.networking import androidx.core.util.PatternsCompat import com.verygoodsecurity.vgscheckout.util.logger.VGSCheckoutLogger import java.net.MalformedURLException import java.net.URL import java.util.regex.Pattern private const val HTTP_SCHEME = "http://" private const val HTTPS_SCHEME = "https://" /** @suppress */ internal fun String.setupLocalhostURL(port: Int?): String { val divider = ":" val prt = if (!port.isValidPort()) { VGSCheckoutLogger.warn(message = "Port is not valid") "" } else { divider + port } return StringBuilder(HTTP_SCHEME) .append(this) .append(prt) .toString() } /** @suppress */ internal fun String.setupURL(env: String, routeId: String? = null): String { return when { this.isEmpty() || !isTenantIdValid() -> { VGSCheckoutLogger.warn(message = "Vault ID is not valid") return "" } env.isEmpty() || !env.isEnvironmentValid() -> { VGSCheckoutLogger.warn(message = "Environment is not valid") return "" } else -> this.buildURL(env, routeId) } } private fun String.buildURL(env: String, routeId: String?): String { val DOMEN = "verygoodproxy.com" val DIVIDER = "." val SCHEME = "https://" val builder = StringBuilder(SCHEME) .append(this) if (!routeId.isNullOrEmpty()) builder.append("-").append(routeId) return builder.append(DIVIDER) .append(env) .append(DIVIDER) .append(DOMEN) .toString() } internal fun String.isTenantIdValid(): Boolean = Pattern.compile("^[a-zA-Z0-9]*\$").matcher(this).matches() internal fun String.isEnvironmentValid(): Boolean = Pattern.compile("^(live|sandbox|LIVE|SANDBOX)+((-)+([a-zA-Z0-9]+)|)+\$").matcher(this).matches() internal fun String?.isUrlValid(): Boolean { return when { isNullOrBlank() -> false else -> PatternsCompat.WEB_URL.matcher(this).matches() } } internal fun String.isValidIp(): Boolean { return when { isNullOrEmpty() -> false else -> PatternsCompat.IP_ADDRESS.matcher(this).matches() } } private const val AVD_LOCALHOST_ALIAS = "10.0.2.2" private const val GENYMOTION_LOCALHOST_ALIAS = "10.0.3.2" private const val PRIVATE_NETWORK_IP_PREFIX = "192.168." internal fun String.isIpAllowed() = this == AVD_LOCALHOST_ALIAS || this == GENYMOTION_LOCALHOST_ALIAS || this.startsWith(PRIVATE_NETWORK_IP_PREFIX) internal const val PORT_MIN_VALUE = 1L internal const val PORT_MAX_VALUE = 65353L internal fun Int?.isValidPort(): Boolean = this != null && this in PORT_MIN_VALUE..PORT_MAX_VALUE internal fun String.toHostnameValidationUrl(tnt: String): String { return String.format( "https://js.verygoodvault.com/collect-configs/%s__%s.txt", this.toHost(), tnt ) } internal infix fun String.equalsUrl(name: String?): Boolean { return toHost() == name?.toHost() } internal fun String.toHttps(): String { return when { startsWith(HTTP_SCHEME) -> this startsWith(HTTPS_SCHEME) -> this else -> "$HTTPS_SCHEME$this" } } internal fun String.toHost(): String { return try { URL(this.toHttps()).host } catch (e: MalformedURLException) { "" } }
5
Kotlin
2
2
49fdede7a225435b37837f5396dcfea06217e275
3,355
vgs-checkout-android
MIT License
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/areas/spawns/spawns_14671.plugin.kts
2011Scape
578,880,245
false
null
package gg.rsmod.plugins.content.areas.spawns spawn_npc(npc = Npcs.LIVING_ROCK_PROTECTOR, x = 3648, z = 5094, walkRadius = 5, direction = Direction.SOUTH_EAST) spawn_npc(npc = Npcs.LIVING_ROCK_STRIKER, x = 3649, z = 5089, walkRadius = 5, direction = Direction.SOUTH_EAST) spawn_npc(npc = Npcs.LIVING_ROCK_STRIKER, x = 3656, z = 5091, walkRadius = 5, direction = Direction.NORTH_EAST) spawn_npc(npc = Npcs.LIVING_ROCK_PROTECTOR, x = 3661, z = 5087, walkRadius = 5, direction = Direction.WEST) spawn_npc(npc = Npcs.LIVING_ROCK_PROTECTOR, x = 3668, z = 5080, walkRadius = 5, direction = Direction.SOUTH_WEST) spawn_npc(npc = Npcs.LIVING_ROCK_STRIKER, x = 3671, z = 5094, walkRadius = 5, direction = Direction.NORTH) spawn_npc(npc = Npcs.LIVING_ROCK_STRIKER, x = 3677, z = 5101, walkRadius = 5, direction = Direction.NORTH_EAST) spawn_npc(npc = Npcs.LIVING_ROCK_PROTECTOR, x = 3681, z = 5098, walkRadius = 5, direction = Direction.SOUTH_EAST) spawn_npc(npc = Npcs.LIVING_ROCK_PROTECTOR, x = 3681, z = 5106, walkRadius = 5, direction = Direction.EAST) spawn_npc(npc = Npcs.LIVING_ROCK_STRIKER, x = 3672, z = 5104, walkRadius = 5, direction = Direction.SOUTH_WEST) spawn_npc(npc = Npcs.LIVING_ROCK_PROTECTOR, x = 3659, z = 5099, walkRadius = 5, direction = Direction.SOUTH_EAST) spawn_npc(npc = Npcs.ROCK_CRITTER, x = 3659, z = 5113, walkRadius = 5, direction = Direction.NORTH_WEST) spawn_npc(npc = Npcs.ROCK_CRITTER, x = 3670, z = 5113, walkRadius = 5, direction = Direction.EAST) spawn_npc(npc = Npcs.ROCK_CRITTER, x = 3656, z = 5095, walkRadius = 5, direction = Direction.NORTH_EAST) spawn_npc(npc = Npcs.ROCK_CRITTER, x = 3667, z = 5081, walkRadius = 5, direction = Direction.SOUTH_EAST) spawn_npc(npc = Npcs.ROCK_CRITTER, x = 3670, z = 5090, walkRadius = 5, direction = Direction.NORTH_WEST) spawn_npc(npc = Npcs.ROCK_CRITTER, x = 3678, z = 5101, walkRadius = 5, direction = Direction.WEST) spawn_npc(npc = Npcs.CAVEFISH_SHOAL, x = 3653, z = 5085, direction = Direction.SOUTH, static = true) spawn_npc(npc = Npcs.CAVEFISH_SHOAL, x = 3674, z = 5115, direction = Direction.NORTH, static = true) spawn_npc(npc = Npcs.ROCKTAIL_SHOAL, x = 3684, z = 5109, direction = Direction.EAST, static = true)
39
null
82
34
e5400cc71bfa087164153d468979c5a3abc24841
2,213
game
Apache License 2.0
indispensable-josef/src/jvmTest/kotlin/at/asitplus/signum/indispensable/josef/JwkTest.kt
a-sit-plus
700,518,667
false
{"Kotlin": 1106936, "Swift": 554}
package at.asitplus.signum.indispensable.josef import at.asitplus.signum.indispensable.* import at.asitplus.signum.indispensable.asn1.Asn1String import at.asitplus.signum.indispensable.asn1.Asn1Time import at.asitplus.signum.indispensable.io.Base64Strict import at.asitplus.signum.indispensable.pki.AttributeTypeAndValue import at.asitplus.signum.indispensable.pki.RelativeDistinguishedName import at.asitplus.signum.indispensable.pki.TbsCertificate import at.asitplus.signum.indispensable.pki.X509Certificate import at.asitplus.signum.indispensable.josef.JsonWebAlgorithm import at.asitplus.signum.indispensable.josef.JsonWebKey import at.asitplus.signum.indispensable.josef.JwkType import com.ionspin.kotlin.bignum.integer.BigInteger import com.ionspin.kotlin.bignum.integer.Sign import io.kotest.core.spec.style.FreeSpec import io.kotest.datatest.withData import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import io.kotest.property.azstring import io.matthewnelson.encoding.core.Encoder.Companion.encodeToString import kotlinx.datetime.Clock import java.security.KeyPairGenerator import java.security.interfaces.ECPublicKey import kotlin.random.Random class JwkTest : FreeSpec({ "EC" - { withData(256, 384, 521) { bits -> val keys = List<ECPublicKey>(10) { val ecKp = KeyPairGenerator.getInstance("EC").apply { initialize(bits) }.genKeyPair() ecKp.public as ECPublicKey } withData( nameFn = { "(x: ${ it.w.affineX.toByteArray().encodeToString(Base64Strict) } y: ${it.w.affineY.toByteArray().encodeToString(Base64Strict)})" }, keys ) { pubKey -> val cryptoPubKey = CryptoPublicKey.EC.fromJcaPublicKey(pubKey).getOrThrow().also { it.jwkId = it.didEncoded } val own = cryptoPubKey.toJsonWebKey() own.keyId shouldBe cryptoPubKey.jwkId own.shouldNotBeNull() println(own.serialize()) own.toCryptoPublicKey().getOrThrow().iosEncoded shouldBe cryptoPubKey.iosEncoded CryptoPublicKey.fromDid(own.keyId!!) shouldBe cryptoPubKey } } } "Serialize and deserialize EC" { val jwk = JsonWebKey( curve = ECCurve.SECP_256_R_1, type = JwkType.EC, x = Random.nextBytes(32), y = Random.nextBytes(32), publicKeyUse = Random.nextBytes(16).encodeToString(Base64Strict), keyOperations = setOf(Random.nextBytes(16).encodeToString(Base64Strict)), certificateUrl = Random.nextBytes(16).encodeToString(Base64Strict), certificateChain = listOf(randomCertificate()), certificateSha1Thumbprint = Random.nextBytes(20), certificateSha256Thumbprint = Random.nextBytes(32), ) val serialized = jwk.serialize().also { println(it) } val parsed = JsonWebKey.deserialize(serialized).getOrThrow() parsed shouldBe jwk } "Serialize and deserialize Algos" - { withData(JsonWebAlgorithm.entries) { jwa -> val jwk = JsonWebKey( curve = ECCurve.SECP_256_R_1, type = JwkType.EC, algorithm = jwa, x = Random.nextBytes(32), y = Random.nextBytes(32), publicKeyUse = Random.nextBytes(16).encodeToString(Base64Strict), keyOperations = setOf(Random.nextBytes(16).encodeToString(Base64Strict)), certificateUrl = Random.nextBytes(16).encodeToString(Base64Strict), certificateChain = listOf(randomCertificate()), certificateSha1Thumbprint = Random.nextBytes(20), certificateSha256Thumbprint = Random.nextBytes(32), ) val serialized = jwk.serialize().also { println(it) } val parsed = JsonWebKey.deserialize(serialized).getOrThrow() parsed shouldBe jwk } } "Serialize and deserialize RSA" { val jwk = JsonWebKey( type = JwkType.RSA, n = Random.nextBytes(64), e = Random.nextBytes(8), publicKeyUse = Random.nextBytes(16).encodeToString(Base64Strict), keyOperations = setOf(Random.nextBytes(16).encodeToString(Base64Strict)), certificateUrl = Random.nextBytes(16).encodeToString(Base64Strict), certificateChain = listOf(randomCertificate()), certificateSha1Thumbprint = Random.nextBytes(20), certificateSha256Thumbprint = Random.nextBytes(32), ) val parsed = JsonWebKey.deserialize(jwk.serialize()).getOrThrow() parsed shouldBe jwk } "Regression test: JWK (no keyId) -> CryptoPublicKey -> JWK (no keyId)" { val key = randomCertificate().publicKey.toJsonWebKey() key.keyId shouldBe null val cpk = key.toCryptoPublicKey().getOrThrow() cpk.toJsonWebKey().keyId shouldBe null val kid = Random.azstring(16) cpk.toJsonWebKey(keyId = kid).keyId shouldBe kid } }) private fun randomCertificate() = X509Certificate( TbsCertificate( serialNumber = Random.nextBytes(16), issuerName = listOf(RelativeDistinguishedName(AttributeTypeAndValue.CommonName(Asn1String.Printable("Test")))), publicKey = CryptoPublicKey.EC.fromJcaPublicKey(KeyPairGenerator.getInstance("EC").apply { initialize(256) } .genKeyPair().public as ECPublicKey).getOrThrow(), signatureAlgorithm = X509SignatureAlgorithm.ES256, subjectName = listOf(RelativeDistinguishedName(AttributeTypeAndValue.CommonName(Asn1String.Printable("Test")))), validFrom = Asn1Time(Clock.System.now()), validUntil = Asn1Time(Clock.System.now()), ), X509SignatureAlgorithm.ES256, CryptoSignature.EC.fromRS( BigInteger.fromByteArray(Random.nextBytes(16), Sign.POSITIVE), BigInteger.fromByteArray(Random.nextBytes(16), Sign.POSITIVE) ) )
17
Kotlin
2
41
d40a11909be205a55e424699323cb0044433bf81
6,190
signum
Apache License 2.0
src/main/kotlin/com/marufh/photo/security/repository/UserRepository.kt
akorshon
737,740,614
false
{"Kotlin": 124302}
package com.marufh.photo.security.repository import com.marufh.photo.security.entity.User import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Query interface UserRepository : JpaRepository<User, String>{ @Query("SELECT u FROM User u JOIN FETCH u.roles WHERE u.email = ?1") fun findByEmail(email: String): User? //@Query("SELECT u FROM User u WHERE u.email=:email") //fun findByEmail(@Param("email") email: String?): Optional<User?>? }
0
Kotlin
0
0
0920792f25a75f2cc52c915e789ef6f6a64a3659
511
photo-server
Apache License 2.0
app/src/main/java/edu/uoc/avalldeperas/eatsafe/auth/data/UsersRepository.kt
avalldeperas
767,722,753
false
{"Kotlin": 279197}
package edu.uoc.avalldeperas.eatsafe.auth.data import edu.uoc.avalldeperas.eatsafe.auth.domain.model.User import kotlinx.coroutines.flow.Flow interface UsersRepository { val user: User fun getUser(userId: String): Flow<User?> suspend fun save(user: User): Boolean suspend fun update(user: User): Boolean }
2
Kotlin
0
1
bea2e59bdb80779ae7cac19f4e3ed85ad7b285d3
323
EatSafe
Creative Commons Attribution 4.0 International
miniapp/src/main/java/com/rakuten/tech/mobile/miniapp/api/ApiClientRepository.kt
rakutentech
225,744,634
false
{"Kotlin": 1372714}
package com.rakuten.tech.mobile.miniapp.api import androidx.collection.ArrayMap import com.rakuten.tech.mobile.miniapp.MiniAppSdkConfig internal class ApiClientRepository { private val apiClients: MutableMap<MiniAppSdkConfig, ApiClient> = ArrayMap() fun registerApiClient(config: MiniAppSdkConfig, apiClient: ApiClient) = apiClients.put(config, apiClient) fun getApiClientFor(config: MiniAppSdkConfig): ApiClient? = apiClients[config] }
9
Kotlin
35
73
466c9551161b1240cc4963d7108a342355b983de
453
android-miniapp
MIT License
app/src/main/java/com/example/androiddevchallenge/WeatherOvertureRepository.kt
afterefx
349,598,364
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge class WeatherOvertureRepository { private val api = NetworkModule.api suspend fun getWeatherZip(zip: String) = api.getCurrentWeatherZip(zip) suspend fun getWeatherCity(city: String) = api.getCurrentWeatherCity(city) suspend fun getForcastZip(zip: String) = api.getForcastZip(zip) suspend fun getForecastCity(city: String) = api.getForcastCity(city) }
0
Kotlin
0
1
cc217effbeedd92f219c5b6d080797b9aefa01a7
1,032
WeatherOverture
Apache License 2.0
src/test/kotlin/no/nav/modiapersonoversikt/ApplicationTest.kt
navikt
186,823,411
false
{"CSS": 157055, "TypeScript": 66009, "Kotlin": 57784, "SCSS": 6658, "HTML": 949, "Less": 437, "Shell": 313, "Dockerfile": 137}
package no.nav.modiapersonoversikt import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.server.testing.* import no.nav.modiapersonoversikt.skrivestotte.model.Tekst import no.nav.modiapersonoversikt.skrivestotte.model.Tekster import no.nav.modiapersonoversikt.utils.fromJson import org.junit.jupiter.api.Test import java.util.* import kotlin.test.assertEquals class ApplicationTest : WithDatabase { @Test fun `should load backup if database is empty`() { withExternalDependencies { withTestApp(connectionUrl()) { val response = getTexts() assertEquals(response.status, 200) assertEquals(response.data.size, 811) } } } @Test fun `should filter resultset based on tags`() { withExternalDependencies { withTestApp(connectionUrl()) { val response = getTexts(tags = listOf("sto")) assertEquals(response.status, 200) assertEquals(response.data.size, 231) } } } } class JsonResponse<T>(val status: Int, val data: T) suspend fun ApplicationTestBuilder.getTexts( tags: List<String> = emptyList(), usageSort: Boolean = false ): JsonResponse<Tekster> { val queryParams = tags .map { "tags" to it } .plus("usageSort" to usageSort) .map { "${it.first}=${it.second}" } .joinToString("&") .let { if (it.isNotEmpty()) "?$it" else "" } val response = client.get("/modiapersonoversikt-skrivestotte/skrivestotte$queryParams") val data = response.bodyAsText().fromJson<Map<UUID, Tekst>>() return JsonResponse(response.status.value, data) }
5
CSS
0
0
9ba027348ae96bc3ce09e57e50944a6913772861
1,717
modiapersonoversikt-skrivestotte
MIT License
app/src/main/java/com/example/androiddevchallenge/ui/components/PetGrid.kt
Trak-X
343,113,094
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.ui.components import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import com.example.androiddevchallenge.db.PetObj @Composable fun PetGrid(names: List<PetObj>, onPetSelected: (PetObj) -> Unit) { LazyColumn { items(count = names.size) { pet -> PetCard(pet = names[pet], onPetSelected) } } }
0
Kotlin
0
0
426fc10e1e304ce9959127b83193e09ff82fb5d4
1,026
Petoption
Apache License 2.0
pastelPlaceholder/src/main/java/com/zedlabs/pastelplaceholder/LightColors.kt
zedlabs
306,322,831
false
null
package com.zedlabs.pastelplaceholder object LightColors { val list: List<Int> = listOf( R.color.green, R.color.pink, R.color.orange, R.color.orange_alternate, R.color.blue, R.color.blue_mid, R.color.brown, R.color.green_mid, R.color.pink_high ) }
0
Kotlin
0
5
413d77b8d3038f8f193ced8c3ad7002bd5f6a4dd
318
pastelPlaceholders
Apache License 2.0
src/main/kotlin/org/oso/core/services/EmergencyStatusTypeService.kt
OSOSystem
156,911,157
false
null
package org.oso.core.services import org.oso.core.entities.EmergencyStatusType interface EmergencyStatusTypeService { fun findByName(name: String): EmergencyStatusType }
14
Kotlin
4
12
70473b0dca460ff313f5d839b7d166efdd11d0fb
175
oso-backend
Apache License 2.0
src/commonTest/kotlin/com/github/murzagalin/evaluator/integration/DoubleValuesTests.kt
murzagalin
406,453,824
false
{"Kotlin": 95637}
package com.github.murzagalin.evaluator.integration import com.github.murzagalin.evaluator.Evaluator import kotlin.math.pow import kotlin.test.Test import kotlin.test.assertEquals class DoubleValuesTests { private val evaluator = Evaluator() @Test fun simple_value() { assertEquals(3214.235, evaluator.evaluateDouble("3214.235")) } @Test fun sum() { assertEquals(3214.235+23576.1245+375.23576+1756.135, evaluator.evaluateDouble("3214.235+23576.1245+375.23576+1756.135")) } @Test fun double_with_int() { assertEquals(23+0.123*(124/60.124), evaluator.evaluateDouble("23+0.123*(124/60.124)")) } @Test fun expressions() { assertEquals(3 * 23.toDouble().pow(3.2), evaluator.evaluateDouble("23^3.2*3")) } }
0
Kotlin
3
25
2d91e011a22f918667d2c48dc45fbea85312314f
791
multiplatform-expressions-evaluator
Apache License 2.0
app/src/main/java/com/example/parstagram/EditProfile.kt
sureshritika
551,484,347
false
null
package com.example.parstagram import android.content.Intent import android.graphics.BitmapFactory import android.graphics.Color import android.net.Uri import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.util.Log import android.view.MenuItem import android.view.View import android.widget.* import androidx.appcompat.app.ActionBar import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.content.FileProvider import androidx.core.view.children import androidx.core.view.get import androidx.core.view.iterator import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.parse.ParseFile import com.parse.ParseUser import java.io.File import java.io.FileOutputStream import java.io.InputStream class EditProfile : AppCompatActivity() { lateinit var profileImg : ImageView lateinit var changeProfImgBtn : Button lateinit var profileInfoLayout : TableLayout lateinit var nameInfoTxt : TextView lateinit var usernameInfoTxt : TextView lateinit var bioInfoTxt : TextView lateinit var cancelBtn : Button lateinit var doneBtn : Button lateinit var doneProgress : ProgressBar var row : Int = 0 var CHANGE_PROFILE_INFO_REQUEST_CODE = 1234 var photoFileName = "profileImg.jpg" var photoFile: File? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_edit_profile) supportActionBar!!.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM supportActionBar!!.setDisplayShowCustomEnabled(true) supportActionBar!!.setCustomView(R.layout.header_edit_profile) val view = supportActionBar!!.customView (view.parent as Toolbar).setContentInsetsAbsolute(0 , 0) profileImg = findViewById(R.id.id_profileImg) changeProfImgBtn = findViewById(R.id.id_changeProfImgBtn) profileInfoLayout = findViewById(R.id.id_profileInfoLayout) nameInfoTxt = findViewById(R.id.id_nameInfoTxt) usernameInfoTxt = findViewById(R.id.id_usernameInfoTxt) bioInfoTxt = findViewById(R.id.id_bioInfoTxt) cancelBtn = findViewById(R.id.id_cancelBtn) doneBtn = findViewById(R.id.id_doneBtn) doneProgress = findViewById(R.id.id_doneProgress) Glide.with(this).load(ParseUser.getCurrentUser().getParseFile("profileImage")?.url).apply(RequestOptions.circleCropTransform()).into(profileImg) nameInfoTxt.text = ParseUser.getCurrentUser().getString("name") usernameInfoTxt.text = ParseUser.getCurrentUser().getString("username") bioInfoTxt.text = ParseUser.getCurrentUser().getString("bio") profileInfoLayout.iterator().forEach { it -> it.setOnClickListener { it as TableRow row = profileInfoLayout.indexOfChild(it) val item = ((it)[0] as TextView).text val itemInfo = ((it)[1] as TextView).text Log.d("RITIKA" , "sending item: ${item} ; itemInfo: ${itemInfo}") val intent = Intent(this , EditProfileItem::class.java) intent.putExtra("item" , "$item") intent.putExtra("itemInfo" , "$itemInfo") startActivityForResult(intent , CHANGE_PROFILE_INFO_REQUEST_CODE) } } cancelBtn.setOnClickListener { finish() } doneBtn.setOnClickListener { Log.d("RITIKA" , "turn loading prog on ${doneProgress}") progressOn() ParseUser.getCurrentUser().put("name" , nameInfoTxt.text) ParseUser.getCurrentUser().put("username" , usernameInfoTxt.text) ParseUser.getCurrentUser().put("bio" , bioInfoTxt.text) Log.d("RITIKA" , "photogile $photoFile") if (photoFile != null) ParseUser.getCurrentUser().put("profileImage" , ParseFile(photoFile)) ParseUser.getCurrentUser().saveInBackground() { exception -> Log.d("RITIKA" , "turn loading prog off ${doneProgress}") progressOff() if (exception != null) { // Something has went wrong Log.e("RITIKA" , "doneBtn failure ${exception}") exception.printStackTrace() } else { Log.i("RITIKA" , "doneBtn success") setResult(RESULT_OK , intent) finish() } } } changeProfImgBtn.setOnClickListener { val popup = PopupMenu(this, changeProfImgBtn) popup.menuInflater.inflate(R.menu.change_prof_img_menu, popup.menu) popup.setOnMenuItemClickListener(object : MenuItem.OnMenuItemClickListener, PopupMenu.OnMenuItemClickListener { override fun onMenuItemClick(item: MenuItem): Boolean { if (item.itemId == R.id.id_takePhotoBtn) { Log.d("RITIKA" , "takephoto") onLaunchCamera() } if (item.itemId == R.id.id_chooseFromGalleryBtn) { Log.d("RITIKA" , "gallery") onPickPhoto() } return true } }) popup.show() } } fun progressOn() { doneProgress.visibility = View.VISIBLE findViewById<RelativeLayout>(R.id.id_editProfileLayout)?.children?.iterator()?.forEach { it.isEnabled = false it.alpha = 0.25F } profileInfoLayout.children.forEach { (it as TableRow).isEnabled = false } cancelBtn.isEnabled = false cancelBtn.alpha = 0.25F doneBtn.isEnabled = false doneBtn.alpha = 0.25F } fun progressOff() { doneProgress.visibility = View.GONE findViewById<RelativeLayout>(R.id.id_editProfileLayout)?.children?.iterator()?.forEach { it.isEnabled = true it.alpha = 1F } profileInfoLayout.children.forEach { (it as TableRow).isEnabled = true } cancelBtn.isEnabled = true cancelBtn.alpha = 1F doneBtn.isEnabled = true doneBtn.alpha = 1F } fun onLaunchCamera() { val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) photoFile = getPhotoFileUri(photoFileName) Log.d("RITIKA" , "launch file $photoFile") if (photoFile != null) { val fileProvider: Uri = FileProvider.getUriForFile(this, "com.codepath.fileprovider", photoFile!!) intent.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider) if (intent.resolveActivity(this.packageManager) != null) { startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) } } } fun getPhotoFileUri(fileName: String): File { val mediaStorageDir = File(this.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "RITIKA") if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) { Log.d("RITIKA", "failed to create directory") } return File(mediaStorageDir.path + File.separator + fileName) } fun onPickPhoto() { val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) if (intent.resolveActivity(packageManager) != null) { startActivityForResult(intent, PICK_PHOTO_CODE) } } fun loadFromStream(inputStream : InputStream) { val storeDirectory = this.getExternalFilesDir(Environment.DIRECTORY_DCIM) // DCIM folder photoFile = File(storeDirectory, photoFileName) inputStream.use { input -> val outputStream = FileOutputStream(photoFile) outputStream.use { output -> val buffer = ByteArray(4 * 1024) // buffer size while (true) { val byteCount = input.read(buffer) if (byteCount < 0) break output.write(buffer, 0, byteCount) } output.flush() } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == RESULT_OK && requestCode == CHANGE_PROFILE_INFO_REQUEST_CODE) { val itemInfo = data?.getStringExtra("itemInfo") Log.d("RITIKA" , "got from editprofileitem to editprofile ${itemInfo}") ((profileInfoLayout[row] as TableRow)[1] as TextView).text = itemInfo } if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { val takenImage = BitmapFactory.decodeFile(photoFile!!.absolutePath) Glide.with(this).load(takenImage).apply(RequestOptions.circleCropTransform()).into(profileImg) } else { Log.d("RITIKA" , "picture wasn't taken") val toast = Toast.makeText(this, "Was not able to take picture. Please try again later.", Toast.LENGTH_LONG); toast.view?.setBackgroundColor(Color.RED) toast.show() } } if (requestCode === PICK_PHOTO_CODE && data != null) { val inputStream: InputStream = this.getContentResolver().openInputStream(data.data!!)!! loadFromStream(inputStream) val takenImage = BitmapFactory.decodeFile(photoFile!!.absolutePath) Glide.with(this).load(takenImage).apply(RequestOptions.circleCropTransform()).into(profileImg) } } companion object { val CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1034 val PICK_PHOTO_CODE = 1046 } }
2
Kotlin
0
0
b51a7cbaf403a98c4024ca083363da92ad5e3eb2
9,901
Parstagram
Apache License 2.0
feature-proxy-api/src/main/java/io/novafoundation/nova/feature_proxy_api/data/calls/ExtrinsicBuilderExt.kt
novasamatech
415,834,480
false
{"Kotlin": 11112596, "Rust": 25308, "Java": 17664, "JavaScript": 425}
package io.novafoundation.nova.feature_proxy_api.data.calls import io.novafoundation.nova.common.utils.Modules import io.novafoundation.nova.feature_proxy_api.domain.model.ProxyType import java.math.BigInteger import io.novasama.substrate_sdk_android.runtime.AccountId import io.novasama.substrate_sdk_android.runtime.RuntimeSnapshot import io.novasama.substrate_sdk_android.runtime.definitions.types.composite.DictEnum import io.novasama.substrate_sdk_android.runtime.definitions.types.instances.AddressInstanceConstructor import io.novasama.substrate_sdk_android.runtime.extrinsic.ExtrinsicBuilder fun ExtrinsicBuilder.addProxyCall(proxyAccountId: AccountId, proxyType: ProxyType): ExtrinsicBuilder { return call( Modules.PROXY, "add_proxy", argumentsForProxy(runtime, proxyAccountId, proxyType) ) } fun ExtrinsicBuilder.removeProxyCall(proxyAccountId: AccountId, proxyType: ProxyType): ExtrinsicBuilder { return call( Modules.PROXY, "remove_proxy", argumentsForProxy(runtime, proxyAccountId, proxyType) ) } private fun argumentsForProxy(runtime: RuntimeSnapshot, proxyAccountId: AccountId, proxyType: ProxyType): Map<String, Any> { return mapOf( "delegate" to AddressInstanceConstructor.constructInstance(runtime.typeRegistry, proxyAccountId), "proxy_type" to DictEnum.Entry(proxyType.name, null), "delay" to BigInteger.ZERO ) }
14
Kotlin
30
50
166755d1c3388a7afd9b592402489ea5ca26fdb8
1,432
nova-wallet-android
Apache License 2.0
app/src/main/java/app/airsignal/weather/view/widget/BaseWidgetProvider.kt
tekken5953
611,614,821
false
{"Kotlin": 418472, "Java": 2615}
package app.airsignal.weather.view.widget import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.os.Build import app.airsignal.weather.api.retrofit.ApiModel import app.airsignal.weather.api.retrofit.HttpClient import app.airsignal.weather.db.sp.GetAppInfo import app.airsignal.weather.db.sp.SetAppInfo import app.airsignal.weather.utils.DataTypeParser.getCurrentTime import app.airsignal.weather.view.perm.RequestPermissionsUtil import org.koin.core.component.KoinComponent import org.koin.core.component.inject import retrofit2.awaitResponse import java.time.LocalDateTime open class BaseWidgetProvider: AppWidgetProvider(), KoinComponent { companion object { const val REFRESH_BUTTON_CLICKED = "app.airsignal.weather.view.widget.REFRESH_DATA" const val ENTER_APPLICATION = "app.airsignal.weather.view.widget.ENTER_APP" const val REFRESH_BUTTON_CLICKED_42 = "app.airsignal.weather.view.widget.REFRESH_DATA42" const val ENTER_APPLICATION_42 = "app.airsignal.weather.view.widget.ENTER_APP42" const val WIDGET_42 = "42" const val WIDGET_22 = "22" } private val httpClient: HttpClient by inject() suspend fun requestWeather(lat: Double, lng: Double, rCount: Int): ApiModel.WidgetData? = kotlin.runCatching { httpClient.retrofit .getWidgetForecast(lat, lng, rCount) .awaitResponse().body() }.getOrNull() fun requestPermissions(context: Context, sort: String, id: Int?) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return if (RequestPermissionsUtil(context).isBackgroundRequestLocation()) return val intent = Intent(context, WidgetPermActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK putExtra("sort",sort) putExtra("id",id) } context.startActivity(intent) } fun currentIsAfterRealtime(currentTime: String, realTime: String?): Boolean = LocalDateTime.parse(realTime)?.let {LocalDateTime.parse(currentTime).isAfter(it)} ?: true fun isRefreshable(context: Context, type: String): Boolean { val currentTime = getCurrentTime() val lastRefresh = when (type) { WIDGET_42 -> GetAppInfo.getLastRefreshTime42(context) WIDGET_22 -> GetAppInfo.getLastRefreshTime22(context) else -> currentTime } return currentTime - lastRefresh >= 1000 * 60 } fun setRefreshTime(context: Context, type: String) { if (type == WIDGET_42) SetAppInfo.setLastRefreshTime42(context, getCurrentTime()) else if (type == WIDGET_22) SetAppInfo.setLastRefreshTime22(context, getCurrentTime()) } }
0
Kotlin
1
1
36011d3ad2bdc9e0a7f02007de9b65557639da22
2,776
AS_Cloud_App
Open Market License
core/navigation/src/main/kotlin/br/com/mob1st/core/navigation/Navigable.kt
mob1st
526,655,668
false
{"Kotlin": 444566, "Shell": 1558}
package br.com.mob1st.core.navigation import androidx.compose.runtime.Immutable /** * Helper function for a class to provide a [NavTarget] as part of the state of the UI. * * This can be used to side-effect navigation events triggered by ViewModels to the UI layer. * With this interface is possible to match the same name convention in the project. */ @Immutable interface Navigable<T : NavTarget> { val navTarget: T }
11
Kotlin
0
3
f13bcd2a645dc7c51385c5ef414a4d6a4d09194c
432
bet-app-android
Apache License 2.0
app/src/main/java/com/niyaj/popos/features/reminder/presentation/daily_salary_reminder/DailySalaryReminderWorkerViewModel.kt
skniyajali
579,613,644
false
null
package com.niyaj.popos.features.reminder.presentation.daily_salary_reminder import android.app.Application import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.core.net.toUri import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import com.niyaj.popos.R import com.niyaj.popos.features.MainActivity import com.niyaj.popos.features.employee.domain.repository.EmployeeRepository import com.niyaj.popos.features.reminder.domain.model.DailySalaryReminder import com.niyaj.popos.features.reminder.domain.model.toReminder import com.niyaj.popos.features.reminder.domain.repository.ReminderRepository import com.niyaj.popos.features.reminder.presentation.absent_reminder.EmployeeAbsentReminderWorker import com.niyaj.popos.utils.Constants.DAILY_SALARY_REMINDER_ID import com.niyaj.popos.utils.Constants.DAILY_SALARY_REMINDER_TEXT import com.niyaj.popos.utils.Constants.DAILY_SALARY_REMINDER_TITLE import com.niyaj.popos.utils.Constants.SALARY_HOST import com.niyaj.popos.utils.showPendingIntentNotification import com.niyaj.popos.utils.stopPendingIntentNotification import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.concurrent.TimeUnit import javax.inject.Inject @HiltViewModel class DailySalaryReminderWorkerViewModel @Inject constructor( private val reminderRepository : ReminderRepository, private val employeeRepository : EmployeeRepository, application: Application, ): ViewModel() { private val workManager = WorkManager.getInstance(application.applicationContext) private val currentTime = System.currentTimeMillis().toString() private val _salaryReminder = MutableStateFlow(DailySalaryReminder()) val salaryReminder = _salaryReminder.asStateFlow() private val doesEmployeeExist = employeeRepository.doesAnyEmployeeExist() val salaryWorker = PeriodicWorkRequestBuilder<EmployeeAbsentReminderWorker>( _salaryReminder.value.reminderInterval.toLong(), TimeUnit.valueOf(_salaryReminder.value.reminderIntervalTimeUnit) ).addTag(_salaryReminder.value.dailySalaryRemId).build() private val dailyReminderIntent = Intent( Intent.ACTION_VIEW, SALARY_HOST.toUri(), application.applicationContext, MainActivity::class.java ) private val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.getActivity( /* context = */ application.applicationContext, /* requestCode = */ 0, /* intent = */ dailyReminderIntent, /* flags = */ PendingIntent.FLAG_IMMUTABLE ) }else { PendingIntent.getActivity( /* context = */ application.applicationContext, /* requestCode = */ 0, /* intent = */ dailyReminderIntent, /* flags = */ PendingIntent.FLAG_UPDATE_CURRENT ) } init { getDailySalaryReminderOnCurrentDate(application.applicationContext) } private fun getDailySalaryReminderOnCurrentDate(context : Context) { viewModelScope.launch { if (doesEmployeeExist) { val reminder = reminderRepository.getDailySalaryReminder() if (reminder == null || _salaryReminder.value.reminderStartTime != reminder.reminderStartTime) { withContext(Dispatchers.IO) { reminderRepository.createOrUpdateReminder(_salaryReminder.value.toReminder()) } } _salaryReminder.value = reminderRepository.getDailySalaryReminder()!! enqueueDailySalaryReminderWorker(context) } } } private fun enqueueDailySalaryReminderWorker(context: Context) { if (!_salaryReminder.value.isCompleted) { if (currentTime in _salaryReminder.value.reminderStartTime .. _salaryReminder.value.reminderEndTime) { workManager.enqueueUniquePeriodicWork( _salaryReminder.value.reminderName, ExistingPeriodicWorkPolicy.KEEP, salaryWorker ) showPendingIntentNotification( context = context, notificationId = _salaryReminder.value.notificationId, pendingIntent = pendingIntent, channelId = DAILY_SALARY_REMINDER_ID, title = DAILY_SALARY_REMINDER_TITLE, text = DAILY_SALARY_REMINDER_TEXT, icon = R.drawable.baseline_account ) } }else { workManager.cancelWorkById(salaryWorker.id) stopPendingIntentNotification(context, _salaryReminder.value.notificationId) } } }
4
Kotlin
0
1
6e00bd5451336314b99f6ae1f1f43eea0f2079ad
5,156
POS-Application
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/dynamodb/GlobalSecondaryIndexPropsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.dynamodb import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.dynamodb.GlobalSecondaryIndexProps @Generated public fun buildGlobalSecondaryIndexProps(initializer: @AwsCdkDsl GlobalSecondaryIndexProps.Builder.() -> Unit): GlobalSecondaryIndexProps = GlobalSecondaryIndexProps.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
449
aws-cdk-kt
Apache License 2.0
app/src/main/java/com/thejoyrun/androidrouter/demo/KotlinActivity.kt
yznyan
206,520,237
true
{"Java": 56651, "Kotlin": 9040}
package com.thejoyrun.androidrouter.demo import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.TextView import com.thejoyrun.router.* import com.thejoyrun.router.RouterActivity @RouterActivity("fourth") class KotlinActivity : AppCompatActivity() { private val uid: Long by routerLongArgOr("uid") private val age: Int by routerIntArgOr("age") private val name: String by routerStringArgOr("name") private val man:Boolean by routerBooleanArgOr("man", true) private val manger: Boolean by routerBooleanArgOr("manger", false) private val formActivity: String by routerStringArgOr("formActivity") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_third) val builder = StringBuilder() builder.append("uid:$uid").append('\n') builder.append("age:$age").append('\n') builder.append("name:$name").append('\n') builder.append("man:$man").append('\n') builder.append("manger:$manger").append('\n') builder.append("formActivity:$formActivity").append('\n') val textView = findViewById<View>(R.id.text) as TextView textView.text = builder.toString() } }
0
null
0
0
4e1af7350963b8dab42efd52c4accd6b09e2de39
1,346
ActivityRouter
Apache License 2.0
FruitSeller/src/main/kotlin/furhatos/app/fruitseller/main.kt
FurhatRobotics
418,899,332
false
null
package furhatos.app.fruitseller import furhatos.app.fruitseller.flow.* import furhatos.skills.Skill import furhatos.flow.kotlin.* class FruitsellerSkill : Skill() { override fun start() { Flow().run(Init) } } fun main(args: Array<String>) { Skill.main(args) }
1
null
12
4
70aa5af3ca6f1d4a1e81f01db9d86444aa838043
284
tutorials
MIT License
app/src/main/java/net/yslibrary/monotweety/login/domain/IsLoggedIn.kt
yshrsmz
69,078,478
false
{"Kotlin": 444779}
package net.yslibrary.monotweety.login.domain import io.reactivex.Single import net.yslibrary.monotweety.appdata.session.SessionRepository import javax.inject.Inject import javax.inject.Singleton @Singleton class IsLoggedIn @Inject constructor(private val sessionRepository: SessionRepository) { fun execute(): Single<Boolean> { return sessionRepository.getActiveSession() .map { token -> token.toNullable() != null } } }
10
Kotlin
25
113
7b5b5fe9e0b1dd4667a024d5e22947132b01c426
453
monotweety
Apache License 2.0
src/main/kotlin/com/falconer/utils/ui/EditTaskView.kt
Kyle-Falconer
374,835,129
false
null
package com.falconer.utils.ui import androidx.compose.desktop.AppManager import androidx.compose.foundation.layout.* import androidx.compose.material.Button import androidx.compose.material.OutlinedTextField import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.falconer.utils.task.* @Composable fun saveButton(originalModel: Runner, updatedModel: Runner, controller: Controller) { Button(modifier=Modifier.padding(10.dp), onClick = { controller.updateRunner(originalRunner=originalModel, updatedRunner=updatedModel) AppManager.focusedWindow?.close() }) { Text("Save changes") } } @Composable fun cancelButton() { Button(modifier=Modifier.padding(10.dp), onClick = { AppManager.focusedWindow?.close() }) { Text("cancel") } } @Composable fun editFieldsForPortType(model: PortRunner, controller: Controller) { var runnerName by remember { mutableStateOf(model.name) } var localPort by remember { mutableStateOf(model.localPort) } var remotePort by remember { mutableStateOf(model.remotePort) } Column (modifier = Modifier.fillMaxWidth().fillMaxWidth().fillMaxHeight().padding(10.dp)){ OutlinedTextField( label= {Text("name")}, value = runnerName, onValueChange = { runnerName=it }) OutlinedTextField( label= {Text("local port")}, value =localPort.toString(), onValueChange = { localPort=Integer.parseInt(it) }) OutlinedTextField( label= {Text("remote port")}, value =remotePort.toString(), onValueChange = { remotePort=Integer.parseInt(it) }) Row(modifier = Modifier.fillMaxWidth().fillMaxWidth().fillMaxHeight().padding(10.dp), horizontalArrangement = Arrangement.SpaceAround, verticalAlignment = Alignment.Bottom) { cancelButton() saveButton(originalModel =model, updatedModel = PortRunner(name = runnerName, localPort=localPort, remotePort = remotePort), controller = controller) } } } @Composable fun editFieldsForLongJob(model: LongRunner, controller: Controller) { var runnerName by remember { mutableStateOf(model.name) } var userScript by remember { mutableStateOf(model.userScript) } Column (modifier = Modifier.fillMaxWidth().fillMaxWidth().fillMaxHeight().padding(10.dp)){ OutlinedTextField( label= {Text("name")}, value = runnerName, onValueChange = { runnerName=it }) OutlinedTextField( label= {Text("script")}, value =userScript, onValueChange = { userScript=it }) Row(modifier = Modifier.fillMaxWidth().fillMaxWidth().fillMaxHeight().padding(10.dp), horizontalArrangement = Arrangement.SpaceAround, verticalAlignment = Alignment.Bottom) { cancelButton() saveButton(originalModel =model, updatedModel = LongRunner(name = runnerName, userScript=userScript), controller = controller) } } } @Composable fun editFieldsForNOTYETIMPLEMENTED(model: Runner, controller: Controller) { Column (modifier = Modifier.fillMaxWidth().fillMaxWidth().fillMaxHeight().padding(10.dp)){ Text("Editing of type ${model.runnerType} is not yet implemented") Row(modifier = Modifier.fillMaxWidth().fillMaxWidth().fillMaxHeight().padding(10.dp), horizontalArrangement = Arrangement.SpaceAround, verticalAlignment = Alignment.Bottom) { cancelButton() } } } @Composable fun editTaskView(controller: Controller, model: Runner) { val modelUnderEdit = model.clone() when(model.runnerType) { RunnerType.PORT -> editFieldsForPortType(modelUnderEdit as PortRunner, controller) RunnerType.LONG_JOB -> editFieldsForLongJob(modelUnderEdit as LongRunner, controller) RunnerType.COOKIE -> editFieldsForNOTYETIMPLEMENTED(modelUnderEdit, controller) RunnerType.MONITOR -> editFieldsForNOTYETIMPLEMENTED(modelUnderEdit, controller) RunnerType.DOCKER_MONITOR -> editFieldsForNOTYETIMPLEMENTED(modelUnderEdit, controller) } }
0
Kotlin
0
0
7fd3a01a5fb3ceae5b8ad87c8f82789e58e626d3
4,191
Forrest
Apache License 2.0
samples/star/src/main/kotlin/com/slack/circuit/star/di/Scopes.kt
slackhq
523,011,227
false
{"Kotlin": 226332, "Shell": 4085}
// Copyright (C) 2022 Slack Technologies, LLC // SPDX-License-Identifier: Apache-2.0 package com.slack.circuit.star.di import javax.inject.Scope import kotlin.reflect.KClass @Scope annotation class SingleIn(val scope: KClass<*>) class AppScope private constructor()
24
Kotlin
38
997
ba829880215a7ee0d8f70f86a8aa4278d0207827
269
circuit
Apache License 2.0
build-logic/katana-convention/src/main/kotlin/dev/alvr/katana/buildlogic/mp/mobile/KatanaMultiplatformMobileExtension.kt
alvr
446,535,707
false
null
package dev.alvr.katana.buildlogic.multiplatform import javax.inject.Inject import org.gradle.api.Project import org.jetbrains.kotlin.gradle.plugin.KotlinDependencyHandler open class KatanaMultiplatformMobileExtension @Inject constructor( project: Project ) : KatanaMultiplatformCoreExtension(project) { fun androidMainDependencies(dependencies: KotlinDependencyHandler.() -> Unit) { configureSourceSet("androidMain", dependencies) } fun androidUnitTestDependencies(dependencies: KotlinDependencyHandler.() -> Unit) { configureSourceSet("androidUnitTest", dependencies) } fun iosMainDependencies(dependencies: KotlinDependencyHandler.() -> Unit) { configureSourceSet("iosMain", dependencies) } fun iosTestDependencies(dependencies: KotlinDependencyHandler.() -> Unit) { configureSourceSet("iosTest", dependencies) } fun iosSimulatorMainDependencies(dependencies: KotlinDependencyHandler.() -> Unit) { configureSourceSet("iosSimulatorArm64Main", dependencies) } fun iosSimulatorTestDependencies(dependencies: KotlinDependencyHandler.() -> Unit) { configureSourceSet("iosSimulatorArm64Test", dependencies) } }
3
null
0
56
12a1bce0bb802079cba324d10e9a4da7df2bdc07
1,215
katana
Apache License 2.0
common/src/main/kotlin/dev/paulshields/assistantview/lang/AssistantViewClass.kt
Pkshields
445,326,540
false
{"Kotlin": 113569}
package dev.paulshields.assistantview.lang import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile interface AssistantViewClass { val project: Project val superClasses: List<AssistantViewClass> val interfaces: List<AssistantViewClass> val containingFile: VirtualFile? val name: String }
0
Kotlin
0
1
d4a9cb5ec8877522b007649898e5bfc071ba8055
341
AssistantView
MIT License
KotlinBoilerplate/core/src/main/java/com/tiknil/app/core/views/BaseFragment.kt
tiknil
231,347,612
false
null
package com.tiknil.app.core.views import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import androidx.annotation.LayoutRes import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.lifecycle.lifecycleScope import com.tiknil.app.core.viewmodels.AbstractBaseViewModel import com.tiknil.app.core.utils.ThreadUtils import com.trello.rxlifecycle4.components.support.RxFragment import dagger.android.support.AndroidSupportInjection import java.text.DateFormat /** * Fragment di base che racchiude le funzionalità comuni a tutti i fragment e predispone il link con il view model relativo */ abstract class BaseFragment<T: ViewDataBinding, V: AbstractBaseViewModel> : RxFragment() { //region Inner enums //endregion //region Constants //endregion //region Instance Fields protected lateinit var binding: T private lateinit var mViewModel: V private lateinit var mRootView: View private val isThisFragmentTheCurrentVisible: Boolean get() { val fragments = parentFragmentManager.fragments return fragments[fragments.size - 1] === this } protected var isViewAppeared = false var params: Any? = null set(value) { field = value if (::mViewModel.isInitialized) { viewModel().setParams(value) field = null } } var flowDelegate: Any? = null set(value) { field = value if (::mViewModel.isInitialized) { viewModel().flowDelegate = value } } protected var keyboardModeResizingView = false protected var defaultTimeFormat: DateFormat? = null private var needToSetupBinding = true //endregion //region Class methods //endregion //region Constructors / Lifecycle override fun onCreate(savedInstanceState: Bundle?) { performDependecyInjection() super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreateView(inflater, container, savedInstanceState) binding = DataBindingUtil.inflate(inflater, layoutId(), container, false) binding.lifecycleOwner = this mRootView = binding.root return mRootView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mViewModel = viewModel() mViewModel.onCreated() binding.setVariable(bindingVariable(), mViewModel) binding.executePendingBindings() setupUI() setupBinding() needToSetupBinding = false } override fun onStart() { super.onStart() viewModel().onStart() if (!isViewAppeared) { if (isThisFragmentTheCurrentVisible) { viewModel().flowDelegate = flowDelegate viewModel().setParams(params) ThreadUtils.runOnCoroutineScope(viewLifecycleOwner.lifecycleScope) { viewModel().onViewAppear() } isViewAppeared = true } } } override fun onStop() { super.onStop() isViewAppeared = false needToSetupBinding = true viewModel().onStop() } override fun onDestroy() { super.onDestroy() viewModel().onDestroy() } /** * Metodo chiamato quando il fragment viene visualizzato */ fun onViewAppear() { ThreadUtils.runOnUiThread { if (keyboardModeResizingView) { initKeyboardModeResizingView() } hideKeyboard() if(needToSetupBinding) { needToSetupBinding = false setupBinding() } if(!isViewAppeared) { viewModel().onViewAppear() } isViewAppeared = true } } /** * Metodo chiamato quando il fragment viene nascosto */ fun onViewDisappear() { ThreadUtils.runOnUiThread { isViewAppeared = false resetKeyboardToStandardMode() hideKeyboard() if (::mViewModel.isInitialized) { viewModel().onViewDisappear() } } } //endregion //region Custom accessors //endregion //region Public /** * Ritorna l'oggetto ViewModel * * @return l'istanza del view model */ abstract fun viewModel() : V /** * Ritorna il riferimento all'oggetto ViewDataBinding * * @return il riferimento all'oggetto ViewDataBinding */ abstract fun bindingVariable(): Int /** * Ritorna il layout * * @return il resource id del layout dell'activity */ @LayoutRes abstract fun layoutId(): Int //endregion //region Protected, without modifier /** * Imposta la UI, va eseguito l'override nelle classe figlie */ open protected fun setupUI() {} /** * Imposta il binding delle variabili RxJava, va eseguito l'override nelle classe figlie */ open protected fun setupBinding() {} /** * Nasconde la tastiera se visualizzata */ protected fun hideKeyboard() { if (activity != null && activity is BaseActivity<*, *>) { (activity as BaseActivity<*, *>).hideKeyboard() } } /** * Imposta il comportamento della tastiera */ protected fun initKeyboardModeResizingView() { if (activity != null && !requireActivity().isFinishing) { requireActivity().window .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) } } /** * Reimposta la tastiera al funzionamento standard */ protected fun resetKeyboardToStandardMode() { if (activity != null && !requireActivity().isFinishing) { requireActivity().window .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING) } } //endregion //region Private /** * Crea il graph di dependecy */ private fun performDependecyInjection() { AndroidSupportInjection.inject(this) } //endregion //region Override methods and callbacks //endregion //region Inner classes or interfaces //endregion }
0
Kotlin
0
0
3f23aff48af14ab54756aad4f5aad3ac2f6bd28b
6,678
kotlin-boilerplate-mvvm
Apache License 2.0
tvShowComponent/src/main/java/com/bitIO/tvshowcomponent/data/repository/TvShowRepositoryImpl.kt
Bit-Camp-IO
643,303,285
false
null
package com.bitIO.tvshowcomponent.data.repository import com.bitIO.tvshowcomponent.data.mapper.toTVShow import com.bitIO.tvshowcomponent.data.mapper.toTvShowDetails import com.bitIO.tvshowcomponent.data.mapper.toTvShowPage import com.bitIO.tvshowcomponent.data.remote.TvShowApiService import com.bitIO.tvshowcomponent.domain.entity.TvShow import com.bitIO.tvshowcomponent.domain.entity.TvShowDetails import com.bitIO.tvshowcomponent.domain.entity.TvShowPage import com.bitIO.tvshowcomponent.domain.repository.TvShowRepository import com.example.sharedComponent.entities.Video import com.example.sharedComponent.entities.credits.Credits import com.example.sharedComponent.entities.people.PersonDetails import com.example.sharedComponent.entities.review.Review import com.example.sharedComponent.mappers.toCredits import com.example.sharedComponent.mappers.toPersonDetails import com.example.sharedComponent.mappers.toReview import com.example.sharedComponent.mappers.toVideo import okhttp3.MediaType import okhttp3.RequestBody import javax.inject.Inject class TvShowRepositoryImpl @Inject constructor(private val api: TvShowApiService) : TvShowRepository { override suspend fun getPopularTvShows(pageIndex: Int): TvShowPage { return api.getPopularTvShows(pageIndex).toTvShowPage() } override suspend fun getOnTheAirTvShows(pageIndex: Int): TvShowPage { return api.getOnTheAirTvShows(pageIndex).toTvShowPage() } override suspend fun getTopRatedTvShows(pageIndex: Int): TvShowPage { return api.getTopRatedTvShows(pageIndex).toTvShowPage() } override suspend fun getTrendingTvShows(): TvShowPage { return api.getTrendyTvShows().toTvShowPage() } override suspend fun getSimilarTvShows(tvShowId: Int, pageIndex: Int): TvShowPage { return api.getSimilarTvShows(tvShowId, pageIndex).toTvShowPage() } override suspend fun getRecommendedTvShows(tvShowId: Int, pageIndex: Int): TvShowPage { return api.getRecommendations(tvShowId, pageIndex).toTvShowPage() } override suspend fun getSeriesVideos(tvShowId: Int): List<Video> { return api.getTvVideos(tvShowId).results.map { it.toVideo() } } override suspend fun searchSeries( keyword: String, includeAdults: Boolean, page: Int ): TvShowPage { return api.searchSeries(keyword, includeAdults, page).toTvShowPage() } override suspend fun getTvShowDetails(tvShowId: Int): TvShowDetails { return api.getTvShowDetails(tvShowId).toTvShowDetails() } override suspend fun getCredits(tvShowId: Int): Credits = api.getCredits(tvShowId).toCredits() override suspend fun getAiringTodayTvShows(pageIndex: Int): TvShowPage { return api.getAiringTodayTvShows().toTvShowPage() } override suspend fun getPersonDetails(personId: Int): PersonDetails { return api.getPersonDetails(personId).toPersonDetails() } override suspend fun getPersonSeries(personId: Int): List<TvShow> { return api.getPersonSeries(personId).cast.map { it.toTVShow() } } override suspend fun getBookMarkedSeries( accountId: Int, sessionId: String, page: Int ): TvShowPage { return api.getBookMarkedSeries(accountId, sessionId, page).toTvShowPage() } override suspend fun getTvShowReviews(tvShowId: Int): List<Review> { return api.getTvReviews(tvShowId,1).results.map { it.toReview()} } override suspend fun getTvSavedState(seriesId: Int,sessionId: String): Boolean { return api.getTvSavedState(seriesId, sessionId).watchList } override suspend fun addSeriesToWatchList(sessionId: String,seriesId: Int, isAddRequest: Boolean) { api.postToWatchList( accountId = 16874876, sessionId =sessionId, body = makePostToWatchListBody(type = "tv", mediaId = seriesId, isAddRequest) ) } private fun makePostToWatchListBody( type: String, mediaId: Int, isSaveRequest: Boolean ): RequestBody { val mediaType = MediaType.parse("application/json") return RequestBody.create( mediaType, "{\"media_type\":\"$type\",\"media_id\":\"$mediaId\",\"watchlist\":$isSaveRequest}" ) } }
0
Kotlin
1
2
82141ba5d053fe9c3112d1150b226aceb6125a48
4,325
TMDA-Android
Apache License 2.0
app/src/main/java/com/vkhooda24/knowyourcountry/ui/activities/CountryDetailActivity.kt
vkhooda24
164,041,872
false
null
package com.vkhooda24.knowyourcountry.ui.activities import android.app.Activity import android.os.Bundle import com.bumptech.glide.Glide import com.vkhooda24.knowyourcountry.R import com.vkhooda24.knowyourcountry.app.AppConstants import com.vkhooda24.knowyourcountry.constants.IntentKeys import com.vkhooda24.knowyourcountry.viewmodel.CountryDetailViewModel import com.vkhooda24.utils.StringUtil import dagger.android.AndroidInjection import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.activity_country_detail.* import javax.inject.Inject /** * Created by <NAME> on 12/24/18. */ class CountryDetailActivity : Activity() { internal var countryDetailViewModel: CountryDetailViewModel? = null @Inject set // can not assign null to this property i.e non nullable property private var countryName: String = AppConstants.DEFAULT_COUNTRY_NAME private val compositeDisposable by lazy { CompositeDisposable() } override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_country_detail) countryName = intent?.extras?.getString(IntentKeys.COUNTRY_NAME) ?: AppConstants.DEFAULT_COUNTRY_NAME countryNameTextView.text = countryName compositeDisposable.add(countryDetailViewModel!!.getCountryDetail(countryName).subscribe( { countryDetail -> val domainName = countryDetail?.topLevelDomain?.get(0) ?: "" val timezone = countryDetail?.timezones?.get(0) ?: "" countryNameTextView.text = countryDetail.name countryCapitalTextView.text = getString(R.string.capital, countryDetail.capital) countryNativeNameTextView.text = getString(R.string.native_name, countryDetail.nativeName) countryTopLevelDomainTextView.text = getString(R.string.domain_name, domainName) countryRegionTextView.text = getString(R.string.region_name, countryDetail.region) countrySubRegionTextView.text = getString(R.string.sub_region_name, countryDetail.subregion) countryTimeZoneTextView.text = getString(R.string.timezone, timezone) countryPopulationTextView.text = getString( R.string.population, StringUtil.formatNumberWithCommas(countryDetail?.population?.get(0).toString()) ) countryAlphaNameTextView.text = getString(R.string.alpha_code_name, countryDetail.alpha3Code) Glide.with(this).apply { load(AppConstants.IMAGE_NOT_FOUND_URL).into(countryFlagImageView) } }, // { it.printStackTrace() } { t: Throwable? -> t?.printStackTrace() } )) } }
0
Kotlin
0
0
aa83731fa9305ee4071e07afa7a62683c652cb09
2,921
Know-Your-Country-K.
Apache License 2.0
src/main/kotlin/com/mineinabyss/plugin/MineInAbyssPluginImpl.kt
MineInAbyss
115,279,675
false
null
package com.mineinabyss.plugin import com.mineinabyss.geary.api.addon.GearyLoadPhase.ENABLE import com.mineinabyss.geary.papermc.dsl.GearyAddon import com.mineinabyss.geary.papermc.dsl.gearyAddon import com.mineinabyss.geary.papermc.store.PrefabNamespaceMigrations import com.mineinabyss.guilds.database.GuildJoinQueue import com.mineinabyss.guilds.database.Guilds import com.mineinabyss.guilds.database.Players import com.mineinabyss.helpers.MessageQueue import com.mineinabyss.idofront.commands.Command import com.mineinabyss.idofront.commands.execution.IdofrontCommandExecutor import com.mineinabyss.idofront.platforms.IdofrontPlatforms import com.mineinabyss.idofront.plugin.getServiceOrNull import com.mineinabyss.idofront.plugin.registerService import com.mineinabyss.mineinabyss.core.* import net.milkbowl.vault.economy.Economy import org.bukkit.command.CommandSender import org.bukkit.command.TabCompleter import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.SchemaUtils import org.jetbrains.exposed.sql.StdOutSqlLogger import org.jetbrains.exposed.sql.addLogger import org.jetbrains.exposed.sql.transactions.transaction class MineInAbyssPluginImpl : MineInAbyssPlugin() { override fun onLoad() { IdofrontPlatforms.load(this, "mineinabyss") } override fun onEnable() { saveDefaultConfig() gearyAddon { PrefabNamespaceMigrations.migrations += listOf("looty" to "mineinabyss", "mobzy" to "mineinabyss") registerService<AbyssContext>(object : AbyssContext { override val econ = getServiceOrNull<Economy>("Vault") override val addonScope: GearyAddon = this@gearyAddon override val miaSubcommands = mutableListOf<Command.() -> Unit>() override val tabCompletions = mutableListOf<TabCompletion.() -> List<String>?>() override val db = Database.connect("jdbc:sqlite:" + dataFolder.path + "/data.db", "org.sqlite.JDBC") override val commandExecutor = object : IdofrontCommandExecutor(), TabCompleter { override val commands = commands(this@MineInAbyssPluginImpl) { ("mineinabyss" / "mia")(desc = "The main command for Mine in Abyss") { miaSubcommands.forEach { it() } } } override fun onTabComplete( sender: CommandSender, command: org.bukkit.command.Command, alias: String, args: Array<String> ): List<String> { val tab = TabCompletion(sender, command, alias, args) return tabCompletions.mapNotNull { it(tab) }.flatten() } } }) autoScanAll() autoScan<AbyssFeature>() startup { ENABLE { val config = MIAConfigImpl() config.load() registerService<MIAConfig>(config) registerService<AbyssWorldManager>(AbyssWorldManagerImpl()) } } } transaction(AbyssContext.db) { addLogger(StdOutSqlLogger) SchemaUtils.createMissingTablesAndColumns(Guilds, Players, GuildJoinQueue, MessageQueue) } } }
18
Kotlin
24
58
4ae8fc5c9e8dbc24e897f88b2801eeb552906237
3,433
MineInAbyss
MIT License
backend/src/main/kotlin/common/chat/ChatRepository.kt
MarceloATabone
771,157,093
false
{"Kotlin": 50233, "PLpgSQL": 357, "Dockerfile": 231}
package common.chat import application.DataBase.dbQuery import io.ktor.http.* import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq import util.* class ChatRepositoryImpl : ChatRepository { private fun ResultRow.toChat() = Chat( id = this[ChatTable.id], userId = this[ChatTable.userId], name = this[ChatTable.name], createAt = this[ChatTable.createAt].format(Formatting.formatterISO8601), updateAt = this[ChatTable.updatedAt].format(Formatting.formatterISO8601) ) override suspend fun get(id: Int): Either<Error, Chat> = dbQuery { ChatTable.select { ChatTable.id.eq(id) }.limit(1).singleOrNull()?.toChat() ?.let { Either.Success(it) } ?: Either.Failure( Error( HttpStatusCode.NotFound, ErrorMessage("No chat found by ID") ) ) } override suspend fun getByUserId(userId: Int): Either<Error, List<Chat>> = dbQuery { val count = ChatTable.select(ChatTable.userId.eq(userId)).count() if (count > 0) { val chats = ChatTable.select(ChatTable.userId.eq(userId)).orderBy(ChatTable.createAt to SortOrder.DESC) .map { it.toChat() } Either.Success(chats) } else { Either.Success(emptyList()) } } override suspend fun insert(chat: Chat): Either<Error, Chat> = dbQuery { ChatTable.insert { it[name] = chat.name it[userId] = chat.userId }.resultedValues?.get(0)?.toChat()?.let { Either.Success(it) } ?: Either.Failure(Error(HttpStatusCode.InternalServerError, ErrorMessage("Failed to insert chat."))) } override suspend fun update(chat: Chat): Either<Error, Boolean> = dbQuery { if (chat.id != null) { val updated = ChatTable.update({ ChatTable.id.eq(chat.id) }) { it[name] = chat.name }.validateIfSQLOperationSucceeded() if (updated) Either.Success(true) else Either.Failure(Error(HttpStatusCode.InternalServerError, ErrorMessage("Failed to update chat."))) } else { Either.Failure(Error(HttpStatusCode.NotFound, ErrorMessage("No chat found by ID in Insert"))) } } override suspend fun delete(chatId: Int): Either<Error, Boolean> = dbQuery { val delete = ChatTable.deleteWhere { ChatTable.id eq chatId }.validateIfSQLOperationSucceeded() if (delete) Either.Success(true) else Either.Failure(Error(HttpStatusCode.InternalServerError, ErrorMessage("Failed to delete chat."))) } } interface ChatRepository { suspend fun get(id: Int): Either<Error, Chat> suspend fun getByUserId(userId: Int): Either<Error, List<Chat>> suspend fun insert(chat: Chat): Either<Error, Chat> suspend fun update(chat: Chat): Either<Error, Boolean> suspend fun delete(chatId: Int): Either<Error, Boolean> }
0
Kotlin
0
0
6dc1b4ffea5c492539cbca13554877e1beb80757
2,965
chat-gpt-kotlin-backend
Apache License 2.0
app/src/test/java/com/persival/realestatemanagerkotlin/ui/main/MainViewModelTest.kt
persival001
664,734,716
false
{"Kotlin": 232455, "HTML": 54594}
package com.persival.realestatemanagerkotlin.ui.main import org.junit.Assert.* class MainViewModelTest
0
Kotlin
0
1
7370ba765c0a8eb42657e3ff637318a33e04c62e
104
RealEstateManagerKotlin
MIT License
core/src/main/java/com/nabla/sdk/core/ui/helpers/mediapicker/CaptureImageFromCameraActivityContract.kt
nabla
478,468,099
false
{"Kotlin": 1146406, "Java": 20507}
package com.nabla.sdk.core.ui.helpers.mediapicker import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.provider.MediaStore import androidx.activity.result.contract.ActivityResultContract import com.nabla.sdk.core.annotation.NablaInternal import com.nabla.sdk.core.domain.entity.MimeType import com.nabla.sdk.core.ui.helpers.mediapicker.mimetypedetector.MimeTypeHelper import com.nabla.sdk.core.ui.providers.CameraFileProvider import java.io.File @NablaInternal public class CaptureImageFromCameraActivityContract( private val context: Context, ) : ActivityResultContract<Unit, MediaPickingResult<LocalMedia.Image>>() { private var currentFile: File? = null override fun createIntent(context: Context, input: Unit): Intent { val file = CameraFileProvider.createFile(context) currentFile = file val takePhotoIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) takePhotoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) takePhotoIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION) file.parentFile?.mkdirs() file.createNewFile() val imageUri: Uri = CameraFileProvider.getUri(context, file) takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri) return takePhotoIntent } override fun parseResult(resultCode: Int, intent: Intent?): MediaPickingResult<LocalMedia.Image> { try { if (resultCode == Activity.RESULT_CANCELED) { return MediaPickingResult.Cancelled() } if (resultCode != Activity.RESULT_OK) { throw RuntimeException("Activity result: $resultCode") } val file = currentFile ?: throw IllegalStateException("No file available") val mimeType = MimeTypeHelper.getInstance(context).getFileMediaMimeType(file) as? MimeType.Image ?: throw IllegalArgumentException("Mime type is not a supported image one") return MediaPickingResult.Success( LocalMedia.Image( file.toURI(), generateFileName(extension = mimeType.subtype), mimeType, ), ) } catch (error: Exception) { return MediaPickingResult.Failure(error) } finally { currentFile = null } } }
0
Kotlin
2
18
57e42d4bfc7bbb5202cf472e8c9279a23de090cc
2,433
nabla-android
MIT License
app/src/main/java/com/migualador/cocktails/presentation/home/HomeFragment.kt
migualador
719,969,621
false
{"Kotlin": 113009}
package com.migualador.cocktails.presentation.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.compose.ui.res.colorResource import androidx.compose.ui.unit.dp import androidx.fragment.app.Fragment import androidx.navigation.NavController import androidx.navigation.findNavController import com.migualador.cocktails.CocktailsApp import com.migualador.cocktails.R import com.migualador.cocktails.presentation.Event import com.migualador.cocktails.presentation.cocktails_list.CocktailsListFragment import com.migualador.cocktails.presentation.composables.Composables import com.migualador.cocktails.presentation.composables.HomeComposables import com.migualador.cocktails.presentation.home.ui_states.LoadingUiState import com.migualador.cocktails.presentation.home.ui_states.NavigateUiState import javax.inject.Inject /** * HomeFragment * */ class HomeFragment: Fragment() { @Inject lateinit var viewModel: HomeViewModel private lateinit var navController: NavController override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { injectDependencies() return ComposeView(requireContext()).apply { setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) setContent { Screen() } } } private fun injectDependencies() { (activity?.application as CocktailsApp).appComponent .getViewModelComponent() .create(this) .inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) navController = view.findNavController() setupObservers() viewModel.requestUiState() } @Composable fun Screen() { val loadingUiState by viewModel.loadingUiStateLiveData.observeAsState(false) val loading = (loadingUiState as Event<LoadingUiState>).getContentIfNotHandled()?.loading if ((loading != null) && (loading == false)) { ScreenReady() } else { ScreenLoading() } } @Composable fun ScreenLoading() { Column { Spacer(modifier = Modifier.height(30.dp)) Composables.TopBar() Box( Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { CircularProgressIndicator( color = colorResource(R.color.progress_color) ) } } } @Composable fun ScreenReady() { Column( modifier = Modifier.verticalScroll(rememberScrollState()) ) { val featuredCocktailsList by viewModel.featuredCocktailsLiveData.observeAsState( initial = emptyList() ) val alcoholicCocktailsList by viewModel.alcoholicCocktailsLiveData.observeAsState( initial = emptyList() ) val nonAlcoholicCocktailsList by viewModel.nonAlcoholicCocktailsLiveData.observeAsState( initial = emptyList() ) val favoriteCocktailsList by viewModel.favoriteCocktailsLiveData.observeAsState( initial = emptyList() ) Spacer(modifier = Modifier.height(30.dp)) Composables.TopBar() Composables.FeaturedCocktails(featuredCocktailsList) Composables.Header(R.string.home_alcoholic_cocktails) { viewModel.alcoholicCocktailsHeaderPressed() } Composables.Cocktails(alcoholicCocktailsList) Composables.Header(R.string.home_non_alcoholic_cocktails) { viewModel.nonAlcoholicCocktailsHeaderPressed() } Composables.Cocktails(nonAlcoholicCocktailsList) Composables.Header(R.string.home_favorite_cocktails) { viewModel.favoriteCocktailsHeaderPressed() } HomeComposables.FavoriteCocktails(favoriteCocktailsList) Spacer(modifier = Modifier.height(32.dp)) } } private fun setupObservers() { with(viewModel) { navigateLiveData.observe(viewLifecycleOwner) { navigateToDetailUiStateEvent -> navigateToDetailUiStateEvent.getContentIfNotHandled()?.let { when (it) { is NavigateUiState.NavigateToDetail -> navigateToCocktailDetail(it.cocktailId) is NavigateUiState.NavigateToAlcoholicCocktailsList -> navigateToAlcoholicCocktailsList() is NavigateUiState.NavigateToNonAlcoholicCocktailsList -> navigateToNonAlcoholicCocktailsList() is NavigateUiState.NavigateToFavoriteCocktailsList -> navigateToFavoriteCocktailsList() } } } } } private fun navigateToCocktailDetail(cocktailId: String) { val bundle = Bundle() bundle.putString("id", cocktailId) navController.navigate(R.id.action_homeFragment_to_featuredDetailFragment, bundle) } private fun navigateToAlcoholicCocktailsList() { val bundle = Bundle() bundle.putString("listType", CocktailsListFragment.Companion.ListType.ALCOHOLIC_COCKTAILS_LIST.name) navController.navigate(R.id.action_homeFragment_to_cocktailListFragment, bundle) } private fun navigateToNonAlcoholicCocktailsList() { val bundle = Bundle() bundle.putString("listType", CocktailsListFragment.Companion.ListType.NON_ALCOHOLIC_COCKTAILS_LIST.name) navController.navigate(R.id.action_homeFragment_to_cocktailListFragment, bundle) } private fun navigateToFavoriteCocktailsList() { val bundle = Bundle() bundle.putString("listType", CocktailsListFragment.Companion.ListType.FAVORITE_COCKTAILS_LIST.name) navController.navigate(R.id.action_homeFragment_to_cocktailListFragment, bundle) } }
0
Kotlin
0
0
9936484c1a9404d97a93814d2274af6cc20e5315
6,846
android-kotlin-mvvm-architecture
Apache License 2.0