path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/mystical/wildlegion/network/models/EditClanMemberRequest.kt
DeveloperXY
145,738,735
false
null
package com.mystical.wildlegion.network.models import com.mystical.wildlegion.screens.main.models.Member data class EditClanMemberRequest( var _id: String, var nickname: String, var gamerangerId: String, var rank: String, var isActive: Boolean) { constructor(member: Member) : this(member._id, member.nickname, member.gamerangerId, member.rank + "", member.isActive) }
1
null
1
1
3743e5e88fe95c0722f98334f8799cb11111e59a
426
WildLegion
MIT License
lesson4.kts
Ismoil-cmd
531,971,254
false
null
import java.util.* var scan = Scanner(System.`in`); print("Enter first number: "); var a = scan.nextDouble(); print("Enter second number: "); var b = scan.nextDouble(); print("Enter operation: "); var operator = scan.next(); var calc = Calc(); calc.solve(operator,a,b); class Calc(){ fun solve(operator:String,a:Double, b:Double){ if(operator == "+"){ print(a + b); } else if(operator == "-"){ print(a - b); } else if(operator == "*"){ print(a * b); } else if(operator == "/"){ print(a / b); } } }
0
Kotlin
0
0
2be75e9445be9afe2665a183275b27ea1b1dbecd
627
Kotlin-coding
Apache License 2.0
app/src/main/java/com/trilema/doctrinalang/ui/AboutFragmet.kt
jimmycw74
298,804,278
false
{"Gradle": 3, "Java Properties": 6, "Shell": 1, "Text": 14, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "SVG": 3, "Proguard": 1, "Java": 4, "XML": 179, "Kotlin": 11, "JSON": 245, "Roff": 3, "INI": 3}
package com.trilema.doctrinalang.ui import android.app.Dialog import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import com.trilema.doctrinalang.R class AboutFragmet : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(activity!!) // Get the layout inflater val inflater = requireActivity().layoutInflater // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout builder.setView(inflater.inflate(R.layout.about_fragment, null)) .setCancelable(true) .setNegativeButton("OK") { dialog, id -> dialog!!.cancel() } return builder.create() } }
1
null
1
1
b93972793ee36e927c21db60e61a185da810f1d2
824
DoctrinaLang
Apache License 2.0
src/main/kotlin/pl/exbook/exbook/basket/adapter/rest/BasketEndpoint.kt
Ejden
339,380,956
false
null
package pl.exbook.exbook.basket.adapter.rest import org.springframework.http.ResponseEntity import org.springframework.http.ResponseEntity.ok import org.springframework.security.access.prepost.PreAuthorize import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import pl.exbook.exbook.basket.BasketFacade import pl.exbook.exbook.basket.adapter.rest.dto.AddExchangeBookMapper import pl.exbook.exbook.basket.adapter.rest.dto.AddExchangeBookToBasketRequest import pl.exbook.exbook.basket.adapter.rest.dto.AddItemToBasketMapper import pl.exbook.exbook.basket.adapter.rest.dto.AddItemToBasketRequest import pl.exbook.exbook.basket.adapter.rest.dto.BasketDto import pl.exbook.exbook.basket.adapter.rest.dto.BasketMapper import pl.exbook.exbook.basket.adapter.rest.dto.ChangeItemQuantityMapper import pl.exbook.exbook.basket.adapter.rest.dto.DetailedBasketMapper import pl.exbook.exbook.basket.adapter.rest.dto.ChangeItemQuantityRequest import pl.exbook.exbook.basket.adapter.rest.dto.DetailedBasketDto import pl.exbook.exbook.order.domain.Order import pl.exbook.exbook.shared.ContentType import pl.exbook.exbook.shared.ExchangeBookId import pl.exbook.exbook.shared.OfferId import pl.exbook.exbook.shared.UserId import pl.exbook.exbook.util.callhandler.handleRequest @RestController @RequestMapping("api/basket") class BasketEndpoint(private val basketFacade: BasketFacade) { @PreAuthorize("isFullyAuthenticated()") @GetMapping(produces = [ContentType.V1]) fun getBasket(user: UsernamePasswordAuthenticationToken): ResponseEntity<DetailedBasketDto> = handleRequest( mapper = DetailedBasketMapper, call = { basketFacade.getDetailedUserBasket(user.name) }, response = { ok(it) } ) @PreAuthorize("isFullyAuthenticated()") @PutMapping(produces = [ContentType.V1]) fun addItemToBasket( @RequestBody request: AddItemToBasketRequest, user: UsernamePasswordAuthenticationToken ): ResponseEntity<BasketDto> = handleRequest( mapper = AddItemToBasketMapper(user.name), requestBody = request, call = { basketFacade.addItemToBasket(it) }, response = { ok(it) } ) @PreAuthorize("isFullyAuthenticated()") @DeleteMapping("{orderType}/{offerId}", produces = [ContentType.V1]) fun removeItemFromBasket( @PathVariable orderType: Order.OrderType, @PathVariable offerId: OfferId, user: UsernamePasswordAuthenticationToken ): ResponseEntity<BasketDto> = handleRequest( mapper = BasketMapper, call = { basketFacade.removeItemFromBasket(user.name, offerId, orderType) }, response = { ok(it) } ) @PreAuthorize("isFullyAuthenticated()") @PostMapping("{offerId}") fun changeItemQuantityInBasket( @PathVariable offerId: OfferId, @RequestBody request: ChangeItemQuantityRequest, user: UsernamePasswordAuthenticationToken ): ResponseEntity<BasketDto> = handleRequest( mapper = ChangeItemQuantityMapper(offerId, user.name), requestBody = request, call = { basketFacade.changeItemQuantityInBasket(it) }, response = { ok(it) } ) @PreAuthorize("isFullyAuthenticated()") @PostMapping("/sellers/{sellerId}/books", consumes = [ContentType.V1], produces = [ContentType.V1]) fun addExchangeBookToBasket( @PathVariable sellerId: UserId, @RequestBody request: AddExchangeBookToBasketRequest, user: UsernamePasswordAuthenticationToken ): ResponseEntity<BasketDto> = handleRequest( mapper = AddExchangeBookMapper(sellerId, user.name), requestBody = request, call = { basketFacade.addExchangeBookToBasket(it) }, response = { ok(it) } ) @PreAuthorize("isFullyAuthenticated()") @DeleteMapping("/sellers/{sellerId}/books/{bookId}", produces = [ContentType.V1]) fun removeExchangeBookToBasket( @PathVariable sellerId: UserId, @PathVariable bookId: ExchangeBookId, user: UsernamePasswordAuthenticationToken ): ResponseEntity<BasketDto> = handleRequest( mapper = BasketMapper, call = { basketFacade.removeExchangeBookFromBasket(user.name, sellerId, bookId) }, response = { ok(it) } ) }
1
Kotlin
0
1
ac636229a26daf6e82f7f7d0ea1c02f32788c782
4,743
exbook-backend
The Unlicense
src/main/kotlin/br/com/fugisawa/adopetbackendapi/domain/user/Role.kt
lucasfugisawa
615,549,042
false
null
package br.com.fugisawa.adopetbackendapi.domain.user import jakarta.persistence.* import org.hibernate.annotations.GenericGenerator import org.hibernate.annotations.Parameter @Entity @Table(name = "role") class Role( @Id @GeneratedValue(generator = "app_role-sequence-generator") @GenericGenerator( name = "role-sequence-generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = [ Parameter(name = "sequence_name", value = "role_SEQ"), Parameter(name = "initial_value", value = "100"), Parameter(name = "increment_size", value = "1") ] ) val id: Int, @Column(name = "name", updatable = false) var name: String? = null, @Column(name = "description", updatable = false) var description: String? = null, @ManyToMany(mappedBy = "roles") var users: MutableSet<User>? = null )
6
Kotlin
0
0
64dace3f48fbeed2f3d7340c02d4ed3f98f26805
862
adopet-backend-api
MIT License
samples/simple/src/main/kotlin/space/traversal/kapsule/demo/Demo.kt
timobaehr
98,441,365
true
{"Kotlin": 23676}
/* * Copyright 2017 Traversal Space * * 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 space.traversal.kapsule.demo import space.traversal.kapsule.Injects import space.traversal.kapsule.demo.di.Module fun main(args: Array<String>) { val demo = Demo(Context()) println("First name: ${demo.firstName}") println("Last name: ${demo.lastName}") println("Emails: ${demo.emails}") } /** * Demo app definition. */ class Demo(context: Context) : Injects<Module> { var firstName by required { firstName } val lastName by optional { lastName } val emails by required { emails } init { inject(context.module) } }
0
Kotlin
0
0
04adda695cbe412dd4e0e95decd528a5ec5c5ced
1,654
kapsule
MIT License
jps-plugin/src/main/kotlin/com/github/bobi/osgiannotationprocessor/scr/processor/ReportingBuilder.kt
bobi
516,809,414
false
null
package com.github.bobi.osgiannotationprocessor.scr.processor import aQute.bnd.osgi.Analyzer import aQute.bnd.osgi.Builder import aQute.bnd.osgi.Jar import aQute.service.reporter.Report import aQute.service.reporter.Reporter import com.github.bobi.osgiannotationprocessor.jps.OSGIScrBuildTarget import com.github.bobi.osgiannotationprocessor.scr.logger.ScrLogger import com.github.bobi.osgiannotationprocessor.scr.logger.SourceLocation import com.github.bobi.osgiannotationprocessor.settings.OSGIScrConfiguration import com.github.bobi.osgiannotationprocessor.settings.OSGIScrSpec import org.apache.felix.scrplugin.bnd.SCRDescriptorBndPlugin import java.io.File import java.io.IOException import java.util.* class ReportingBuilder( private val target: OSGIScrBuildTarget, private val classDir: File, private val logger: ScrLogger ) : Builder() { private val configuration: OSGIScrConfiguration = target.configuration private val moduleName: String = target.module.name init { this.isTrace = logger.isDebugEnabled this.base = classDir this.setJar(classDir) } override fun error(string: String, vararg args: Any): Reporter.SetLocation { val errLocation = super.error(string, *args) val location = errLocation.location() logger.error(location.message, toSourceLocation(location)) return errLocation } override fun warning(string: String, vararg args: Any): Reporter.SetLocation { val warnLocation = super.warning(string, *args) val location = warnLocation.location() logger.warn(location.message, toSourceLocation(location)) return warnLocation } override fun build(): Jar { configure() return super.build() } private fun configure() { this.properties = buildProperties() this.setClasspath(buildClasspath()) } private fun buildProperties(): Properties { val properties = Properties() properties[Analyzer.BUNDLE_SYMBOLICNAME] = moduleName properties[Analyzer.DSANNOTATIONS] = "*" properties[Analyzer.METATYPE_ANNOTATIONS] = "*" properties[Analyzer.IMPORT_PACKAGE] = "*" if (configuration.manualSpec) { properties[Analyzer.DSANNOTATIONS_OPTIONS] = "version;minimum=${configuration.spec.version};maximum=${configuration.spec.version}" } properties[Analyzer.STRICT] = configuration.strictMode.toString() addFelixPluginProperties(properties) return properties } private fun addFelixPluginProperties(properties: Properties) { //TODO: for future. Instead of using static felix scr dependency, lookup scr plugin in classpath and add it only when found if (configuration.felixEnabled) { val felixScrPluginOptionsMap = mutableMapOf<String, String>( "strictMode" to configuration.strictMode.toString(), "generateAccessors" to configuration.generateAccessors.toString(), "log" to if (configuration.debugLogging) "Debug" else "Warn", "destdir" to classDir.canonicalPath ) if (configuration.manualSpec) { felixScrPluginOptionsMap["specVersion"] = OSGIScrSpec.felixSpec(configuration.spec).version } val felixScrPluginOptions = felixScrPluginOptionsMap .map { "${it.key}=${it.value}" } .joinToString(separator = ";") properties[PLUGIN] = "${SCRDescriptorBndPlugin::class.java.name};${felixScrPluginOptions}" .replace("[\r\n]".toRegex(), "") } } @Throws(IOException::class) private fun buildClasspath(): List<Jar> { val classpath = mutableListOf<Jar>() if (classDir.isDirectory) { classpath.add(Jar(moduleName, classDir)) } val moduleClasspath = target.getModuleClasspath() logger.debug( "classpath: ${ moduleClasspath.joinToString( prefix = "[", postfix = "]", separator = ", " ) { it.canonicalPath } }" ) for (cpe in moduleClasspath) { if (cpe.exists()) { classpath.add(Jar(cpe)) } else { logger.warn("Path ${cpe.canonicalPath} does not exist") } } return classpath } private fun toSourceLocation(location: Report.Location): SourceLocation { if (location.file?.endsWith(".class") == true) { val moduleSourceRoots = target.getModuleSourceRoots() val moduleOutputRoots = target.getModuleOutputRoots() val out = moduleOutputRoots.find { location.file.contains(it.canonicalPath) } if (out != null) { val loc = File(location.file).canonicalPath val relativePath = loc.substring(out.canonicalPath.length, loc.length - 6) + ".java" for (root in moduleSourceRoots) { val file = File(root, relativePath) if (file.exists()) { return SourceLocation(file.canonicalPath, location.line) } } } } return SourceLocation(location.file, location.line) } }
1
Kotlin
0
1
1967909e2b887bee675e3204275b1b63c017cade
5,424
osgi-annotation-processor
Apache License 2.0
platform/warmup/performanceTesting/src/com/intellij/warmup/util.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.warmup import com.intellij.openapi.ui.playback.commands.AbstractCommand import com.intellij.tools.ide.performanceTesting.commands.CommandChain const val BUILD_PREFIX = AbstractCommand.CMD_PREFIX + "checkWarmupBuild" const val GIT_LOG_PREFIX = AbstractCommand.CMD_PREFIX + "checkGitLogIndexing" fun <T : CommandChain> T.checkWarmupBuild(): T { addCommand(BUILD_PREFIX) return this } fun <T : CommandChain> T.checkGitLogIndexing(): T { addCommand(GIT_LOG_PREFIX) return this }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
629
intellij-community
Apache License 2.0
src/controller/UserController.kt
imalik8088
260,903,159
false
null
package io.imalik8088.github.ktorstarter.controller import com.fasterxml.jackson.annotation.JsonIgnore import io.imalik8088.github.ktorstarter.API_VERSION import io.imalik8088.github.ktorstarter.Constants.Companion.DATABASE import io.ktor.application.call import io.ktor.http.HttpStatusCode import io.ktor.response.respond import io.ktor.routing.Route import io.ktor.routing.get import io.ktor.routing.post import io.ktor.routing.route import org.bson.codecs.pojo.annotations.BsonId import org.koin.ktor.ext.inject import org.litote.kmongo.coroutine.CoroutineClient import org.litote.kmongo.eq import org.slf4j.LoggerFactory import java.util.UUID val ENDPOINT = "$API_VERSION/users" fun Route.userRoutes() { val LOG = LoggerFactory.getLogger("UserController") val client: CoroutineClient by inject() val COLLECTION = "users" route(ENDPOINT) { get { val users = client.getDatabase(DATABASE) .getCollection<User>(COLLECTION) .find() .toList() call.respond(HttpStatusCode.OK, users) } get("/{email}") { val emailParam = call.parameters.get("email") val user = client.getDatabase(DATABASE).getCollection<User>(COLLECTION).findOne(User::email eq emailParam) if (user != null) { call.respond(HttpStatusCode.OK, user) } else { call.respond(HttpStatusCode.NotFound, "") } } post<RegisterRequest>("/register") { request -> val user = User( username = request.username, password = request.password, email = request.email ) client.getDatabase(DATABASE) .getCollection<User>(COLLECTION) .insertOne(user) call.respond(HttpStatusCode.Created) } } } data class User( @BsonId val id: UUID = UUID.randomUUID(), val username: String, @JsonIgnore val password: String?, val email: String? ) data class RegisterRequest(val username: String, val password: String, val email: String?)
0
Kotlin
1
1
e42be055e574f61bc6e20cdb161ccfb957723bab
2,153
ktor-starter
MIT License
features/map/map-ui/src/main/kotlin/com/egoriku/grodnoroads/map/mode/drive/alerts/Alerts.kt
egorikftp
485,026,420
false
null
package com.egoriku.grodnoroads.map.mode.drive.alerts import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.egoriku.grodnoroads.foundation.theme.GrodnoRoadsPreview import com.egoriku.grodnoroads.foundation.theme.GrodnoRoadsTheme import com.egoriku.grodnoroads.map.domain.model.Alert import com.egoriku.grodnoroads.map.domain.model.Alert.CameraAlert import com.egoriku.grodnoroads.map.domain.model.Alert.IncidentAlert import com.egoriku.grodnoroads.map.domain.model.MapEventType.* import com.egoriku.grodnoroads.map.domain.model.MessageItem import com.egoriku.grodnoroads.map.domain.model.Source import com.egoriku.grodnoroads.resources.R import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf @Composable fun Alerts( modifier: Modifier = Modifier, alerts: ImmutableList<Alert> ) { LazyColumn( modifier = modifier .fillMaxWidth() .padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { items(alerts) { alert -> when (alert) { is IncidentAlert -> { val title = when (alert.mapEventType) { RoadIncident -> stringResource(R.string.alerts_incident) TrafficPolice -> stringResource(R.string.alerts_traffic_police) CarCrash -> stringResource(R.string.alerts_car_crash) TrafficJam -> stringResource(R.string.alerts_traffic_jam) WildAnimals -> stringResource(R.string.alerts_wild_animals) else -> stringResource(R.string.alerts_unsupported_message) } IncidentAlert( emoji = alert.mapEventType.emoji, title = title, distance = alert.distance, messages = alert.messages ) } is CameraAlert -> { val title = when (alert.mapEventType) { StationaryCamera -> stringResource(R.string.alerts_stationary_camera) MobileCamera -> stringResource(R.string.alerts_mobile_camera) else -> throw IllegalArgumentException("title not applicable") } val icon = when (alert.mapEventType) { StationaryCamera -> R.drawable.ic_stationary_camera MobileCamera -> R.drawable.ic_mobile_camera else -> throw IllegalArgumentException("title not applicable") } CameraAlert( distance = alert.distance, speedLimit = alert.speedLimit, drawableId = icon, title = title ) } } } } } @GrodnoRoadsPreview @Composable private fun AlertsPreview() { GrodnoRoadsTheme { Column(verticalArrangement = Arrangement.spacedBy(16.dp)) { Alerts( alerts = persistentListOf( IncidentAlert( mapEventType = TrafficPolice, distance = 1, messages = persistentListOf( MessageItem( message = "Славинского беларуснефть на скорость", source = Source.Viber ) ) ) ) ) Alerts( alerts = persistentListOf( CameraAlert( distance = 2, speedLimit = 60, mapEventType = StationaryCamera ) ) ) Alerts( alerts = persistentListOf( IncidentAlert( distance = 5, messages = persistentListOf( MessageItem( message = "(15:30) Старый мост ДТП в правой полосе по направлению от кольца в центр", source = Source.Viber ), MessageItem( message = "(15:45) Новый мост в левой полосе по направлению", source = Source.Viber ) ), mapEventType = RoadIncident ) ) ) Alerts( alerts = persistentListOf( CameraAlert(distance = 220, speedLimit = -1, mapEventType = MobileCamera) ) ) Alerts( alerts = persistentListOf( CameraAlert(distance = 220, speedLimit = 60, mapEventType = MobileCamera) ) ) } } }
2
Kotlin
1
6
4c13949a65f68379426b54b3fe2561f9698ec214
5,533
GrodnoRoads
Apache License 2.0
app/src/main/java/com/dojo/moovies/out/db/MyListDao.kt
pgsilva
739,863,015
false
null
package com.dojo.moovies.out.db import androidx.room.Dao import androidx.room.Query import androidx.room.Upsert import com.dojo.moovies.out.db.entity.MyListEntity import com.dojo.moovies.out.db.entity.TABLE_NAME_MY_LIST import kotlinx.coroutines.flow.Flow @Dao interface MyListDao { @Query("SELECT * FROM $TABLE_NAME_MY_LIST") fun findAll(): Flow<List<MyListEntity>> @Query("SELECT * FROM $TABLE_NAME_MY_LIST LIMIT 20") fun findAllLimit20(): Flow<List<MyListEntity>> @Query("SELECT * FROM $TABLE_NAME_MY_LIST WHERE mooviesId = :id") suspend fun findByMooviesId(id: String): MyListEntity? @Query("SELECT * FROM $TABLE_NAME_MY_LIST WHERE id = :id AND mediaType = :mediaType") suspend fun findByIdAndMediaType(id: Long, mediaType: String): MyListEntity? @Query("DELETE FROM $TABLE_NAME_MY_LIST WHERE id = :id AND mediaType = :mediaType") suspend fun deleteByIdAndMediaType(id: Long, mediaType: String) @Upsert suspend fun update(myListEntity: MyListEntity) @Query("DELETE FROM $TABLE_NAME_MY_LIST") suspend fun deleteAll() }
1
null
0
1
91629eaf72938878bdf15d06592a011d9cd30cb0
1,087
moovies
MIT License
HelloArchitectureRetrofit/domain/src/main/java/dev/seabat/android/helloarchitectureretrofit/domain/usecase/GithubUseCase.kt
seabat
636,759,391
false
null
package dev.seabat.android.helloarchitectureretrofit.domain.usecase import dev.seabat.android.helloarchitectureretrofit.domain.entity.RepositoryListEntity import dev.seabat.android.helloarchitectureretrofit.domain.repository.GithubRepositoryContract class GithubUseCase(val githubRepository: GithubRepositoryContract) : GithubUseCaseContract { override suspend fun loadRepos(): RepositoryListEntity? { return githubRepository.fetchRepos() } }
0
Kotlin
0
0
c2c4f036825640aab138dcb14727eaf711308160
460
hello-architecture-retrofit
Apache License 2.0
io/io-ktor/src/commonMain/kotlin/app/meetacy/sdk/io/ByteReadChannelExt.kt
meetacy
604,657,616
false
{"Kotlin": 291810, "Swift": 9285, "HTML": 129, "JavaScript": 114}
package app.meetacy.sdk.io import app.meetacy.sdk.io.bytes.ByteArrayView import io.ktor.utils.io.* public suspend fun ByteReadChannel.readMaxBytes(destination: ByteArrayView): Int { return readMaxBytes( destination = destination, readAcc = 0 ) } private tailrec suspend fun ByteReadChannel.readMaxBytes(destination: ByteArrayView, readAcc: Int): Int { val readSize = this.readAvailable( dst = destination.underlying, offset = destination.fromIndex + readAcc, length = destination.size - readAcc ) if (readSize <= 0) return readAcc return readMaxBytes(destination, readAcc = readAcc + readSize) }
9
Kotlin
1
29
4673093606cacf21f8e850aba221a32487de67a6
665
sdk
MIT License
app/src/main/java/com/example/twitturin/auth/presentation/kind/vm/KindViewModel.kt
extractive-mana-pulse
708,689,521
false
{"Kotlin": 318582, "Java": 2351}
package com.example.twitturin.auth.presentation.kind.vm import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.twitturin.auth.presentation.kind.sealed.KindUiEvent import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch class KindViewModel : ViewModel() { private val channel = Channel<KindUiEvent>(Channel.BUFFERED) val kindEventResult = channel.receiveAsFlow() fun onBackPressedKind(){ viewModelScope.launch { channel.send(KindUiEvent.OnBackPressed) } } fun onProfPressed(){ viewModelScope.launch { channel.send(KindUiEvent.NavigateToProfReg) } } fun onStudPressed(){ viewModelScope.launch { channel.send(KindUiEvent.NavigateToStudReg) } } }
1
Kotlin
0
1
9c94fd0f8b139cdf0412839140f6632e8cbf3c91
772
Twittur-In-
MIT License
debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/timeranges/MonthRangeCollection.kt
debop
60,844,667
false
null
/* * Copyright (c) 2016. <NAME> <<EMAIL>> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.timeperiod.timeranges import debop4k.core.kodatimes.today import debop4k.timeperiod.DefaultTimeCalendar import debop4k.timeperiod.ITimeCalendar import debop4k.timeperiod.utils.monthRangeSequence import debop4k.timeperiod.utils.startTimeOfMonth import org.joda.time.DateTime /** * Created by debop */ open class MonthRangeCollection @JvmOverloads constructor(startTime: DateTime = today(), monthCount: Int = 1, calendar: ITimeCalendar = DefaultTimeCalendar) : MonthTimeRange(startTime.startTimeOfMonth(), monthCount, calendar) { @JvmOverloads constructor(year: Int, month: Int, monthCount: Int = 1, calendar: ITimeCalendar = DefaultTimeCalendar) : this(startTimeOfMonth(year, month), monthCount, calendar) fun monthSequence(): Sequence<MonthRange> { return monthRangeSequence(start, monthCount, calendar) } fun months(): List<MonthRange> { return monthSequence().toList() } }
1
null
10
40
5a621998b88b4d416f510971536abf3bf82fb2f0
1,686
debop4k
Apache License 2.0
src/main/kotlin/dev/usbharu/hideout/core/service/post/PostCreateDto.kt
usbharu
627,026,893
false
{"Kotlin": 1337734, "Mustache": 111614, "Gherkin": 21440, "JavaScript": 1112, "HTML": 341}
/* * Copyright (C) 2024 usbharu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.usbharu.hideout.core.service.post import dev.usbharu.hideout.core.domain.model.post.Visibility data class PostCreateDto( val text: String, val overview: String? = null, val visibility: Visibility = Visibility.PUBLIC, val repostId: Long? = null, val repolyId: Long? = null, val userId: Long, val mediaIds: List<Long> = emptyList() )
38
Kotlin
0
9
5512c43ffacf0480f652465ccf5f71b559387592
971
Hideout
Apache License 2.0
acornui-core/src/jvmTest/kotlin/com/acornui/core/io/file/FilesTopDownSequenceTest.kt
fuzzyweapon
130,889,917
true
{"Kotlin": 2963922, "JavaScript": 15366, "HTML": 5956, "Java": 4507}
/* * Copyright 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.acornui.core.io.file import com.acornui.collection.isSorted import com.acornui.io.file.FilesManifestSerializer import com.acornui.serialization.JsonSerializer import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class FilesTopDownSequenceTest { @Test fun walk() { val json = """ { "files": [ { "path": "assets/Overview2263.csv", "modified": 1525269404081, "size": 231269, "mimeType": "application/vnd.ms-excel" }, { "path": "assets/Overview2263.json", "modified": 1493668608599, "size": 10089, "mimeType": null }, { "path": "assets/Overview22630.png", "modified": 1493668608601, "size": 43004, "mimeType": "image/png" }, { "path": "assets/Overview22631.png", "modified": 1493668608604, "size": 104554, "mimeType": "image/png" }, { "path": "assets/build.txt", "modified": 1525269404222, "size": 3, "mimeType": "text/plain" }, { "path": "assets/countries.tsv", "modified": 1493157224402, "size": 13319, "mimeType": null }, { "path": "assets/files.json", "modified": 1525269256031, "size": 11996, "mimeType": null }, { "path": "assets/flags.json", "modified": 1493157224412, "size": 43684, "mimeType": null }, { "path": "assets/flags0.png", "modified": 1493157224412, "size": 44553, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/1ghost.png.png", "modified": 1525269404084, "size": 1422, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/2 ghost.png.png", "modified": 1525269404087, "size": 3252, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/5 ghost.png.png", "modified": 1525269404090, "size": 3231, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/ButtonPlaceHolder.png", "modified": 1525269404097, "size": 284, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/MachineButtonPlaceHolder.png", "modified": 1525269404207, "size": 298, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/Tunnel 2 ghost small.png.png", "modified": 1525269404213, "size": 675, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/WaEx 1 ghost.png.png", "modified": 1525269404216, "size": 1849, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/_packSettings.json", "modified": 1525269404219, "size": 535, "mimeType": null }, { "path": "assets/Overview2263_unpacked/deviceCloser.bmp.png", "modified": 1525269404099, "size": 63904, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/machinessss.png", "modified": 1525269404210, "size": 224, "mimeType": "image/png" }, { "path": "assets/images/2017-01-29.jpg", "modified": 1493157224412, "size": 114071, "mimeType": "image/jpeg" }, { "path": "assets/images/image128.jpg", "modified": 1493157224412, "size": 34850, "mimeType": "image/jpeg" }, { "path": "assets/images/image2.jpg", "modified": 1493157224412, "size": 34074, "mimeType": "image/jpeg" }, { "path": "assets/images/pigbar.jpg", "modified": 1493157224412, "size": 131041, "mimeType": "image/jpeg" }, { "path": "assets/res/datagrid.properties", "modified": 1493157224412, "size": 805, "mimeType": null }, { "path": "assets/res/datagrid_de_DE.properties", "modified": 1493157224412, "size": 834, "mimeType": null }, { "path": "assets/res/datagrid_en_US.properties", "modified": 1493157224422, "size": 810, "mimeType": null }, { "path": "assets/res/datagrid_fr_FR.properties", "modified": 1493157224422, "size": 817, "mimeType": null }, { "path": "assets/res/ui.properties", "modified": 1493668608605, "size": 0, "mimeType": null }, { "path": "assets/uiskin/uiskin.json", "modified": 1493668608638, "size": 5628, "mimeType": null }, { "path": "assets/uiskin/uiskin0.png", "modified": 1493668608640, "size": 46581, "mimeType": "image/png" }, { "path": "assets/uiskin/verdana_14.bmfc", "modified": 1493668608643, "size": 747, "mimeType": null }, { "path": "assets/uiskin/verdana_14.fnt", "modified": 1493668608646, "size": 26502, "mimeType": null }, { "path": "assets/uiskin/verdana_14_bold.fnt", "modified": 1493668608648, "size": 22077, "mimeType": null }, { "path": "assets/uiskin/verdana_14_bold_italic.fnt", "modified": 1493668608651, "size": 22084, "mimeType": null }, { "path": "assets/uiskin/verdana_14_italic.fnt", "modified": 1493668608653, "size": 22079, "mimeType": null }, { "path": "assets/Overview2263_unpacked/Bag Assets/BagThing.png", "modified": 1525269404094, "size": 417, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/MachineAssets/MachineThing.png", "modified": 1525269404204, "size": 406, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutDevices/Indexer.png", "modified": 1525269404106, "size": 1399, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutDevices/LiveRailSingle.png", "modified": 1525269404109, "size": 804, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutDevices/OpenerStyleA.png", "modified": 1525269404111, "size": 2008, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutDevices/Sensor.png", "modified": 1525269404114, "size": 198, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutDevices/StopDefaultDown.png", "modified": 1525269404119, "size": 934, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutDevices/StopDefaultUp.png", "modified": 1525269404122, "size": 891, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutDevices/conveyor_arrow.png", "modified": 1525269404103, "size": 188, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutDevices/stabilizer.png", "modified": 1525269404116, "size": 143, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutDevices/threeway_object.png", "modified": 1525269404125, "size": 106, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutRail/Curve45_short.png", "modified": 1525269404128, "size": 340, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutRail/Curve90LowerLeft.png", "modified": 1525269404131, "size": 724, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutRail/Curve90LowerRight.png", "modified": 1525269404135, "size": 690, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutRail/Curve90UpperLeft.png", "modified": 1525269404138, "size": 677, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutRail/Curve90UpperRight.png", "modified": 1525269404141, "size": 727, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutRail/RailHorizontal.png", "modified": 1525269404144, "size": 125, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutRail/RailVertical.png", "modified": 1525269404146, "size": 117, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutSwitches/Switch2wayCurve_shortFat.png", "modified": 1525269404153, "size": 2516, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutSwitches/Switch2wayCurve_tallFat.png", "modified": 1525269404156, "size": 2563, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutSwitches/Switch2wayCurve_tallSkinny.png", "modified": 1525269404158, "size": 2613, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutSwitches/Switch2wayStraight45B.png", "modified": 1525269404161, "size": 2093, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutSwitches/Switch2wayStraight_shortFat.png", "modified": 1525269404164, "size": 2179, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutSwitches/Switch2wayStraight_shortSkinny.png", "modified": 1525269404166, "size": 2132, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutSwitches/Switch2wayStraight_tallFat.png", "modified": 1525269404169, "size": 2233, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutSwitches/Switch2wayStraight_tallSkinny.png", "modified": 1525269404172, "size": 2078, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutSwitches/Switch3WayLeft.png", "modified": 1525269404174, "size": 6329, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutSwitches/Switch3WayLeft2.png", "modified": 1525269404177, "size": 5458, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutSwitches/Switch3WayLeftB.png", "modified": 1525269404180, "size": 6631, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutSwitches/Switch3WayRightB.png", "modified": 1525269404183, "size": 6358, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/layoutSwitches/cthreeway.png", "modified": 1525269404150, "size": 739, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/machine objects/Conveyor Horizontal.png.png", "modified": 1525269404189, "size": 221, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/machine objects/Conveyor Vertical.png.png", "modified": 1525269404193, "size": 756, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/machine objects/Milnor Dryer.png.png", "modified": 1525269404196, "size": 2165, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/machine objects/Table Dumper.png.png", "modified": 1525269404200, "size": 2511, "mimeType": "image/png" }, { "path": "assets/Overview2263_unpacked/machine objects/clean12.png.png", "modified": 1525269404186, "size": 3455, "mimeType": "image/png" }, { "path": "assets/uiskin/cursors/Alias.png", "modified": 1493668608609, "size": 2983, "mimeType": "image/png" }, { "path": "assets/uiskin/cursors/AllScroll.png", "modified": 1493668608612, "size": 2918, "mimeType": "image/png" }, { "path": "assets/uiskin/cursors/Cell.png", "modified": 1493668608614, "size": 2886, "mimeType": "image/png" }, { "path": "assets/uiskin/cursors/Copy.png", "modified": 1493668608616, "size": 2983, "mimeType": "image/png" }, { "path": "assets/uiskin/cursors/Crosshair.png", "modified": 1493668608618, "size": 2856, "mimeType": "image/png" }, { "path": "assets/uiskin/cursors/Help.png", "modified": 1493668608620, "size": 2940, "mimeType": "image/png" }, { "path": "assets/uiskin/cursors/IBeam.png", "modified": 1493668608623, "size": 2862, "mimeType": "image/png" }, { "path": "assets/uiskin/cursors/Move.png", "modified": 1493668608625, "size": 2919, "mimeType": "image/png" }, { "path": "assets/uiskin/cursors/NotAllowed.png", "modified": 1493668608628, "size": 2961, "mimeType": "image/png" }, { "path": "assets/uiskin/cursors/PointerWait.png", "modified": 1493668608630, "size": 3029, "mimeType": "image/png" }, { "path": "assets/uiskin/cursors/ResizeNE.png", "modified": 1493668608632, "size": 2884, "mimeType": "image/png" }, { "path": "assets/uiskin/cursors/ResizeSE.png", "modified": 1493668608634, "size": 2891, "mimeType": "image/png" }, { "path": "assets/uiskin/cursors/Wait.png", "modified": 1493668608636, "size": 2958, "mimeType": "image/png" } ] } """ val list = ArrayList<FileEntry>() val manifest = JsonSerializer.read(json, FilesManifestSerializer) val files = FilesImpl(manifest) files.getDir("")!!.walkFilesTopDown().forEach { fileEntry -> list.add(fileEntry) } assertEquals(files.getDir("")!!.totalFiles, list.size) assertTrue(list.isSorted()) } }
0
Kotlin
1
0
a57100f894721ee342d23fe8cacb3fcbcedbe6dc
13,252
acornui
Apache License 2.0
app/src/main/java/net/vapormusic/animexstream/ui/main/player/VideoPlayerViewModel.kt
androiddevnotesforks
337,019,411
false
null
package net.vapormusic.animexstream.ui.main.player import android.content.Intent import android.net.Uri import android.util.Log import androidx.core.content.ContextCompat.startActivity import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import io.reactivex.disposables.CompositeDisposable import io.reactivex.observers.DisposableObserver import io.realm.Realm import kotlinx.android.synthetic.main.fragment_settings.view.* import net.vapormusic.animexstream.BuildConfig import net.vapormusic.animexstream.utils.CommonViewModel import net.vapormusic.animexstream.utils.constants.C import net.vapormusic.animexstream.utils.model.Content import net.vapormusic.animexstream.utils.model.SettingsModel import net.vapormusic.animexstream.utils.parser.HtmlParser import net.vapormusic.animexstream.utils.realm.InitalizeRealm import okhttp3.ResponseBody import timber.log.Timber class VideoPlayerViewModel : CommonViewModel() { private val episodeRepository = EpisodeRepository() private var compositeDisposable = CompositeDisposable() private var _content = MutableLiveData<Content>(Content()) var liveContent: LiveData<Content> = _content init { episodeRepository.clearContent() } fun fetchEpisodeMediaUrl(fetchFromDb: Boolean = true) { liveContent.value?.episodeUrl?.let { updateErrorModel(show = false, e = null, isListEmpty = false) updateLoading(loading = true) val result = episodeRepository.fetchContent(it) val animeName = _content.value?.animeName if (fetchFromDb) { result?.let { result.animeName = animeName ?: "" _content.value = result updateLoading(false) } ?: kotlin.run { fetchFromInternet(it) } } else { fetchFromInternet(it) } } } private fun fetchFromInternet(url: String) { compositeDisposable.add( episodeRepository.fetchEpisodeMediaUrl(url = url).subscribeWith( getEpisodeUrlObserver( C.TYPE_MEDIA_URL ) ) ) } fun updateEpisodeContent(content: Content) { _content.value = content } private fun getEpisodeUrlObserver(type: Int): DisposableObserver<ResponseBody> { return object : DisposableObserver<ResponseBody>() { override fun onComplete() { updateErrorModel(show = false, e = null, isListEmpty = false) } override fun onNext(response: ResponseBody) { var googlecdn_on = false val realm: Realm = Realm.getInstance(InitalizeRealm.getConfig()); try { realm.executeTransaction { realm1: Realm -> val settings = realm1.where(SettingsModel::class.java).findFirst() if (settings == null) { val settings2 = realm1.createObject(SettingsModel::class.java) realm1.insertOrUpdate(settings2) } else { googlecdn_on = settings.googlecdn }} } catch (ignored: Exception) { } if (type == C.TYPE_MEDIA_URL) { val episodeInfo = HtmlParser.parseMediaUrl(response = response.string()) episodeInfo.vidcdnUrl?.let { Timber.e("lolxd3 :"+response.string()) var url = episodeInfo.vidcdnUrl!!.replace("streaming.php", "streaming.php") if (googlecdn_on){ url = episodeInfo.vidcdnUrl!!.replace("load.php", "loadserver.php") compositeDisposable.add( episodeRepository.fetchGoogleUrl(url).subscribeWith( getEpisodeUrlObserver(C.TYPE_M3U8_URL) // episodeRepository.fetchM3u8Url("https://gogo-stream.com/videos"+ _content.value?.episodeUrl).subscribeWith( // getEpisodeUrlObserver(C.TYPE_M3U8_PREPROCESS_URL) ) ) } else{ url = episodeInfo.vidcdnUrl!!.replace("load.php", "loadserver.php") compositeDisposable.add( episodeRepository.fetchM3u8Url(url).subscribeWith( getEpisodeUrlObserver(C.TYPE_M3U8_URL) // episodeRepository.fetchM3u8Url("https://gogo-stream.com/videos"+ _content.value?.episodeUrl).subscribeWith( // getEpisodeUrlObserver(C.TYPE_M3U8_PREPROCESS_URL) ) ) episodeRepository.fetchM3u8Urlv2( url, url.replace("loadserver.php", "streaming.php") ).subscribeWith( getEpisodeUrlObserver(C.TYPE_M3U8_URL) ) } } val watchedEpisode = episodeRepository.fetchWatchedDuration(_content.value?.episodeUrl.hashCode()) _content.value?.watchedDuration = watchedEpisode?.watchedDuration ?: 0 _content.value?.previousEpisodeUrl = episodeInfo.previousEpisodeUrl _content.value?.nextEpisodeUrl = episodeInfo.nextEpisodeUrl } else if (type == C.TYPE_M3U8_URL) { // Timber.v("vapor xcx:"+ response.string()) val m3u8Url = HtmlParser.parseM3U8Url(response = response.string()) Timber.e("lolxd4: "+ m3u8Url) val content = _content.value content?.url = m3u8Url _content.value = content saveContent(content!!) updateLoading(false) } else if (type == C.TYPE_M3U8_PREPROCESS_URL) { val m3u8Urlx = HtmlParser.getGoGoHLS(response = response.string()) Timber.e("lolxd4: "+ m3u8Urlx) val content = _content.value content?.referer = m3u8Urlx!!.replace("amp;", "").replace( "loadserver", "streaming" ) _content.value = content saveContent(content!!) compositeDisposable.add( episodeRepository.fetchM3u8Urlv2( m3u8Urlx!!.replace("amp;", "").replace( "streaming", "loadserver" ), m3u8Urlx!!.replace("amp;", "").replace("////", "//") ).subscribeWith( getEpisodeUrlObserver(C.TYPE_M3U8_URL) ) ) // Timber.e("vapor_x: "+m3u8Urlx) } } override fun onError(e: Throwable) { updateLoading(false) updateErrorModel(true, e, false) } } } fun saveContent(content: Content) { if (!content.url.isNullOrEmpty()) { episodeRepository.saveContent(content) } } override fun onCleared() { if (!compositeDisposable.isDisposed) { compositeDisposable.dispose() } super.onCleared() } }
0
Kotlin
6
9
ea8a900769abaff526f934be65eafe871209ca66
7,932
AnimeXStream
MIT License
src/main/kotlin/com/soogung/ohouse/global/security/auth/AuthDetailsService.kt
soolung
529,124,995
false
{"Kotlin": 62357}
package com.soogung.ohouse.global.security.auth import com.soogung.ohouse.domain.user.facade.UserFacade import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.stereotype.Service @Service class AuthDetailsService( val userFacade: UserFacade, ): UserDetailsService { override fun loadUserByUsername(email: String): UserDetails { return AuthDetails(userFacade.findUserByEmail(email)) } }
0
Kotlin
0
0
fd2d83227aa885e082021bbbdc98503056ef790b
516
clone-ohouse-server
MIT License
app/src/test/java/com/rrvieira/trendyt/data/movies/MoviesRemoteDataSourceTest.kt
rrvieira
485,406,045
false
null
package com.coderio.themoviedb.data.movies import com.coderio.themoviedb.api.MoviesApiClient import com.coderio.themoviedb.api.responses.MovieResponse import com.coderio.themoviedb.api.responses.PopularMovie import com.coderio.themoviedb.api.responses.PopularMoviesResponse import io.mockk.coEvery import io.mockk.mockk import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Test import java.util.* @OptIn(ExperimentalCoroutinesApi::class) class MoviesRemoteDataSourceTest { @Test fun getPopularMovies() = runTest { val popularMoviesResponse = PopularMoviesResponse( page = 1, popularMovies = listOf( PopularMovie( adult = false, backdropPath = "/sonic-backdropPath.jpg", genreIds = listOf(28, 878, 35, 10751, 12), id = 0, originalLanguage = "en", originalTitle = "Sonic the Hedgehog 2", overview = "Sonic overview.", popularity = 10.0, posterPath = "/sonic-poster.jpg", releaseDate = GregorianCalendar(2022, Calendar.MARCH, 30).time, title = "Sonic the Hedgehog 2", video = false, voteAverage = 7.7f, voteCount = 1000 ), PopularMovie( adult = false, backdropPath = "/batman-backdropPath.jpg", genreIds = listOf(80, 9648, 53), id = 1, originalLanguage = "en", originalTitle = "The Batman", overview = "Batman overview", popularity = 3.0, posterPath = "/batman-poster.jpg", releaseDate = GregorianCalendar(2022, Calendar.MARCH, 1).time, title = "The Batman", video = false, voteAverage = 7.8f, voteCount = 2000 ), ), totalPages = 1, totalResults = 2 ) val expected = Result.success(popularMoviesResponse) val pageToFetch = 1 val mockMoviesApiClient = mockk<MoviesApiClient> { coEvery { getPopularMovies(pageToFetch) } returns Result.success(popularMoviesResponse) } val moviesRemoteDataSource = MoviesRemoteDataSource(mockMoviesApiClient, UnconfinedTestDispatcher(testScheduler)) assertEquals(expected, moviesRemoteDataSource.getPopularMovies(pageToFetch)) } @Test fun getMovieDetails() = runTest { val movieDetailsResponse = MovieResponse( id = 1, title = "The Batman", tagline = "The Batman tagline", overview = "The Batman Overview", runtime = 240, voteAverage = 7.8f, releaseDate = GregorianCalendar(2022, Calendar.MARCH, 1).time, genres = listOf( MovieResponse.Genre(id = 1, name = "Action"), MovieResponse.Genre(id = 2, name = "Crime") ), posterPath = "/batman-poster.jpg", backdropPath = "/batman-backdropPath.jpg", adult = false, belongsToCollection = false, budget = 0, homepage = "", imdbId = "", originalLanguage = "", originalTitle = "", popularity = 0.0, productionCompanies = emptyList(), productionCountries = emptyList(), revenue = 0, spokenLanguages = emptyList(), status = "", video = false, voteCount = 0 ) val expected = Result.success(movieDetailsResponse) val mockMoviesApiClient = mockk<MoviesApiClient> { coEvery { getMovieDetails(movieDetailsResponse.id) } returns Result.success(movieDetailsResponse) } val moviesRemoteDataSource = MoviesRemoteDataSource(mockMoviesApiClient, UnconfinedTestDispatcher(testScheduler)) assertEquals(expected, moviesRemoteDataSource.getMovieDetails(movieDetailsResponse.id)) } }
0
null
1
2
fa5b8cdad4d37d97a015762e3485d272ad2eca34
4,410
trendyt-android-app
MIT License
app/src/iosMain/kotlin/kosh/app/di/IosAppComponent.kt
niallkh
855,100,709
false
{"Kotlin": 1892361, "Swift": 21492}
package kosh.app.di import kosh.domain.core.provider import platform.Foundation.NSBundle internal class IosAppComponent : AppComponent { override val debug: Boolean by provider { NSBundle.mainBundle.objectForInfoDictionaryKey("DEBUG") == "true" } }
0
Kotlin
0
3
e0149252019f8b47ceede5c0c1eb78c0a1e1c203
267
kosh
MIT License
kotlin/src/main/kotlin/com/laioffer/Kotlin基础/pkg17_委托/p2_属性委托/l2_非空属性/HiKotlin.kt
yuanuscfighton
632,030,844
false
{"Kotlin": 1007874, "Java": 774893}
package Kotlin基础.pkg17_委托.p2_属性委托.l2_非空属性 import kotlin.properties.Delegates /** * 类的描述: 2.委托属性 -- 非空属性 * Created by 春夏秋冬在中南 on 2023/4/15 20:12 */ class MyPerson { // notNull适用于那些无法在初始化阶段就确定的属性值的场合 var address: String by Delegates.notNull<String>() } fun main() { val myPerson = MyPerson() myPerson.address = "上海" println(myPerson.address) }
0
Kotlin
0
0
b4091c1374f5f0dc0eb8387f7d09ce00eeaacc9d
358
SiberianHusky
Apache License 2.0
app/src/main/java/tuver/movies/ui/movie/moviedetail/MovieDetailViewModel.kt
cemtuver
611,461,467
false
null
package tuver.movies.ui.movie.moviedetail import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import tuver.movies.domain.GetMovieUseCase import tuver.movies.model.MovieModel import tuver.movies.model.MovieSummaryModel import tuver.movies.util.SingleLiveEvent import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import kotlinx.coroutines.launch class MovieDetailViewModel @AssistedInject constructor( @Assisted private val movieSummaryModel: MovieSummaryModel, private val getMovieUseCase: GetMovieUseCase ) : ViewModel() { private val mutableMovieModel = MutableLiveData( movieSummaryModel.run { MovieModel( id = id, title = title, overview = overview, releaseDate = releaseDate, posterImageUrlPath = posterImageUrlPath, backdropImageUrlPath = null, runtimeInMinutes = 0 ) } ) private val mutableNavigation = tuver.movies.util.SingleLiveEvent<MovieDetailNavigation>() val movieModel: LiveData<MovieModel> get() = mutableMovieModel val navigation: LiveData<MovieDetailNavigation> get() = mutableNavigation init { viewModelScope.launch { getMovieUseCase.getMovieUseCase(movieSummaryModel.id).onSuccess { mutableMovieModel.postValue(it) } } } fun onBackClick() { mutableNavigation.postValue(MovieDetailNavigation.NavigateUp) } companion object { @AssistedFactory interface Factory { fun create(movieSummaryModel: MovieSummaryModel): MovieDetailViewModel } } }
0
Kotlin
0
0
657f26f39607f47634e97708281426bdb9652a48
1,847
android-movies
MIT License
app/src/main/java/com/example/testassigmentlogin/usecase/ObserveUserUseCase.kt
mikhail-vasilyeu
498,242,010
false
null
package com.example.testassigmentlogin.usecase import com.example.testassigmentlogin.model.domain.User import com.example.testassigmentlogin.utils.DATASTORE_LOGGED_IN_EMAIL_KEY import com.example.testassigmentlogin.utils.DatastoreManager import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import javax.inject.Inject class ObserveUserUseCase @Inject constructor( private val datastoreManager: DatastoreManager ) { operator fun invoke(): Flow<User?> { return datastoreManager.observeKeyValue(DATASTORE_LOGGED_IN_EMAIL_KEY).map { if (it != null) { User(it) } else { null } } } }
0
Kotlin
0
0
c11d8d2a5704340a7d1703e9ddbc96598e62b929
694
smalpe-login-application
Apache License 2.0
barchart/src/main/kotlin/com/tomasznajda/tomobarchart/label/ImageUrlLabel.kt
tomasznajda
158,443,259
false
null
package com.tomasznajda.tomobarchart.label import android.view.View import com.squareup.picasso.Picasso import com.tomasznajda.ktx.android.gone import com.tomasznajda.ktx.android.visible import kotlinx.android.synthetic.main.view_chart_item.view.* data class ImageUrlLabel(val url: String) : Label { override fun render(view: View) = with(view) { Picasso.get().load(url).into(imgLabel) imgLabel.visible() txtLabel.gone() } }
0
Kotlin
0
0
1947551a2c906f98f454f3daa0423d0f03e95f28
459
tomo-bar-chart
Apache License 2.0
src/main/kotlin/com/cognifide/gradle/aem/pkg/tasks/sync/CleanerRule.kt
wttech
90,353,060
false
null
package com.cognifide.gradle.aem.pkg.tasks.sync import com.cognifide.gradle.common.utils.Patterns import com.cognifide.gradle.aem.common.pkg.vault.VaultException import java.io.File class CleanerRule(value: String) { private var pattern: String = value private var excludedPaths: List<String> = listOf() private var includedPaths: List<String> = listOf() init { if (value.contains(PATHS_DELIMITER)) { val parts = value.split(PATHS_DELIMITER) if (parts.size == 2) { pattern = parts[0].trim() val paths = parts[1].split(PATH_DELIMITER) excludedPaths = paths.filter { it.contains(EXCLUDE_FLAG) }.map { it.removePrefix(EXCLUDE_FLAG).trim() } includedPaths = paths.filter { !it.contains(EXCLUDE_FLAG) }.map { it.trim() } } else { throw VaultException("Cannot parse VLT content property: '$value'") } } } private fun isIncluded(file: File) = Patterns.wildcard(file, includedPaths) private fun isExcluded(file: File) = Patterns.wildcard(file, excludedPaths) fun match(file: File, value: String): Boolean { return Patterns.wildcard(value, pattern) && match(file) } private fun match(file: File): Boolean { return (excludedPaths.isEmpty() || !isExcluded(file)) && (includedPaths.isEmpty() || isIncluded(file)) } companion object { const val PATHS_DELIMITER = "|" const val PATH_DELIMITER = "," const val EXCLUDE_FLAG = "!" fun manyFrom(props: List<String>): List<CleanerRule> { return props.map { CleanerRule(it) } } } }
67
null
35
158
18d6cab33481f8f883c6139267fb059f7f6047ae
1,690
gradle-aem-plugin
Apache License 2.0
CodeCafe/app/src/main/java/top/codecafe/app/utils/SupportMethod.kt
yumobei
44,727,078
true
{"Java": 485775, "Kotlin": 48474}
package top.codecafe.app.utils import android.app.Activity import android.content.Context import android.content.Intent import android.support.v4.app.Fragment import android.util.Log import android.util.TypedValue import android.widget.Toast /** * 工具方法 * * @author kymjs (http://www.kymjs.com/) on 15/8/21. */ fun Context.toast(message: CharSequence, cxt: Context = this, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(cxt, message, duration).show() } fun Fragment.toast(message: CharSequence, cxt: Context = activity, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(cxt, message, duration).show() } fun Context.screenHeight(): Int = getResources().getDisplayMetrics().heightPixels fun Context.screenWidth(): Int = getResources().getDisplayMetrics().widthPixels fun Context.dip2px(dpValue: Float): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, getResources().getDisplayMetrics()).toInt(); fun Context.sp2px(value: Float): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, value, getResources().getDisplayMetrics()).toInt(); fun Context.px2sp(value: Float): Int = (value / getResources().getDisplayMetrics().scaledDensity + 0.5f).toInt() fun Context.px2dp(value: Float): Int = (value / getResources().getDisplayMetrics().density + 0.5f).toInt() fun Context.showActivity(clazz: Class<*>) { startActivity(Intent(this, clazz)) } fun Context.showActivity(intent: Intent) { startActivity(intent) } fun Activity.skipActivity(clazz: Class<*>) { startActivity(Intent(this, clazz)) finish(); } fun Fragment.showActivity(clazz: Class<*>) { startActivity(Intent(getActivity(), clazz)) } fun Fragment.showActivity(intent: Intent) { startActivity(intent) } fun Fragment.skipActivity(clazz: Class<*>) { startActivity(Intent(getActivity(), clazz)) getActivity().finish(); } fun Any.kjlog(msg: String? = "") { val element: StackTraceElement = Thread.currentThread().getStackTrace()[3] Log.i("kymjs", StringBuilder().append("[") .append(element.getFileName()) .append(":") .append(element.getLineNumber()) .append("]-->") .append(msg ?: "").toString()) }
0
Java
0
0
62b9256a46ad13919237125766f0e71681088d1a
2,227
CodeCafe
Apache License 2.0
app/src/main/java/com/surrus/galwaybus/model/BusRoute.kt
puru2u
260,859,968
true
{"Kotlin": 144432, "Java": 73115, "Swift": 14760, "GLSL": 9264, "Ruby": 6076, "JavaScript": 651, "HTML": 572}
package com.surrus.galwaybus.model import androidx.room.Entity import androidx.room.PrimaryKey import com.surrus.galwaybus.cache.db.GalwayBusDatabaseConstants @Entity(tableName = GalwayBusDatabaseConstants.BUS_ROUTES_TABLE_NAME) data class BusRoute(@PrimaryKey val timetableId: String, val longName: String, val shortName: String)
0
null
0
0
7c06ce70bff9ab4bfd9a00bf1ce0d6d516335f5e
334
galway-bus-android
MIT License
app/src/main/java/com/example/superwe/Utils.kt
PhoenixMiao
607,780,081
false
null
package com.example.superwe import android.widget.Toast /** * 描述:包装Toast */ fun shortToast(msg: String) = Toast.makeText(SuperApp.instance, msg, Toast.LENGTH_SHORT).show() fun longToast(msg: String) = Toast.makeText(SuperApp.instance, msg, Toast.LENGTH_LONG).show()
0
Kotlin
0
0
d84c0f6c767b4b7068a678be6263bab2c1c0257e
270
SuperWe
Mulan Permissive Software License, Version 2
generator/src/main/kotlin/family/amma/deep_link/generator/fileSpec/common/Minor.kt
AMMA-Family
339,682,898
false
null
package family.amma.deep_link.generator.fileSpec.common import family.amma.deep_link.generator.entity.DeepLink import family.amma.deep_link.generator.ext.toCamelCase internal val indent: String = List(size = 4) { ' ' }.joinToString(separator = "") internal fun DeepLink.camelCaseName() = id.identifier.toCamelCase()
0
Kotlin
0
9
98364a6bf39aaaf37adba8c7c446b124c5352938
319
android-navigation-deeplinks
MIT License
src/main/kotlin/team/karakum/App.kt
aerialist7
388,885,791
false
null
package team.karakum import csstype.Auto.auto import csstype.Display import csstype.GridTemplateAreas import csstype.array import kotlinx.browser.document import mui.material.useMediaQuery import mui.system.Box import mui.system.sx import react.FC import react.Props import react.create import react.dom.client.createRoot import react.router.dom.HashRouter import team.karakum.common.Area import team.karakum.common.Sizes.Header import team.karakum.common.Sizes.Sidebar import team.karakum.component.* fun main() { createRoot(document.createElement("div").also { document.body!!.appendChild(it) }) .render(App.create()) } private val App = FC<Props> { val mobileMode = useMediaQuery("(max-width:960px)") HashRouter { ShowcasesModule { ThemeModule { Box { sx { display = Display.grid gridTemplateRows = array( Header.Height, auto, ) gridTemplateColumns = array( Sidebar.Width, auto, ) gridTemplateAreas = GridTemplateAreas( arrayOf(Area.Header, Area.Header), if (mobileMode) arrayOf(Area.Content, Area.Content) else arrayOf(Area.Sidebar, Area.Content), ) } Header() if (mobileMode) Menu() else Sidebar() Content() } } } } }
0
Kotlin
6
43
c44c8dbc20da85090fc5dbd3823f26a07cdac56e
1,724
kotlin-material-ui-sample
Apache License 2.0
src/testFixtures/kotlin/uk/gov/justice/digital/hmpps/educationandworkplanapi/resource/model/induction/InductionResponseAssert.kt
ministryofjustice
653,598,082
false
{"Kotlin": 1103515, "Mustache": 2705, "Dockerfile": 1346}
package uk.gov.justice.digital.hmpps.educationandworkplanapi.resource.model.induction import org.assertj.core.api.AbstractObjectAssert import uk.gov.justice.digital.hmpps.educationandworkplanapi.resource.model.FutureWorkInterestsResponse import java.time.OffsetDateTime import java.util.UUID fun assertThat(actual: FutureWorkInterestsResponse?) = FutureWorkInterestsResponseAssert(actual) /** * AssertJ custom assertion for a single [FutureWorkInterestsResponse]. */ class FutureWorkInterestsResponseAssert(actual: FutureWorkInterestsResponse?) : AbstractObjectAssert<FutureWorkInterestsResponseAssert, FutureWorkInterestsResponse?>( actual, FutureWorkInterestsResponseAssert::class.java, ) { fun hasReference(expected: UUID): FutureWorkInterestsResponseAssert { isNotNull with(actual!!) { if (reference != expected) { failWithMessage("Expected reference to be $expected, but was $reference") } } return this } fun wasCreatedAt(expected: OffsetDateTime): FutureWorkInterestsResponseAssert { isNotNull with(actual!!) { if (createdAt != expected) { failWithMessage("Expected createdAt to be $expected, but was $createdAt") } } return this } fun wasCreatedAfter(dateTime: OffsetDateTime): FutureWorkInterestsResponseAssert { isNotNull with(actual!!) { if (!createdAt.isAfter(dateTime)) { failWithMessage("Expected createdAt to be after $dateTime, but was $createdAt") } } return this } fun wasUpdatedAt(expected: OffsetDateTime): FutureWorkInterestsResponseAssert { isNotNull with(actual!!) { if (updatedAt != expected) { failWithMessage("Expected updatedAt to be $expected, but was $updatedAt") } } return this } fun wasUpdatedAfter(dateTime: OffsetDateTime): FutureWorkInterestsResponseAssert { isNotNull with(actual!!) { if (!updatedAt.isAfter(dateTime)) { failWithMessage("Expected updatedAt to be after $dateTime, but was $updatedAt") } } return this } fun wasCreatedBy(expected: String): FutureWorkInterestsResponseAssert { isNotNull with(actual!!) { if (createdBy != expected) { failWithMessage("Expected createdBy to be $expected, but was $createdBy") } } return this } fun wasCreatedByDisplayName(expected: String): FutureWorkInterestsResponseAssert { isNotNull with(actual!!) { if (createdByDisplayName != expected) { failWithMessage("Expected createdByDisplayName to be $expected, but was $createdByDisplayName") } } return this } fun wasUpdatedBy(expected: String): FutureWorkInterestsResponseAssert { isNotNull with(actual!!) { if (updatedBy != expected) { failWithMessage("Expected updatedBy to be $expected, but was $updatedBy") } } return this } fun wasUpdatedByDisplayName(expected: String): FutureWorkInterestsResponseAssert { isNotNull with(actual!!) { if (updatedByDisplayName != expected) { failWithMessage("Expected updatedByDisplayName to be $expected, but was $updatedByDisplayName") } } return this } fun wasCreatedAtPrison(expected: String): FutureWorkInterestsResponseAssert { isNotNull with(actual!!) { if (createdAtPrison != expected) { failWithMessage("Expected createdAtPrison to be $expected, but was $createdAtPrison") } } return this } fun wasUpdatedAtPrison(expected: String): FutureWorkInterestsResponseAssert { isNotNull with(actual!!) { if (updatedAtPrison != expected) { failWithMessage("Expected updatedAtPrison to be $expected, but was $updatedAtPrison") } } return this } }
7
Kotlin
0
2
f5c50221eca6847fff26d03ed9e55175da077bc6
3,781
hmpps-education-and-work-plan-api
MIT License
core/test/utils/src/main/kotlin/org/sollecitom/chassis/core/test/utils/Assertions.kt
sollecitom
669,483,842
false
{"Kotlin": 808742, "Java": 30834}
package org.sollecitom.chassis.core.test.utils import assertk.Assert import assertk.assertions.isEqualTo import org.sollecitom.chassis.core.domain.naming.Name fun Assert<Name>.hasValue(expectedValue: String) = given { actual -> assertThat(actual.value).isEqualTo(expectedValue) }
0
Kotlin
0
2
a9ffd2d2fd649fc1c967098da9add4aac73a74b0
286
chassis
MIT License
app/src/main/java/com/example/android/notas/NovaNotaActivity.kt
Yusufaky
347,202,803
false
null
package com.example.android.notas import android.app.Activity import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.util.Log import android.widget.Button import android.widget.EditText import androidx.appcompat.app.AppCompatActivity import com.aplicacao.android.notas.R class NovaNotaActivity : AppCompatActivity() { public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_new_nota) val editnotaView = findViewById<EditText>(R.id.edit_nota) val editnotaViewProblema = findViewById<EditText>(R.id.edit_problema) var id: Int = intent.getIntExtra("ID", 0) var editNota = intent.getStringExtra("nota") var editProblema = intent.getStringExtra("problema") findViewById<EditText>(R.id.edit_nota).setText(editNota) findViewById<EditText>(R.id.edit_problema).setText(editProblema) val button = findViewById<Button>(R.id.guardar) button.setOnClickListener { val replyIntent = Intent() if (TextUtils.isEmpty(editnotaView.text) || TextUtils.isEmpty(editnotaViewProblema.text)) { setResult(Activity.RESULT_CANCELED, replyIntent) } else { val nota = editnotaView.text.toString() val problema = editnotaViewProblema.text.toString() replyIntent.putExtra(EXTRA_REPLY_Nota, nota) replyIntent.putExtra(EXTRA_REPLY_Problema, problema) replyIntent.putExtra(EXTRA_REPLY_ID, id) setResult(Activity.RESULT_OK, replyIntent) } finish() } } companion object { const val EXTRA_REPLY_Nota = "com.example.android.nota" const val EXTRA_REPLY_Problema = "com.example.android.problema" const val EXTRA_REPLY_ID = "com.example.android.id" } }
0
Kotlin
0
0
767a5b8b95f38b435448dcff875a9f1922eacbea
1,961
Nota
Apache License 2.0
component/component-kaiheila-parent/kaiheila-core/src/main/java/love/forte/simbot/kaiheila/event/system/channel/SelfJoinedGuild.kt
simple-robot
554,852,615
false
null
package love.forte.simbot.kaiheila.event.system.channel import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * * 自己加入服务器 * * `self_joined_guild` * * @author ForteScarlet */ @Serializable public data class SelfJoinedGuildExtraBody( @SerialName("guild_id") val guildId: String, ) : ChannelEventExtraBody
0
Kotlin
0
3
c5d7c9ca8c81b2bddc250090739d7c7d0c110328
352
simple-robot-v2
Apache License 2.0
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/quicksight/CfnAnalysisTextControlPlaceholderOptionsPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION") package cloudshift.awscdk.dsl.services.quicksight import cloudshift.awscdk.common.CdkDslMarker import software.amazon.awscdk.services.quicksight.CfnAnalysis import kotlin.String /** * The configuration of the placeholder options in a text control. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.quicksight.*; * TextControlPlaceholderOptionsProperty textControlPlaceholderOptionsProperty = * TextControlPlaceholderOptionsProperty.builder() * .visibility("visibility") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-analysis-textcontrolplaceholderoptions.html) */ @CdkDslMarker public class CfnAnalysisTextControlPlaceholderOptionsPropertyDsl { private val cdkBuilder: CfnAnalysis.TextControlPlaceholderOptionsProperty.Builder = CfnAnalysis.TextControlPlaceholderOptionsProperty.builder() /** * @param visibility The visibility configuration of the placeholder options in a text control. */ public fun visibility(visibility: String) { cdkBuilder.visibility(visibility) } public fun build(): CfnAnalysis.TextControlPlaceholderOptionsProperty = cdkBuilder.build() }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
1,528
awscdk-dsl-kotlin
Apache License 2.0
nbt_data_remote/src/main/java/com/example/nbt_data_remote/data_transfer_models/NetworkFood.kt
adnanharis
326,511,418
false
null
package com.example.nbt_data_remote.data_transfer_models import com.example.nbt_domain.models.Food import com.squareup.moshi.JsonClass /** * Network related models for domain models */ @JsonClass(generateAdapter = true) data class NetworkFoodContainer(val meals: List<NetworkFood>) @JsonClass(generateAdapter = true) data class NetworkFood(val idMeal: String, val strMeal: String, val strMealThumb: String) fun NetworkFoodContainer.asDomainModel(category: String): List<Food> { return meals.map { Food(it.idMeal, it.strMeal, it.strMealThumb, category) } }
0
Kotlin
0
0
839f61fcdbb3f5ca547f2991554b107a8021dab4
578
DinDinnTest
Apache License 2.0
src/main/kotlin/ru/nsu/lupa/ChainNode.kt
lilvadim
576,661,907
false
{"Kotlin": 22514, "Java": 836}
package ru.nsu.lupa /** * Linked list like data structure */ data class ChainNode<L, N>( val value: N?, /** * Null if there is no next node */ var next: ChainNode<L, N>?, /** * Null if there is no next node */ val label: L? )
0
Kotlin
0
0
9388aa69457bc625317a3732f2afcd52e02ef1a1
268
lupa
Apache License 2.0
barrage-fly/src/main/java/tech/ordinaryroad/barrage/fly/util/BarrageFlyUtil.kt
OrdinaryRoad-Project
689,200,873
false
null
/* * Copyright 2023 OrdinaryRoad * * 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 tech.ordinaryroad.barrage.fly.util import cn.hutool.core.io.FileUtil import cn.hutool.core.io.resource.ResourceUtil import cn.hutool.core.util.RandomUtil import cn.hutool.extra.spring.SpringUtil import tech.ordinaryroad.barrage.fly.constant.MsgTypeEnum import tech.ordinaryroad.barrage.fly.constant.PlatformEnum import tech.ordinaryroad.barrage.fly.dal.entity.BarrageFlyTaskDO import tech.ordinaryroad.barrage.fly.dto.msg.BarrageFlyMsgDTO import tech.ordinaryroad.barrage.fly.express.BarrageFlyExpressContext import tech.ordinaryroad.barrage.fly.express.BarrageFlyExpressRunner import tech.ordinaryroad.barrage.fly.express.operator.OperatorSendDanmu.Companion.KEY_DO_SEND_DANMU_BOOLEAN import tech.ordinaryroad.live.chat.client.codec.bilibili.msg.DanmuMsgMsg import tech.ordinaryroad.live.chat.client.codec.bilibili.msg.SendGiftMsg import tech.ordinaryroad.live.chat.client.codec.bilibili.msg.SuperChatMessageMsg import tech.ordinaryroad.live.chat.client.codec.douyu.msg.ChatmsgMsg import tech.ordinaryroad.live.chat.client.codec.douyu.msg.DgbMsg import tech.ordinaryroad.live.chat.client.codec.huya.msg.MessageNoticeMsg import tech.ordinaryroad.live.chat.client.codec.huya.msg.SendItemSubBroadcastPacketMsg import tech.ordinaryroad.live.chat.client.commons.base.msg.IMsg import tech.ordinaryroad.live.chat.client.commons.util.OrJacksonUtil import tech.ordinaryroad.live.chat.client.commons.util.OrLiveChatCookieUtil import java.util.function.Consumer /** * * * @author mjz * @date 2023/9/15 */ object BarrageFlyUtil { private val msgFiles = arrayOf( "express/msg-examples-bilibili.txt", "express/msg-examples-bilibili-SUPER_CHAT.txt", "express/msg-examples-douyu.txt", "express/msg-examples-huya.txt" ) fun generateRandomMsgDTOs(count: Int = 10, consumer: Consumer<BarrageFlyMsgDTO>) { var current = 0 while (current < count) { for (i in msgFiles.indices) { val msgFile = msgFiles.random() val lines = FileUtil.readUtf8Lines(ResourceUtil.getResource(msgFile)) for (j in 0 until lines.size) { val line = lines.random() if (current >= count) { return } var barrageFlyMsgDTO: BarrageFlyMsgDTO? = null try { val jsonNode = OrJacksonUtil.getInstance().readTree(line) val roomId = jsonNode.get("roomId").asText() val msgString = jsonNode.get("msg").toString() val platformEnum = PlatformEnum.getByString(jsonNode.get("platform").asText()) val msgTypeEnum = MsgTypeEnum.getByString(jsonNode.get("type").asText()) val msg: IMsg? = if (platformEnum == null || msgTypeEnum == null) null else when (platformEnum) { PlatformEnum.BILIBILI -> { when (msgTypeEnum) { MsgTypeEnum.DANMU -> OrJacksonUtil.getInstance().readValue( msgString, DanmuMsgMsg::class.java ) MsgTypeEnum.GIFT -> OrJacksonUtil.getInstance().readValue( msgString, SendGiftMsg::class.java ) MsgTypeEnum.SUPER_CHAT -> OrJacksonUtil.getInstance().readValue( msgString, SuperChatMessageMsg::class.java ) else -> null } } PlatformEnum.DOUYU -> { when (msgTypeEnum) { MsgTypeEnum.DANMU -> OrJacksonUtil.getInstance().readValue( msgString, ChatmsgMsg::class.java ) MsgTypeEnum.GIFT -> OrJacksonUtil.getInstance().readValue( msgString, DgbMsg::class.java ) MsgTypeEnum.SUPER_CHAT -> { null } else -> null } } PlatformEnum.HUYA -> { when (msgTypeEnum) { MsgTypeEnum.DANMU -> OrJacksonUtil.getInstance().readValue( msgString, MessageNoticeMsg::class.java ) MsgTypeEnum.GIFT -> { OrJacksonUtil.getInstance().readValue( msgString, SendItemSubBroadcastPacketMsg::class.java ) } MsgTypeEnum.SUPER_CHAT -> { null } else -> null } } else -> null } if (msg != null) { barrageFlyMsgDTO = BarrageFlyMsgDTO(roomId, msg) } } catch (e: Exception) { // ignore } if (barrageFlyMsgDTO != null && RandomUtil.randomBoolean()) { current++ consumer.accept(barrageFlyMsgDTO) } } } } } fun generateRandomMsgDTOs(count: Int = 10): List<BarrageFlyMsgDTO> { val list = ArrayList<BarrageFlyMsgDTO>(count) generateRandomMsgDTOs(count, list::add) while (list.size > count) { list.removeAt(list.size - 1) } return list } fun BarrageFlyTaskDO.validate(): Boolean { if (platform == null) { return false } if (roomId.isNullOrBlank()) { return false } try { OrLiveChatCookieUtil.parseCookieString(cookie) } catch (e: Exception) { throw e } return true } fun BarrageFlyTaskDO.validateTaskExpress(): Boolean { try { val expressRunner = SpringUtil.getBean(BarrageFlyExpressRunner::class.java) val context = BarrageFlyExpressContext() context[KEY_DO_SEND_DANMU_BOOLEAN] = false generateRandomMsgDTOs().forEach { msgDTO -> context.setMsg(msgDTO) var result = expressRunner.executePreMapExpress(this.msgPreMapExpress, context) context.setMsg(result) if (expressRunner.executeFilterExpress(this.msgFilterExpress, context)) { result = expressRunner.executePostMapExpress(this.msgPostMapExpress, context) context.setMsg(result) } } } catch (e: Exception) { throw e } return true } @JvmStatic fun main(args: Array<String>) { val generateRandomMsgDTOs = generateRandomMsgDTOs(10) println(generateRandomMsgDTOs.size) for (msg in generateRandomMsgDTOs) { println(msg) } } }
8
null
2
26
19d790f0adb366caaf1b3df2e3b2b474bde5ae61
8,649
ordinaryroad-barrage-fly
Apache License 2.0
src/test/kotlin/uk/gov/justice/hmpps/probationsearch/controllers/ProbationStatusIntegrationTest.kt
ministryofjustice
226,127,381
false
null
package uk.gov.justice.hmpps.offendersearch.controllers import io.restassured.RestAssured import net.javacrumbs.jsonunit.assertj.assertThatJson import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.springframework.http.MediaType import uk.gov.justice.hmpps.offendersearch.util.LocalStackHelper class ProbationStatusIntegrationTest : LocalstackIntegrationBase() { @BeforeEach fun `load offenders`() { LocalStackHelper(esClient).loadData() } @Nested inner class OffenderSearch { @Test fun `ProbationStatus is returned from the search`() { val response = RestAssured.given() .auth() .oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY")) .contentType(MediaType.APPLICATION_JSON_VALUE) .body("""{"crn": "X00001"}""") .post("/search") .then() .statusCode(200) .extract() .body().asString() assertThatJson(response).node("[0].otherIds.crn").isEqualTo("X00001") assertThatJson(response).node("[0].probationStatus.status").isEqualTo("CURRENT") assertThatJson(response).node("[0].probationStatus.inBreach").isEqualTo(true) assertThatJson(response).node("[0].probationStatus.preSentenceActivity").isEqualTo(false) assertThatJson(response).node("[0].probationStatus.previouslyKnownTerminationDate").isEqualTo("2021-02-08") } @Test fun `ProbationStatus with null fields is handled in the response`() { val response = RestAssured.given() .auth() .oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY")) .contentType(MediaType.APPLICATION_JSON_VALUE) .body("""{"crn": "X00004"}""") .post("/search") .then() .statusCode(200) .extract() .body().asString() assertThatJson(response).node("[0].otherIds.crn").isEqualTo("X00004") assertThatJson(response).node("[0].probationStatus.status").isEqualTo("PREVIOUSLY_KNOWN") assertThatJson(response).node("[0].probationStatus.inBreach").isAbsent() assertThatJson(response).node("[0].probationStatus.preSentenceActivity").isEqualTo(false) assertThatJson(response).node("[0].probationStatus.previouslyKnownTerminationDate").isAbsent() } @Test fun `Missing ProbationStatus is not included in the response`() { val response = RestAssured.given() .auth() .oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY")) .contentType(MediaType.APPLICATION_JSON_VALUE) .body("""{"crn": "X00002"}""") .post("/search") .then() .statusCode(200) .extract() .body().asString() assertThatJson(response).node("[0].otherIds.crn").isEqualTo("X00002") assertThatJson(response).node("[0].probationStatus").isAbsent() } } @Nested inner class OffenderMatch { @Test fun `ProbationStatus is returned from the match`() { val response = RestAssured.given() .auth() .oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY")) .contentType(MediaType.APPLICATION_JSON_VALUE) .body("""{"surname": "Smith", "dateOfBirth": "1978-01-06"}""") .post("/match") .then() .statusCode(200) .extract() .body().asString() assertThatJson(response).node("matches[0].offender.otherIds.crn").isEqualTo("X00001") assertThatJson(response).node("matches[0].offender.probationStatus.status").isEqualTo("CURRENT") assertThatJson(response).node("matches[0].offender.probationStatus.inBreach").isEqualTo(true) assertThatJson(response).node("matches[0].offender.probationStatus.preSentenceActivity").isEqualTo(false) assertThatJson(response).node("matches[0].offender.probationStatus.previouslyKnownTerminationDate").isEqualTo("2021-02-08") } @Test fun `ProbationStatus with null fields is returned from the match`() { val response = RestAssured.given() .auth() .oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY")) .contentType(MediaType.APPLICATION_JSON_VALUE) .body("""{"surname": "Gramsci", "dateOfBirth": "1988-01-06"}""") .post("/match") .then() .statusCode(200) .extract() .body().asString() assertThatJson(response).node("matches[0].offender.otherIds.crn").isEqualTo("X00004") assertThatJson(response).node("matches[0].offender.probationStatus.status").isEqualTo("PREVIOUSLY_KNOWN") assertThatJson(response).node("matches[0].offender.probationStatus.inBreach").isAbsent() assertThatJson(response).node("matches[0].offender.probationStatus.preSentenceActivity").isEqualTo(false) assertThatJson(response).node("matches[0].offender.probationStatus.previouslyKnownTerminationDate").isAbsent() } @Test fun `Missing ProbationStatus is not included in the response`() { val response = RestAssured.given() .auth() .oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY")) .contentType(MediaType.APPLICATION_JSON_VALUE) .body("""{"surname": "Smith", "dateOfBirth": "1978-01-16"}""") .post("/match") .then() .statusCode(200) .extract() .body().asString() assertThatJson(response).node("matches[0].offender.otherIds.crn").isEqualTo("X00002") assertThatJson(response).node("matches[0].offender.probationStatus").isAbsent() } } }
3
null
2
3
f0dbcdf231c343380284f56f4796a272ddbb5ae2
5,503
probation-offender-search
MIT License
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/Eject.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36756847}
package compose.icons.cssggicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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 compose.icons.CssGgIcons public val CssGgIcons.Eject: ImageVector get() { if (_eject != null) { return _eject!! } _eject = Builder(name = "Eject", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.9498f, 14.3948f) lineTo(18.364f, 12.9805f) lineTo(12.0f, 6.6166f) lineTo(5.6361f, 12.9805f) lineTo(7.0503f, 14.3948f) lineTo(12.0f, 9.445f) lineTo(16.9498f, 14.3948f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(6.0001f, 17.3835f) horizontalLineTo(18.0001f) verticalLineTo(15.3835f) horizontalLineTo(6.0001f) verticalLineTo(17.3835f) close() } } .build() return _eject!! } private var _eject: ImageVector? = null
15
Kotlin
20
460
651badc4ace0137c5541f859f61ffa91e5242b83
2,104
compose-icons
MIT License
src/main/kotlin/com/xxuz/piclane/foltiaapi/model/vo/StationQueryInput.kt
piclane
471,198,708
false
{"Kotlin": 136299, "Shell": 2824}
package com.xxuz.piclane.foltiaapi.model.vo import com.xxuz.piclane.foltiaapi.model.Station /** * チャンネルクエリ入力 */ data class StationQueryInput( /** * 受信可能なチャンネルのみを取得する場合 true * 受信不能なチャンネルのみを取得する場合 false * すべてのチャンネルを取得する場合 null */ val receivableStation: Boolean?, /** * チャンネル種別 */ val digitalStationBands: Set<Station.DigitalStationBand>?, )
0
Kotlin
0
0
0213e646e16fe68829304911d832eb4f192896c4
390
FalPlusAPI
MIT License
Android/Podium/app/src/main/java/xyz/thisisjames/boulevard/android/podium/listmanagers/OptionsRecyclerAdapter.kt
JamesNjong
652,773,723
false
{"Kotlin": 76766, "JavaScript": 13790}
package xyz.thisisjames.boulevard.android.podium.listmanagers import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import xyz.thisisjames.boulevard.android.podium.R import xyz.thisisjames.boulevard.android.podium.R.color.dark_primary import xyz.thisisjames.boulevard.android.podium.databinding.OptionsItemBinding import xyz.thisisjames.boulevard.android.podium.listmanagers.viewholders.OptionsViewHolder import xyz.thisisjames.boulevard.android.podium.models.Options class OptionsRecyclerAdapter (private val values: List<Options>, private val currentAnswer:Int, private val onItemClicked: (Int,Boolean)->Unit) : RecyclerView.Adapter<OptionsViewHolder>() { private lateinit var context:Context; override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OptionsViewHolder { context = parent.context return OptionsViewHolder( OptionsItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemCount(): Int { return values.size } override fun onBindViewHolder(holder: OptionsViewHolder, position: Int) { val item = values[position] holder.textView.text = item.text holder.radioButton.isChecked = position == currentAnswer holder.radioButton.setOnCheckedChangeListener { buttonView, isChecked -> onItemClicked(position, isChecked) } holder.itemView.setOnClickListener{ onItemClicked(position, true) } if (position == currentAnswer){ holder.itemView.background = context.getDrawable(R.drawable.option_selected) holder.tag.setTextColor(context.getColor(dark_primary) ) holder.textView.setTextColor(context.getColor(dark_primary) ) } holder.tag.text = when(position){ 0 -> "A" 1-> "B" 2-> "C" else -> "D" } } }
0
Kotlin
0
0
0d843d3045de6b0cd9eff085f2f289fc4a653488
2,119
Podium
Creative Commons Zero v1.0 Universal
src/main/kotlin/org/rust/lang/core/psi/ext/RsTypeReference.kt
mattsse
211,165,404
true
{"Kotlin": 3257698, "Rust": 77474, "Lex": 18933, "HTML": 11268, "Shell": 760, "Java": 586, "RenderScript": 318}
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import com.intellij.psi.util.PsiTreeUtil import org.rust.lang.core.psi.RsTypeReference val RsTypeReference.typeElement: RsTypeElement? get() = PsiTreeUtil.getStubChildOfType(this, RsTypeElement::class.java)
1
null
1
1
fd96ed4524a6365ea89bfad3e761954a1361edbc
357
intellij-rust
MIT License
vgsshow/src/test/java/com/verygoodsecurity/vgsshow/widget/text/method/RangePasswordTransformationMethodTest.kt
ilovetea
329,250,478
true
{"Kotlin": 138221}
package com.verygoodsecurity.vgsshow.widget.text.method import com.verygoodsecurity.vgsshow.widget.view.textview.method.RangePasswordTransformationMethod import org.junit.Assert.assertEquals import org.junit.Test class RangePasswordTransformationMethodTest { @Test fun test_1() { val charSequence = RangePasswordTransformationMethod() .getTransformation(EXAMPLE, null) assertEquals("••••••••••••••••", charSequence.toString()) } @Test fun test_2() { val charSequence = RangePasswordTransformationMethod(6, 12) .getTransformation(EXAMPLE, null) assertEquals("424242••••••4242", charSequence.toString()) } @Test fun test_3() { val charSequence = RangePasswordTransformationMethod(start = -12) .getTransformation(EXAMPLE, null) assertEquals("••••••••••••••••", charSequence.toString()) } @Test fun test_4() { val charSequence = RangePasswordTransformationMethod(start = 77) .getTransformation(EXAMPLE, null) assertEquals("••••••••••••••••", charSequence.toString()) } @Test fun test_5() { val charSequence = RangePasswordTransformationMethod(start = 3) .getTransformation(EXAMPLE, null) assertEquals("424•••••••••••••", charSequence.toString()) } @Test fun test_6() { val charSequence = RangePasswordTransformationMethod(7, 3) .getTransformation(EXAMPLE, null) assertEquals("••••••••••••••••", charSequence.toString()) } @Test fun test_7() { val charSequence = RangePasswordTransformationMethod(end = 3) .getTransformation(EXAMPLE, null) assertEquals("•••2424242424242", charSequence.toString()) } @Test fun test_8() { val charSequence = RangePasswordTransformationMethod(end = -3) .getTransformation(EXAMPLE, null) assertEquals("••••••••••••••••", charSequence.toString()) } @Test fun test_9() { val charSequence = RangePasswordTransformationMethod(end = 88) .getTransformation(EXAMPLE, null) assertEquals("••••••••••••••••", charSequence.toString()) } @Test fun test_10() { val charSequence = RangePasswordTransformationMethod(3, 3) .getTransformation(EXAMPLE, null) assertEquals("4242424242424242", charSequence.toString()) } @Test fun test_11() { val charSequence = RangePasswordTransformationMethod(3, 3) .getTransformation("", null) assertEquals("", charSequence.toString()) } @Test fun test_12() { val text = "*&&^%\$#@!()_+_\\\\}{}\$" val charSequence = RangePasswordTransformationMethod() .getTransformation(text, null) assertEquals("••••••••••••••••••••", charSequence.toString()) } companion object { private const val EXAMPLE = "4242424242424242" } }
0
null
0
0
d5b5bb673917f1c6b63230a31a8cbca0a61c79e4
2,990
vgs-show-android
MIT License
src/main/kotlin/no/nav/syfo/model/Sykmelder.kt
navikt
250,256,212
false
null
package no.nav.syfo.model import no.nav.syfo.client.Godkjenning data class Sykmelder( val hprNummer: String?, val fnr: String?, val aktorId: String?, val fornavn: String?, val mellomnavn: String?, val etternavn: String?, val godkjenninger: List<Godkjenning>? )
2
Kotlin
1
0
91651e063517e3e7eddddf2b2f464455aa51825a
291
smregistrering-backend
MIT License
src/main/kotlin/io/swagger/client/models/TransactionDto.kt
em-ad
443,796,768
false
null
/** * Datyar REST APIs * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.swagger.client.models import io.swagger.client.models.StateMachine_string_ /** * * @param amount * @param paymentToken * @param stateMachine * @param subscriberId * @param userId */ data class TransactionDto ( val amount: kotlin.Double? = null, val paymentToken: kotlin.String? = null, val stateMachine: StateMachine_string_? = null, val subscriberId: kotlin.String? = null, val userId: kotlin.String? = null ) { }
0
Kotlin
0
0
be4c2e4a6222d467a51d9148555eed25264c7eb0
801
kotlinsdk
Condor Public License v1.1
service_1/src/main/kotlin/ml/senior_sigan/service_1/App.kt
senior-sigan
133,525,794
false
null
package ml.senior_sigan.service_1 import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.cloud.client.discovery.EnableDiscoveryClient import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @SpringBootApplication @EnableDiscoveryClient class Service1Application fun main(args: Array<String>) { runApplication<Service1Application>(*args) } @RestController class Api( @Value("\${my.prop}") private val prop: String ) { @GetMapping("/") fun getHello() = Response(hello = "world", prop = prop) data class Response(val hello: String, val prop: String) }
0
Kotlin
0
0
c156c9ff8545b2b41cd19dd17d8e6fcc6035ae73
783
spring-cloud-config-example
MIT License
app/src/main/java/dev/shreyansh/peco/Views/AddPersonalTaskFragment.kt
Nandita-Sreekumar
143,089,248
false
null
package dev.shreyansh.peco.Views import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.CheckBox import android.widget.EditText import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProviders import com.google.android.material.button.MaterialButton import dev.shreyansh.peco.Concept.PersonalTask import dev.shreyansh.peco.Fragments.PersonalTaskFragViewModel import dev.shreyansh.peco.R class AddPersonalTaskFragment : Fragment() { companion object { fun newInstance() = AddPersonalTaskFragment() } private lateinit var title: EditText private lateinit var time: EditText private lateinit var date: EditText private lateinit var isallDay: CheckBox private lateinit var insertButton: MaterialButton private lateinit var personalTaskViewModel: PersonalTaskFragViewModel override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { val view = inflater.inflate(R.layout.add_personal_task_fragment, container, false) title = view.findViewById(R.id.add_task_title) time = view.findViewById(R.id.add_task_time) date = view.findViewById(R.id.add_task_date) isallDay = view.findViewById(R.id.add_task_all_day_check) insertButton = view.findViewById(R.id.add_task_insert) isallDay.setOnCheckedChangeListener { _, isChecked -> if(isChecked) time.visibility = View.GONE else time.visibility = View.VISIBLE } insertButton.setOnClickListener( { insert() } ) val imm = this.activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(date.windowToken, 0) return view } private fun insert() { val personalTask: PersonalTask = PersonalTask(title.text.toString(), date.text.toString(), time.text.toString(), null) personalTaskViewModel = ViewModelProviders.of(this).get(PersonalTaskFragViewModel::class.java) personalTaskViewModel.insert(personalTask) this.activity?.finish() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) } }
0
Kotlin
0
0
69310d021d6503fac8ab98199a3e98ffd4b11611
2,420
PeCo
MIT License
src/main/kotlin/test2/weatherForecast/weatherData/TemperatureData.kt
samorojy
340,891,499
false
null
package test2.weatherForecast.weatherData import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class TemperatureData( @SerialName("temp") val temp: Double, @SerialName("pressure") val pressure: Int, @SerialName("humidity") val humidity: Int, @SerialName("temp_min") val tempMin: Double, @SerialName("temp_max") val tempMax: Double )
1
Kotlin
0
0
86f12486bb17a5873d8140d457d470801746a1d6
403
spbu_kotlin_course
Apache License 2.0
subs/compose/src/main/java/com/engineer/compose/viewmodel/ChatViewModel.kt
REBOOTERS
65,188,539
false
{"Java": 1964772, "Kotlin": 587605, "C": 161111, "HTML": 73887, "JavaScript": 32332, "SCSS": 13539, "CSS": 2727, "CMake": 2593, "C++": 1259, "Groovy": 557, "Ruby": 300}
package com.engineer.compose.viewmodel import android.os.Handler import android.os.Looper import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class ChatViewModel : ViewModel() { private val TAG = "ChatViewModel" val handler = Handler(Looper.getMainLooper()) private val _messageList = MutableLiveData<ArrayList<ChatMessage>>() val messageList: LiveData<ArrayList<ChatMessage>> = _messageList val kkk = MutableLiveData<String>() fun query(userQuery: String) { val history = _messageList.value ?: ArrayList() val userMsg = ChatMessage("IAM四十二", userQuery, true) history.add(userMsg) _messageList.value = history mockRequestResult() } val chatBuffer = StringBuilder() fun queryResult(response: String) { val history = _messageList.value ?: ArrayList() val lastMsg = history.last() chatBuffer.append(response) if (lastMsg.sender == "Bot") { val newMsg = ChatMessage("Bot", chatBuffer.toString(), false) history[history.size - 1] = newMsg } else { val newMsg = ChatMessage("Bot", chatBuffer.toString(), false) history.add(newMsg) } Log.d(TAG, "history $history") _messageList.postValue(history) } private fun mockRequestResult() { val mockResponse = "天空呈现蓝色的原因主要与光的散射有关。当太阳光进入大气层后,大气中的气体分子和悬浮微粒会对阳光进行散射。散射的强度与光的波长有关,波长较短的紫光散射强度最大,其次是蓝光,而波长较长的红光和黄光的散射强度较弱。\n" + "\n" + "由于蓝光在散射过程中受到的散射强度较大,因此更容易向四面八方散射,这使得我们看到的天空呈现出蓝色。同时,由于人眼对紫光并不敏感,因此即使紫光散射强度最大,我们看到的天空也不会是紫色,而是蓝色。\n" + "\n" + "此外,天空的颜色也会随着时间和地点的变化而有所不同。在日出和日落时,由于阳光需要穿过更厚的大气层,散射效果更加显著,天空可能会呈现出橙色或红色。而在晴朗的天气下,由于大气中尘埃和水滴较少,散射作用相对较弱,天空则会呈现出深蓝色。\n" + "\n" + "总之,天空之所以是蓝色的,主要是由于大气对阳光中蓝光的强烈散射作用所致。".toCharArray() val sb = StringBuilder() Thread { for (c in mockResponse) { val history = _messageList.value ?: ArrayList() val lastMsg = history.last() sb.append(c) kkk.postValue(sb.toString()) if (lastMsg.sender == "Bot") { val newMsg = ChatMessage("Bot", sb.toString(), false) history[history.size - 1] = newMsg } else { val newMsg = ChatMessage("Bot", sb.toString(), false) history.add(newMsg) } Log.d(TAG, "history $history") _messageList.postValue(history) Thread.sleep(10) } }.start() } }
4
Java
351
1,877
bc826172cec68d2f22a8c58595e7379348b92756
2,761
AndroidAnimationExercise
Apache License 2.0
modules/feature/schedule/api/src/main/kotlin/kekmech/ru/feature_schedule_api/presentation/navigation/ScheduleScreenApi.kt
tonykolomeytsev
203,239,594
false
{"Kotlin": 972736, "JavaScript": 9100, "Python": 2365, "Shell": 46}
package kekmech.ru.feature_schedule_api.presentation.navigation import kekmech.ru.lib_navigation_api.NavTarget interface ScheduleScreenApi { fun navTarget(): NavTarget }
19
Kotlin
4
41
15c3c17e33d0ffffc0e269ad0cd6fe47b0bc971a
177
mpeiapp
MIT License
src/test/kotlin/g1601_1700/s1686_stone_game_vi/SolutionTest.kt
javadev
190,711,550
false
{"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1601_1700.s1686_stone_game_vi import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test internal class SolutionTest { @Test fun stoneGameVI() { assertThat(Solution().stoneGameVI(intArrayOf(1, 3), intArrayOf(2, 1)), equalTo(1)) } @Test fun stoneGameVI2() { assertThat(Solution().stoneGameVI(intArrayOf(1, 2), intArrayOf(3, 1)), equalTo(0)) } @Test fun stoneGameVI3() { assertThat( Solution().stoneGameVI(intArrayOf(2, 4, 3), intArrayOf(1, 6, 7)), equalTo(-1) ) } }
0
Kotlin
20
43
e8b08d4a512f037e40e358b078c0a091e691d88f
619
LeetCode-in-Kotlin
MIT License
library/src/main/java/io/github/chenfei0928/view/OutlineType.kt
chenfei0928
130,954,695
false
{"Kotlin": 1031341, "Java": 254586}
package io.github.chenfei0928.view import android.graphics.Canvas import android.graphics.Outline import android.graphics.Paint import android.graphics.Path import android.graphics.RectF import android.graphics.drawable.Drawable import android.graphics.drawable.GradientDrawable import android.os.Build import android.view.View import android.view.ViewOutlineProvider import io.github.chenfei0928.util.Log /** * 通过outline实现对View进行圆角、圆形显示的支持,只支持5.0及以上系统。 * RoundImageView对硬件加速图像和加载动画支持状况不佳, * 而通过imageView+outline可实现效果的同时允许硬件加速的bitmap来优化性能。 * * [Android中绘制圆角的三种方式](https://teoking.github.io/post/draw_round_corner_3ways_in_android/) * * [InfoQ镜像](https://xie.infoq.cn/article/83198028c199a3ae284e63eb6) * * @author chenf() * @date 2024-01-26 17:38 */ sealed class OutlineType : ViewOutlineProvider() { /** * 绘制边线 * * @param canvas * @param paint * @param rectF */ abstract fun drawBorder(canvas: Canvas, paint: Paint, rectF: RectF) /** * 裁剪到圆形 */ data object Oval : OutlineType() { override fun drawBorder(canvas: Canvas, paint: Paint, rectF: RectF) { canvas.drawOval(rectF, paint) } override fun getOutline(view: View, outline: Outline) { outline.setOval( view.paddingLeft, view.paddingTop, view.width - view.paddingRight, view.height - view.paddingBottom ) } } /** * 根据[getBackground]的[Drawable.getOutline]裁剪 */ data object Background : OutlineType() { override fun drawBorder(canvas: Canvas, paint: Paint, rectF: RectF) { Log.w(TAG, "drawBorder: clipToBackground 时不支持绘制边框") } override fun getOutline(view: View?, outline: Outline?) { BACKGROUND.getOutline(view, outline) } } /** * 四个角圆角大小一致 * * 可直接更新[cornerRadius],后调用[View.invalidateOutline]方法即可 */ data class SameCornerRadius( var cornerRadius: Float ) : OutlineType() { override fun drawBorder(canvas: Canvas, paint: Paint, rectF: RectF) { canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, paint) } override fun getOutline(view: View, outline: Outline) { outline.setRoundRect( view.paddingLeft, view.paddingTop, view.width - view.paddingRight, view.height - view.paddingBottom, cornerRadius ) } } /** * 基于[Path] * * 可直接更新[path],后调用[View.invalidateOutline]方法即可 */ open class PathType : OutlineType() { val path: Path = Path() override fun drawBorder(canvas: Canvas, paint: Paint, rectF: RectF) { canvas.drawPath(path, paint) } override fun getOutline(view: View, outline: Outline) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { outline.setPath(path) } else { outline.setConvexPath(path) } } } /** * 自定义圆角大小 * * 可直接更新[cornerRadii]块,后调用[View.invalidateOutline]方法即可 * * @property cornerRadii 圆角大小,类似[GradientDrawable.setCornerRadii],或[Path.addRoundRect] */ data class CornerRadii( var cornerRadii: FloatArray ) : PathType() { override fun getOutline(view: View, outline: Outline) { path.rewind() path.addRoundRect( view.paddingLeft.toFloat(), view.paddingTop.toFloat(), view.width - view.paddingRight.toFloat(), view.height - view.paddingBottom.toFloat(), cornerRadii, Path.Direction.CW ) super.getOutline(view, outline) } } /** * 需要view尺寸配置自定义路径 * * 可直接更新[block]块,后调用[View.invalidateOutline]方法即可 */ class ViewPath( var block: (view: View, path: Path) -> Unit ) : PathType() { override fun getOutline(view: View, outline: Outline) { path.rewind() block(view, path) super.getOutline(view, outline) } } companion object { private const val TAG = "OutlineType" } }
1
Kotlin
0
8
f110d596a6c7da518ce260337b1ec4fddeb747f7
4,294
Util
MIT License
component-acgschedule/src/main/java/com/rabtman/acgschedule/di/component/ScheduleMainComponent.kt
Rabtman
129,618,096
false
null
package com.rabtman.acgschedule.di.component import com.rabtman.acgschedule.di.module.ScheduleMainModule import com.rabtman.acgschedule.mvp.ui.fragment.ScheduleMainFragment import com.rabtman.common.di.component.AppComponent import com.rabtman.common.di.scope.FragmentScope import dagger.Component /** * @author Rabtman */ @FragmentScope @Component(modules = [ScheduleMainModule::class], dependencies = [AppComponent::class]) interface ScheduleMainComponent { fun inject(fragment: ScheduleMainFragment) }
2
null
120
840
9150f3abe50e046afd83cc97cb4415a39b1f1bd1
512
AcgClub
Apache License 2.0
app/src/fdroid/kotlin/org/sirekanyan/outline/CrashReporter.kt
sirekanian
680,634,623
false
null
package org.sirekanyan.outline @Suppress("UNUSED_PARAMETER") object CrashReporter { fun init(app: App) { // no-op } fun handleException(throwable: Throwable) { // no-op } }
3
null
0
35
cf6ca3fc55086f0907b8ce7fa9cce18efe495b3a
208
outline
Apache License 2.0
analysis/analysis-api-standalone/tests/org/jetbrains/kotlin/analysis/api/standalone/fir/test/configurators/StandaloneModeTestServiceRegistrar.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.api.standalone.fir.test.configurators import com.intellij.mock.MockProject import com.intellij.openapi.Disposable import org.jetbrains.kotlin.analysis.test.framework.test.configurators.AnalysisApiTestServiceRegistrar import org.jetbrains.kotlin.test.services.TestServices /** * Registers services specific to Standalone mode *tests*, in addition to the Standalone production services registered by * [FirStandaloneServiceRegistrar][org.jetbrains.kotlin.analysis.api.standalone.base.project.structure.FirStandaloneServiceRegistrar]. */ object StandaloneModeTestServiceRegistrar : AnalysisApiTestServiceRegistrar() { override fun registerProjectModelServices(project: MockProject, disposable: Disposable, testServices: TestServices) { } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
998
kotlin
Apache License 2.0
analysis/analysis-api-standalone/tests/org/jetbrains/kotlin/analysis/api/standalone/fir/test/configurators/StandaloneModeTestServiceRegistrar.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.api.standalone.fir.test.configurators import com.intellij.mock.MockProject import com.intellij.openapi.Disposable import org.jetbrains.kotlin.analysis.test.framework.test.configurators.AnalysisApiTestServiceRegistrar import org.jetbrains.kotlin.test.services.TestServices /** * Registers services specific to Standalone mode *tests*, in addition to the Standalone production services registered by * [FirStandaloneServiceRegistrar][org.jetbrains.kotlin.analysis.api.standalone.base.project.structure.FirStandaloneServiceRegistrar]. */ object StandaloneModeTestServiceRegistrar : AnalysisApiTestServiceRegistrar() { override fun registerProjectModelServices(project: MockProject, disposable: Disposable, testServices: TestServices) { } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
998
kotlin
Apache License 2.0
diktat-rules/src/test/resources/test/paragraph3/newlines/FunctionalStyleExpected.kt
akuleshov7
280,211,043
false
null
package test.paragraph3.newlines fun foo(list: List<Bar>?) { list!! .filterNotNull() .map { it.baz() } .firstOrNull { it.condition() } ?.qux() ?:foobar } fun bar(x :Int,y:Int) = x+ y fun goo() { x.map() .gro() .gh() t.map() .hg() .hg() t .map() .filter() .takefirst() x .map() .filter() .hre() } fun foo() { foo ?: bar.baz() .qux() foo ?: bar.baz() .qux() }
1
null
1
1
9eefb12b73fd6b44d164199c3ef0295c8908054d
501
diKTat
MIT License
src/main/kotlin/betman/Application.kt
ration
129,735,439
false
null
package betman import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.web.servlet.config.annotation.EnableWebMvc @SpringBootApplication class Application fun main(args: Array<String>) { SpringApplication.run(Application::class.java, *args) }
2
Kotlin
0
1
140fae3b6623c6c57a8a9478fa88df41db9bd906
338
betman
MIT License
client_restaurant/shared/src/commonMain/kotlin/presentation/main/composables/ChartItem.kt
TheChance101
671,967,732
false
{"Kotlin": 2352766, "Ruby": 8872, "HTML": 7663, "JavaScript": 6785, "Swift": 3621, "CSS": 1822, "Dockerfile": 1407, "Shell": 1140}
package presentation.main.composables import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.unit.dp import com.beepbeep.designSystem.ui.theme.Theme import resources.Resources @Composable fun ChartItem( imagePainter: Painter, title: String, modifier: Modifier = Modifier, shape: Shape = RoundedCornerShape(Theme.radius.medium), content: @Composable () -> Unit ) { Column( modifier.widthIn(max = 328.dp).clip(shape).background(Theme.colors.surface) .padding(16.dp), verticalArrangement = Arrangement.spacedBy(24.dp), ) { Column( Modifier.fillMaxWidth(), ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) { Column() { Image(painter = imagePainter, contentDescription = null, Modifier.size(24.dp)) Text( text = title, style = Theme.typography.titleMedium.copy(color = Theme.colors.contentPrimary) ) } Column( verticalArrangement = Arrangement.spacedBy(4.dp), horizontalAlignment = Alignment.End ) { Text( text = "$4700", style = Theme.typography.title.copy(color = Theme.colors.contentPrimary) ) Text( text = Resources.strings.thisWeek, style = Theme.typography.caption.copy(color = Theme.colors.contentTertiary) ) } } Box(Modifier.fillMaxWidth().aspectRatio(1f)) { content() } } } }
4
Kotlin
33
464
9d747f467f7a4e3c1f1f19755261580563731323
2,769
beep-beep
Apache License 2.0
app/src/main/java/com/example/ronensabag/imageloader/mainActivity/MainActivityModule.kt
SabagRonen
109,687,965
false
null
package com.example.ronensabag.imageloader.mainActivity import android.arch.lifecycle.ViewModelProviders import com.example.ronensabag.imageloader.bitmapRepository.BitmapEntity import dagger.Binds import dagger.Module import dagger.Provides import javax.inject.Named import javax.inject.Singleton @Module class MainActivityModule { @Provides internal fun provideMainViewModel(featureActivity: MainActivity): MainViewModel { return ViewModelProviders.of(featureActivity).get(MainViewModel::class.java) } @Provides internal fun provideMainLifecycleObserver(featureActivity: MainActivity): MainLifecycleObserver { val mainLifecycleObserver = MainLifecycleObserver() featureActivity.lifecycle.addObserver(mainLifecycleObserver) return mainLifecycleObserver } }
0
Kotlin
1
2
276f4966b18e173ae60c5bc39e79a1575d9be41a
815
Image-Loader
MIT License
widgetssdk/src/testSnapshot/java/com/glia/widgets/chat/VisitorFileAttachmentChatItemsSnapshotTest.kt
salemove
312,288,713
false
{"Kotlin": 1962137, "Java": 448482, "Shell": 1802}
package com.glia.widgets.chat import com.glia.widgets.SnapshotTest import com.glia.widgets.chat.model.ChatState import com.glia.widgets.snapshotutils.SnapshotAttachment import com.glia.widgets.snapshotutils.SnapshotChatScreen import com.glia.widgets.snapshotutils.SnapshotChatView import org.junit.Test internal class VisitorFileAttachmentChatItemsSnapshotTest : SnapshotTest(), SnapshotChatView, SnapshotChatScreen, SnapshotAttachment { private fun chatState() = ChatState() .changeVisibility(true) // MARK: Visitor File without labels @Test fun defaultTheme() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile()) ).root ) } @Test fun withoutLabelsWithUiTheme() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile()), uiTheme = uiTheme() ).root ) } @Test fun withoutLabelsWithGlobalColors() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile()), unifiedTheme = unifiedThemeWithGlobalColors() ).root ) } @Test fun withoutLabelsWithUnifiedTheme() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile()), unifiedTheme = unifiedTheme() ).root ) } @Test fun withoutLabelsWithUnifiedThemeWithoutVisitorMessage() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile()), unifiedTheme = unifiedThemeWithoutVisitorMessage() ).root ) } // MARK: Visitor File with delivered label @Test fun deliveredLabel() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile(showDelivered = true)) ).root ) } @Test fun deliveredLabelWithUiTheme() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile(showDelivered = true)), uiTheme = uiTheme() ).root ) } @Test fun deliveredLabelWithGlobalColors() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile(showDelivered = true)), unifiedTheme = unifiedThemeWithGlobalColors() ).root ) } @Test fun deliveredLabelWithUnifiedTheme() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile(showDelivered = true)), unifiedTheme = unifiedTheme() ).root ) } @Test fun deliveredLabelWithUnifiedThemeWithoutVisitorMessage() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile(showDelivered = true)), unifiedTheme = unifiedThemeWithoutVisitorMessage() ).root ) } // MARK: Visitor File with error label @Test fun errorLabel() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile(showError = true)) ).root ) } @Test fun errorLabelWithUiTheme() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile(showError = true)), uiTheme = uiTheme() ).root ) } @Test fun errorLabelWithGlobalColors() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile(showError = true)), unifiedTheme = unifiedThemeWithGlobalColors() ).root ) } @Test fun errorLabelWithUnifiedTheme() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile(showError = true)), unifiedTheme = unifiedTheme() ).root ) } @Test fun errorLabelWithUnifiedThemeWithoutVisitorMessage() { snapshot( setupView( chatState = chatState(), chatItems = listOf(visitorAttachmentItemFile(showError = true)), unifiedTheme = unifiedThemeWithoutVisitorMessage() ).root ) } }
3
Kotlin
1
7
3c499a6624bc787a276956bca46d07aa514d3625
4,976
android-sdk-widgets
MIT License
src/commonMain/kotlin/com/algolia/search/model/settings/CustomRankingCriterion.kt
pallavirawat
205,637,107
true
{"Kotlin": 941656, "Ruby": 4462}
package com.algolia.search.model.settings import com.algolia.search.helper.toAttribute import com.algolia.search.model.Attribute import com.algolia.search.model.Raw import com.algolia.search.serialize.KeyAsc import com.algolia.search.serialize.KeyDesc import com.algolia.search.serialize.regexAsc import com.algolia.search.serialize.regexDesc import kotlinx.serialization.Decoder import kotlinx.serialization.Encoder import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.internal.StringSerializer /** * [Documentation][https://www.algolia.com/doc/guides/managing-results/must-do/custom-ranking/#custom-ranking] */ @Serializable(CustomRankingCriterion.Companion::class) public sealed class CustomRankingCriterion(override val raw: String) : Raw<String> { /** * Sort an [Attribute] value by ascending order. */ public data class Asc(val attribute: Attribute) : CustomRankingCriterion("$KeyAsc($attribute)") /** * Sort an [Attribute] value by descending order. */ public data class Desc(val attribute: Attribute) : CustomRankingCriterion("$KeyDesc($attribute)") public data class Other(override val raw: String) : CustomRankingCriterion(raw) override fun toString(): String { return raw } companion object : KSerializer<CustomRankingCriterion> { private val serializer = StringSerializer override val descriptor = serializer.descriptor override fun serialize(encoder: Encoder, obj: CustomRankingCriterion) { serializer.serialize(encoder, obj.raw) } override fun deserialize(decoder: Decoder): CustomRankingCriterion { val string = serializer.deserialize(decoder) val findAsc = regexAsc.find(string) val findDesc = regexDesc.find(string) return when { findAsc != null -> Asc(findAsc.groupValues[1].toAttribute()) findDesc != null -> Desc(findDesc.groupValues[1].toAttribute()) else -> Other(string) } } } }
0
Kotlin
0
0
a7127793476d4453873266222ea71b1fce5c8c32
2,108
algoliasearch-client-kotlin
MIT License
jvm/src/main/kotlin/com/antongoncharov/demo/surveys/model/r2dbc/ChoiceResponseRow.kt
anton-goncharov
357,641,384
false
null
package com.antongoncharov.demo.surveys.model.r2dbc data class ChoiceResponseRow( var uuid: String? = null, var surveyResponseUuid: String? = null, var questionUuid: String? = null, var choiceUuid: String? = null )
0
Kotlin
1
6
3da7f0e67dc0db24a89e0157fc10c858292ce0a9
232
kotlin-vue-surveys-demo
MIT License
wgpu4k/src/commonMain/kotlin/io.ygdrasil.wgpu/Buffer.kt
wgpu4k
773,068,055
false
null
package io.ygdrasil.wgpu expect class Buffer : AutoCloseable { val size: GPUSize64 val usage: Set<BufferUsage> val mapState: BufferMapState fun unmap() fun mapFrom(buffer: FloatArray, offset: Int = 0) fun mapFrom(buffer: ByteArray, offset: Int = 0) fun mapInto(buffer: ByteArray, offset: Int) suspend fun map(mode: Set<MapMode>, offset: GPUSize64 = 0, size: GPUSize64 = this.size) override fun close() } data class BufferDescriptor( val size: GPUSize64, val usage: Set<BufferUsage>, val mappedAtCreation: Boolean = false, val label: String? = null, )
7
null
6
41
822c304afaa72411ae42e86f20c7b5c62b5f9815
611
wgpu4k
MIT License
app/src/main/java/com/moataz/afternoonhadeeth/ui/hadiths/view/activity/DisplayHadithListActivity.kt
ahmed-tasaly
533,010,125
false
null
package com.moataz.afternoonhadeeth.ui.hadiths.view.activity import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.moataz.afternoonhadeeth.R import com.moataz.afternoonhadeeth.data.model.hadith.Hadith import com.moataz.afternoonhadeeth.databinding.ActivityDisplayHadithsBinding import com.moataz.afternoonhadeeth.ui.hadiths.adapter.HadithListAdapter import com.moataz.afternoonhadeeth.utils.helper.Views class DisplayHadithListActivity : AppCompatActivity() { private var adapter = HadithListAdapter() private lateinit var binding: ActivityDisplayHadithsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDisplayHadithsBinding.inflate(layoutInflater) setContentView(binding.root) intiView() intiToolbar() intiAdapter() getList() } private fun intiView() { Views.intiViews(window) window.navigationBarColor = resources.getColor(R.color.card_color) } private fun intiToolbar() { val intent: Intent = intent val title: String? = intent.getStringExtra("hadithTitle") binding.topText.text = title binding.backToLastActivity.setOnClickListener { backToLastActivity() } } private fun intiAdapter() { binding.recyclerView.layoutManager = LinearLayoutManager(this) binding.recyclerView.setHasFixedSize(true) } private fun getList() { val intent: Intent = intent val extras = intent.extras val hadithList = extras?.getParcelableArrayList<Hadith>("hadithList") adapter.setHadithList(hadithList) binding.recyclerView.adapter = adapter } private fun backToLastActivity() { finish() } }
0
Kotlin
0
1
ec70b362b5966475693e7f7a406a397ee08099d4
1,892
Sunset-Hadith-Market
Apache License 2.0
domain/src/main/java/org/commcare/dalvik/domain/usecases/ConfirmMobileOtpUsecase.kt
dimagi
531,775,811
false
null
package org.commcare.dalvik.domain.usecases import org.commcare.dalvik.domain.model.VerifyOtpRequestModel import org.commcare.dalvik.domain.repositories.AbdmRepository import javax.inject.Inject class ConfirmMobileOtpUsecase@Inject constructor(val repository: AbdmRepository) { fun execute(verifyOtpRequestModel: VerifyOtpRequestModel) = repository.confirmMobileOtp(verifyOtpRequestModel) }
0
Kotlin
1
0
e5e4c7f57f1eebfe12c8fcf4af2f160acf3f6d46
407
abdm-app
Apache License 2.0
app/src/main/java/com/example/composecalculator/CalculatorOperation.kt
jocode
546,691,079
false
{"Kotlin": 19108}
package com.example.composecalculator sealed class CalculatorOperation(val symbol: String) { object Add: CalculatorOperation("+") object Subtract: CalculatorOperation("-") object Multiply: CalculatorOperation("x") object Divide: CalculatorOperation("/") }
0
Kotlin
0
0
1eadcab88a84828abbc2e39d4f76670724c4a591
273
ComposeCalculator
MIT License
lab-axon-gradle-kt/src/main/kotlin/cn/jaylong/axon/SnowflakeIdentifierProperties.kt
jay1ong
514,093,496
false
{"Kotlin": 43500}
package cn.jaylong.axon import org.springframework.boot.context.properties.ConfigurationProperties /** * * Created by IntelliJ IDEA. * Author: I'm * Date: 2022/7/13 * Url: <a href="https://jaylong.cn">https://jaylong.cn</a> */ @ConfigurationProperties(prefix = SnowflakeIdentifierProperties.PREFIX) data class SnowflakeIdentifierProperties( /** * 是否启用@ControllerAdvice */ var enabled: Boolean ) { companion object { const val PREFIX: String = "lab.axon.snowflake-identifier" } }
0
Kotlin
0
0
683b0e795b7983282034b3f9c5aa37286685c790
523
lab-framework-gradle-kt
Apache License 2.0
app/src/main/java/com/listenergao/kotlinsample/object/ObjectType.kt
ListenerGao
618,736,081
false
null
package com.listenergao.kotlinsample.`object` import android.view.View import com.listenergao.kotlinsample.KotlinApplication fun main() { } /** * kotlin 中 object 关键字三种语义,以及它的具体使用场景。 * * 1、匿名内部类 * 2、单例模式 * 3、伴生对象 * 之所以出现这种现象,是因为 kotlin 的设计者认为,这三种语义本质上都是在"声明一个类的同时,还创建了对象"。 */ /************************************** object 之匿名内部类 start ***********************************/ /** * object 之匿名内部类 */ class ObjectTypeOne { /** * 这是典型的匿名内部类的写法,因为 View.OnClickListener 是一个接口(抽象类也可以), * 我们想要创建它的时候,必须实现它内部没有实现的方法。 */ fun testOne() { val view = View(KotlinApplication.application) // 当 kotlin 的匿名内部类中只有一个方法时,可以使用 SAM 转换, // 使用 lambda 表达式简写:view.setOnClickListener { } view.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View?) { println("ObjectTypeOne testOne......") } }) } /** * kotlin 的匿名内部类相比 java 来说,还有一个特殊的地方, * 就是我们在使用 kotlin 定义匿名内部类时,它可以在继承一个抽象类的同时,来实现多个接口。 * 如下例 */ fun testTwo() { // 声明匿名内部类,在继承抽象类 C 的同时,还实现 A、B 接口 val inner = object : C(), A, B { override fun funC() { // do something } override fun funA() { // do something } override fun funB() { // do something } } } interface A { fun funA() } interface B { fun funB() } abstract class C { abstract fun funC() } } /************************************** object 之匿名内部类 end *************************************/ /*************************************** object 之单例模式 start ************************************/ /** * objet 之单例模式 * * 实现原理: * 利用 show kotlin Bytecode 反编译后查看,kotlin 编译器会将其转换为""静态代码块的单例模式, * 由于 static 代码块会在类初始化时只加载一次。因此,它在保证线程安全的前提下,同时保证 INSTANCE 实例 * 仅会初始化一次。 * * 缺点:不支持懒加载、不支持传参构造单例; * * 反编译后源码: * public final class ObjectTypeTwo { * @NotNull * public static final ObjectTypeTwo INSTANCE; * * public final void testTwo() { * } * * private ObjectTypeTwo() { * } * * static { * ObjectTypeTwo var0 = new ObjectTypeTwo(); * INSTANCE = var0; * } * } */ object ObjectTypeTwo { fun testTwo() { } } /*************************************** object 之单例模式 end ************************************/ /*************************************** object 之伴生对象 start ***********************************/ /** * object 之伴生对象 * kotlin 中没有 static 关键字,利用伴生对象来实现静态方法和变量。 */ class ObjectTypeThree { /** * object 定义单例的一种特殊情况,内部类中定义单例类,单例就与外部类形成类嵌套关系。 * * 具体调用: * kotlin中:ObjectTypeThree.InnerSingleton.foo() * java中 :ObjectTypeThree.InnerSingleton.INSTANCE.foo() * * 通过反编译查看:我们发现 foo() 并不是静态方法,而是通过调用单例的实例实现的。 * * 如何实现类似 java 中的静态方法代码呢? * 我们只需要使用 "@JvmStatic" 注解 foo() 即可。 */ object InnerSingleton { @JvmStatic fun foo() { } } /** * companion object (伴生对象),它其实是嵌套单例的单例的一种特殊情况。 * 也就是,在伴生对象的内部,如果存在"@JvmStatic"修饰的方法和属性,它就会被挪到 * 伴生对象外部的类中,变成静态成员。 * * 查看反编译发现: * 被挪到外部的静态方法 other(),它最终还是调用了单例 InnerSingletonOther 的成员方法 other(), * 所以它只是做了一层转接而已。 * * 具体调用:(kotlin 与 java 调用一致) * ObjectTypeThree.foo() * * 由此可见: * object 单例、伴生对象中间的演变关系为:普通的 object 单例,演变出了嵌套的单例; * 嵌套的单例,演变出了伴生对象。 * * 或者说: * 嵌套单例,是 object 单例的一种特殊情况;伴生对象,是嵌套单例的一种特殊情况。 */ companion object InnerSingletonOther { @JvmStatic fun other() { } } } /*************************************** object 之伴生对象 end ***********************************/
0
Kotlin
6
52
69ab8c0c2f7a04fabc030e5fb99c5148aa5fc8a4
3,810
Kotlin-Sample
Apache License 2.0
mokkery-runtime/src/commonTest/kotlin/dev/mokkery/internal/verify/render/TemplateGroupedMatchingResultsRendererTest.kt
lupuuss
652,785,006
false
{"Kotlin": 502021}
package dev.mokkery.internal.verify.render import dev.mokkery.internal.matcher.CallMatchResult import dev.mokkery.internal.templating.CallTemplate import dev.mokkery.internal.tracing.CallTrace import dev.mokkery.internal.verify.results.TemplateGroupedMatchingResults import dev.mokkery.test.StubRenderer import dev.mokkery.test.assert import dev.mokkery.test.fakeCallTemplate import dev.mokkery.test.fakeCallTrace import kotlin.test.Test class TemplateGroupedMatchingResultsRendererTest { private val renderer = TemplateGroupedMatchingResultsRenderer( indentation = 3, matchersFailuresRenderer = StubRenderer("MATCHERS", StubRenderer.Mode.RepeatWithBreak(2)), traceRenderer = StubRenderer("TRACE") ) private val template = fakeCallTemplate() private val traces = listOf(fakeCallTrace(), fakeCallTrace()) private val singleTrace = listOf(fakeCallTrace()) @Test fun testRendersProperlyMatchingGroup() { renderer.assert(fakeMatchingResults(template, CallMatchResult.Matching to traces)) { """ Results for mock@1: # Matching calls: RENDERER_TRACE RENDERER_TRACE """.trimIndent() } } @Test fun testRendersProperlyFailingMatchersGroup() { renderer.assert(fakeMatchingResults(template, CallMatchResult.SameReceiverMethodSignature to traces)) { """ Results for mock@1: # Calls to the same method with failing matchers: RENDERER_TRACE RENDERER_MATCHERS RENDERER_MATCHERS RENDERER_TRACE RENDERER_MATCHERS RENDERER_MATCHERS """.trimIndent() } } @Test fun testRendersProperlyOverloadsGroup() { renderer.assert(fakeMatchingResults(template, CallMatchResult.SameReceiverMethodOverload to traces)) { """ Results for mock@1: # Calls to the same overload: RENDERER_TRACE RENDERER_TRACE """.trimIndent() } } @Test fun testRendersProperlyOtherCallsGroup() { renderer.assert(fakeMatchingResults(template, CallMatchResult.SameReceiver to traces)) { """ Results for mock@1: # Other calls to this mock: RENDERER_TRACE RENDERER_TRACE """.trimIndent() } } @Test fun testRendersAllGroupsInCorrectOrder() { renderer.assert( fakeMatchingResults( template, CallMatchResult.Matching to singleTrace, CallMatchResult.SameReceiverMethodSignature to singleTrace, CallMatchResult.SameReceiverMethodOverload to singleTrace, CallMatchResult.SameReceiver to singleTrace, ) ) { """ Results for mock@1: # Matching calls: RENDERER_TRACE # Calls to the same method with failing matchers: RENDERER_TRACE RENDERER_MATCHERS RENDERER_MATCHERS # Calls to the same overload: RENDERER_TRACE # Other calls to this mock: RENDERER_TRACE """.trimIndent() } } @Test fun testSkipsEmptyGroups() { renderer.assert( fakeMatchingResults( template, CallMatchResult.Matching to singleTrace, CallMatchResult.SameReceiverMethodSignature to emptyList(), CallMatchResult.SameReceiverMethodOverload to singleTrace, CallMatchResult.SameReceiver to emptyList(), ) ) { """ Results for mock@1: # Matching calls: RENDERER_TRACE # Calls to the same overload: RENDERER_TRACE """.trimIndent() } } @Test fun testRendersEmptyState() { renderer.assert( fakeMatchingResults( template, CallMatchResult.Matching to emptyList(), CallMatchResult.SameReceiverMethodSignature to emptyList(), CallMatchResult.SameReceiverMethodOverload to emptyList(), CallMatchResult.SameReceiver to emptyList(), ) ) { """ Results for mock@1: # No calls to this mock! """.trimIndent() } } private fun fakeMatchingResults( template: CallTemplate, vararg groups: Pair<CallMatchResult, List<CallTrace>>, ) = TemplateGroupedMatchingResults(template, groups.toMap()) }
1
Kotlin
5
96
26a50ef902b4cae76b67f9081efe501065973597
4,871
Mokkery
Apache License 2.0
web/widgets/src/jvmMain/kotlin/modifiers/onSizeChanged.kt
JetBrains
293,498,508
false
null
package org.jetbrains.compose.common.ui.layout import org.jetbrains.compose.common.ui.Modifier import org.jetbrains.compose.common.ui.unit.IntSize import org.jetbrains.compose.common.internal.castOrCreate import androidx.compose.ui.layout.onSizeChanged import org.jetbrains.compose.annotations.webWidgetsDeprecationMessage import org.jetbrains.compose.common.ui.ExperimentalComposeWebWidgetsApi @ExperimentalComposeWebWidgetsApi @Deprecated(message = webWidgetsDeprecationMessage) actual fun Modifier.onSizeChanged( onSizeChanged: (IntSize) -> Unit ): Modifier = castOrCreate().apply { modifier = modifier.onSizeChanged { onSizeChanged(IntSize(it.width, it.height)) } }
668
Kotlin
645
9,090
97266a0ac8c0d7a8ad8d19ead1c925751a00ff1c
692
compose-jb
Apache License 2.0
src/aws/lambdas/incremental_distribution/src/test/java/uk/nhs/nhsx/analyticsevents/PayloadValidatorTest.kt
nhsx-mirror
333,407,092
true
{"Kotlin": 1307116, "HCL": 350528, "Ruby": 278734, "Java": 114825, "JavaScript": 8765, "Python": 8418, "Shell": 3088, "Dockerfile": 2996, "HTML": 1487, "Makefile": 542}
package uk.nhs.nhsx.analyticsevents import com.natpryce.hamkrest.absent import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.present import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class PayloadValidatorTest { @Test fun `valid payload returns value`() { val payload = PayloadValidator().maybeValidPayload( """ { "metadata": { "operatingSystemVersion": "iPhone OS 13.5.1 (17F80)", "latestApplicationVersion": "3.0", "deviceModel": "iPhone11,2", "postalDistrict": "A1" }, "events": [ { "type": "exposure_window", "version": 1, "payload": { "date": "2020-08-24T21:59:00Z", "infectiousness": "high|none|standard", "scanInstances": [ { "minimumAttenuation": 1, "secondsSinceLastScan": 5, "typicalAttenuation": 2 } ], "riskScore": "FIXME: sample int value (range?) or string value (enum?)" } } ] } """.trimIndent() ) assertThat(payload, present()) } @Test fun `empty json returns empty`() { val payload = PayloadValidator().maybeValidPayload("{}") assertThat(payload, absent()) } @Test fun `invalid json returns empty`() { val payload = PayloadValidator().maybeValidPayload("!@£$%^") assertThat(payload, absent()) } @Test fun `missing fields in json returns empty`() { val payload = PayloadValidator().maybeValidPayload( """ { "metadata": { "operatingSystemVersion": "iPhone OS 13.5.1 (17F80)" }, "events": [ { "type": "exposure_window", "version": 1, "payload": { "date": "2020-08-24T21:59:00Z", "infectiousness": "high|none|standard", "scanInstances": [ { "minimumAttenuation": 1, "secondsSinceLastScan": 5, "typicalAttenuation": 2 } ], "riskScore": "FIXME: sample int value (range?) or string value (enum?)" } } ] } """.trimIndent() ) assertThat(payload, absent()) } @Test fun `missing events payload returns empty`() { val payload = PayloadValidator().maybeValidPayload( """ { "metadata": { "operatingSystemVersion": "iPhone OS 13.5.1 (17F80)", "latestApplicationVersion": "3.0", "deviceModel": "iPhone11,2", "postalDistrict": "A1" } } """.trimIndent() ) assertThat(payload, absent()) } @Test fun `empty events payload returns empty`() { val payload = PayloadValidator().maybeValidPayload( """ { "metadata": { "operatingSystemVersion": "iPhone OS 13.5.1 (17F80)", "latestApplicationVersion": "3.0", "deviceModel": "iPhone11,2", "postalDistrict": "A1" }, "events": [ {} ] } """.trimIndent() ) assertThat(payload, absent()) } @Test fun `invalid metadata type returns empty`() { val payload = PayloadValidator().maybeValidPayload( """ { "metadata": "not supposed to be a string", "events": [ {} ] } """.trimIndent() ) assertThat(payload, absent()) } @Test fun `invalid events type returns empty`() { val payload = PayloadValidator().maybeValidPayload( """ { "metadata": { "operatingSystemVersion": "iPhone OS 13.5.1 (17F80)", "latestApplicationVersion": "3.0", "deviceModel": "iPhone11,2", "postalDistrict": "A1" }, "events": "not supposed to be a string" } """.trimIndent() ) assertThat(payload, absent()) } }
0
Kotlin
0
0
b0871e684c526b90c7ae25004e838b9103644e4f
5,111
covid19-app-system-public
MIT License
automation/dataseedingapi/src/main/kotlin/com/instructure/dataseeding/api/SubmissionsApi.kt
XinicsInc
123,872,784
true
{"Markdown": 5, "INI": 18, "Shell": 27, "Proguard": 16, "Gradle": 54, "Ignore List": 38, "Java": 1391, "XML": 1946, "Gradle Kotlin DSL": 2, "Kotlin": 965, "Ruby": 19, "Protocol Buffer": 14, "JSON": 7, "GraphQL": 1, "Text": 12, "Batchfile": 2, "Java Properties": 11, "HTML": 7, "Python": 1, "YAML": 3, "CSS": 1, "Ant Build System": 1}
/* * Copyright (C) 2017 - present Instructure, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.instructure.dataseeding.api import com.instructure.dataseeding.model.AssignmentApiModel import com.instructure.dataseeding.model.CreateSubmissionCommentWrapper import com.instructure.dataseeding.model.SubmissionApiModel import com.instructure.dataseeding.model.SubmitCourseAssignmentSubmissionWrapper import com.instructure.dataseeding.util.CanvasRestAdapter import com.instructure.dataseeding.util.Randomizer import com.instructure.soseedy.SubmissionType import retrofit2.Call import retrofit2.http.Body import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Path object SubmissionsApi { interface SubmissionsService { @POST("courses/{courseId}/assignments/{assignmentId}/submissions") fun submitCourseAssignment( @Path("courseId") courseId: Long, @Path("assignmentId") assignmentId: Long, @Body submitCourseAssignmentSubmission: SubmitCourseAssignmentSubmissionWrapper): Call<SubmissionApiModel> @PUT("courses/{courseId}/assignments/{assignmentId}/submissions/self") fun commentOnSubmission( @Path("courseId") courseId: Long, @Path("assignmentId") assignmentId: Long, @Body createSubmissionComment: CreateSubmissionCommentWrapper ): Call<AssignmentApiModel> } private fun submissionsService(token: String): SubmissionsService = CanvasRestAdapter.retrofitWithToken(token).create(SubmissionsService::class.java) fun submitCourseAssignment(submissionType: SubmissionType, courseId: Long, assignmentId: Long, fileIds: MutableList<Long>, studentToken: String): SubmissionApiModel { val submission = Randomizer.randomSubmission(submissionType, fileIds) return submissionsService(studentToken) .submitCourseAssignment(courseId, assignmentId, SubmitCourseAssignmentSubmissionWrapper(submission)) .execute() .body()!! } fun commentOnSubmission(studentToken: String, courseId: Long, assignmentId: Long, fileIds: MutableList<Long>): AssignmentApiModel { val comment = Randomizer.randomSubmissionComment(fileIds) return submissionsService(studentToken) .commentOnSubmission(courseId, assignmentId, CreateSubmissionCommentWrapper(comment)) .execute() .body()!! } }
0
Java
0
1
70b0cd08042e05293fc78478f90c3608a31831e1
3,256
instructure-android
Apache License 2.0
kotlin/src/main/java/androidx/swift/session/SessionDelegate.kt
raedev
303,111,174
false
{"Java": 1529959, "Kotlin": 57521, "Shell": 475}
package androidx.swift.session /** * Session 委托接口 * @author RAE * @date 2022/06/12 * @copyright Copyright (c) https://github.com/raedev All rights reserved. */ interface SessionDelegate { /** 获取当前登录的用户 */ fun <T> getUser(): T? /** 设置当前登录用户 */ fun <T> setUser(user: T) /** 获取当前登录的用户,为空会报异常,请调用[isLogin]进行前置判断 */ fun <T> requireUser(): T = getUser<T>()!! /** 是否已经登录 */ fun <T> isLogin(): Boolean = getUser<T>() != null /** 退出登录 */ fun forgot() /** 清除所有信息 */ fun clear() /** * 存储Session额外的值 * @param key 存储的键 * @param value 存储的值,自动推断类型进行保存 */ fun put(key: String, value: Any) /** * 获取Session额外的值 * * @param key 存储的键 */ fun <V> get(key: String, cls: Class<V>): V? /** * 移除Session值 * * @param key 存储的键 */ fun remove(key: String) /** * 获取Session额外的值 * * @param key 存储的键 * @param defaultValue 当为空时返回的默认值 */ fun getString(key: String, defaultValue: String? = null): String? /** * 获取Session额外的值 * * @param key 存储的键 * @param defaultValue 当为空时返回的默认值 */ fun getInt(key: String, defaultValue: Int? = null): Int? /** * 获取Session额外的值 * * @param key 存储的键 * @param defaultValue 当为空时返回的默认值 */ fun getBoolean(key: String, defaultValue: Boolean = false): Boolean /** * 获取Session额外的值 * * @param key 存储的键 * @param defaultValue 当为空时返回的默认值 */ fun getFloat(key: String, defaultValue: Float? = null): Float? /** * 获取Session额外的值 * * @param key 存储的键 * @param defaultValue 当为空时返回的默认值 */ fun getLong(key: String, defaultValue: Long? = null): Long? /** * 添加用户监听 */ fun addSessionListener(listener: SessionStateListener) /** * 移除用户监听 */ fun removeSessionListener(listener: SessionStateListener) }
1
null
1
1
70e074a02c64de31e45e8019d3ab63492393e5f9
1,921
androidx-swift
Apache License 2.0
library/src/androidMain/kotlin/com/myunidays/segmenkt/integrations/IdentifyPayload.kt
MyUNiDAYS
570,463,826
false
{"Kotlin": 37806, "Ruby": 1615, "Shell": 1057}
package com.myunidays.segmenkt.integrations actual typealias IdentifyPayload = com.segment.analytics.integrations.IdentifyPayload
0
Kotlin
0
5
d6a2990fa6ccd76770da9a3e0b5858528d0875a6
131
Segmenkt
MIT License
src/test/kotlin/com/github/kindermax/intellijlets/completion/field/FieldsTest.kt
lets-cli
276,188,439
false
null
package com.github.kindermax.intellijlets.completion.field import com.github.kindermax.intellijlets.DEFAULT_SHELLS import com.intellij.testFramework.fixtures.BasePlatformTestCase import junit.framework.TestCase import org.junit.Test open class FieldsTest : BasePlatformTestCase() { @Test fun testRootCompletion() { myFixture.configureByText( "lets.yaml", """ shell: bash commands: run: cmd: Echo Run <caret> """.trimIndent() ) val variants = myFixture.getCompletionVariants("lets.yaml") ?: return TestCase.fail("completion variants must not be null") val expected = listOf( "env", "eval_env", "version", "mixins", "before" ) TestCase.assertEquals(expected.sorted(), variants.sorted()) } @Test fun testShellCompletion() { myFixture.configureByText( "lets.yaml", """ shell: <caret> """.trimIndent() ) val variants = myFixture.getCompletionVariants("lets.yaml") ?: return TestCase.fail("completion variants must not be null") TestCase.assertEquals(DEFAULT_SHELLS.sorted(), variants.sorted()) } @Test fun testCommandCompletionWithCLetter() { myFixture.configureByText( "lets.yaml", """ shell: bash commands: echo: c<caret> """.trimIndent() ) val variants = myFixture.getCompletionVariants("lets.yaml") ?: return TestCase.fail("completion variants must not be null") val expected = listOf( "description", "checksum", "persist_checksum", "cmd" ) TestCase.assertEquals(expected.sorted(), variants.sorted()) } @Test fun testCommandOptionsCompletionOnlyOptions() { myFixture.configureByText( "lets.yaml", """ shell: bash commands: echo: op<caret> """.trimIndent() ) myFixture.completeBasic() TestCase.assertEquals(myFixture.caretOffset, 63) TestCase.assertEquals( myFixture.file.text.trimIndent(), """ shell: bash commands: echo: options: | Usage: lets """.trimIndent() ) } @Test fun testCommandOptionsCompletionNotOnlyOptions() { myFixture.configureByText( "lets.yaml", """ shell: bash commands: echo: cmd: echo Hi op<caret> """.trimIndent() ) myFixture.completeBasic() TestCase.assertEquals(myFixture.caretOffset, 80) TestCase.assertEquals( myFixture.file.text.trimIndent(), """ shell: bash commands: echo: cmd: echo Hi options: | Usage: lets """.trimIndent() ) } @Test fun testDependsCompletionWorks() { myFixture.configureByText( "lets.yaml", """ shell: bash commands: hello: cmd: echo Hello depends: [world] hi: cmd: echo Hi lol: cmd: echo Lol world: depends: [<caret>] cmd: echo World """.trimIndent() ) val variants = myFixture.getCompletionVariants("lets.yaml") ?: return TestCase.fail("completion variants must not be null") val expected = listOf( "hi", "lol" ) TestCase.assertEquals(expected.sorted(), variants.sorted()) } @Test fun testDependsCompletionWorksNoCommandYet() { myFixture.configureByText( "lets.yaml", """ shell: bash commands: hi: cmd: echo Hi run: depends: - <caret> """.trimIndent() ) val variants = myFixture.getCompletionVariants("lets.yaml") ?: return TestCase.fail("completion variants must not be null") val expected = listOf("hi") TestCase.assertEquals(expected.sorted(), variants.sorted()) } @Test fun testCommandDependsCompletionArray() { myFixture.configureByText( "lets.yaml", """ shell: bash commands: echo: dep<caret> """.trimIndent() ) myFixture.completeBasic() TestCase.assertEquals( myFixture.file.text, """ shell: bash commands: echo: depends: - """.trimIndent() ) } }
1
Kotlin
1
3
4cbffac7a3a75031c81230b1a524c66373cb8d5a
5,191
intellij-lets
Apache License 2.0
app/src/main/java/com/frogobox/appsdk/source/AppDataSource.kt
frogobox
463,917,159
false
{"Kotlin": 329728, "Java": 141587, "AIDL": 1633}
package com.frogobox.appsdk.source import com.frogobox.appsdk.model.Article import com.frogobox.appsdk.model.SourceResponse import com.frogobox.coresdk.response.FrogoDataResponse import com.frogobox.coresdk.response.FrogoStateResponse import com.frogobox.coresdk.source.ICoreDataSource /* * Created by faisalamir on 08/04/22 * FrogoSDK * ----------------------------------------- * Name : <NAME> * E-mail : <EMAIL> * Github : github.com/amirisback * ----------------------------------------- * Copyright (C) 2022 Frogobox Media Inc. * All rights reserved * */ interface AppDataSource : ICoreDataSource { // Get Top Headline fun getTopHeadline( q: String?, sources: String?, category: String?, country: String?, pageSize: Int?, page: Int?, callback: FrogoDataResponse<List<Article>> ) // Get Everythings fun getEverythings( q: String?, from: String?, to: String?, qInTitle: String?, sources: String?, domains: String?, excludeDomains: String?, language: String?, sortBy: String?, pageSize: Int?, page: Int?, callback: FrogoDataResponse<List<Article>> ) // Get Sources fun getSources( language: String, country: String, category: String, callback: FrogoDataResponse<SourceResponse> ) fun saveArticles(data: List<Article>, callback: FrogoStateResponse) fun deleteArticles(callback: FrogoStateResponse) }
0
Kotlin
5
18
e99b554e5f4d95562d941401a63237fc91109867
1,563
frogo-sdk
Apache License 2.0
app/src/main/java/com/todou/nestrefresh/example/ui/activity/SingleActivity.kt
ToDou
189,685,177
false
null
package com.todou.nestrefresh.example.ui.activity import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import com.todou.nestrefresh.base.OnRefreshListener import com.todou.nestrefresh.example.R import com.todou.nestrefresh.example.ui.adapter.RecyclerAdapterInHeader import com.todou.nestrefresh.example.ui.adapter.RecyclerAdapterScroll import com.todou.nestrefresh.example.ui.widget.ItemDecoration import kotlinx.android.synthetic.main.activity_nest_refresh_recycler.* import java.util.Collections class SingleActivity : AppCompatActivity() { private lateinit var adapter: RecyclerAdapterInHeader private lateinit var recyclerAdapterScroll: RecyclerAdapterScroll override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_nest_refresh_recycler) recycler_view_inner.layoutManager = LinearLayoutManager(this) adapter = RecyclerAdapterInHeader() recycler_view_inner.adapter = adapter adapter.updateDatas(Collections.nCopies(5, Any())) recycler_view.layoutManager = LinearLayoutManager(this) recyclerAdapterScroll = RecyclerAdapterScroll() recycler_view.adapter = recyclerAdapterScroll recycler_view.addItemDecoration( ItemDecoration( this, RecyclerView.VERTICAL , resources.getDimensionPixelSize(R.dimen.margin_normal) ) ) recyclerAdapterScroll.updateDatas(Collections.nCopies(20, Any())) view_refresh_header.setOnRefreshListener(object : OnRefreshListener { override fun onRefresh() { view_refresh_header.postDelayed({ view_refresh_header.stopRefresh() }, 2000) } }) } }
6
null
20
98
07299263f13a2755cb2834808c90968a4fd1a20a
1,919
nestrefresh
Apache License 2.0
app/src/main/java/com/fatlytics/app/ui/addfood/search/FoodSearchAdapter.kt
necatisozer
177,310,241
false
null
package com.fatlytics.app.ui.addfood.search import android.view.ViewGroup import com.fatlytics.app.data.source.api.entity.FoodsSearch import com.fatlytics.app.databinding.ItemFoodSearchBinding import com.fatlytics.app.extension.getInflater import com.fatlytics.app.ui.base.BaseAdapter import com.fatlytics.app.ui.base.BaseViewHolder class FoodSearchAdapter : BaseAdapter<FoodsSearch.Foods.Food, SearchViewHolder>() { override fun onCreateViewHolder(root: ViewGroup) = SearchViewHolder(ItemFoodSearchBinding.inflate(root.getInflater(), root, false)) } class SearchViewHolder(binding: ItemFoodSearchBinding) : BaseViewHolder<FoodsSearch.Foods.Food, ItemFoodSearchBinding>(binding) { override fun bindData(data: FoodsSearch.Foods.Food) { val foodName = StringBuilder().apply { data.brand_name?.let { append("$it ") } data.food_name?.let { append(it) } } binding.foodName.text = foodName binding.foodDescription.text = data.food_description } }
0
Kotlin
0
1
6f5cadb83570d09f5aea89d9fc1139b7ccb7bc0c
1,025
Fatlytics
Apache License 2.0
03/RecyclerView/app/src/main/java/com/lfg/recyclerview/fragments/LoginFragment.kt
leonelgomez1990
402,218,277
false
null
package com.lfg.recyclerview.fragments import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.navigation.findNavController import com.google.android.material.snackbar.Snackbar import com.lfg.recyclerview.R import com.lfg.recyclerview.functions.hideKeyboard import com.lfg.recyclerview.repositories.UserRepository import com.lfg.recyclerview.viewmodels.LoginViewModel class LoginFragment : Fragment() { companion object { fun newInstance() = LoginFragment() } private lateinit var viewModelLogin: LoginViewModel private lateinit var v : View lateinit var btnLogin : Button lateinit var txtUser : TextView lateinit var txtPassword : TextView lateinit var frameLayout : ConstraintLayout private var userRepository = UserRepository() lateinit var btnCreate : Button override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { v = inflater.inflate(R.layout.login_fragment, container, false) //Binding btnLogin = v.findViewById(R.id.btnLogin) txtUser = v.findViewById(R.id.txtUser) txtPassword = v.findViewById(R.id.txtPassword) frameLayout = v.findViewById(R.id.frameLayout1) btnCreate = v.findViewById(R.id.btnCreate) return v } // override fun onConfigurationChanged(newConfig: Configuration) { // super.onConfigurationChanged(newConfig) // //cuando giro la pantalla // } override fun onStart() { super.onStart() txtUser.text = "" txtPassword.text = "" btnLogin.setOnClickListener { this.hideKeyboard() if(txtUser.length() <= 0) { Snackbar.make(frameLayout, R.string.msg_empty, Snackbar.LENGTH_SHORT).show() } else { val id = userRepository.getList().firstOrNull() { t -> t.user == txtUser.text.toString() } if(id != null) { //chequeo contraseña if (txtPassword.text.toString() == id.password) { navegateLoginSuccesful() } else { Snackbar.make(frameLayout, R.string.msg_wrongpassword, Snackbar.LENGTH_SHORT).show() } } else { Snackbar.make(frameLayout, R.string.msg_wronguser, Snackbar.LENGTH_SHORT).show() } } } btnCreate.setOnClickListener { navegateCreateNewUser() } } fun navegateLoginSuccesful(){ val action = LoginFragmentDirections.actionFragment1ToMainActivity2() v.findNavController().navigate(action) } fun navegateCreateNewUser(){ val action2 = LoginFragmentDirections.actionFragment1ToFragment3() v.findNavController().navigate(action2) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModelLogin = ViewModelProvider(this).get(LoginViewModel::class.java) // TODO: Use the ViewModel } }
0
Kotlin
0
0
ce39f62befef83d53a3809411dbf60c2dcd410cc
3,523
kotlin1
MIT License
app/src/main/java/com/byy/mvvm_interviewtest/exchangerate/ExchangeRateActivity.kt
bbyhao
132,335,526
false
null
package com.byy.mvvm_interviewtest.exchangerate import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.helper.ItemTouchHelper import com.byy.mvvm_interviewtest.BaseActivity import com.byy.mvvm_interviewtest.R import com.byy.mvvm_interviewtest.databinding.ActivityExchangerateBinding import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback import com.chad.library.adapter.base.listener.OnItemDragListener import com.google.gson.Gson import kotlinx.android.synthetic.main.activity_exchangerate.* import org.jetbrains.anko.toast /** * @author Created by fq on 2018/4/28. */ class ExchangeRateActivity : BaseActivity<ExchangeRateViewMode>() { companion object { val Rate_ORDER="rate_order" } // override fun initViewModel(): Class<ExchangeRateViewMode> = ExchangeRateViewMode::class.java override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) DataBindingUtil.setContentView<ActivityExchangerateBinding>(this, R.layout.activity_exchangerate) .apply { viewModel = mViewModel } initData() initListener() } private fun initListener() { tv_rate_update.setOnClickListener { mViewModel.update() } } private fun initData() { recycleView.layoutManager = LinearLayoutManager(this) val mAdapter = RateAdapter(mViewModel.item.get()) recycleView.adapter = mAdapter mViewModel.update() val itemDragAndSwipeCallback = ItemDragAndSwipeCallback(mAdapter) val itemTouchHelper = ItemTouchHelper(itemDragAndSwipeCallback) itemTouchHelper.attachToRecyclerView(recycleView) // 开启拖拽 mAdapter.enableDragItem(itemTouchHelper) mAdapter.setOnItemDragListener(object :OnItemDragListener{ override fun onItemDragMoving(source: RecyclerView.ViewHolder?, from: Int, target: RecyclerView.ViewHolder?, to: Int) { } override fun onItemDragStart(viewHolder: RecyclerView.ViewHolder?, pos: Int) { } override fun onItemDragEnd(viewHolder: RecyclerView.ViewHolder?, pos: Int) { val map=HashMap<String,Int>() for ((index,item) in mAdapter.data.withIndex()) { map[item.country] = index } mViewModel.mOrder=Gson().toJson(map) } }) // 开启滑动删除 // mAdapter.enableSwipeItem() // mAdapter.setOnItemSwipeListener(onItemSwipeListener) mAdapter.setOnItemClickListener { adapter, view, position -> toast("1111111") } } }
0
Kotlin
0
6
efaac1eb91e32cf87b51b99e143982cce7628ebb
2,828
mvvm_interview
Apache License 2.0
ui-kit/src/main/kotlin/org/p2p/uikit/components/UiKitFourDigitsLargeInput.kt
p2p-org
306,035,988
false
{"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252}
package org.p2p.uikit.components import android.content.Context import android.util.AttributeSet import androidx.annotation.DrawableRes import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.res.use import androidx.core.view.isVisible import com.redmadrobot.inputmask.MaskedTextChangedListener import org.p2p.uikit.R import org.p2p.uikit.databinding.ComponentLargeInputFourDigitsBinding import org.p2p.core.utils.emptyString import org.p2p.uikit.utils.focusAndShowKeyboard import org.p2p.uikit.utils.inflateViewBinding private val NO_ICON: Int? = null private const val INPUT_MASK = "[000] [000]" class UiKitFourDigitsLargeInput @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { interface Listener { fun onLeftIconClicked() = Unit fun onRightIconClicked() = Unit fun onInputChanged(inputValue: String) = Unit } @DrawableRes var leftIconRes: Int? = NO_ICON set(value) { value?.let { binding.leftIconImage.setImageResource(it) } binding.leftIconImage.isVisible = value != null field = value } var isChevronIconVisible: Boolean get() = binding.chevronImage.isVisible set(value) { binding.chevronImage.isVisible = value } var inputText: String get() = binding.fourDigitsInput.text?.toString().orEmpty() set(value) { binding.fourDigitsInput.setText(value) } @DrawableRes var rightIconRes: Int? = NO_ICON set(value) { value?.let { binding.rightIconImage.setImageResource(it) } binding.leftIconImage.isVisible = value != null field = value } private val binding: ComponentLargeInputFourDigitsBinding = inflateViewBinding() private var listener: Listener? = null private val onTextChangedListener = object : MaskedTextChangedListener.ValueListener { override fun onTextChanged(maskFilled: Boolean, extractedValue: String, formattedValue: String) { listener?.onInputChanged(extractedValue) } } init { context.obtainStyledAttributes(attrs, R.styleable.UiKitFourDigitsLargeInput).use { typedArray -> rightIconRes = typedArray.getResourceId(R.styleable.UiKitFourDigitsLargeInput_rightIcon, -1) .takeIf { it != -1 } rightIconRes = typedArray.getResourceId(R.styleable.UiKitFourDigitsLargeInput_leftIcon, -1) .takeIf { it != -1 } isChevronIconVisible = typedArray.getBoolean(R.styleable.UiKitFourDigitsLargeInput_isChevronVisible, false) } with(binding.fourDigitsInput) { MaskedTextChangedListener.installOn( editText = this, primaryFormat = INPUT_MASK, valueListener = onTextChangedListener ) .also { hint = it.placeholder() } } binding.leftIconImage.setOnClickListener { listener?.onLeftIconClicked() } binding.rightIconImage.setOnClickListener { listener?.onRightIconClicked() } } fun setInputListener(listener: Listener) { this.listener = listener } fun focusAndShowKeyboard() { binding.fourDigitsInput.focusAndShowKeyboard() } fun setErrorState(errorMessage: String) { binding.contentCardLayout.setBackgroundResource(R.drawable.background_input_stroke_oval_error) binding.errorText.isVisible = true binding.errorText.text = errorMessage } fun clearErrorState() { binding.contentCardLayout.setBackgroundResource(R.drawable.background_input_stroke_oval) binding.errorText.isVisible = false binding.errorText.text = emptyString() } }
8
Kotlin
18
34
d091e18b7d88c936b7c6c627f4fec96bcf4a0356
3,834
key-app-android
MIT License
library/src/main/java/com/luckyhan/studio/mokaeditor/span/paragraph/MokaQuoteSpan.kt
junhanRyu
365,757,498
false
{"Kotlin": 54117}
package com.luckyhan.studio.mokaeditor.span.paragraph import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.text.Layout import android.text.style.LeadingMarginSpan import com.luckyhan.studio.mokaeditor.span.MokaParagraphStyle import com.luckyhan.studio.mokaeditor.span.MokaSpan import org.json.JSONObject class MokaQuoteSpan( private val mColor : Int = Color.BLACK, private val mStripeWidth : Int = 10, private val mGapWidth : Int = 80) : MokaParagraphStyle, LeadingMarginSpan { override fun copy(): MokaSpan { return MokaQuoteSpan(mColor, mStripeWidth, mGapWidth) } override fun getSpanTypeName(): String { return "quote" } override fun writeToJson(json: JSONObject) { return } override fun getLeadingMargin(first: Boolean): Int { return mGapWidth } override fun drawLeadingMargin( canvas: Canvas?, paint: Paint?, x: Int, dir: Int, lineTop: Int, baseline: Int, lineBottom: Int, text: CharSequence?, startOffset: Int, endOffset: Int, first: Boolean, layout: Layout? ) { canvas?.let { paint?.let { val style = paint.style val color = paint.color paint.style = Paint.Style.FILL paint.color = mColor val xPosition = (x+mGapWidth-mStripeWidth)/2f canvas.drawRect(xPosition, lineTop.toFloat(), (xPosition + dir * mStripeWidth), lineBottom.toFloat(), paint) paint.style = style paint.color = color } } } }
1
Kotlin
0
4
64baa5e0561e06a47ca2806abeb3f6f145609929
1,713
MokaEditor
Apache License 2.0
app/src/main/java/com/panda/pda/app/operation/qms/NgReasonFragment.kt
Givennn
402,701,983
false
null
package com.panda.pda.app.operation.qms import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.setFragmentResult import by.kirich1409.viewbindingdelegate.viewBinding import com.jakewharton.rxbinding4.view.clicks import com.panda.pda.app.R import com.panda.pda.app.base.BaseFragment import com.panda.pda.app.base.extension.toast import com.panda.pda.app.common.WheelPickerDialogFragment import com.panda.pda.app.common.adapter.CommonViewBindingAdapter import com.panda.pda.app.databinding.FragmentNgReasonBinding import com.panda.pda.app.databinding.ItemNgReasonBinding import com.panda.pda.app.operation.qms.data.model.QualityNgReasonModel import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.Types import com.trello.rxlifecycle4.kotlin.bindToLifecycle import java.util.concurrent.TimeUnit /** * created by AnJiwei 2021/10/12 */ class NgReasonFragment : BaseFragment(R.layout.fragment_ng_reason) { private val viewBinding by viewBinding<FragmentNgReasonBinding>() private lateinit var ngReasons: List<QualityNgReasonModel> private val ngReasonAdapter = getNgReasonAdapter() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewBinding.topAppBar.setNavigationOnClickListener { navBackListener.invoke(it) } ngReasons = ngReasonAdapter.fromJson( requireArguments().getString(NG_REASON_ARG_KEY, "") ) ?: listOf() viewBinding.rvNgList.adapter = object : CommonViewBindingAdapter<ItemNgReasonBinding, QualityNgReasonModel>( ngReasons.toMutableList() ) { override fun createBinding(parent: ViewGroup): ItemNgReasonBinding { return ItemNgReasonBinding.inflate( LayoutInflater.from(parent.context), parent, false ) } override fun onBindViewHolderWithData( holder: ViewBindingHolder, data: QualityNgReasonModel, position: Int ) { holder.itemViewBinding.cbNgReason.text = data.badnessReasonName holder.itemViewBinding.cbNgReason.setOnCheckedChangeListener { _, isChecked -> data.isChecked = isChecked } } } viewBinding.btnConfirm.clicks() .throttleFirst(500, TimeUnit.MILLISECONDS) .bindToLifecycle(requireView()) .subscribe { val reasons = ngReasons.filter { it.isChecked } if (reasons.isEmpty()) { toast(getString(R.string.ng_reason_empty_message)) } else { confirm(reasons) } } } private fun confirm(reasons: List<QualityNgReasonModel>) { setFragmentResult(REQUEST_KEY, Bundle().apply { putString(NG_REASON_ARG_KEY, ngReasonAdapter.toJson(reasons)) }) navBackListener.invoke(requireView()) } companion object { const val REQUEST_KEY = "NG_REASON_REQUEST" const val NG_REASON_ARG_KEY = "NG_REASON_ARGS" fun getNgReasonAdapter(): JsonAdapter<List<QualityNgReasonModel>> { return Moshi.Builder().build().adapter( Types.newParameterizedType( List::class.java, QualityNgReasonModel::class.java ) ) } } }
0
Kotlin
0
0
24f6284eed22b1fe91b5462a0cdd5a466d6531ad
3,650
pda
MIT License
backend/src/main/kotlin/de/debuglevel/walkingdinner/backend/calculation/client/CalculationResponse.kt
debuglevel
133,810,544
false
{"Gradle": 5, "YAML": 10, "Markdown": 3, "Ignore List": 9, "Procfile": 1, "Java Properties": 3, "Shell": 17, "Text": 1, "Batchfile": 1, "Dockerfile": 5, "OASv3-yaml": 2, "Kotlin": 153, "Java": 1, "XML": 21, "JSON": 10, "INI": 1, "JSON with Comments": 2, "JavaScript": 1, "EditorConfig": 1, "Browserslist": 1, "HTML": 15, "CSS": 15, "Nginx": 1, "Twig": 1}
package de.debuglevel.walkingdinner.backend.calculation.client import java.time.LocalDateTime import java.util.* data class CalculationResponse( /** * UUID of the calculation */ val id: UUID, /** * Whether the calculation of the plan has finished or is still in progress */ val finished: Boolean, /** * Size of the population (for calculation with Genetic Algorithm) */ val populationSize: Int, /** * Fitness level to beat (minimization problem, i.e. fitness must be less than this threshold) (for calculation with Genetic Algorithm) */ val fitnessThreshold: Double, /** * Number of generations with constant fitness level to stop further calculations (for calculation with Genetic Algorithm) */ val steadyFitness: Int, /** * Teams to calculate into the plan */ val teams: List<TeamResponse>, /** * UUID of the plan, once it is calculated */ val planId: UUID?, /** * When the calculation began */ var begin: LocalDateTime? = null, /** * When the calculation finished */ var end: LocalDateTime? = null ) //fun Calculation.toCalculationResponse(): CalculationResponse { // return CalculationResponse( // id = this.id!!, // finished = this.finished, // fitnessThreshold = this.fitnessThreshold, // populationSize = this.populationSize, // steadyFitness = this.steadyFitness, // teams = this.teams.map { it.toTeamResponse() }, // planId = this.plan?.id // ) //}
36
Kotlin
0
0
2ddc1054723e79282320eb5aa950dcfe50f407ef
1,577
walkingdinner-geneticplanner
The Unlicense
src/test/kotlin/no/nav/syfo/testhelper/TestEnvironment.kt
navikt
331,892,633
false
null
package no.nav.syfo.testhelper import no.nav.syfo.application.ApplicationEnvironmentKafka import no.nav.syfo.application.ApplicationState import no.nav.syfo.application.Environment import java.net.ServerSocket import java.util.* fun testEnvironment( kafkaBootstrapServers: String, dokarkivUrl: String = "http://dokarkiv", azureTokenEndpoint: String = "azureTokenEndpoint", isdialogmotepdfgenUrl: String? = null, isproxyUrl: String = "isproxy", krrUrl: String = "krr", syfobehandlendeenhetUrl: String? = null, syfotilgangskontrollUrl: String? = null, narmestelederUrl: String? = null, pdlUrl: String? = null, allowVarselMedFysiskBrev: Boolean = false, allowMotedeltakerBehandler: Boolean = false, ) = Environment( aadAppClient = "isdialogmote-client-id", aadAppSecret = "isdialogmote-secret", aadTokenEndpoint = azureTokenEndpoint, azureAppWellKnownUrl = "wellknown", dokarkivClientId = "dokarkiv-client-id", isproxyClientId = "isproxy-client-id", isproxyUrl = isproxyUrl, electorPath = "electorPath", loginserviceIdportenDiscoveryUrl = "", loginserviceIdportenAudience = listOf("idporten"), kafka = ApplicationEnvironmentKafka( bootstrapServers = kafkaBootstrapServers, schemaRegistryUrl = "http://kafka-schema-registry.tpa.svc.nais.local:8081", aivenBootstrapServers = kafkaBootstrapServers, aivenSchemaRegistryUrl = "http://kafka-schema-registry.tpa.svc.nais.local:8081", aivenRegistryUser = "registryuser", aivenRegistryPassword = "<PASSWORD>", aivenSecurityProtocol = "SSL", aivenCredstorePassword = "<PASSWORD>", aivenTruststoreLocation = "truststore", aivenKeystoreLocation = "keystore", ), allowVarselMedFysiskBrev = allowVarselMedFysiskBrev, allowMotedeltakerBehandler = allowMotedeltakerBehandler, redisHost = "localhost", redisPort = 6599, redisSecret = "<PASSWORD>", serviceuserUsername = "user", serviceuserPassword = "<PASSWORD>", isdialogmoteDbHost = "localhost", isdialogmoteDbPort = "5432", isdialogmoteDbName = "isdialogmote_dev", isdialogmoteDbUsername = "username", isdialogmoteDbPassword = "<PASSWORD>", dialogmoteArbeidstakerUrl = "https://www.nav.no/dialogmote", dokarkivUrl = dokarkivUrl, isdialogmotepdfgenUrl = isdialogmotepdfgenUrl ?: "http://isdialogmotepdfgen", krrClientId = "dev-gcp.team-rocket.digdir-krr-proxy", krrUrl = krrUrl, syfobehandlendeenhetClientId = "syfobehandlendeenhetClientId", syfobehandlendeenhetUrl = syfobehandlendeenhetUrl ?: "syfobehandlendeenhet", syfotilgangskontrollClientId = "syfotilgangskontrollclientid", syfotilgangskontrollUrl = syfotilgangskontrollUrl ?: "tilgangskontroll", journalforingCronjobEnabled = false, publishDialogmoteStatusEndringCronjobEnabled = false, mqUsername = "mquser", mqPassword = "<PASSWORD>", mqTredjepartsVarselQueue = "queuename", mqSendingEnabled = false, narmestelederClientId = "narmestelederClientId", narmestelederUrl = narmestelederUrl ?: "http://narmesteleder", pdlClientId = "pdlClientId", pdlUrl = pdlUrl ?: "http://pdl", toggleKafkaProcessingDialogmeldinger = true, ) fun testAppState() = ApplicationState( alive = true, ready = true ) fun getRandomPort() = ServerSocket(0).use { it.localPort } fun Properties.overrideForTest(): Properties = apply { remove("security.protocol") remove("sasl.mechanism") }
1
Kotlin
0
0
e7a334eebbbc5ce316772ba2a94fe62acfa6e1e6
3,531
isdialogmote
MIT License
app/src/main/java/com/sunnyweather/android/logic/dao/PlaceDao.kt
dire1228
296,022,968
false
null
package com.sunnyweather.android.logic.dao import android.content.Context import androidx.core.content.edit import com.google.gson.Gson import com.sunnyweather.android.LogUtil import com.sunnyweather.android.SunnyWeatherApplication import com.sunnyweather.android.logic.model.Place /** * 记录选中的城市 */ object PlaceDao { /** * 存储位置 */ fun savePlace(place: Place) { sharedPreferences().edit() { putString("place", Gson().toJson(place)) } } /** * 获取存储的位置 */ fun getSavedPlace(): Place { val placeJson = sharedPreferences().getString("place", "") LogUtil.v("PlaceDao", "---获取存储位置${placeJson}") return Gson().fromJson(placeJson, Place::class.java) } /** * 是否有存储 */ fun isPlaceSaved() = sharedPreferences().contains("place") /** * 创建SharePreference */ private fun sharedPreferences() = SunnyWeatherApplication.context.getSharedPreferences("sunny_weather", Context.MODE_PRIVATE) }
0
Kotlin
0
0
92589008d445cbc775e26fdc354590f715a76117
1,011
SunneyWeather
Apache License 2.0
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/HeatPumpOutlined.kt
karakum-team
387,062,541
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/HeatPumpOutlined") @file:JsNonModule package mui.icons.material @JsName("default") external val HeatPumpOutlined: SvgIconComponent
0
null
5
35
83952a79ffff62f5409461a2928102d0ff95d86b
214
mui-kotlin
Apache License 2.0
src/main/kotlin/ru/spbau/mit/world/Creature.kt
stasbel
117,672,839
false
null
package ru.spbau.mit.world /** * A type of [Creature]. * @author belaevstanislav */ enum class CreatureType(val bonus: Params) { PLAYER(Params(hp = +5, maxHp = +5, attack = +2)), MOB(Params(attack = +3, armor = +1)); companion object { val DEFAULT = MOB } } /** * Race of [Creature]. * @author belaevstanislav */ enum class Race(val bonus: Params) { HUMAN(Params(armor = +2)), ORK(Params(hpRegen = +1)); companion object { val DEFAULT = ORK } } /** * Status of [Creature]. * @author belaevstanislav */ enum class CreatureStatus { ALIVE, DEAD; companion object { val DEFAULT = ALIVE } } /** * Creature abstract class. You can create an instance of it only using Builder. * Creature is essential of living unit of the game field which have some params. * @author belaevstanislav * @param pos [Pos] of creature * @param creatureType [CreatureType] of creature * @param race [Race] of creature * @param params [Params] of creature * @param items [Items] of creature * @param status [CreatureStatus] of creature */ abstract class Creature private constructor(pos: Pos, val creatureType: CreatureType, val race: Race, val params: Params, val items: Items, var status: CreatureStatus) : Unit(pos) { /** * A class implementing Builder pattern for Creature class. * Has bunch of setter for [Creature] field, finishing with build() func to * complete create. */ class Builder private constructor() { companion object { fun create() = Builder() } private var pos: Pos = Pos.NULL private var creatureType: CreatureType = CreatureType.DEFAULT private var race: Race = Race.DEFAULT private var params: Params = Params.DEFAULT private var items: Items = Items() private val status: CreatureStatus = CreatureStatus.DEFAULT fun setPos(pos: Pos): Builder = run { this.pos = pos; this } fun setCreatureType(creatureType: CreatureType): Builder = run { this.creatureType = creatureType; this } fun setRace(race: Race): Builder = run { this.race = race; this } fun setParams(params: Params): Builder = run { this.params = params; this } fun addItems(items: Set<Item>): Builder = run { items.forEach { it.status = ItemStatus.STORED this.items.addItem(it) } this } fun build(): Creature = object : Creature( pos = pos, creatureType = creatureType, race = race, params = params + creatureType.bonus + race.bonus, items = items, status = status ) {} } /** * Adds item to [this] [Creature] changing it status to STORED. * @param item an item to add */ fun addItem(item: Item) { items.findItem(item).apply { if (this == null) { when (item.status) { ItemStatus.DROPPED -> { item.status = ItemStatus.STORED [email protected](item) } ItemStatus.USED -> run {} ItemStatus.STORED -> run {} } } else { run {} } } } /** * Adds item to [this] [Creature] changing it status from USED to STORED and vice versa. * @param item an item to toggle */ fun toggleItem(item: Item) { items.findItem(item).apply { if (this == null) { run {} } else { when (status) { ItemStatus.DROPPED -> run {} ItemStatus.USED -> { [email protected] -= type.params status = ItemStatus.STORED } ItemStatus.STORED -> { [email protected] += type.params status = ItemStatus.USED } } } } } /** * Proceeding a periodically events. */ fun periodically() { // hp regen params.apply { this += Params(hp = +this.hpRegen) } } }
0
Kotlin
0
0
1f557211587adcf80558a3fe5a1e481bff5bac05
4,549
rogalix
MIT License
model/src/jvmMain/kotlin/LocaleMessage.kt
henteko
164,647,878
true
{"Kotlin": 272498, "Java": 21515, "Shell": 7799, "Ruby": 2640}
package io.github.droidkaigi.confsched2019.model actual fun LocaleMessage.get() = if (defaultLang() != Lang.JA) enMessage else jaMessage
0
Kotlin
0
0
6e96ce44ca49dceb4f4fa3f0cc0a39da8903ebe8
138
conference-app-2019
Apache License 2.0
app/src/main/java/com/ilgiz/kitsu/presentation/models/anime/ReviewsUI.kt
ilgiz05
493,465,307
false
null
package com.ilgiz.kitsu.presentation.models.anime import com.ilgiz.kitsu.domain.models.anime.ReviewsModel data class ReviewsUI( val links: LinksXXXXXXUI ) fun ReviewsModel.toUI() = ReviewsUI(links.toUI())
0
Kotlin
0
0
f9d4b4b9899bc2faa3fc992233c3187774d3d8d8
212
lesson7.kotlin3
MIT License
core/designsystem/src/main/java/com/minux/monitoring/core/designsystem/component/DropDownMenu.kt
MINUX-organization
756,381,294
false
{"Kotlin": 234602}
package com.minux.monitoring.core.designsystem.component import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.TweenSpec import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExposedDropdownMenuBox import androidx.compose.material3.ExposedDropdownMenuDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.minux.monitoring.core.designsystem.icon.MNXIcons import com.minux.monitoring.core.designsystem.theme.MNXTheme import com.minux.monitoring.core.designsystem.theme.grillSansMtFamily @OptIn(ExperimentalMaterial3Api::class) @Composable fun MNXDropDownMenu( modifier: Modifier = Modifier, shape: Shape = RoundedCornerShape(4.dp), iconPadding: Dp = 10.dp, contentPadding: PaddingValues = PaddingValues( start = 10.dp, top = 7.dp, end = 9.dp, bottom = 7.dp ), menuItems: List<String>, selectedItem: MutableState<String> ) { val isExpandedState = remember { mutableStateOf(false) } val scaleY = remember { Animatable(initialValue = 1f) } LaunchedEffect(key1 = isExpandedState.value) { scaleY.animateTo( targetValue = if (isExpandedState.value) -1f else 1f, animationSpec = TweenSpec( durationMillis = 250, easing = LinearEasing ) ) } ExposedDropdownMenuBox( modifier = modifier, expanded = isExpandedState.value, onExpandedChange = { isExpandedState.value = !isExpandedState.value } ) { MNXTextField( modifier = Modifier .fillMaxWidth() .menuAnchor(), value = selectedItem.value, onValueChange = { selectedItem.value = it }, readOnly = true, shape = shape, suffix = { Icon( modifier = Modifier .graphicsLayer { this.scaleY = scaleY.value } .padding(start = iconPadding), painter = painterResource(id = MNXIcons.DropDown), tint = MaterialTheme.colorScheme.primary, contentDescription = null ) }, contentPadding = contentPadding ) DropdownMenu( modifier = Modifier.exposedDropdownSize(), expanded = isExpandedState.value, onDismissRequest = { isExpandedState.value = false } ) { menuItems.forEachIndexed { index, text -> DropdownMenuItem( text = { Text( text = text, color = MaterialTheme.colorScheme.onPrimaryContainer, fontSize = 16.sp, fontFamily = grillSansMtFamily, fontWeight = FontWeight.Normal ) }, onClick = { selectedItem.value = menuItems[index] isExpandedState.value = false }, contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding ) } } } } @Preview @Composable private fun MNXDropDownMenuPreview() { MNXTheme { val list = listOf("Alg 1", "Alg 2") val selectedText = remember { mutableStateOf("Sort by") } Column(modifier = Modifier.padding(10.dp)) { MNXDropDownMenu( menuItems = list, selectedItem = selectedText ) MNXDropDownMenu( modifier = Modifier.padding(top = 10.dp), shape = RectangleShape, contentPadding = PaddingValues( start = 10.dp, top = 9.dp, end = 9.dp, bottom = 9.dp ), menuItems = list, selectedItem = selectedText ) } } }
0
Kotlin
0
0
ea0ed05ff1b07f2d970f772b2af1c9179872ccf1
5,399
MNX.Mobile.Monitoring
MIT License
app/src/main/java/com/patmore/android/features/foryou/presentation/adapter/CategoryPagerAdapter.kt
jawnpaul
514,394,689
false
{"Kotlin": 189149}
package com.patmore.android.features.foryou.presentation.adapter import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter import com.patmore.android.features.foryou.presentation.view.CategoryFragment class CategoryPagerAdapter(fragment: Fragment, val list: List<CategoryFragment>) : FragmentStateAdapter(fragment) { override fun getItemCount(): Int { return list.size } override fun createFragment(position: Int): Fragment { return list[position] } }
3
Kotlin
1
11
9a36efdd72ea4b7ee51e09de28c863be52cf53fa
523
patmore-android
MIT License
library/src/main/java/ru/yoomoney/sdk/kassa/payments/payment/sbp/bankList/impl/BankListBusinessLogic.kt
card-of-day
696,877,156
false
{"Kotlin": 1543812, "Java": 2389}
/* * The MIT License (MIT) * Copyright © 2023 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.payment.sbp.bankList.impl import ru.yoomoney.sdk.kassa.payments.payment.sbp.bankList.BankList import ru.yoomoney.sdk.march.Logic import ru.yoomoney.sdk.march.Out import ru.yoomoney.sdk.march.input import ru.yoomoney.sdk.march.output internal class BankListBusinessLogic( val showState: suspend (BankList.State) -> BankList.Action, val showEffect: suspend (BankList.Effect) -> Unit, val source: suspend () -> BankList.Action, val interactor: BankListInteractor, val confirmationUrl: String, val paymentId: String, ) : Logic<BankList.State, BankList.Action> { override fun invoke( state: BankList.State, action: BankList.Action, ): Out<BankList.State, BankList.Action> { return when (state) { is BankList.State.Progress -> handleProgress(state, action) is BankList.State.Error -> handleError(state, action) is BankList.State.ShortBankListContent -> handleShortBankListContent(state, action) is BankList.State.FullBankListContent -> handleFullBankListContent(state, action) is BankList.State.ShortBankListStatusProgress -> handleShortBankListStatusProgress(state, action) is BankList.State.FullBankListStatusProgress -> handleFullBankListStatusProgress(state, action) is BankList.State.PaymentShortBankListStatusError -> handleShortBankListPaymentStatusError(state, action) is BankList.State.PaymentFullBankListStatusError -> handleFullBankListPaymentStatusError(state, action) is BankList.State.ActivityNotFoundError -> handleActivityNotFoundStatusError(state, action) } } private fun handleShortBankListContent( state: BankList.State.ShortBankListContent, action: BankList.Action, ): Out<BankList.State, BankList.Action> = when (action) { is BankList.Action.LoadOtherBankList -> Out(BankList.State.FullBankListContent(state.fullBankList, true)) { input { showState(this.state) } } is BankList.Action.BackToBankList -> Out(state) { input(source) output { showEffect(BankList.Effect.CloseBankList) } } is BankList.Action.SelectBank -> handleOpenBank(state, action.deeplink) is BankList.Action.BankInteractionFinished -> handleBankInteractionFinishedShortList(state) is BankList.Action.ActivityNotFound -> handleActivityNotFound(action.throwable, state) else -> Out.skip(state, source) } private fun handleBankInteractionFinishedShortList(state: BankList.State.ShortBankListContent) = Out( BankList.State.ShortBankListStatusProgress( state.shortBankList, state.fullBankList ) ) { input { showState(this.state) } input { interactor.getPaymentStatus(paymentId) } } private fun handleFullBankListContent( fullBankListContent: BankList.State.FullBankListContent, action: BankList.Action, ): Out<BankList.State, BankList.Action> = when (action) { is BankList.Action.BackToBankList -> Out(fullBankListContent) { input(source) if (fullBankListContent.showBackNavigation) { input { interactor.getPriorityBanks(fullBankListContent.bankList) } } else { output { showEffect(BankList.Effect.CloseBankList) } } } is BankList.Action.LoadShortBankListSuccess -> Out( BankList.State.ShortBankListContent( action.shortBankList, fullBankListContent.bankList ) ) { input { showState(this.state) } } is BankList.Action.SelectBank -> handleOpenBank(fullBankListContent, action.deeplink) is BankList.Action.BankInteractionFinished -> handleBankInteractionFinishedFullList(fullBankListContent) is BankList.Action.ActivityNotFound -> handleActivityNotFound(action.throwable, fullBankListContent) is BankList.Action.Search -> Out( fullBankListContent.copy( searchText = action.searchText, searchedBanks = interactor.searchBank(action.searchText, fullBankListContent.bankList) ) ) { input { showState(this.state) } } is BankList.Action.CancelSearch -> Out( fullBankListContent.copy( searchText = "", searchedBanks = emptyList() ) ) { input { showState(this.state) } } else -> Out.skip(fullBankListContent, source) } private fun handleBankInteractionFinishedFullList(fullBankListContent: BankList.State.FullBankListContent) = Out( BankList.State.FullBankListStatusProgress( fullBankListContent.bankList, fullBankListContent.showBackNavigation ) ) { input { showState(this.state) } input { interactor.getPaymentStatus(paymentId) } } private fun handleProgress( state: BankList.State.Progress, action: BankList.Action, ): Out<BankList.State, BankList.Action> = when (action) { is BankList.Action.LoadShortBankListSuccess -> Out( BankList.State.ShortBankListContent( action.shortBankList, action.fullBankList ) ) { input { showState(this.state) } } is BankList.Action.LoadFullBankListSuccess -> Out( BankList.State.FullBankListContent( action.fullBankList, action.showBackNavigation ) ) { input { showState(this.state) } } is BankList.Action.LoadBankListFailed -> Out(BankList.State.Error(action.throwable)) { input { showState(this.state) } } else -> Out.skip(state, source) } private fun handleShortBankListStatusProgress( state: BankList.State.ShortBankListStatusProgress, action: BankList.Action, ): Out<BankList.State, BankList.Action> = when (action) { is BankList.Action.PaymentProcessInProgress -> Out( BankList.State.ShortBankListContent( state.shortBankList, state.fullBankList ) ) { input { showState(this.state) } } is BankList.Action.PaymentProcessFinished -> Out(state) { input(source) output { showEffect(BankList.Effect.CloseBankListWithFinish) } } is BankList.Action.PaymentStatusError -> Out( BankList.State.PaymentShortBankListStatusError( action.throwable, state.shortBankList, state.fullBankList ) ) { input { showState(this.state) } } else -> Out.skip(state, source) } private fun handleFullBankListStatusProgress( state: BankList.State.FullBankListStatusProgress, action: BankList.Action, ): Out<BankList.State, BankList.Action> = when (action) { is BankList.Action.PaymentProcessInProgress -> Out( BankList.State.FullBankListContent( state.fullBankList, state.showBackNavigation ) ) { input { showState(this.state) } } is BankList.Action.PaymentProcessFinished -> Out(state) { input(source) output { showEffect(BankList.Effect.CloseBankListWithFinish) } } is BankList.Action.PaymentStatusError -> Out( BankList.State.PaymentFullBankListStatusError( action.throwable, state.fullBankList, state.showBackNavigation ) ) { input { showState(this.state) } } else -> Out.skip(state, source) } private fun handleError( state: BankList.State.Error, action: BankList.Action, ): Out<BankList.State, BankList.Action> = when (action) { is BankList.Action.LoadBankList -> Out(BankList.State.Progress) { input { showState(this.state) } input { interactor.getSbpBanks(confirmationUrl) } } else -> Out.skip(state, source) } private fun handleShortBankListPaymentStatusError( state: BankList.State.PaymentShortBankListStatusError, action: BankList.Action, ): Out<BankList.State, BankList.Action> = when (action) { is BankList.Action.LoadPaymentStatus, BankList.Action.BankInteractionFinished -> Out( BankList.State.ShortBankListStatusProgress( state.shortBankList, state.fullBankList ) ) { input { showState(this.state) } input { interactor.getPaymentStatus(paymentId) } } else -> Out.skip(state, source) } private fun handleFullBankListPaymentStatusError( state: BankList.State.PaymentFullBankListStatusError, action: BankList.Action, ): Out<BankList.State, BankList.Action> = when (action) { is BankList.Action.LoadPaymentStatus, BankList.Action.BankInteractionFinished -> Out( BankList.State.FullBankListStatusProgress( state.bankList, state.showBackNavigation ) ) { input { showState(this.state) } input { interactor.getSbpBanks(confirmationUrl) } } else -> Out.skip(state, source) } private fun handleOpenBank(state: BankList.State, deeplink: String) = Out(state) { input(source) output { showEffect(BankList.Effect.OpenBank(deeplink)) } interactor.bankWasSelected = true } private fun handleActivityNotFound(throwable: Throwable, state: BankList.State) = Out(BankList.State.ActivityNotFoundError(throwable, state)) { input { showState(this.state) } } private fun handleActivityNotFoundStatusError( state: BankList.State.ActivityNotFoundError, action: BankList.Action, ): Out<BankList.State, BankList.Action> = when (action) { is BankList.Action.BackToBankList -> Out(state.previosListState) { input { showState(this.state) } } is BankList.Action.BankInteractionFinished -> Out(state) { input { showState(this.state) } } else -> Out.skip(state, source) } }
0
Kotlin
0
0
9e7a83335afeea2f14bc3c5a79b09d682a27f389
11,714
yookassa-android-sdk
MIT License
app/src/main/java/org/simple/clinic/home/overdue/OverdueUiRenderer.kt
simpledotorg
132,515,649
false
null
package org.simple.clinic.home.overdue import org.simple.clinic.mobius.ViewRenderer import java.util.UUID class OverdueUiRenderer( private val ui: OverdueUi, private val isOverdueSectionsFeatureEnabled: Boolean ) : ViewRenderer<OverdueModel> { override fun render(model: OverdueModel) { if (isOverdueSectionsFeatureEnabled) { loadOverdueSections(model) } } private fun loadOverdueSections(model: OverdueModel) { if (model.hasLoadedOverdueAppointments) { ui.showOverdueAppointments( model.overdueAppointmentSections!!, model.selectedOverdueAppointments, model.overdueListSectionStates ) ui.showOverdueCount(model.overdueCount) ui.hideProgress() renderOverdueListLoadedViews(model) renderOverdueListSelectedCount(model.selectedOverdueAppointments) } else { renderOverdueListLoadingViews() } } private fun renderOverdueListSelectedCount(selectedOverdueAppointments: Set<UUID>) { if (selectedOverdueAppointments.isNotEmpty()) { ui.showSelectedOverdueAppointmentCount(selectedOverdueAppointments.size) } else { ui.hideSelectedOverdueAppointmentCount() } } private fun renderOverdueListLoadingViews() { ui.showProgress() ui.hideOverdueRecyclerView() ui.hideNoOverduePatientsView() } private fun renderOverdueListLoadedViews(model: OverdueModel) { if (model.isOverdueAppointmentSectionsListEmpty) { ui.showNoOverduePatientsView() ui.hideOverdueRecyclerView() } else { ui.hideNoOverduePatientsView() ui.showOverdueRecyclerView() } } }
4
Kotlin
70
216
bd39df23dd07d9b9fb976f38be828f181f96817e
1,632
simple-android
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/wafv2/CfnLoggingConfigurationMatchPatternPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.wafv2 import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import io.cloudshiftdev.awscdkdsl.common.MapBuilder import kotlin.Any import kotlin.String import kotlin.Unit import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.services.wafv2.CfnLoggingConfiguration /** * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.wafv2.*; * Object all; * MatchPatternProperty matchPatternProperty = MatchPatternProperty.builder() * .all(all) * .includedPaths(List.of("includedPaths")) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafv2-loggingconfiguration-matchpattern.html) */ @CdkDslMarker public class CfnLoggingConfigurationMatchPatternPropertyDsl { private val cdkBuilder: CfnLoggingConfiguration.MatchPatternProperty.Builder = CfnLoggingConfiguration.MatchPatternProperty.builder() private val _includedPaths: MutableList<String> = mutableListOf() /** @param all the value to be set. */ public fun all(all: MapBuilder.() -> Unit = {}) { val builder = MapBuilder() builder.apply(all) cdkBuilder.all(builder.map) } /** @param all the value to be set. */ public fun all(all: Any) { cdkBuilder.all(all) } /** @param includedPaths the value to be set. */ public fun includedPaths(vararg includedPaths: String) { _includedPaths.addAll(listOf(*includedPaths)) } /** @param includedPaths the value to be set. */ public fun includedPaths(includedPaths: Collection<String>) { _includedPaths.addAll(includedPaths) } public fun build(): CfnLoggingConfiguration.MatchPatternProperty { if (_includedPaths.isNotEmpty()) cdkBuilder.includedPaths(_includedPaths) return cdkBuilder.build() } }
0
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
2,241
awscdk-dsl-kotlin
Apache License 2.0
kompass-android/src/main/java/io/sellmair/kompass/android/fragment/dsl/FragmentTransitionBuilder.kt
sellmair
113,365,232
false
null
package io.sellmair.kompass.android.fragment.dsl import androidx.fragment.app.Fragment import io.sellmair.kompass.android.fragment.FragmentTransition import io.sellmair.kompass.android.fragment.GenericFragmentTransition import io.sellmair.kompass.android.fragment.internal.EmptyFragmentTransition import io.sellmair.kompass.android.fragment.internal.erased import io.sellmair.kompass.android.fragment.internal.reified import io.sellmair.kompass.android.fragment.plus import io.sellmair.kompass.core.Route @FragmentRouterDsl class FragmentTransitionBuilder { private var transition: FragmentTransition = EmptyFragmentTransition @FragmentRouterDsl fun register(transition: FragmentTransition) { this.transition += transition } @JvmName("registerGeneric") @FragmentRouterDsl inline fun <reified ExitFragment : Fragment, reified ExitRoute : Route, reified EnterFragment : Fragment, reified EnterRoute : Route> register( transition: GenericFragmentTransition<ExitFragment, ExitRoute, EnterFragment, EnterRoute> ) = register(transition.reified().erased()) internal fun build(): FragmentTransition { return transition } }
9
Kotlin
12
345
0f46ef4d70a686ac231ef320844af7389f1cd0b1
1,197
kompass
MIT License
Framework/src/main/java/com/bihe0832/android/framework/router/RouterAction.kt
AndroidAppFactory
222,415,705
false
null
package com.bihe0832.android.framework.router import android.app.Activity import android.content.Intent import com.bihe0832.android.framework.R import com.bihe0832.android.framework.ZixieContext import com.bihe0832.android.lib.log.ZLog import com.bihe0832.android.lib.router.Routers /** * Created by zixie on 2017/6/27. * */ object RouterAction { val SCHEME by lazy { ZixieContext.applicationContext?.getString(R.string.router_schema) ?: "zixie" } /** * 通过传入path和参数,获取最终完整的路由链接,调用示例 * * RouterHelper.getFinalURL("zixie", RouterConstants.MODULE_NAME_TEST,mutableMapOf( * RouterConstants.INTENT_EXTRA_KEY_TEST_ITEM_TAB to 1 * )) * * */ fun getFinalURL(schema: String, path: String, para: Map<String, String>?): String { var url = "${schema}://$path" para?.apply { if (this.isNotEmpty()) { url = "$url?" for ((key, value) in para) { url = "$url$key=$value&" } } } ZLog.d("Router:$url") return url } fun getFinalURL(pathHost: String, para: Map<String, String>?): String { return getFinalURL(SCHEME, pathHost, para) } /** * 通过传入path和参数,获取最终完整的路由链接,调用示例 * * RouterHelper.getFinalURL("zixie", RouterConstants.MODULE_NAME_TEST) * * return zixie://test * */ fun getFinalURL(schema: String, path: String): String { return "${schema}://$path" } fun getFinalURL(pathHost: String): String { return getFinalURL(SCHEME, pathHost) } fun open(schema: String, path: String) { Routers.open(ZixieContext.applicationContext, "${schema}://$path", "", Intent.FLAG_ACTIVITY_SINGLE_TOP) } fun open(schema: String, path: String, para: Map<String, String>?) { Routers.open(ZixieContext.applicationContext, getFinalURL(schema, path, para), "", Intent.FLAG_ACTIVITY_SINGLE_TOP) } fun open(schema: String, path: String, para: Map<String, String>?,flag: Int) { Routers.open(ZixieContext.applicationContext, getFinalURL(schema, path, para), "", flag) } fun openFinalURL(path: String) { openFinalURL(path, Intent.FLAG_ACTIVITY_SINGLE_TOP) } fun openFinalURL(path: String, startFlag: Int) { Routers.open(ZixieContext.applicationContext, path, "", startFlag) } fun openForResult(schema: String, activity: Activity, path: String, requestCode: Int) { Routers.openForResult(activity, getFinalURL(schema, path), "", requestCode, Intent.FLAG_ACTIVITY_SINGLE_TOP) } fun openForResult(schema: String, activity: Activity, path: String, para: Map<String, String>?, requestCode: Int) { Routers.openForResult(activity, getFinalURL(schema, path, para), "", requestCode, Intent.FLAG_ACTIVITY_SINGLE_TOP) } fun openForResult(activity: Activity, url: String, requestCode: Int) { Routers.openForResult(activity, url, "", requestCode, Intent.FLAG_ACTIVITY_SINGLE_TOP) } fun openPageByRouter(pathHost: String, para: Map<String, String>?) { open(SCHEME, pathHost, para) } fun openPageByRouter(pathHost: String, para: Map<String, String>?, flag: Int) { open(SCHEME, pathHost, para, flag) } fun openPageByRouter(pathHost: String) { open(SCHEME, pathHost) } }
0
null
21
72
e11cbca06d092a3bdd5a58dd4a5260b1f4a208d8
3,394
AndroidAppFactory
MIT License