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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
libnavigation-router/src/test/java/com/mapbox/navigation/route/offboard/router/MapboxDirectionsUtilsTest.kt | engelzero | 371,880,512 | true | {"Kotlin": 3077882, "Java": 96097, "Python": 11740, "Makefile": 6255, "Shell": 1686} | package com.mapbox.navigation.route.offboard.router
import com.mapbox.api.directions.v5.MapboxDirections
import com.mapbox.api.directions.v5.models.RouteOptions
import com.mapbox.geojson.Point
import com.mapbox.navigation.base.extensions.applyDefaultNavigationOptions
import io.mockk.mockk
import io.mockk.verify
import org.junit.Test
class MapboxDirectionsUtilsTest {
private val mapboxDirectionsBuilder: MapboxDirections.Builder = mockk(relaxed = true)
@Test
fun `should create mapbox directions from options`() {
val routeOptions = RouteOptions.builder()
.accessToken("test_access_token")
.coordinates(
listOf(
Point.fromLngLat(-121.470162, 38.563121),
Point.fromLngLat(-121.483304, 38.583313)
)
)
.applyDefaultNavigationOptions()
.build()
mapboxDirectionsBuilder.routeOptions(routeOptions, refreshEnabled = true)
verify { mapboxDirectionsBuilder.baseUrl(routeOptions.baseUrl()) }
verify { mapboxDirectionsBuilder.user(routeOptions.user()) }
verify { mapboxDirectionsBuilder.profile(routeOptions.profile()) }
}
}
| 0 | null | 0 | 0 | a29fc2e301880748ab67b9d1a90c61532dce975d | 1,210 | mapbox-navigation-android | Apache License 2.0 |
beckon-mesh/src/main/java/com/technocreatives/beckon/mesh/BeckonMeshClient.kt | technocreatives | 364,517,134 | false | null | package com.technocreatives.beckon.mesh
import android.content.Context
import androidx.core.content.edit
import arrow.core.Either
import arrow.core.computations.either
import arrow.core.right
import arrow.core.rightIfNotNull
import com.technocreatives.beckon.BeckonClient
import com.technocreatives.beckon.mesh.data.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.*
class BeckonMeshClient(
private val context: Context,
private val beckonClient: BeckonClient,
private val repository: MeshRepository,
private val config: BeckonMeshClientConfig,
) {
private var currentMesh: BeckonMesh? = null
private suspend fun disconnect(): Either<MeshLoadError, Unit> {
val result = currentMesh?.let {
it.disconnect().mapLeft { BleDisconnectError(it.throwable) }.map { }
} ?: Unit.right()
currentMesh?.unregister()
currentMesh = null
return result
}
suspend fun loadCurrentMesh(): Either<MeshLoadError, BeckonMesh> = either {
disconnect().bind()
val meshOrNull = repository.currentMesh()
.mapLeft { DatabaseError(it) }
.bind()
val mesh = meshOrNull.rightIfNotNull { NoCurrentMeshFound }.bind()
val meshApi =
BeckonMeshManagerApi(context, repository)
meshApi.load(mesh.id).bind()
BeckonMesh(context, beckonClient, meshApi, config)
}
suspend fun load(): Either<MeshLoadError, BeckonMesh> = either {
disconnect().bind()
val meshApi =
BeckonMeshManagerApi(context, repository)
meshApi.load().bind()
BeckonMesh(context, beckonClient, meshApi, config)
}
suspend fun import(id: UUID): Either<MeshLoadError, BeckonMesh> = either {
disconnect().bind()
val mesh = findMeshById(id).bind()
import(mesh).bind()
}
suspend fun findMeshById(id: UUID): Either<MeshLoadError, MeshData> = either {
disconnect().bind()
val meshOrNull = repository.find(id)
.mapLeft { DatabaseError(it) }
.bind()
meshOrNull.rightIfNotNull { MeshIdNotFound(id) }.bind()
}
/**
* load current mesh or import mesh data
* */
suspend fun loadOrImport(id: UUID): Either<MeshLoadError, BeckonMesh> = either {
if (id == currentMeshID()) {
load().bind()
} else {
val mesh = findMeshById(id).bind()
import(mesh).bind().also {
setCurrentMeshId(id)
}
}
}
private suspend fun import(mesh: MeshData): Either<MeshLoadError, BeckonMesh> {
val meshApi =
BeckonMeshManagerApi(context, repository)
return meshApi.import(mesh).map { BeckonMesh(context, beckonClient, meshApi, config) }
}
suspend fun fromJson(json: String) =
withContext(Dispatchers.IO) {
MeshConfigSerializer.decode(json)
}
suspend fun toJson(meshConfig: MeshConfig) =
withContext(Dispatchers.IO) {
MeshConfigSerializer.encode(meshConfig)
}
private val sharedPreferences by lazy {
context.getSharedPreferences(
"com.technocreatives.beckon.mesh",
Context.MODE_PRIVATE
)
}
private suspend fun currentMeshID(): UUID? =
withContext(Dispatchers.IO) {
sharedPreferences.getString("mesh_uuid", null)?.let {
UUID.fromString(it)
}
}
private fun setCurrentMeshId(id: UUID) =
sharedPreferences.edit(commit = true) {
this.putString("mesh_uuid", id.toString())
}
} | 1 | Kotlin | 1 | 8 | 2e252df19c02104821c393225ee8d5abefa07b74 | 3,669 | beckon-android | Apache License 2.0 |
features/home/src/main/kotlin/id/rivaldy/feature/home/ui/home/sections/HomeSearchBar.kt | im-o | 718,908,780 | false | {"Kotlin": 156609} | package id.rivaldy.feature.home.ui.home.sections
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import id.rivaldy.core.R
import id.rivaldy.core.ui.molecules.SearchBar
import id.rivaldy.core.util.Dimens
/** Created by github.com/im-o on 11/17/2023. */
@Composable
fun HomeSearchBar(
modifier: Modifier = Modifier,
) {
Row(
modifier = modifier
.padding(horizontal = Dimens.dp16)
.fillMaxWidth(),
) {
Box(
modifier = modifier
.size(Dimens.dp40)
.shadow(elevation = Dimens.dp3, shape = CircleShape)
.background(color = Color.White, shape = CircleShape)
.clickable { },
) {
Icon(
modifier = modifier
.fillMaxSize()
.padding(Dimens.dp12),
painter = painterResource(id = R.drawable.ic_filter),
contentDescription = stringResource(R.string.close),
tint = MaterialTheme.colorScheme.primary,
)
}
Spacer(modifier = modifier.width(Dimens.dp24))
SearchBar(
hint = stringResource(R.string.search),
cornerShape = RoundedCornerShape(Dimens.dp20),
)
}
} | 0 | Kotlin | 1 | 0 | 6cc1658634eb8273d6cf6d02d37b3a9c7f33dd30 | 2,155 | android-compose-haidoc-ui | MIT License |
app/src/main/java/com/donfreddy/troona/domain/model/Song.kt | donfreddy | 736,820,576 | false | {"Kotlin": 163323} | /*
=============
Author: Don Freddy
Github: https://github.com/donfreddy
Website: https://donfreddy.com
=============
Application: Troona - Music Player
Homepage: https://github.com/donfreddy/troona
License: https://github.com/donfreddy/troona/blob/main/LICENSE
Copyright: © 2023, Don Freddy. All rights reserved.
=============
*/
package com.donfreddy.troona.domain.model
import android.net.Uri
import kotlinx.datetime.LocalDateTime
data class Song(
val id: Long,
val title: String,
val trackNumber: Int,
val duration: Long,
val size: Int,
val year: Int?,
val albumId: Long,
val albumName: String,
val albumArtist: String?,
val artistId: Long,
val artistName: String,
val data: String?,
val mediaUri: Uri,// data
val artworkUri: Uri, // img
val folder: String,
val mineType: String?,
val composer: String?,
val dateAdded: LocalDateTime?,
val dateModified: LocalDateTime?,
) {
companion object {
val EMPTY = Song(
id = -1,
title = "",
trackNumber = -1,
duration = -1,
size = -1,
year = -1,
albumId = -1,
albumName = "",
albumArtist = "",
artistId = -1,
artistName = "",
data = "",
mediaUri = Uri.EMPTY,
artworkUri = Uri.EMPTY,
folder = "",
mineType = "",
composer = "",
dateAdded = null,
dateModified = null,
)
}
} | 0 | Kotlin | 0 | 0 | 1e59a5f24ee507f6dce0c153199d7a00d519c7d2 | 1,381 | troona | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsstafflookupservice/config/HmppsStaffLookupServiceExceptionHandler.kt | ministryofjustice | 593,643,618 | false | {"Kotlin": 55666, "Dockerfile": 1371, "PLpgSQL": 211} | package uk.gov.justice.digital.hmpps.hmppsstafflookupservice.config
import jakarta.validation.ValidationException
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.http.HttpStatus.BAD_REQUEST
import org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
import org.springframework.http.ResponseEntity
import org.springframework.security.access.AccessDeniedException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.server.MissingRequestValueException
import reactor.core.publisher.Mono
@RestControllerAdvice
class HmppsStaffLookupServiceExceptionHandler {
@ExceptionHandler(ValidationException::class)
fun handleValidationException(e: Exception): Mono<ResponseEntity<ErrorResponse>> {
log.info("Validation exception: {}", e.message)
return Mono.just(
ResponseEntity
.status(BAD_REQUEST)
.body(
ErrorResponse(
status = BAD_REQUEST,
userMessage = "Validation failure: ${e.message}",
developerMessage = e.message,
),
),
)
}
@ExceptionHandler(MissingRequestValueException::class)
fun handleMissingRequestValueException(e: Exception): Mono<ResponseEntity<ErrorResponse>> {
log.info("Missing Request Value exception: {}", e.message)
return Mono.just(
ResponseEntity
.status(BAD_REQUEST)
.body(
ErrorResponse(
status = BAD_REQUEST,
userMessage = "Missing Request Value failure: ${e.message}",
developerMessage = e.message,
),
),
)
}
@ExceptionHandler(java.lang.Exception::class)
fun handleException(e: java.lang.Exception): Mono<ResponseEntity<ErrorResponse>> {
log.error("Unexpected exception", e)
return Mono.just(
ResponseEntity
.status(INTERNAL_SERVER_ERROR)
.body(
ErrorResponse(
status = INTERNAL_SERVER_ERROR,
userMessage = "Unexpected error: ${e.message}",
developerMessage = e.message,
),
),
)
}
@ExceptionHandler(AccessDeniedException::class)
fun handleAccessDeniedException(e: AccessDeniedException): ResponseEntity<ErrorResponse?>? {
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body(
ErrorResponse(
status = HttpStatus.FORBIDDEN,
userMessage = "Access is denied",
developerMessage = e.message,
),
)
}
companion object {
private val log = LoggerFactory.getLogger(this::class.java)
}
}
data class ErrorResponse(
val status: Int,
val errorCode: Int? = null,
val userMessage: String? = null,
val developerMessage: String? = null,
val moreInfo: String? = null,
) {
constructor(
status: HttpStatus,
errorCode: Int? = null,
userMessage: String? = null,
developerMessage: String? = null,
moreInfo: String? = null,
) :
this(status.value(), errorCode, userMessage, developerMessage, moreInfo)
}
| 3 | Kotlin | 0 | 0 | 89cad3abbbd8d4220b635217de9391045af26ec2 | 3,106 | hmpps-staff-lookup-service | MIT License |
app/src/main/java/com/lx/todaysbing/data/bingapis/Images.kt | liuxue0905 | 348,978,492 | false | null | package com.lx.todaysbing.data.bingapis
import com.google.gson.annotations.SerializedName
data class ImageAnswer(
@field:SerializedName("_type") val _type: String,
@field:SerializedName("readLink") val readLink: String,
@field:SerializedName("webSearchUrl") val webSearchUrl: String,
@field:SerializedName("totalEstimatedMatches") val totalEstimatedMatches: Int,
@field:SerializedName("images") val images: List<Image>,
)
data class Image(
@field:SerializedName("name") val name: String,
@field:SerializedName("webSearchUrl") val webSearchUrl: String,
@field:SerializedName("webSearchUrlPingSuffix") val webSearchUrlPingSuffix: String,
@field:SerializedName("thumbnailUrl") val thumbnailUrl: String,
@field:SerializedName("datePublished") val datePublished: String,
@field:SerializedName("contentUrl") val contentUrl: String,
@field:SerializedName("hostPageUrl") val hostPageUrl: String,
@field:SerializedName("hostPageUrlPingSuffix") val hostPageUrlPingSuffix: String,
@field:SerializedName("contentSize") val contentSize: Int,
@field:SerializedName("encodingFormat") val encodingFormat: String,
@field:SerializedName("hostPageDisplayUrl") val hostPageDisplayUrl: String,
@field:SerializedName("width") val width: Int,
@field:SerializedName("height") val height: Int,
@field:SerializedName("thumbnail") val thumbnail: Thumbnail,
@field:SerializedName("imageInsightsToken") val imageInsightsToken: String,
@field:SerializedName("imageId") val imageId: String,
@field:SerializedName("insightsSourcesSummary") val insightsSourcesSummary: InsightsSourcesSummary,
)
data class Thumbnail(
@field:SerializedName("width") val width: Int,
@field:SerializedName("height") val height: Int,
) {
companion object {
@JvmStatic
fun dimensionRatio(thumbnail: Thumbnail): String {
return "${thumbnail.width}:${thumbnail.height}"
}
}
}
data class InsightsSourcesSummary(
@field:SerializedName("shoppingSourcesCount") val shoppingSourcesCount: Int,
@field:SerializedName("recipeSourcesCount") val recipeSourcesCount: Int,
) | 0 | Kotlin | 0 | 0 | 6eadfb2af127581510ee02f5484aa96924f7a845 | 2,158 | Today-s-Bing-2 | Apache License 2.0 |
server/src/main/kotlin/org/tod87et/roomkn/server/plugins/Metrics.kt | spbu-math-cs | 698,579,800 | false | {"Kotlin": 162233, "JavaScript": 143389, "CSS": 11387, "HTML": 1871, "Dockerfile": 1208, "Shell": 483} | package org.tod87et.roomkn.server.plugins
import io.ktor.server.application.Application
import io.ktor.server.application.call
import io.ktor.server.application.install
import io.ktor.server.metrics.micrometer.MicrometerMetrics
import io.ktor.server.response.respond
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import io.micrometer.core.instrument.binder.jvm.ClassLoaderMetrics
import io.micrometer.core.instrument.binder.jvm.JvmGcMetrics
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig
import io.micrometer.prometheus.PrometheusConfig
import io.micrometer.prometheus.PrometheusMeterRegistry
fun Application.configureMetrics() {
val appMicrometerRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT)
install(MicrometerMetrics) {
distributionStatisticConfig = DistributionStatisticConfig.Builder()
.percentilesHistogram(true)
.build()
meterBinders = listOf(
JvmMemoryMetrics(),
JvmGcMetrics(),
ClassLoaderMetrics(),
)
registry = appMicrometerRegistry
}
routing {
get("/metrics") {
call.respond(appMicrometerRegistry.scrape())
}
}
}
| 55 | Kotlin | 0 | 3 | f323ac4c4072414d15d5b65547fd84ed576d840f | 1,303 | roomkn | Apache License 2.0 |
app/src/main/java/eu/kanade/presentation/theme/colorscheme/TealTurqoiseColorScheme.kt | mihonapp | 743,704,912 | false | {"Kotlin": 2940843} | package eu.kanade.presentation.theme.colorscheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.ui.graphics.Color
/**
* Colors for Teal Turqoise theme
*/
internal object TealTurqoiseColorScheme : BaseColorScheme() {
override val darkScheme = darkColorScheme(
primary = Color(0xFF40E0D0),
onPrimary = Color(0xFF000000),
primaryContainer = Color(0xFF40E0D0),
onPrimaryContainer = Color(0xFF000000),
inversePrimary = Color(0xFF008080),
secondary = Color(0xFF40E0D0), // Unread badge
onSecondary = Color(0xFF000000), // Unread badge text
secondaryContainer = Color(0xFF18544E), // Navigation bar selector pill & progress indicator (remaining)
onSecondaryContainer = Color(0xFF40E0D0), // Navigation bar selector icon
tertiary = Color(0xFFBF1F2F), // Downloaded badge
onTertiary = Color(0xFFFFFFFF), // Downloaded badge text
tertiaryContainer = Color(0xFF200508),
onTertiaryContainer = Color(0xFFBF1F2F),
background = Color(0xFF202125),
onBackground = Color(0xFFDFDEDA),
surface = Color(0xFF202125),
onSurface = Color(0xFFDFDEDA),
surfaceVariant = Color(0xFF233133), // Navigation bar background (ThemePrefWidget)
onSurfaceVariant = Color(0xFFDFDEDA),
surfaceTint = Color(0xFF40E0D0),
inverseSurface = Color(0xFFDFDEDA),
inverseOnSurface = Color(0xFF202125),
outline = Color(0xFF899391),
surfaceContainerLowest = Color(0xFF202C2E),
surfaceContainerLow = Color(0xFF222F31),
surfaceContainer = Color(0xFF233133), // Navigation bar background
surfaceContainerHigh = Color(0xFF28383A),
surfaceContainerHighest = Color(0xFF2F4244),
)
override val lightScheme = lightColorScheme(
primary = Color(0xFF008080),
onPrimary = Color(0xFFFFFFFF),
primaryContainer = Color(0xFF008080),
onPrimaryContainer = Color(0xFFFFFFFF),
inversePrimary = Color(0xFF40E0D0),
secondary = Color(0xFF008080), // Unread badge text
onSecondary = Color(0xFFFFFFFF), // Unread badge text
secondaryContainer = Color(0xFFCFE5E4), // Navigation bar selector pill & progress indicator (remaining)
onSecondaryContainer = Color(0xFF008080), // Navigation bar selector icon
tertiary = Color(0xFFFF7F7F), // Downloaded badge
onTertiary = Color(0xFF000000), // Downloaded badge text
tertiaryContainer = Color(0xFF2A1616),
onTertiaryContainer = Color(0xFFFF7F7F),
background = Color(0xFFFAFAFA),
onBackground = Color(0xFF050505),
surface = Color(0xFFFAFAFA),
onSurface = Color(0xFF050505),
surfaceVariant = Color(0xFFEBF3F1), // Navigation bar background (ThemePrefWidget)
onSurfaceVariant = Color(0xFF050505),
surfaceTint = Color(0xFFBFDFDF),
inverseSurface = Color(0xFF050505),
inverseOnSurface = Color(0xFFFAFAFA),
outline = Color(0xFF6F7977),
surfaceContainerLowest = Color(0xFFE1E9E7),
surfaceContainerLow = Color(0xFFE6EEEC),
surfaceContainer = Color(0xFFEBF3F1), // Navigation bar background
surfaceContainerHigh = Color(0xFFF0F8F6),
surfaceContainerHighest = Color(0xFFF7FFFD),
)
}
| 280 | Kotlin | 447 | 9,867 | f3a2f566c8a09ab862758ae69b43da2a2cd8f1db | 3,389 | mihon | Apache License 2.0 |
neo4k-reporting/src/main/kotlin/me/roybailey/neo4k/reporting/ReportRunner.kt | roybailey | 189,282,455 | false | null | package me.roybailey.neo4k.reporting
import com.google.common.net.MediaType
import me.roybailey.neo4k.api.Neo4jService
import me.roybailey.neo4k.dsl.QueryStatement
import mu.KotlinLogging
import java.io.ByteArrayOutputStream
import java.io.OutputStream
data class ReportColumn(
val name: String,
val type: String = String::class.java.simpleName,
val width: Int = 4,
val format: String = ""
)
open class ReportDefinition(
val reportName: String,
val query: QueryStatement,
val columns: List<ReportColumn> = emptyList()
)
data class ReportOutput(
val contentType: String = MediaType.CSV_UTF_8.toString(),
val outputName: String,
val outputStream: OutputStream = ByteArrayOutputStream()
)
interface ReportRunner {
fun runReport(report: ReportDefinition, visitor: ReportVisitor)
}
/**
*
*/
class Neo4kReportRunner(val neo4jService: Neo4jService) : ReportRunner {
private val logger = KotlinLogging.logger {}
fun getSafeValue(value: Any?): Any = when (value) {
null -> ""
is Number -> value
else -> value.toString()
}
override fun runReport(report: ReportDefinition, visitor: ReportVisitor) {
//val visitor = CompositeReportVisitor(this::processNeo4jColumns, suppliedVisitor)::reportVisit
var ctx = ReportContext(
evt = ReportEvent.START_REPORT,
name = report.reportName,
meta = report.columns,
row = -1, column = -1)
ctx = visitor(ctx)
neo4jService.query(report.query.query) { record ->
ctx = visitor(ctx.copy(evt = ReportEvent.START_ROW, row = ctx.row + 1, column = -1))
// first row will generate default column meta data if it doesn't exist in definition
if (ctx.meta.isEmpty()) {
val columnNames = record.keys().map { ReportColumn(it) }
ctx = ctx.copy(meta = columnNames)
}
ctx.meta.forEachIndexed { cdx, column ->
val name = column.name
var value = record[name]
if (value == null) {
logger.warn { "ReportRunner couldn't find value for $name in row ${ctx.row} " }
}
ctx = ctx.copy(evt = ReportEvent.DATA)
ctx = visitor(ctx.copy(column = ctx.column + 1, name = name, value = getSafeValue(value)))
}
ctx = visitor(ctx.copy(evt = ReportEvent.END_ROW))
}
ctx = visitor(ctx.copy(evt = ReportEvent.END_REPORT, name = report.reportName))
}
}
| 10 | Kotlin | 0 | 0 | 1749bafb650a95fd2668dc05cea8ecb1aefbda35 | 2,630 | neo4k | Apache License 2.0 |
buisness/account/src/main/kotlin/net/sergey/kosov/account/domains/User.kt | Sergey34 | 104,038,580 | false | {"JavaScript": 193369, "Kotlin": 169128, "HTML": 59327, "Groovy": 48321, "CSS": 4132, "Shell": 2658, "Dockerfile": 2029} | package net.sergey.kosov.account.domains
import com.fasterxml.jackson.annotation.JsonFormat
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import net.sergey.kosov.common.annotations.NoArgs
import net.sergey.kosov.common.serializers.ObjectIdSerializer
import net.sergey.kosov.common.utils.DateTimeUtils.Companion.dateUtc
import org.bson.types.ObjectId
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.index.Indexed
import org.springframework.data.mongodb.core.mapping.Document
import java.time.LocalDate
@NoArgs
@Document(collection = "users")
data class User(@Id @JsonSerialize(using = ObjectIdSerializer::class) var id: ObjectId = ObjectId(),
var fullName: String,
var firstName: String,
var lastName: String,
@Indexed(unique = true, name = "email_index")
var email: String,
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
var birthDay: LocalDate = dateUtc(),
var country: String = "N/a",
var gender: Gender,
var account: Account,
var needUpdatePassword: Boolean = true) {
@NoArgs
data class User(var username: String,
var password: String)
}
| 4 | JavaScript | 0 | 5 | ac24b0b643ea910260ff408c2277edf0cccbcc60 | 1,330 | platform-sales | Apache License 2.0 |
Alter/alter-core/src/main/java/com/pixocial/alter/core/lifecycle/dispatcher/IDispatcher.kt | Pixocial | 506,082,070 | false | {"Kotlin": 125556, "Groovy": 15216, "Java": 1679} | package com.pixocial.alter.core.lifecycle.dispatcher
interface IDispatcher {
fun callCreateOnMainThread(): Boolean
fun toWait()
fun toNotify()
} | 0 | Kotlin | 0 | 5 | c1ea25c2cf9bad17224546cb1925b5aecd7782e4 | 161 | Alter-Android | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/ui/welcome/WelcomeActivity.kt | JMoicano | 347,425,383 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.welcome
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.ui.ExperimentalComposeUiApi
import com.example.androiddevchallenge.ui.login.LoginActivity
import com.example.androiddevchallenge.ui.theme.MyTheme
@ExperimentalComposeUiApi
class WelcomeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.apply {
clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
statusBarColor = Color.TRANSPARENT
}
setContent {
MyTheme {
Welcome() {
startActivity(Intent(applicationContext, LoginActivity::class.java))
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 9568e2d7225adf8a387de6e127df46effd6a76a7 | 1,776 | AndroidDevChallengeWeek3 | Apache License 2.0 |
app/src/main/kotlin/dev/mbo/dbq/db/model/types/retrystrategy/RetryDelayProcessor.kt | mbogner | 487,622,806 | false | {"Kotlin": 77379, "PLpgSQL": 4569} | /*
* Copyright 2022 mbo.dev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.mbo.dbq.db.model.types.retrystrategy
import dev.mbo.dbq.db.model.types.QueueMeta
import dev.mbo.dbq.db.model.types.RetryDelayStrategy
import dev.mbo.dbq.db.model.types.retrystrategy.impl.RetryDelayLinear
import dev.mbo.dbq.db.model.types.retrystrategy.impl.RetryDelayNone
import dev.mbo.dbq.db.model.types.retrystrategy.impl.RetryDelaySquare
import java.time.Instant
class RetryDelayProcessor {
companion object : RetryDelay {
private val map = retryDelayStrategiesMap()
override fun update(queueMeta: QueueMeta, exc: Exception?, overrideNextAfter: Instant?): QueueMeta {
val strategy = map[queueMeta.retryDelayStrategy]
?: throw IllegalStateException("no implementation for strategy ${queueMeta.retryDelayStrategy}")
strategy.update(queueMeta, exc, overrideNextAfter)
return queueMeta
}
private fun retryDelayStrategiesMap(): Map<RetryDelayStrategy, RetryDelay> {
val strategies = listOf(
RetryDelayNone(),
RetryDelayLinear(),
RetryDelaySquare(),
)
val response = HashMap<RetryDelayStrategy, RetryDelay>(strategies.size)
for (strategy in strategies) {
response[strategy.supportedStrategy()] = strategy
}
return response
}
override fun supportedStrategy(): RetryDelayStrategy {
throw IllegalAccessError()
}
}
} | 0 | Kotlin | 0 | 0 | d89d18513f04f69a61e2a955db496548349e19a1 | 2,088 | dbq | Apache License 2.0 |
src/day24/Day24.kt | gautemo | 317,316,447 | false | null | package day24
import shared.getLines
import kotlin.math.abs
val commands = listOf("e", "se", "sw", "w", "nw", "ne")
fun turnedTiles(input: List<String>, days: Int = 0): Int{
val tiles = mutableMapOf<PointDouble, Boolean>()
for(path in input){
var x = 0.0
var y = 0.0
var pathLeft = path
while(pathLeft.isNotEmpty()){
for(c in commands){
val removed = pathLeft.removePrefix(c)
if(removed != pathLeft){
pathLeft = removed
when(c){
"e" -> x++
"se" -> x += 0.5.also { y += 1 }
"sw" -> x -= 0.5.also { y += 1 }
"w" -> x--
"nw" -> x -= 0.5.also { y -= 1 }
"ne" -> x += 0.5.also { y -= 1 }
}
break
}
}
}
tiles[(PointDouble(x, y))] = !(tiles[(PointDouble(x, y))] ?: false)
}
var mapForDay = TileMap(tiles)
repeat(days){
mapForDay = TileMap(mapForDay.blackTilesNextDay())
}
return mapForDay.tiles.count { it.value }
}
data class PointDouble(val x: Double, val y: Double)
class TileMap(val tiles: MutableMap<PointDouble, Boolean>){
private fun countAdjacent(x: Double, y: Double): Int{
return tiles.count { (point, black) ->
!(point.x == x && point.y == y) &&
abs(point.x - x) <= 1 &&
abs(point.y - y) <= 1 &&
black
}
}
private fun pointsToCheck(): List<PointDouble>{
val points = mutableListOf<PointDouble>()
var y = tiles.minBy { it.key.y }!!.key.y - 1
while(y <= tiles.maxBy { it.key.y }!!.key.y + 1){
var x = (tiles.minBy { it.key.x }!!.key.x - 1).toInt().toDouble()
if(y % 2 != 0.0){
x += 0.5
}
while(x <= tiles.maxBy { it.key.x }!!.key.x + 1){
points.add(PointDouble(x, y))
x++
}
y++
}
return points
}
fun blackTilesNextDay(): MutableMap<PointDouble, Boolean>{
val copy = tiles.toMutableMap()
val check = pointsToCheck()
for(p in check){
val adjacents = countAdjacent(p.x, p.y)
if(tiles[p] == true && (adjacents == 0 || adjacents > 2)){
copy[p] = false
}
if(tiles[p] != true && adjacents == 2){
copy[p] = true
}
}
return copy
}
}
fun main(){
val input = getLines("day24.txt")
val blackTiles = turnedTiles(input)
println(blackTiles)
val blackTiles100Days = turnedTiles(input, 100)
println(blackTiles100Days)
} | 0 | Kotlin | 0 | 0 | ce25b091366574a130fa3d6abd3e538a414cdc3b | 2,795 | AdventOfCode2020 | MIT License |
src/main/kotlin/com/api/project/repository/caddy/CaddyMongo.kt | antoinebou12 | 448,323,978 | false | {"Kotlin": 68077, "Java": 214, "Dockerfile": 114} | package com.api.project.repository.caddy
class CaddyMongo {
} | 1 | Kotlin | 0 | 0 | 3be3bbc6d828edf840ab6edaffee661db671d7db | 62 | SpringBootFilesUploader | MIT License |
app/src/main/java/com/example/androiddevchallenge/data/LocalDataRepository.kt | rohitjakhar | 343,223,902 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.data
import com.example.androiddevchallenge.data.FakeData.boomer
import com.example.androiddevchallenge.data.FakeData.bronson
import com.example.androiddevchallenge.data.FakeData.buzz
import com.example.androiddevchallenge.data.FakeData.dante
import com.example.androiddevchallenge.data.FakeData.kiki
import com.example.androiddevchallenge.data.FakeData.leopold
import com.example.androiddevchallenge.data.FakeData.melva
import com.example.androiddevchallenge.data.FakeData.mona
import com.example.androiddevchallenge.data.FakeData.parvana
import com.example.androiddevchallenge.data.FakeData.pebbles
import com.example.androiddevchallenge.data.FakeData.poohBear
import com.example.androiddevchallenge.data.FakeData.remy
import com.example.androiddevchallenge.data.FakeData.rocky
import com.example.androiddevchallenge.model.Puppy
class LocalDataRepository {
private val listOfPuppy = listOf(
boomer,
bronson,
dante,
melva,
kiki,
pebbles,
mona,
buzz,
parvana,
leopold,
rocky,
poohBear,
remy
)
fun getAllPuppy() = listOfPuppy
fun getPuppyById(id: String): Puppy? {
return listOfPuppy.find { it.id == id }
}
}
| 0 | Kotlin | 0 | 4 | 4ae965c3682f9201ff5c4ef9e766f6bed624a7ef | 1,901 | PuppyAdoption | Apache License 2.0 |
src/main/kotlin/no/nav/aap/rest/tokenx/TokenXJacksonModule.kt | navikt | 432,668,965 | false | {"Kotlin": 45041} | package no.nav.aap.rest.tokenx
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.core.util.VersionUtil.versionFor
import com.fasterxml.jackson.databind.module.SimpleModule
import no.nav.security.token.support.client.core.oauth2.OAuth2AccessTokenResponse
class TokenXJacksonModule : SimpleModule() {
override fun setupModule(ctx : SetupContext?) =
SimpleModule(versionFor(TokenXJacksonModule::class.java))
.setMixInAnnotation(OAuth2AccessTokenResponse::class.java, IgnoreUnknownMixin::class.java)
.setupModule(ctx)
@JsonIgnoreProperties(ignoreUnknown = true)
private interface IgnoreUnknownMixin
} | 1 | Kotlin | 0 | 2 | 99bd63bb9dceb06ab737d41d3ce916faa05262a7 | 684 | aap-domain | MIT License |
src/jsMain/kotlin/sh/christian/website/sheet/ResumeApp.kt | christiandeange | 15,754,740 | false | null | package sh.christian.website.sheet
import org.jetbrains.compose.web.css.CSSMediaQuery.MediaType
import org.jetbrains.compose.web.css.CSSMediaQuery.MediaType.Enum.Print
import org.jetbrains.compose.web.css.CSSSizeValue
import org.jetbrains.compose.web.css.CSSUnit
import org.jetbrains.compose.web.css.CSSUnitValueTyped
import org.jetbrains.compose.web.css.Color
import org.jetbrains.compose.web.css.DisplayStyle.Companion.None
import org.jetbrains.compose.web.css.LineStyle.Companion.Solid
import org.jetbrains.compose.web.css.Position
import org.jetbrains.compose.web.css.StyleSheet
import org.jetbrains.compose.web.css.backgroundColor
import org.jetbrains.compose.web.css.border
import org.jetbrains.compose.web.css.borderRadius
import org.jetbrains.compose.web.css.display
import org.jetbrains.compose.web.css.height
import org.jetbrains.compose.web.css.keywords.auto
import org.jetbrains.compose.web.css.maxHeight
import org.jetbrains.compose.web.css.maxWidth
import org.jetbrains.compose.web.css.media
import org.jetbrains.compose.web.css.mediaMinWidth
import org.jetbrains.compose.web.css.minus
import org.jetbrains.compose.web.css.overflow
import org.jetbrains.compose.web.css.padding
import org.jetbrains.compose.web.css.percent
import org.jetbrains.compose.web.css.plus
import org.jetbrains.compose.web.css.position
import org.jetbrains.compose.web.css.px
import org.jetbrains.compose.web.css.top
import org.jetbrains.compose.web.css.width
object ResumeApp : StyleSheet() {
val myResume by style {
width(100.percent - 64.px)
height(100.percent)
padding(0.px, 32.px)
property("margin", "${0.px} $auto")
media(mediaMinWidth((8.5.inches) + 64.px)) {
self style {
width(8.5.inches)
}
}
media(MediaType(Print)) {
self style {
width(inherit)
maxWidth("$inherit")
maxHeight("$inherit")
property("margin", "${0.px} $auto")
overflow("$visible")
position(Position.Absolute)
top(0.px)
}
}
}
val icons by style {
padding(32.px)
position(Position.Fixed)
media(MediaType(Print)) {
self style {
display(None)
}
}
}
val iconButton by style {
width(24.px)
height(24.px)
padding(8.px)
borderRadius(50.percent)
border(1.px, Solid, Color.black)
(self + hover) style {
backgroundColor(Color("#EBEBEB"))
}
(self + active) style {
backgroundColor(Color.darkgray)
}
}
}
private val Number.inches
get(): CSSSizeValue<CSSUnit.px> = CSSUnitValueTyped(96 * this.toFloat(), CSSUnit.px)
| 0 | Kotlin | 0 | 0 | 4820bfaa6355fdd64ed7da35a2eb835527184f55 | 2,593 | Website | The Unlicense |
fluentui_core/src/main/java/com/microsoft/fluentui/theme/token/controlTokens/CircularProgressIndicatorTokens.kt | microsoft | 257,221,908 | false | {"Kotlin": 3021107, "Shell": 8996} | package com.microsoft.fluentui.theme.token.controlTokens
import android.os.Parcelable
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.microsoft.fluentui.theme.FluentTheme
import com.microsoft.fluentui.theme.token.*
import kotlinx.parcelize.Parcelize
enum class CircularProgressIndicatorSize {
XXSmall,
XSmall,
Medium,
Large,
XLarge
}
open class CircularProgressIndicatorInfo(
val circularProgressIndicatorSize: CircularProgressIndicatorSize = CircularProgressIndicatorSize.XSmall,
val style: FluentStyle = FluentStyle.Neutral
) : ControlInfo
@Parcelize
open class CircularProgressIndicatorTokens : IControlToken, Parcelable {
@Composable
open fun size(circularProgressIndicatorInfo: CircularProgressIndicatorInfo): Dp {
return when (circularProgressIndicatorInfo.circularProgressIndicatorSize) {
CircularProgressIndicatorSize.XXSmall -> FluentGlobalTokens.IconSizeTokens.IconSize120.value
CircularProgressIndicatorSize.XSmall -> FluentGlobalTokens.IconSizeTokens.IconSize160.value
CircularProgressIndicatorSize.Medium -> FluentGlobalTokens.IconSizeTokens.IconSize240.value
CircularProgressIndicatorSize.Large -> 32.dp
CircularProgressIndicatorSize.XLarge -> FluentGlobalTokens.IconSizeTokens.IconSize400.value
}
}
@Composable
open fun strokeWidth(circularProgressIndicatorInfo: CircularProgressIndicatorInfo): Dp {
return when (circularProgressIndicatorInfo.circularProgressIndicatorSize) {
CircularProgressIndicatorSize.XXSmall -> FluentGlobalTokens.StrokeWidthTokens.StrokeWidth10
.value
CircularProgressIndicatorSize.XSmall -> FluentGlobalTokens.StrokeWidthTokens.StrokeWidth10
.value
CircularProgressIndicatorSize.Medium -> FluentGlobalTokens.StrokeWidthTokens.StrokeWidth20
.value
CircularProgressIndicatorSize.Large -> FluentGlobalTokens.StrokeWidthTokens.StrokeWidth30.value
CircularProgressIndicatorSize.XLarge -> FluentGlobalTokens.StrokeWidthTokens.StrokeWidth40
.value
}
}
@Composable
open fun brush(circularProgressIndicatorInfo: CircularProgressIndicatorInfo): Brush {
return SolidColor(
if (circularProgressIndicatorInfo.style == FluentStyle.Neutral) {
FluentColor(
light = FluentGlobalTokens.NeutralColorTokens.Grey56.value,
dark = FluentGlobalTokens.NeutralColorTokens.Grey72.value
).value(
themeMode = FluentTheme.themeMode
)
} else {
FluentTheme.aliasTokens.brandBackgroundColor[FluentAliasTokens.BrandBackgroundColorTokens.BrandBackground1].value(
themeMode = FluentTheme.themeMode
)
}
)
}
} | 25 | Kotlin | 103 | 574 | 851a4989a4fce5db50a1818aa4121538c1fb4ad9 | 3,074 | fluentui-android | MIT License |
simplified-books-api/src/main/java/org/nypl/simplified/books/api/Bookmark.kt | jonathangreen | 292,624,474 | true | {"Gradle": 90, "Shell": 9, "INI": 88, "Text": 2, "Ignore List": 2, "Batchfile": 1, "Markdown": 90, "EditorConfig": 1, "YAML": 1, "XML": 329, "Kotlin": 620, "Java Properties": 1, "JSON": 46, "Java": 280, "CSS": 1, "HTML": 1, "JavaScript": 2} | package org.nypl.simplified.books.api
import com.io7m.jfunctional.Some
import org.joda.time.LocalDateTime
import java.io.Serializable
import java.net.URI
import java.nio.charset.Charset
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
/**
* The saved data for a bookmark.
*
* <p>Note: The type is {@link Serializable} purely because the Android API requires this
* in order pass values of this type between activities. We make absolutely no guarantees
* that serialized values of this class will be compatible with future releases.</p>
*/
data class Bookmark(
/**
* The identifier of the book taken from the OPDS entry that provided it.
*/
val opdsId: String,
/**
* The location of the bookmark.
*/
val location: BookLocation,
/**
* The kind of bookmark.
*/
val kind: BookmarkKind,
/**
* The time the bookmark was created.
*/
val time: LocalDateTime,
/**
* The title of the chapter.
*/
val chapterTitle: String,
/**
* An estimate of the current chapter progress, in the range [0, 1]
*/
val chapterProgress: Double,
/**
* An estimate of the current book progress, in the range [0, 1]
*/
val bookProgress: Double,
/**
* The identifier of the device that created the bookmark, if one is available.
*/
val deviceID: String?,
/**
* The URI of this bookmark, if the bookmark exists on a remote server.
*/
val uri: URI?
) : Serializable {
/**
* The ID of the book to which the bookmark belongs.
*/
val book: BookID = BookIDs.newFromText(this.opdsId)
/**
* The unique ID of the bookmark.
*/
val bookmarkId: BookmarkID = createBookmarkID(this.book, this.location, this.kind)
/**
* Convenience function to convert a bookmark to a last-read-location kind.
*/
fun toLastReadLocation(): Bookmark {
return this.copy(kind = BookmarkKind.ReaderBookmarkLastReadLocation)
}
/**
* Convenience function to convert a bookmark to an explicit kind.
*/
fun toExplicit(): Bookmark {
return this.copy(kind = BookmarkKind.ReaderBookmarkExplicit)
}
companion object {
/**
* Create a bookmark ID from the given book ID, location, and kind.
*/
fun createBookmarkID(
book: BookID,
location: BookLocation,
kind: BookmarkKind
): BookmarkID {
try {
val messageDigest = MessageDigest.getInstance("SHA-256")
val utf8 = Charset.forName("UTF-8")
messageDigest.update(book.value().toByteArray(utf8))
val cfiOpt = location.contentCFI()
if (cfiOpt is Some<String>) {
messageDigest.update(cfiOpt.get().toByteArray(utf8))
}
messageDigest.update(location.idRef().toByteArray(utf8))
messageDigest.update(kind.motivationURI.toByteArray(utf8))
val digestResult = messageDigest.digest()
val builder = StringBuilder(64)
for (index in digestResult.indices) {
val bb = digestResult[index]
builder.append(String.format("%02x", bb))
}
return BookmarkID(builder.toString())
} catch (e: NoSuchAlgorithmException) {
throw IllegalStateException(e)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 34a6fda48570a75372723b71acd36130570e1bcb | 3,221 | Simplified-Android-Core | Apache License 2.0 |
Yogiraj (Android)/Animation/app/src/main/java/com/drawonapp/animation/MainActivity.kt | SwiftUI-Animation-Challenges | 513,304,739 | false | null | package com.drawonapp.animation
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import com.drawonapp.animation.customview.FillAnimation
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
class MainActivity : AppCompatActivity() {
private lateinit var fillAnimation1: FillAnimation
private lateinit var fillAnimation2: FillAnimation
private lateinit var fillAnimation3: FillAnimation
private lateinit var fillAnimation4: FillAnimation
private lateinit var fillAnimation5: FillAnimation
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fillAnimation1 = findViewById(R.id.fill_animation1)
fillAnimation2 = findViewById(R.id.fill_animation2)
fillAnimation3 = findViewById(R.id.fill_animation3)
fillAnimation4 = findViewById(R.id.fill_animation4)
fillAnimation5 = findViewById(R.id.fill_animation5)
fillAnimation1.show_animation(showAnimation = true)
fillAnimation2.show_animation(showAnimation = true)
fillAnimation3.show_animation(showAnimation = true)
fillAnimation4.show_animation(showAnimation = true)
fillAnimation5.show_animation(showAnimation = true)
}
} | 2 | Swift | 20 | 19 | 8ff1f6716655630eb8d6328c2c64668835965e4b | 1,351 | Challenge-1 | MIT License |
playground/main/src/main/kotlin/playground/Second.kt | facebookresearch | 498,810,868 | false | null | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package playground
import shapeTyping.annotations.AllowUnreduced
import shapeTyping.annotations.SType
@SType("S: Shape")
class RuntimeShape(val dims : List<Int>) {
constructor(vararg dims : @SType("S") Int) : this(dims.toList())
}
@SType("S: Shape")
@AllowUnreduced
class Tensor(val shape: @SType("S") RuntimeShape) {
companion object {
@SType("S: Shape")
fun zeros(shape: @SType("S") RuntimeShape): @SType("S") Tensor = Tensor(shape)
}
} | 15 | Kotlin | 2 | 8 | b80b7484b8f1033fbef3e76a401b7a0237a35e05 | 661 | shapekt | MIT License |
core/src/test/kotlin/main/operation/Show_test.kt | elect86 | 364,643,104 | false | null | package main.operation
import main.Commit
import main.SimpleGit
import main.plusAssign
import kotlin.test.Test
class Show_test : SimpleGit() {
@Test
fun `can show diffs in commit that added new file`() {
val fooFile = repoFile("dir1/foo.txt")
fooFile += "foo!"
gik.add(patterns = setOf("."))
val commit = gik.commit(message = "Initial commit")
assert(gik.show(commit = commit) == Commit.Diff(commit, added = setOf("dir1/foo.txt")))
}
@Test
fun `can show diffs in commit that modified existing file`() {
val fooFile = repoFile("bar.txt")
fooFile += "bar!"
gik.add(patterns = setOf("."))
gik.commit(message = "Initial commit")
// Change existing file
fooFile += "monkey!"
gik.add(patterns = setOf("."))
val changeCommit = gik.commit(message = "Added monkey")
assert(gik.show(commit = changeCommit) == Commit.Diff(commit = changeCommit,
modified = setOf("bar.txt")))
}
@Test
fun `can show diffs in commit that deleted existing file`() {
val fooFile = repoFile("bar.txt")
fooFile += "bar!"
gik.add(patterns = setOf("."))
gik.commit(message = "Initial commit")
// Delete existing file
gik.remove(patterns = setOf("bar.txt"))
val removeCommit = gik.commit(message = "Deleted file")
assert(gik.show(commit = removeCommit) == Commit.Diff(commit = removeCommit,
removed = setOf("bar.txt")))
}
@Test
fun `can show diffs in commit with multiple changes`() {
val animalFile = repoFile("animals.txt")
animalFile += "giraffe!"
gik.add(patterns = setOf("."))
gik.commit(message = "Initial commit")
// Change existing file
animalFile += "zebra!"
// Add new file
val fishFile = repoFile("salmon.txt")
fishFile += "salmon!"
gik.add(patterns = setOf("."))
val changeCommit = gik.commit(message = "Add fish and update animals with zebra")
assert(gik.show(commit = changeCommit) == Commit.Diff(commit = changeCommit,
modified = setOf("animals.txt"),
added = setOf("salmon.txt")))
}
@Test
fun `can show diffs in commit with rename`() {
repoFile("elephant.txt") += "I have tusks."
gik.add(patterns = setOf("."))
gik.commit(message = "Adding elephant.")
repoFile("elephant.txt").renameTo(repoFile("mammoth.txt"))
gik.add(patterns = setOf("."))
gik.remove(patterns = setOf("elephant.txt"))
val renameCommit = gik.commit(message = "Renaming to mammoth.")
assert(gik.show(commit = renameCommit) == Commit.Diff(commit = renameCommit,
renamed = setOf("mammoth.txt"),
renamings = mapOf("elephant.txt" to "mammoth.txt")))
}
@Test
fun `can show diffs based on rev string`() {
val fooFile = repoFile("foo.txt")
fooFile += "foo!"
gik.add(patterns = setOf("."))
val commit = gik.commit(message = "Initial commit")
assert(gik.show(commit = commit.id) == Commit.Diff(commit = commit,
added = setOf("foo.txt")))
}
}
| 1 | Kotlin | 1 | 2 | f5f28edfee6a2683ce5da5ea8fdc4e1ba32a3f33 | 3,576 | gik | Apache License 2.0 |
clef-workflow-api/clef-workflow-api-usecase/clef-workflow-api-usecase-stage/src/main/java/io/arkitik/clef/workflow/api/usecase/stage/main/CreateStageUseCase.kt | arkitik | 443,436,455 | false | {"Kotlin": 433170, "Shell": 268, "Dockerfile": 244} | package io.arkitik.clef.workflow.api.usecase.stage.main
import io.arkitik.clef.workflow.api.common.error.StageResponses
import io.arkitik.clef.workflow.api.common.response.ViewIdentify
import io.arkitik.clef.workflow.api.store.stage.InitialStageStore
import io.arkitik.clef.workflow.api.store.stage.StageStore
import io.arkitik.clef.workflow.api.usecase.factory.domain.StageDomainUseCaseFactory
import io.arkitik.clef.workflow.api.usecase.factory.domain.WorkflowDomainUseCaseFactory
import io.arkitik.clef.workflow.api.usecase.factory.domain.request.ExistByKeyRequest
import io.arkitik.clef.workflow.api.usecase.factory.domain.request.FindDomainByKeyRequest
import io.arkitik.clef.workflow.api.usecase.factory.workflow.request.stage.CreateStageRequest
import io.arkitik.radix.develop.shared.ext.unprocessableEntity
import io.arkitik.radix.develop.store.storeCreator
import io.arkitik.radix.develop.usecase.command
import io.arkitik.radix.develop.usecase.execute
import io.arkitik.radix.develop.usecase.validation.functional.ValidationFunctionalUseCase
/**
* Created By [**<NAME> **](https://www.linkedin.com/in/iloom/)<br></br>
* Created At **15**, **Sun Mar, 2020**
* Project **clef-workflow** [arkitik.IO](https://arkitik.io/)<br></br>
*/
class CreateStageUseCase(
private val stageStore: StageStore,
private val initialStageStore: InitialStageStore,
private val stageDomainUseCaseFactory: StageDomainUseCaseFactory,
private val workflowDomainUseCaseFactory: WorkflowDomainUseCaseFactory,
) : ValidationFunctionalUseCase<CreateStageRequest, ViewIdentify>() {
override fun CreateStageRequest.doBefore() {
stageDomainUseCaseFactory.command {
validateStageExistenceUseCase
} execute ExistByKeyRequest(stageKey)
}
override fun CreateStageRequest.doProcess(): ViewIdentify {
val workflowIdentity = workflowDomainUseCaseFactory.findWorkflowByKeyUseCase
.run {
FindDomainByKeyRequest(workflow.key, false)
.process()
.response
}
val stageIdentity = with(stageStore) {
storeCreator(identityCreator()) {
stageKey.stageKey()
stageName.stageName()
workflowIdentity.workflow()
create()
}.save()
}
takeIf { initialStage }?.let {
with(initialStageStore) {
storeQuery.existsByWorkflow(workflowIdentity)
.takeIf { it }?.let {
throw StageResponses.Errors.INITIAL_STAGE_HAS_BEEN_ADDED_BEFORE.unprocessableEntity()
}
storeCreator(identityCreator()) {
stageIdentity.stage()
workflowIdentity.workflow()
create()
}.save()
}
}
return ViewIdentify(stageIdentity.uuid, stageIdentity.stageKey)
}
}
| 0 | Kotlin | 0 | 0 | 785e1b4ee583b6a6e3ea01e656eecd8365f171ef | 2,953 | clef-workflow | Apache License 2.0 |
app/src/main/java/io/github/vladimirmi/internetradioplayer/data/repository/MediaRepository.kt | DL44227 | 178,415,007 | true | {"Kotlin": 342234, "Java": 7538} | package io.github.vladimirmi.internetradioplayer.data.repository
import com.jakewharton.rxrelay2.BehaviorRelay
import io.github.vladimirmi.internetradioplayer.data.utils.Preferences
import io.github.vladimirmi.internetradioplayer.domain.model.Media
import io.github.vladimirmi.internetradioplayer.domain.model.MediaQueue
import javax.inject.Inject
/**
* Created by <NAME> 16.02.2019.
*/
class MediaRepository
@Inject constructor(private val prefs: Preferences) {
lateinit var mediaQueue: MediaQueue
val currentMediaObs = BehaviorRelay.createDefault(Media.nullObj())
var currentMedia: Media
get() = currentMediaObs.value ?: Media.nullObj()
set(value) {
prefs.mediaId = value.id
currentMediaObs.accept(value)
}
fun getNext(id: String): Media {
return mediaQueue.getNext(id) ?: Media.nullObj()
}
fun getPrevious(id: String): Media {
return mediaQueue.getPrevious(id) ?: Media.nullObj()
}
fun getSavedMediaId(): String {
return prefs.mediaId
}
} | 0 | Kotlin | 0 | 0 | d2eac5d745d69ed9510eba5c08529c04927db3f1 | 1,060 | InternetRadioPlayer | MIT License |
src/commonMain/kotlin/nonEmptyList/NonEmptyList+plus.kt | balazstothofficial | 265,933,158 | false | null | package nonEmptyList
operator fun <T> NonEmptyList<T>.plus(value: T) = copy(tail = tail + value)
operator fun <T> NonEmptyList<T>.plus(other: List<T>) = copy(tail = tail + other)
operator fun <T> List<T>.plus(
other: NonEmptyList<T>
): NonEmptyList<T> = other.copy(head = other.firstOrNull() ?: other.head, tail = drop(1) + other.tail)
operator fun <T> NonEmptyList<T>.plus(other: NonEmptyList<T>): NonEmptyList<T> = copy(tail = tail + other) | 0 | Kotlin | 0 | 0 | cb8862db7a520acbf20a41412328315511fd4d82 | 450 | data-structures | MIT License |
scripts/Day2.kts | matthewm101 | 573,325,687 | false | {"Kotlin": 63435} | import java.io.File
enum class Hand(val handScore: Long) {Rock(1), Paper(2), Scissors(3)}
fun charToHand(c: Char) = when(c) {
'A', 'X' -> Hand.Rock
'B', 'Y' -> Hand.Paper
'C', 'Z' -> Hand.Scissors
else -> Hand.Rock
}
enum class Goal(val goalScore: Long) {Loss(0), Tie(3), Win(6)}
fun charToGoal(c: Char) = when(c) {
'X' -> Goal.Loss
'Y' -> Goal.Tie
'Z' -> Goal.Win
else -> Goal.Tie
}
fun judge(yours: Hand, theirs: Hand) = when(yours) {
Hand.Rock -> when(theirs) {
Hand.Rock -> Goal.Tie
Hand.Paper -> Goal.Loss
Hand.Scissors -> Goal.Win
}
Hand.Paper -> when(theirs) {
Hand.Rock -> Goal.Win
Hand.Paper -> Goal.Tie
Hand.Scissors -> Goal.Loss
}
Hand.Scissors -> when(theirs) {
Hand.Rock -> Goal.Loss
Hand.Paper -> Goal.Win
Hand.Scissors -> Goal.Tie
}
}
fun reverseJudge(theirs: Hand, goal: Goal) = when(goal) {
Goal.Win -> when(theirs) {
Hand.Rock -> Hand.Paper
Hand.Paper -> Hand.Scissors
Hand.Scissors -> Hand.Rock
}
Goal.Tie -> theirs
Goal.Loss -> when(theirs) {
Hand.Rock -> Hand.Scissors
Hand.Paper -> Hand.Rock
Hand.Scissors -> Hand.Paper
}
}
data class RoundV1(val opponent: Hand, val player: Hand) {
fun playerScore() = judge(player, opponent).goalScore + player.handScore
}
val roundsV1: List<RoundV1> = File("../inputs/2.txt").readLines().map {
s -> RoundV1(charToHand(s[0]), charToHand(s[2]))
}.toList()
val totalPlayerScoreV1 = roundsV1.map { r -> r.playerScore() }.sum()
println("Using the initial instructions, the player's total score from all rounds is $totalPlayerScoreV1.")
data class RoundV2(val opponent: Hand, val goal: Goal) {
fun playerScore() = goal.goalScore + reverseJudge(opponent, goal).handScore
}
val roundsV2: List<RoundV2> = File("../inputs/2.txt").readLines().map {
s -> RoundV2(charToHand(s[0]), charToGoal(s[2]))
}.toList()
val totalPlayerScoreV2 = roundsV2.map { r -> r.playerScore() }.sum()
println("Using the fixed instructions, the player's total score from all rounds is $totalPlayerScoreV2.") | 0 | Kotlin | 0 | 0 | bbd3cf6868936a9ee03c6783d8b2d02a08fbce85 | 2,158 | adventofcode2022 | MIT License |
app/src/main/java/ru/ozh/android/recycler/decorator/sample/pager/controllers/StubController.kt | ozh-dev | 193,144,003 | false | {"Kotlin": 84727} | package ru.ozh.android.recycler.decorator.sample.pager.controllers
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.viewbinding.ViewBinding
import ru.ozh.android.recycler.decorator.sample.pager.controllers.StubController.Holder
import ru.surfstudio.android.easyadapter.controller.NoDataItemController
import ru.surfstudio.android.easyadapter.holder.BaseViewHolder
class StubController<T : ViewBinding>(private val binding: (ViewGroup) -> T) : NoDataItemController<Holder>() {
override fun viewType(): Int {
return binding.hashCode()
}
override fun createViewHolder(parent: ViewGroup): Holder =
Holder(binding(parent))
class Holder(binding: ViewBinding) : BaseViewHolder(binding.root)
} | 1 | Kotlin | 19 | 92 | c3718d6a58a5712933d4e92ce333b4fb57e262b2 | 756 | recycler-decorator-library-sample | Apache License 2.0 |
fluxo-core/src/commonMain/kotlin/kt/fluxo/core/intent/IntentRequest.kt | fluxo-kt | 566,869,438 | false | {"Kotlin": 540610, "Shell": 968, "Dockerfile": 791} | package kt.fluxo.core.intent
import kotlinx.coroutines.CompletableDeferred
import kt.fluxo.common.annotation.ExperimentalFluxoApi
import kotlin.jvm.JvmField
/**
*
* **NOTE: please fill an issue if you need this class to be open for your own specific implementations!**
*
* @see ChannelBasedIntentStrategy for usage
*/
@ExperimentalFluxoApi
internal class IntentRequest<out Intent>(
@JvmField val intent: Intent,
@JvmField val deferred: CompletableDeferred<Unit>?,
)
| 9 | Kotlin | 1 | 28 | aac0f6ba9118e9b3d20ec1cca934e230f3ec8066 | 481 | fluxo | Apache License 2.0 |
src/main/kotlin/com/dubreuia/pih/services/ApplicationService.kt | dubreuia | 435,223,862 | false | {"Kotlin": 8330} | package com.dubreuia.pih.services
import com.dubreuia.pih.MyBundle
class ApplicationService {
init {
println(MyBundle.message("applicationService"))
}
}
| 3 | Kotlin | 1 | 9 | 90527b83b567155ad9cb1b496554149bee189596 | 173 | python-inlay-hints-plugin | MIT License |
core/src/commonMain/kotlin/io/github/aeckar/parsing/typesafe/Symbols.kt | aeckar | 834,956,853 | false | {"Kotlin": 78817} | @file:Suppress("LeakingThis")
package io.github.aeckar.parsing.typesafe
import io.github.aeckar.parsing.*
import io.github.aeckar.parsing.utils.SymbolStream
import io.github.aeckar.parsing.utils.unsafeCast
/**
* A symbol providing type-safe access to its components.
*
* Enables type-safe access to children of each [Node] produced by this symbol.
*/
public abstract class TypeSafeSymbol<
TypeUnsafeT : TypeUnsafeSymbol<InheritorT, TypeUnsafeT>,
InheritorT : TypeSafeSymbol<TypeUnsafeT, InheritorT>
> internal constructor(internal val untyped: TypeUnsafeT) : NameableSymbol<InheritorT>() {
final override fun resolve() = untyped
final override fun match(stream: SymbolStream): Node<*>? {
return untyped.match(stream)?.also { it.unsafeCast<Node<Symbol>>().source = this }
}
final override fun resolveRawName() = untyped.rawName
}
/**
* A type-safe junction wrapper.
*/
public abstract class TypeSafeJunction<InheritorT : TypeSafeJunction<InheritorT>> internal constructor(
untyped: ImplicitJunction<InheritorT>
) : TypeSafeSymbol<ImplicitJunction<InheritorT>, InheritorT>(untyped) {
init {
untyped.typed = this
}
}
/**
* A type-safe sequence wrapper.
*/
public abstract class TypeSafeSequence<InheritorT : TypeSafeSequence<InheritorT>> internal constructor(
untyped: ImplicitSequence<InheritorT>
) : TypeSafeSymbol<ImplicitSequence<InheritorT>, InheritorT>(untyped) {
init {
untyped.typed = this
}
} | 0 | Kotlin | 0 | 0 | 2f13ccfd7fee1242eb784f0ce3d4dd7d35412a03 | 1,484 | power-parse | MIT License |
app/src/main/java/com/littlelemon/menu/ProductsGrid.kt | mamado143 | 649,249,040 | false | null | package com.littlelemon.menu
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ProductsGrid(products: Products, startProductActivity: (ProductItem) -> Unit) {
LazyVerticalGrid(
cells = GridCells.Fixed(count = 2),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
items(
items = products.items,
itemContent = { productItem: ProductItem ->
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(id = productItem.image),
contentDescription = productItem.title,
contentScale = ContentScale.Crop,
modifier = Modifier.clickable {
startProductActivity(productItem)
}
)
Text(text = productItem.title)
}
}
)
}
} | 0 | Kotlin | 0 | 0 | a41e627c4a94afb598d7097b08e09290af668649 | 1,972 | DinnerTableManu | MIT License |
data/src/main/kotlin/repository/model/pdf/content/model/Projects.kt | tardisjphon | 647,261,331 | false | null | package repository.model.pdf.content.model
import repository.model.pdf.content.model.projects.ProjectData
data class Projects(
val id: Int,
val title: String,
val projects: List<ProjectData>? = null
)
| 0 | Kotlin | 0 | 0 | 95f14ec3ad35a5345ed4664ed985dd215a382190 | 216 | CvGenerator | MIT License |
android/src/main/kotlin/africa/ejara/trustdart/interfaces/CoinInterface.kt | jayluxferro | 476,413,025 | true | {"Kotlin": 30680, "Swift": 24442, "Dart": 13985, "Ruby": 2348, "Objective-C": 686} | package africa.ejara.trustdart.interfaces
interface CoinInterface {
fun generateAddress(
path: String,
mnemonic: String,
passphrase: String
): Map<String, String?>?
fun getPrivateKey(path: String, mnemonic: String, passphrase: String): String?
fun getPublicKey(path: String, mnemonic: String, passphrase: String): String?
fun validateAddress(address: String): Boolean
fun signTransaction(
path: String,
txData: Map<String, Any>,
mnemonic: String,
passphrase: String
): String?
} | 0 | Kotlin | 0 | 0 | 778b677697dc3b1c761da89ce1632b5513c594ea | 564 | trustdart | MIT License |
app/src/main/java/com/revolgenx/anilib/radio/ui/view/CircleSimpleDraweeView.kt | rev0lgenX | 244,410,204 | false | null | package com.revolgenx.anilib.radio.ui.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import android.view.View
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.generic.RoundingParams
import com.facebook.drawee.view.SimpleDraweeView
import com.pranavpandey.android.dynamic.support.theme.DynamicTheme
import com.pranavpandey.android.dynamic.utils.DynamicUnitUtils
import com.revolgenx.anilib.R
class CircleSimpleDraweeView : SimpleDraweeView {
constructor(context: Context) : this(context, null)
constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int) : super(
context,
attributeSet,
defStyle
) {
val a = context.theme.obtainStyledAttributes(
attributeSet,
R.styleable.CircleSimpleDraweeView,
defStyle,
0
)
hierarchy.setBackgroundImage(ColorDrawable(Color.WHITE))
hierarchy.actualImageScaleType = ScalingUtils.ScaleType.CENTER_INSIDE
try {
setBorder =
a.getBoolean(R.styleable.CircleSimpleDraweeView_showBorder, false)
} finally {
a.recycle()
}
}
var setBorder: Boolean = false
set(value) {
field = value
hierarchy.roundingParams = if (value) roundingParamsWithBorder else roundingParams
invalidate()
}
private val roundingParams by lazy {
RoundingParams.asCircle()
}
private val roundingParamsWithBorder
get() = roundingParams.also {
it.borderWidth = 6f
it.borderColor = DynamicTheme.getInstance().get().accentColor
}
} | 29 | Kotlin | 3 | 62 | 743e6bf5c865ba5eb601fafe655d498cee04c681 | 1,927 | AniLib | Apache License 2.0 |
app/src/main/java/com/oscarliang/gitfinder/api/GithubService.kt | iamoscarliang | 771,415,562 | false | {"Kotlin": 100365} | package com.oscarliang.gitfinder.api
import retrofit2.http.GET
import retrofit2.http.Query
interface GithubService {
@GET("search/repositories")
suspend fun searchRepos(
@Query("q") query: String,
@Query("per_page") number: Int
): RepoSearchResponse
@GET("search/repositories")
suspend fun searchRepos(
@Query("q") query: String,
@Query("per_page") number: Int,
@Query("page") page: Int
): RepoSearchResponse
} | 0 | Kotlin | 0 | 0 | 07ee831afa9cc19f1862d863c2b13017101c59c6 | 479 | git-finder | MIT License |
DualView/src/main/java/com/microsoft/device/display/samples/dualview/models/AppStateViewModel.kt | microsoft | 329,091,156 | false | null | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
package com.microsoft.device.display.samples.dualview.models
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class AppStateViewModel : ViewModel() {
var viewWidth: Int = 0
var selectionLiveData = MutableLiveData<Int>(-1) // observe the image selection change
}
| 1 | Kotlin | 9 | 27 | 16c6bc36ad741bb0b0024a36eaededca73b20b9d | 406 | surface-duo-compose-samples | MIT License |
basics/ktx/src/main/java/top/sunhy/ktx/StringExt.kt | RDSunhy | 421,280,382 | false | null | package top.sunhy.ktx
//import com.alibaba.fastjson.JSONObject
/**
* 判断字符串不为空
*/
fun CharSequence?.isNotNullOrEmpty(): Boolean {
return !this.isNullOrEmpty()
}
/**
* 判断字符串是否为 json 字符串
*/
/*fun CharSequence?.isJson(): Boolean {
if(this.isNullOrEmpty()){
return false
}
try {
JSONObject.parseObject(this.toString())
}catch (e: Exception){
try {
JSONObject.parseArray(this.toString())
}catch (e: Exception){
return false
}
}
return true
}*/
/**
* 判断字符串是否为 true
*/
fun CharSequence?.isTrue(): Boolean {
if(this.isNullOrEmpty()){
return false
}
return this == "true"
} | 0 | Kotlin | 0 | 0 | ff8d615fceeb21169caba21df32e120e2ac783f6 | 685 | android-component | Apache License 2.0 |
module/src/main/java/com/ke/hs_tracker/module/entity/GraveyardCard.kt | keluokeda | 469,693,055 | false | {"Kotlin": 372770} | package com.ke.hs_tracker.module.entity
data class GraveyardCard(
val card: Card,
/**
* 插入时间
*/
val time: Long = System.currentTimeMillis()
) | 8 | Kotlin | 31 | 216 | b4c42c2ecf385f0f9b18bf5656f1ede42795ef20 | 164 | hs_tracker | MIT License |
module/src/main/java/com/ke/hs_tracker/module/entity/GraveyardCard.kt | keluokeda | 469,693,055 | false | {"Kotlin": 372770} | package com.ke.hs_tracker.module.entity
data class GraveyardCard(
val card: Card,
/**
* 插入时间
*/
val time: Long = System.currentTimeMillis()
) | 8 | Kotlin | 31 | 216 | b4c42c2ecf385f0f9b18bf5656f1ede42795ef20 | 164 | hs_tracker | MIT License |
ion-schema/src/main/kotlin/com/amazon/ionschema/model/TimestampPrecisionValue.kt | amazon-ion | 148,685,964 | false | {"Kotlin": 804755, "Inno Setup": 15625, "Java": 795, "Shell": 631} | package com.amazon.ionschema.model
import com.amazon.ion.Timestamp
import java.lang.Integer.max
class TimestampPrecisionValue private constructor(internal val intValue: Int) : Comparable<TimestampPrecisionValue> {
override fun compareTo(other: TimestampPrecisionValue): Int = this.intValue.compareTo(other.intValue)
override fun equals(other: Any?): Boolean = other is TimestampPrecisionValue && intValue == other.intValue
override fun hashCode(): Int = intValue.hashCode()
override fun toString(): String = "TimestampPrecisionValue($intValue)"
companion object {
@JvmStatic val Year = TimestampPrecisionValue(-4)
@JvmStatic val Month = TimestampPrecisionValue(-3)
@JvmStatic val Day = TimestampPrecisionValue(-2)
@JvmStatic val Minute = TimestampPrecisionValue(-1)
@JvmStatic val Second = TimestampPrecisionValue(0)
@JvmStatic val Millisecond = TimestampPrecisionValue(3)
@JvmStatic val Microsecond = TimestampPrecisionValue(6)
@JvmStatic val Nanosecond = TimestampPrecisionValue(9)
@JvmStatic
fun values() = listOf(Year, Month, Day, Minute, Second, Millisecond, Microsecond, Nanosecond)
@JvmStatic
fun valueSymbolTexts(): List<String> = values().map { it.toSymbolTextOrNull()!! }
@JvmSynthetic
internal fun fromTimestamp(timestamp: Timestamp): TimestampPrecisionValue {
return when (timestamp.precision!!) {
Timestamp.Precision.YEAR -> Year
Timestamp.Precision.MONTH -> Month
Timestamp.Precision.DAY -> Day
Timestamp.Precision.MINUTE -> Minute
Timestamp.Precision.SECOND,
Timestamp.Precision.FRACTION -> TimestampPrecisionValue(max(0, timestamp.decimalSecond.scale()))
}
}
/**
* The symbol text for this value as defined in the ISL specification, if one exists.
*/
fun fromSymbolTextOrNull(symbolText: String): TimestampPrecisionValue? = when (symbolText) {
"year" -> Year
"month" -> Month
"day" -> Day
"minute" -> Minute
"second" -> Second
"millisecond" -> Millisecond
"microsecond" -> Microsecond
"nanosecond" -> Nanosecond
else -> null
}
}
/**
* Returns the ISL symbol text for this [TimestampPrecisionValue], if one exists.
*/
fun toSymbolTextOrNull(): String? = when (this) {
Year -> "year"
Month -> "month"
Day -> "day"
Minute -> "minute"
Second -> "second"
Millisecond -> "millisecond"
Microsecond -> "microsecond"
Nanosecond -> "nanosecond"
else -> null
}
}
| 40 | Kotlin | 14 | 27 | 7a9ee6d06e9cfdaa530310f5d9be9f5a52680d3b | 2,785 | ion-schema-kotlin | Apache License 2.0 |
app/src/main/java/io/github/omisie11/spacexfollower/util/NumbersUtils.kt | OMIsie11 | 159,474,083 | false | null | package io.github.omisie11.spacexfollower.util
import java.math.RoundingMode
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import org.threeten.bp.Instant
import org.threeten.bp.LocalDateTime
import org.threeten.bp.ZoneId
// Used to convert SpaceX valuation, no need to support negative numbers
fun shortenNumberAddPrefix(numberToFormat: Long): String {
val number = numberToFormat.toDouble()
val df = DecimalFormat("#.##").apply { roundingMode = RoundingMode.CEILING }
return when {
number > 1000000000 -> "${df.format(number.div(1000000000))} billion"
number > 1000000 -> "${df.format(number.div(1000000))} million"
else -> number.toInt().toString()
}
}
fun getLocalTimeFromUnix(unixTime: Long): String {
val simpleDateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault())
simpleDateFormat.timeZone = Calendar.getInstance().timeZone
return simpleDateFormat.format(Date(unixTime * 1000))
}
fun getMonthValueFromUnixTime(unixTime: Long): Int {
val instant = Instant.ofEpochSecond(unixTime)
val localDataTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
return localDataTime.monthValue
}
fun getYearValueFromUnixTime(unixTime: Long): Int {
val instant = Instant.ofEpochSecond(unixTime)
val localDataTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
return localDataTime.year
}
| 1 | Kotlin | 9 | 47 | 16c4c0fe50508e9f6c455997256538cbbbde9537 | 1,491 | SpaceXFollower | Apache License 2.0 |
data/test/src/test/java/app/tivi/utils/AuthorizedAuthStore.kt | chrisbanes | 100,624,553 | false | null | /*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.utils
import app.tivi.data.traktauth.AuthState
import app.tivi.data.traktauth.store.AuthStore
object AuthorizedAuthStore : AuthStore {
override suspend fun get(): AuthState = AuthorizedAuthState
override suspend fun save(state: AuthState) = Unit
override suspend fun clear() = Unit
}
object AuthorizedAuthState : AuthState {
override val accessToken: String = "access-token"
override val refreshToken: String = "refresh-token"
override val isAuthorized: Boolean = true
override fun serializeToJson(): String = "{}"
}
| 20 | Kotlin | 792 | 5,749 | 5dc4d831fd801afab556165d547042c517f98875 | 1,160 | tivi | Apache License 2.0 |
app/src/main/java/br/com/renanbarbieri/snakotlin/presentation/ui/GameActivity.kt | renanBarbieri | 134,337,443 | false | {"Kotlin": 33760} | package br.com.renanbarbieri.snakotlin.presentation.ui
import android.arch.lifecycle.ViewModelProviders
import android.content.Intent
import android.graphics.Point
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import br.com.renanbarbieri.snakotlin.R
import br.com.renanbarbieri.snakotlin.domain.saveUserScore.SaveUserScoreViewModel
import br.com.renanbarbieri.snakotlin.presentation.engine.GameLifecycle
import br.com.renanbarbieri.snakotlin.presentation.engine.GameEngine
import br.com.renanbarbieri.snakotlin.presentation.framework.gestureDirection.GestureDetectorFramework
import br.com.renanbarbieri.snakotlin.presentation.framework.screenDrawer.ScreenDrawerFramework
class GameActivity : AppCompatActivity(), GameLifecycle {
private var gameEngine: GameEngine? = null
private var gestureInteractor: GestureDetectorFramework? = null
private var screenDrawer: ScreenDrawerFramework? = null
private var viewModel: SaveUserScoreViewModel? = null
companion object {
val ARG_LEVEL = "br.com.renanbarbieri.snakotlin.presentation.ui.GameActivity.ARG_LEVEL"
enum class Level { EASY, NORMAL, HARD }
/**
* Static method for start this activity with necessary parameters
*/
fun start(level: Level, callerActivity: AppCompatActivity){
val intent = Intent(callerActivity, GameActivity::class.java)
val args = Bundle()
args.putInt(ARG_LEVEL, level.ordinal)
intent.putExtras(args)
callerActivity.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val display = windowManager.defaultDisplay
val size = Point()
display.getSize(size)
this.initFramework(screenX = size.x)
var fps: Long = 6
intent.extras?.let {
fps = when(it.getInt(ARG_LEVEL)){
Level.EASY.ordinal -> 3
Level.HARD.ordinal -> 9
else -> 6
}
}
gameEngine = GameEngine(
context = this,
fps = fps,
screenDimen = size,
drawerInteractor = this.screenDrawer,
gameGestureInteractor = this.gestureInteractor,
gameLifecycle = this
)
viewModel = ViewModelProviders.of(this).get(SaveUserScoreViewModel::class.java)
setContentView(gameEngine)
}
/**
* Initialize the frameworks
*/
private fun initFramework(screenX:Int) {
this.gestureInteractor = GestureDetectorFramework(
minSwipe = screenX/5,
maxSwipe = null
)
this.screenDrawer = ScreenDrawerFramework
}
override fun onResume() {
super.onResume()
gameEngine?.resume()
}
override fun onPause() {
super.onPause()
gameEngine?.pause()
}
/**
* When snake is dead, this method is called.
* - Save the score
*/
override fun onSnakeDead(score: Int) {
viewModel?.saveScore(score)
runOnUiThread({this.showTryAgain()})
}
override fun onGameFinished() {
runOnUiThread({this.showGameFinished()})
}
override fun onError(errorMessage: String) {
runOnUiThread({this.showErrorAlert(errorMessage)})
}
private fun showTryAgain(){
val builder = AlertDialog.Builder(this)
builder.setTitle(R.string.dialogTitleFail)
builder.setMessage(R.string.snakeIsDead)
builder.setPositiveButton(R.string.tryAgain){dialog, which ->
gameEngine?.restartGame()
}
builder.setNeutralButton(R.string.goBack){dialog, which ->
this.onBackPressed()
}
val dialog: AlertDialog = builder.create()
dialog.show()
}
private fun showGameFinished() {
val builder = AlertDialog.Builder(this)
builder.setTitle(R.string.dialogTitleSuccess)
builder.setMessage(R.string.snakeIsTooBig)
builder.setPositiveButton(R.string.success){dialog, which ->
this.onBackPressed()
}
val dialog: AlertDialog = builder.create()
dialog.show()
}
private fun showErrorAlert(message: String) {
val builder = AlertDialog.Builder(this)
builder.setTitle(R.string.dialogTitleError)
builder.setMessage(message)
builder.setPositiveButton(R.string.ok){dialog, which ->
this.onBackPressed()
}
val dialog: AlertDialog = builder.create()
dialog.show()
}
}
| 0 | Kotlin | 0 | 0 | b27e8e8ead9f0eaf27f0712cbde33076257127ce | 4,713 | snakotlin | MIT License |
database/src/main/java/com/demo/minnies/database/room/daos/ProductsDao.kt | jsonkile | 572,488,327 | false | {"Kotlin": 482538, "Java": 28720, "Shell": 1599} | package com.demo.minnies.database.room.daos
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.demo.minnies.database.models.ProductCategory
import com.demo.minnies.database.models.Product
import kotlinx.coroutines.flow.Flow
@Dao
interface ProductsDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(item: Product): Long
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(items: List<Product>): List<Long>
@Query("select * from products")
fun getAll(): Flow<List<Product>>
@Query("select count(name) from products")
fun countAll() : Flow<Int>
@Query("select * from products where productCategory = :productCategory")
fun getItemsByCategory(productCategory: ProductCategory): Flow<List<Product>>
@Query("select * from products where featured == 1")
fun getFeaturedItems(): Flow<List<Product>>
@Query("select * from products where id == :id")
fun get(id: Int): Flow<Product?>
@Query("select * from products where name like :term")
fun searchProducts(term: String): Flow<List<Product>>
} | 0 | Kotlin | 0 | 0 | ce016c05333f8a7301447f412e8d38ed46e1b2db | 1,159 | Minnies | MIT License |
app/src/main/java/com/basaraksanli/photoAlbum/feature_album/presentation/photolistscreen/PhotoListViewModel.kt | basaraksanli | 449,885,231 | false | {"Kotlin": 62324} | package com.basaraksanli.photoAlbum.feature_album.presentation.photolistscreen
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.basaraksanli.photoAlbum.feature_album.domain.use_case.AlbumUseCases
import com.basaraksanli.photoAlbum.feature_album.util.ApiResult
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject
@HiltViewModel
class PhotoListViewModel @Inject constructor(
private val useCases: AlbumUseCases,
private val stateHandle: SavedStateHandle
) : ViewModel() {
private val _state = mutableStateOf<PhotoListScreenState>(PhotoListScreenState.PhotoListScreenLoading)
var state: State<PhotoListScreenState> = _state
val albumTitle = stateHandle.get<String>("albumTitle")
private val albumId = stateHandle.get<Int>("albumId")
val userName = stateHandle.get<String>("userName")
init {
onEvent(PhotoListScreenEvent.LoadPhotos)
}
fun onEvent(event: PhotoListScreenEvent) {
when (event) {
is PhotoListScreenEvent.LoadPhotos -> {
loadPhotoList(albumId!!)
}
}
}
private fun loadPhotoList(albumId: Int) {
viewModelScope.launch {
when (val result = useCases.getPhotoList(albumId = albumId)) {
is ApiResult.Success ->{
_state.value = PhotoListScreenState.PhotoListScreenLoaded(photoList = result.data!!)
}
is ApiResult.Error -> {
if (result.message != null) {
_state.value = PhotoListScreenState.PhotoListNetworkError(result.message)
Timber.e(Throwable(result.message))
} else {
_state.value =
PhotoListScreenState.PhotoListNetworkError("Unknown Error has occurred.")
Timber.e(Throwable("Unknown Error has occurred."))
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 32972f26e9118259ca2d0142a7b8a4e573d934c1 | 2,205 | PhotoAlbum | Apache License 2.0 |
ospf-kotlin-framework-gantt-scheduling/gantt-scheduling-domain-task-context/src/main/fuookami/ospf/kotlin/framework/gantt_scheduling/domain/task/model/Executor.kt | fuookami | 359,831,793 | false | {"Kotlin": 1571399, "Python": 6629} | package fuookami.ospf.kotlin.framework.gantt_scheduling.domain.task.model
import kotlinx.datetime.*
import fuookami.ospf.kotlin.utils.concept.*
open class ExecutorInitialUsability<T : AbstractTask<E, A>, E : Executor, A : AssignmentPolicy<E>>(
open val lastTask: T?,
val enabledTime: Instant
) {
open val on: Boolean get() = lastTask != null
}
open class Executor(
val id: String,
val name: String
) : ManualIndexed() {
open val actualId: String by ::id
open val displayName: String by ::name
}
| 0 | Kotlin | 0 | 1 | 641c80bf9cfa991f9e1a98a049d2982b981bc96e | 526 | ospf-kotlin | Apache License 2.0 |
app/src/main/java/com/luismunyoz/rylaisscepter/data/CloudChampionDataSet.kt | luismunyoz | 102,855,608 | false | null | package com.luismunyoz.rylaisscepter.data
import com.luismunyoz.rylaisscepter.data.riot.mapper.ChampionMapper
import com.luismunyoz.rylaisscepter.data.riot.RiotAPIService
import com.luismunyoz.rylaisscepter.domain.entity.BaseChampion
import com.luismunyoz.rylaisscepter.domain.entity.Champion
import com.luismunyoz.rylaisscepter.repository.dataset.ChampionDataSet
/**
* Created by llco on 11/09/2017.
*/
class CloudChampionDataSet(val riotAPIService: RiotAPIService) : ChampionDataSet {
override fun requestChampion(id: String): Champion? =
riotAPIService.getChampion(id).unwrapCall { ChampionMapper().transform(this) }
override fun requestChampions(): List<BaseChampion> =
riotAPIService.getChampions().unwrapCall {
ChampionMapper().transform(data)
} ?: emptyList()
override fun store(baseChampion: BaseChampion) {
}
override fun store(champion: Champion) {
}
override fun isCacheValid(): Boolean = true
} | 0 | Kotlin | 0 | 0 | 2b390a93de97e1f529b0f8d2759628d85597602d | 984 | Rylais | Apache License 2.0 |
atv-tests-3/app/src/main/java/com/example/android/architecture/blueprints/todoapp/ServiceLocator.kt | gugapadilha | 508,436,828 | false | {"Kotlin": 307791} | package com.example.android.architecture.blueprints.todoapp
import android.content.Context
import androidx.annotation.VisibleForTesting
import androidx.room.Room
import com.example.android.architecture.blueprints.todoapp.data.source.DefaultTasksRepository
import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource
import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository
import com.example.android.architecture.blueprints.todoapp.data.source.local.TasksLocalDataSource
import com.example.android.architecture.blueprints.todoapp.data.source.local.ToDoDatabase
import com.example.android.architecture.blueprints.todoapp.data.source.remote.TasksRemoteDataSource
import kotlinx.coroutines.runBlocking
object ServiceLocator {
private var database: ToDoDatabase? = null
@Volatile
var tasksRepository: TasksRepository? = null
@VisibleForTesting
private val lock = Any()
//Either provides an already existing repository or creates a new one. This method should be synchronized
// on this to avoid, in situations with multiple threads running, ever accidentally creating two repository instances.
fun provideTasksRepository(context: Context): TasksRepository {
synchronized(this) {
return tasksRepository ?: createTasksRepository(context)
}
}
//Code for creating a new repository. Will call createTaskLocalDataSource and create a new TasksRemoteDataSource.
private fun createTasksRepository(context: Context): TasksRepository {
val newRepo = DefaultTasksRepository(TasksRemoteDataSource, createTaskLocalDataSource(context))
tasksRepository = newRepo
return newRepo
}
//Code for creating a new local data source. Will call createDataBase.
private fun createTaskLocalDataSource(context: Context): TasksDataSource {
val database = database ?: createDataBase(context)
return TasksLocalDataSource(database.taskDao())
}
//Code for creating a new database.
private fun createDataBase(context: Context): ToDoDatabase {
val result = Room.databaseBuilder(
context.applicationContext,
ToDoDatabase::class.java, "Tasks.db"
).build()
database = result
return result
}
@VisibleForTesting
fun resetRepository() {
synchronized(lock) {
runBlocking {
TasksRemoteDataSource.deleteAllTasks()
}
// Clear all data to avoid test pollution.
database?.apply {
clearAllTables()
close()
}
database = null
tasksRepository = null
}
}
} | 0 | Kotlin | 0 | 2 | ed404495ac0b3a245aef8ff8249ab370fd69d1be | 2,713 | android-tests-codelabs | Apache License 2.0 |
app/src/main/java/com/example/Foodster/MainActivity.kt | aspirers01 | 701,244,296 | false | {"Kotlin": 63679} | package com.example.Foodster
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.Foodster.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityMainBinding.inflate(layoutInflater )
setContentView(binding.root)
binding.nxtbtn.setOnClickListener{
val intent=Intent(this@MainActivity,loginui::class.java)
startActivity(intent)
}
}
} | 0 | Kotlin | 0 | 0 | c9bb63aff4995e70573d8c1e6979adb36016e37d | 655 | Foodster | MIT License |
domain/src/commonMain/kotlin/ireader/domain/utils/Resource.kt | kazemcodes | 540,829,865 | true | {"Kotlin": 2179459} | package ireader.domain.utils
import ireader.i18n.UiText
sealed class Resource<T>(val data: T? = null, val uiText: UiText? = null) {
class Success<T>(data: T?) : Resource<T>(data)
class Error<T>(uiText: UiText, data: T? = null) : Resource<T>(data, uiText)
}
| 0 | Kotlin | 0 | 6 | b6b2414fa002cec2aa0d199871fcfb4c2e190a8f | 267 | IReader | Apache License 2.0 |
remote/src/main/java/com/androchef/remote/services/intercepter/AuthorizationInterceptor.kt | happysingh23828 | 251,545,848 | false | null | package com.androchef.remote.services.intercepter
import java.io.IOException
import okhttp3.Interceptor
import okhttp3.Response
class AuthorizationInterceptor(private val apiKey: String) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val newHttpUrl = originalRequest.url().newBuilder()
.addQueryParameter("api_key", apiKey).build()
val newRequest = originalRequest.newBuilder().url(newHttpUrl).build()
return chain.proceed(newRequest)
}
}
| 0 | Kotlin | 51 | 293 | 63777c3d98929b31294719a99c9bf0ae4d7cd616 | 594 | Android-Clean-Architecture | MIT License |
library/src/main/java/me/bytebeats/generator/ChineseCharHelper.kt | bytebeats | 401,924,809 | false | null | package me.bytebeats.generator
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException
import java.util.*
import kotlin.math.absoluteValue
import kotlin.random.Random
/**
* @Author bytebeats
* @Email <<EMAIL>>
* @Github https://github.com/bytebeats
* @Created on 2021/9/1 21:08
* @Version 1.0
* @Description TO-DO
*/
class ChineseCharHelper private constructor() {
private val random: Random
get() = Random(Date().time)
fun oneRandomChineseChar(): String? {
val highPosition = 176 + random.nextInt(39).absoluteValue
val lowPosition = 161 + random.nextInt(93).absoluteValue
val bytes = byteArrayOf(highPosition.toByte(), lowPosition.toByte())
return try {
String(bytes, Charset.forName("GB2312"))
} catch (ignore: UnsupportedCharsetException) {
null
}
}
fun randomChineseCharsWithSize(size: Int): String {
val sb = StringBuilder()
for (i in 0 until size) {
sb.append(oneRandomChineseChar())
}
return sb.toString()
}
fun randomChineseCharsWithSizeBetween(start: Int, end: Int): String {
val size = random.nextInt(start, end + 1)
return randomChineseCharsWithSize(size)
}
fun oneRandomTraditionalChineseChar(): Char {
return TRADITIONAL_CHINESE_CHARS.random()
}
fun randomTraditionalChineseCharsWithSize(size: Int): String {
val sb = StringBuilder()
for (i in 0 until size) {
sb.append(oneRandomTraditionalChineseChar())
}
return sb.toString()
}
fun randomTraditionalChineseCharsWithSizeBetween(start: Int, end: Int): String {
val size = random.nextInt(start, end + 1)
return randomTraditionalChineseCharsWithSize(size)
}
companion object {
private var INSTANCE: ChineseCharHelper? = null
fun instance(): ChineseCharHelper {
if (INSTANCE == null) {
synchronized(ChineseCharHelper::class.java) {
if (INSTANCE == null) {
INSTANCE = ChineseCharHelper()
}
}
}
return INSTANCE!!
}
private const val TRADITIONAL_CHINESE_CHARS = ("厷厸厹厺厼厽厾叀叁参叄叅叆叇亝収叏叐叒叓叕叚叜叝叞"
+ "叠叧叨叭叱叴叵叺叻叼叽叾卟叿吀吁吂吅吆吇吋吒吔吖吘吙吚吜吡吢吣吤吥吧吩吪吭吮吰吱吲呐吷吺吽呁呃呄呅呇呉"
+ "呋呋呌呍呎呏呐呒呓呔呕呗呙呚呛呜呝呞呟呠呡呢呣呤呥呦呧周呩呪呫呬呭呮呯呰呱呲呴呶呵呷呸呹呺呻呾呿咀咁咂"
+ "咃咄咅咇咈咉咊咋咍咎咐咑咓咔咕咖咗咘咙咚咛咜咝咞咟咠咡咢咣咤咥咦咧咨咩咪咫咬咭咮咯咰咲咳咴咵咶啕咹咺咻"
+ "呙咽咾咿哂哃哅哆哇哈哊哋哌哎哏哐哑哒哓哔哕哖哗哘哙哚哛哜哝哞哟哠咔哣哤哦哧哩哪哫哬哯哰唝哵哶哷哸哹哻哼"
+ "哽哾哿唀唁唂唃呗唅唆唈唉唊唋唌唍唎唏唑唒唓唔唣唖唗唘唙吣唛唜唝唞唟唠唡唢唣唤唥唦唧唨唩唪唫唬唭唯唰唲唳"
+ "唴唵唶唷念唹唺唻唼唽唾唿啀啁啃啄啅啇啈啉啋啌啍啎问啐啑啒启啔啕啖啖啘啙啚啛啜啝哑启啠啡唡衔啥啦啧啨啩啪"
+ "啫啬啭啮啯啰啱啲啳啴啵啶啷啹啺啻啼啽啾啿喀喁喂喃善喅喆喇喈喉喊喋喌喍喎喏喐喑喒喓喔喕喖喗喙喛喞喟喠喡喢"
+ "喣喤喥喦喨喩喯喭喯喰喱哟喳喴喵営喷喸喹喺喼喽喾喿嗀嗁嗂嗃嗄嗅呛啬嗈嗉唝嗋嗌嗍吗嗏嗐嗑嗒嗓嗕嗖嗗嗘嗙呜嗛"
+ "嗜嗝嗞嗟嗠嗡嗢嗧嗨唢嗪嗫嗬嗭嗮嗰嗱嗲嗳嗴嗵哔嗷嗸嗹嗺嗻嗼嗽嗾嗿嘀嘁嘂嘃嘄嘅嘅嘇嘈嘉嘊嘋嘌喽嘎嘏嘐嘑嘒嘓"
+ "呕嘕啧嘘嘙嘚嘛唛嘝嘞嘞嘟嘠嘡嘢嘣嘤嘥嘦嘧嘨哗嘪嘫嘬嘭唠啸囍嘴哓嘶嘷呒嘹嘺嘻嘼啴嘾嘿噀噂噃噄咴噆噇噈噉噊"
+ "噋噌噍噎噏噐噑噒嘘噔噕噖噗噘噙噚噛噜咝噞噟哒噡噢噣噤哝哕噧噩噪噫噬噭噮嗳噰噱哙噳喷噵噶噷吨噺噻噼噽噾噿"
+ "咛嚁嚂嚃嚄嚅嚆吓嚈嚉嚊嚋哜嚍嚎嚏尝嚑嚒嚓嚔噜嚖嚗嚘啮嚚嚛嚜嚝嚞嚟嚠嚡嚢嚣嚤呖嚧咙嚩咙嚧嚪嚫嚬嚭嚯嚰嚱亸"
+ "喾嚵嘤嚷嚸嚹嚺嚻嚼嚽嚾嚿啭嗫嚣囃囄冁囆囇呓囊囋囍囎囏囐嘱囒啮囔囕囖囘囙囜囝回囟囡団囤囥囦囧囨囩囱囫囬囮"
+ "囯困囱囲図囵囶囷囸囹囻囼图囿圀圁圂圂圃圄圅圆囵圈圉圊国圌圎圏圎圐圑园圆圔圕图圗团圙圚圛圜圝圞凹凸圠圡圢"
+ "圤圥圦圧圩圪圫圬圮圯地圱圲圳圴圵圶圷圸圹圻圼埢鴪址坁坂坃坄坅坆坈坉坊坋坌坍坒坓坔坕坖坘坙坜坞坢坣坥坧坨"
+ "坩坪坫坬坭坮坯垧坱坲坳坴坶坸坹坺坻坼坽坾坿垀垁垃垅垆垇垈垉垊垌垍垎垏垐垑垓垔垕垖垗垘垙垚垛垜垝垞垟垠垡"
+ "垤垥垧垨垩垪垫垬垭垮垯垰垱垲垲垳垴埯垶垷垸垹垺垺垻垼垽垾垽垿埀埁埂埃埄埅埆埇埈埉埊埋埌埍城埏埐埑埒埓埔"
+ "埕埖埗埘埙埚埛野埝埞域埠垭埢埣埤埥埦埧埨埩埪埫埬埭埮埯埰埱埲埳埴埵埶执埸培基埻崎埽埾埿堀堁堃堄坚堆堇堈"
+ "堉垩堋堌堍堎堏堐堑堒堓堔堕垴堗堘堙堚堛堜埚堞堟堠堢堣堥堦堧堨堩堫堬堭堮尧堰报堲堳场堶堷堸堹堺堻堼堽堾堼"
+ "堾碱塀塁塂塃塄塅塇塆塈塉块茔塌塍塎垲塐塑埘塓塕塖涂塘塙冢塛塜塝塟塠墘塣墘塥塦塧塨塩塪填塬塭塮塯塰塱塲塳"
+ "塴尘塶塷塸堑塺塻塼塽塾塿墀墁墂墄墅墆墇墈墉垫墋墌墍墎墏墐墒墒墓墔墕墖墘墖墚墛坠墝增墠墡墢墣墤墥墦墧墨墩"
+ "墪樽墬墭堕墯墰墱墲坟墴墵垯墷墸墹墺墙墼墽垦墿壀壁壂壃壄壅壆坛壈壉壊垱壌壍埙壏壐壑壒压壔壕壖壗垒圹垆壛壜"
+ "壝垄壠壡坜壣壤壥壦壧壨坝塆圭壭壱売壳壴壵壶壷壸壶壻壸壾壿夀夁夃夅夆夈変夊夌夎夐夑夒夓夔夗夘夛夝夞夡夣夤"
+ "夥夦夨夨夬夯夰夲夳夵夶夹夻夼夽夹夿奀奁奃奂奄奃奅奆奊奌奍奏奂奒奓奘奙奚奛奜奝奞奟奡奣奤奦奨奁奫妸奯奰奱"
+ "奲奵奺奻奼奾奿妀妁妅妉妊妋妌妍妎妏妐妑妔妕妗妘妚妛妜妟妠妡妢妤妦妧妩妫妭妮妯妰妱妲妴妵妶妷妸妺妼妽妿姀"
+ "姁姂姃姄姅姆姇姈姉姊姌姗姎姏姒姕姖姘姙姛姝姞姟姠姡姢姣姤姥奸姧姨姩姫姬姭姮姯姰姱姲姳姴姵姶姷姸姹姺姻姼"
+ "姽姾娀威娂娅娆娈娉娊娋娌娍娎娏娐娑娒娓娔娕娖娗娙娚娱娜娝娞娟娠娡娢娣娤娥娦娧娨娩娪娫娬娭娮娯娰娱娲娳娴"
+ "娵娷娸娹娺娻娽娾娿婀娄婂婃婄婅婇婈婋婌婍婎婏婐婑婒婓婔婕婖婗婘婙婛婜婝婞婟婠婡婢婣婤婥妇婧婨婩婪婫娅婮"
+ "婯婰婱婲婳婵婷婸婹婺婻婼婽婾婿媀媁媂媄媃媅媪媈媉媊媋媌媍媎媏媐媑媒媓媔媕媖媗媘媙媚媛媜媝媜媞媟媠媡媢媣"
+ "媤媥媦媨媩媪媫媬媭妫媰媱媲媳媴媵媶媷媸媹媺媻媪媾嫀嫃嫄嫅嫆嫇嫈嫉嫊袅嫌嫍嫎嫏嫐嫑嫒嫓嫔嫕嫖妪嫘嫙嫚嫛嫜"
+ "嫝嫞嫟嫠嫡嫢嫣嫤嫥嫦嫧嫨嫧嫩嫪嫫嫬嫭嫮嫯嫰嫱嫲嫳嫴嫳妩嫶嫷嫸嫹嫺娴嫼嫽嫾婳妫嬁嬂嬃嬄嬅嬆嬇娆嬉嬊娇嬍嬎"
+ "嬏嬐嬑嬒嬓嬔嬕嬖嬗嬘嫱嬚嬛嬜嬞嬟嬠嫒嬢嬣嬥嬦嬧嬨嬩嫔嬫嬬奶嬬嬮嬯婴嬱嬲嬳嬴嬵嬶嬷婶嬹嬺嬻嬼嬽嬾嬿孀孁孂"
+ "娘孄孅孆孇孆孈孉孊娈孋孊孍孎孏嫫婿媚孑孒孓孖孚孛孜孞孠孡孢孥学孧孨孪孙孬孭孮孯孰孱孲孳孴孵孶孷孹孻孼孽"
+ "孾宄宆宊宍宎宐宑宒宓宔宖実宥宧宨宩宬宭宯宱宲宷宸宺宻宼寀寁寃寈寉寊寋寍寎寏寔寕寖寗寘寙寚寜寝寠寡寣寥寪"
+ "寭寮寯寰寱寲寳寴寷寽対尀専尃尅尌尐尒尕尗尛尜尞尟尠尣尢尥尦尨尩尪尫尬尭尮尯尰尲尳尴尵尶尾屃届屇屈屎屐屑"
+ "屒屓屔屖屗屘屙屚屛屉扉屟屡屣履屦屧屦屩屪屫属敳屮屰屲屳屴屵屶屷屸屹屺屻屼屽屾屿岃岄岅岆岇岈岉岊岋岌岍岎"
+ "岏岐岑岒岓岔岕岖岘岙岚岜岝岞岟岠岗岢岣岤岥岦岧岨岪岫岬岮岯岰岲岴岵岶岷岹岺岻岼岽岾岿峀峁峂峃峄峅峆峇峈"
+ "峉峊峋峌峍峎峏峐峑峒峓崓峖峗峘峚峙峛峜峝峞峟峠峢峣峤峥峦峧峨峩峪峬峫峭峮峯峱峲峳岘峵峷峸峹峺峼峾峿崀崁"
+ "崂崃崄崅崆崇崈崉崊崋崌崃崎崏崐崒崓崔崕崖崘崚崛崜崝崞崟岽崡峥崣崤崥崦崧崨崩崪崫崬崭崮崯崰崱崲嵛崴崵崶崷"
+ "崸崹崺崻崼崽崾崿嵀嵁嵂嵃嵄嵅嵆嵇嵈嵉嵊嵋嵌嵍嵎嵏岚嵑岩嵓嵔嵕嵖嵗嵘嵙嵚嵛嵜嵝嵞嵟嵠嵡嵢嵣嵤嵥嵦嵧嵨嵩嵪"
+ "嵫嵬嵭嵮嵯嵰嵱嵲嵳嵴嵵嵶嵷嵸嵹嵺嵻嵼嵽嵾嵿嶀嵝嶂嶃崭嶅嶆岖嶈嶉嶊嶋嶌嶍嶎嶏嶐嶑嶒嶓嵚嶕嶖嶘嶙嶚嶛嶜嶝嶞"
+ "嶟峤嶡峣嶣嶤嶥嶦峄峃嶩嶪嶫嶬嶭崄嶯嶰嶱嶲嶳岙嶵嶶嶷嵘嶹岭嶻屿岳帋巀巁巂巃巄巅巆巇巈巉巊岿巌巍巎巏巐巑峦"
+ "巓巅巕岩巗巘巙巚巛巜巠巡巢巣巤匘巪巬巭巯巵巶巸卺巺巼巽巿帀币帄帇帉帊帋帍帎帏帑帒帓帔帗帙帚帞帟帠帡帢帣"
+ "帤帨帩帪帬帯帰帱帲帴帵帷帹帺帻帼帽帾帿帧幁幂帏幄幅幆幇幈幉幊幋幌幍幎幏幐幑幒幓幖幙幚幛幜幝幞帜幠幡幢幤"
+ "幥幦幧幨幩幪幭幮幯幰幱幷幺吆玄幼兹滋庀庁仄広庅庇庈庉庋庌庍庎庑庖庘庛庝庞庠庡庢庣庤庥庨庩庪库庬庮庯庰庱"
+ "庲庳庴庵庹庺庻庼庽庿廀厕廃厩廅廆廇廋廌廍庼廏廐廑廒廔廕廖廗廘廙廛廜廞庑廤廥廦廧廨廭廮廯廰痈廲廵廸廹廻廼"
+ "廽廿弁弅弆弇弉弋弌弍弎弐弑弖弙弚弜弝弞弡弢弣弤弨弩弪弫弬弭弮弰弲弪弴弶弸弻弼弽弿彀彁彂彃彄彅彇彉彋弥彍"
+ "彏彑彔彖彗彘彚彛彜彝彞彟彡彣彧彨彭彮彯彲澎彳彴彵彶彷彸役彺彻彽彾佛徂徃徆徇徉后徍徎徏径徒従徔徕徖徙徚徛"
+ "徜徝从徟徕御徢徣徤徥徦徧徨复循徫旁徭微徯徰徱徲徳徴徵徶德徸彻徺徻徼徽徾徿忀忁忂忄惔愔忇忈忉忊忋忎忏忐忑"
+ "忒忓忔忕忖忚忛応忝忞忟忡忢忣忥忦忨忩忪忬忭忮忯忰忱忲忳忴念忶汹忸忹忺忻忼忾忿怂怃怄怅怆怇怈怉怊怋怌怍怏"
+ "怐怑怓怔怗怘怙怚怛怞怟怡怢怣怤怦怩怫怬怭怮怯怰怲怳怴怵怶怷怸怹怺怼悙怿恀恁恂恃恄恅恒恇恈恉恊恌恍恎恏恑"
+ "恒恓恔恖恗恘恙恚恛恜恝恞恠恡恦恧恫恬恮恰恱恲恴恷恹恺恻恽恾恿悀悁悂悃悆悇悈悊悋悌悍悎悏悐悑悒悓悕悖悗悘"
+ "悙悚悛悜悝悞悟悡悢悤悥悧悩悪悫悭悮悰悱悳悴悷悹悺悻悼悾悿惀惁惂惃惄惆惈惉惊惋惌惍惎惏惐惑惒惓惔惕惖惗惘"
+ "惙惚惛惜惝惞惠恶惢惣惤惥惦惧惨惩惪惫惬惮恼恽惴惵惶惸惺惼惽惾惿愀愂愃愄愅愆愇愉愊愋愌愍愎愐愑愒愓愕愖愗"
+ "愘愙愝愞愠愡愢愣愥愦愧愩愪愫愬愭愮愯愰愱愲愳怆愵愶恺愸愹愺愻愼愽忾愿慀慁慂慃栗慅慆慈慉慊态慏慐慑慒慓慔"
+ "慖慗惨慙惭慛慜慝慞恸慠慡慢慥慦慧慨慩怄怂慬悯慯慰慲悭慴慵慷慸慹慺慻慽慿憀憁忧憃憄憅憆憇憈憉惫憋憌憍憎憏"
+ "怜憓憔憕憖憗憘憙憛憜憝憞憟憠憡憢憣愤憥憦憧憨憩憪憬憭怃憯憰憱憳憴憵忆憷憸憹憺憻憼憽憾憿懀懁懂懄懅懆恳懈"
+ "懊懋怿懔懎懏懐懑懓懔懕懖懗懘懙懚懛懜懝怼懠懡懢懑懤懥懦懧恹懩懪懫懬懭懮懯懰懱惩懳懴懵懒怀悬懹忏懻惧懽慑"
+ "懿恋戁戂戃戄戅戆懯戉戊戋戌戍戎戓戋戕彧或戗戙戛戜戝戞戟戠戡戢戣戤戥戦戗戨戬截戫戭戮戱戳戴戵戈戚残牋戸戹"
+ "戺戻戼戽戾扂扃扄扅扆扈扊扏扐払扖扗扙扚扜扝扞扟扠扦扢扣扤扥扦扨扪扭扮扰扲扴扵扷扸抵扻扽抁挸抆抇抈抉抋抌"
+ "抍抎抏抐抔抖抙抝択抟抠抡抣护抦抧抨抩抪抬抮抰抲抳抵抶抷抸抹抺押抻抽抾抿拀拁拃拄拇拈拊拌拎拏拑拓拕拗拘拙"
+ "拚拝拞拠拡拢拣拤拧择拪拫括拭拮拯拰拱拲拳拴拵拶拷拸拹拺拻拼拽拾拿挀挂挃挄挅挆挈挊挋挌挍挎挏挐挒挓挔挕挗"
+ "挘挙挚挛挜挝挞挟挠挡挢挣挦挧挨挩挪挫挬挭挮挰挱挲挳挴挵挷挸挹挺挻挼挽挿捀捁捂捃捄捅捆捇捈捊捋捌捍捎捏捐"
+ "捑捒捓捔捕捖捗捘捙捚捛捜捝捞损捠捡换捣捤捥捦捧舍捩捪扪捬捭据捯捰捱捳捴捵捶捷捸捹捺捻捼捽捾捿掀掁掂扫抡"
+ "掅掆掇授掉掊掋掍掎掐掑排掓掔掕挜掖掘挣掚挂掜掝掞掟掠采探掣掤掦措掫掬掭掮掯掰掱掲掳掴掵掶掸掹掺掻掼掽掾"
+ "掿拣揁揂揃揅揄揆揇揈揉揊揋揌揍揎揑揓揔揕揖揗揘揙揜揝揞揟揠揢揤揥揦揧揨揫捂揰揱揲揳援揵揶揷揸揻揼揾揿搀"
+ "搁搂搃搄搅搇搈搉搊搋搌搎搏搐搑搒搓搔搕搘搙搚搛搝擀搠搡搢搣搤捶搦搧搨搩搪搫搬搮搰搱搲搳搴搵搷搸搹搻搼搽"
+ "榨搿摂摅摈摉摋摌摍摎摏摐掴摒摓摔摕摖摗摙摚摛掼摝摞摠摡摢揸摤摥摦摧摨摪摫摬摭摮挚摰摱摲抠摴摵抟摷摹摺掺"
+ "摼摽摾摿撀撁撂撃撄撅撉撊撋撌撍撎挦挠撒挠撔撖撗撘撙捻撛撜撝挢撠撡掸掸撧撨撩撪撬撮撯撱揿撴撵撶撷撸撹撺挞"
+ "撼撽挝擀擃掳擅擆擈擉擌擎擏擐擑擓擕擖擗擘擙擛擜擝擞擟擡擢擤擥擧擨擩擪擫擭擮摈擳擵擶撷擸擹擽擿攁攂攃摅攅"
+ "撵攇攈攉攊攋攌攍攎拢攐攑攒攓攕撄攗攘搀攚撺攞攟攠攡攒挛攥攦攧攨攩搅攫攭攮攰攱攲攳攴攵攸攺攼攽敀敁敂敃敄"
+ "敆敇敉敊敋敍敐敒敓敔敕敖敚敜敟敠敡敤敥敧敨敩敪敫敭敮敯敱敳敶敹敺敻敼敽敾敿斀斁敛斄斅斆敦斈斉斊斍斎斏斒"
+ "斓斔斓斖斑斘斚斛斝斞斟斠斡斢斣斦斨斪斫斩斮斱斲斳斴斵斶斸斺斻於斾斿旀旃旄旆旇旈旊旍旎旐旑旒旓旔旕旖旘旙"
+ "旚旜旝旞旟旡旣旤兂旪旫旮旯旰旱旲旳旴旵旸旹旻旼旽旾旿昀昁昃昄昅昈昉昊昋昍昐昑昒昕昖昗昘昙昚昛昜昝晻昢昣"
+ "昤春昦昧昩昪昫昬昮昰昱昲昳昴昵昶昷昸昹昺昻昼昽昿晀晁时晃晄晅晆晇晈晋晊晌晍晎晏晐晑晒晓晔晕晖晗晘晙晛晜"
+ "晞晟晠晡晰晣晤晥晦晧晪晫晬晭晰晱晲晳晴晵晷晸晹晻晼晽晾晿暀暁暂暃暄暅暆暇晕晖暊暋暌暍暎暏暐暑暒暓暔暕暖"
+ "暗旸暙暚暛暜暝暞暟暠暡暣暤暥暦暧暨暩暪暬暭暮暯暰昵暲暳暴暵暶暷暸暹暺暻暼暽暾暿曀曁曂曃晔曅曈曊曋曌曍曎"
+ "曏曐曑曒曓曔曕曗曘曙曚曛曜曝曞曟旷曡曢曣曤曥曦曧昽曩曪曫晒曭曮曯曰曱曵曶曷曹曺曻曽朁朂朄朅朆朇最羯肜朊"
+ "朌朎朏朐朑朒朓朕朖朘朙朚朜朞朠朡朣朤朥朦胧朩术朰朲朳枛朸朹朻朼朾朿杁杄杅杆圬杈杉杊杋杍杒杓杔杕杗杘杙杚"
+ "杛杝杞杢杣杤杦杧杩杪杫杬杮柿杰东杲杳杴杵杶杷杸杹杺杻杼杽枀枂枃枅枆枇枈枊枋枌枍枎枏析枑枒枓枔枖枘枙枛枞"
+ "枟枠枡枤枥枦枧枨枩枬枭枮枰枱枲枳枵枷枸枹枺枻枼枽枾枿柀柁柂柃柄柅柆柇柈柉柊柋柌柍柎柒柕柖柗柘柙查楂呆柙"
+ "柚柛柜柝柞柟柠柡柢柣柤柦柧柨柩柪柬柭柮柯柰柲柳栅柶柷柸柹拐査柼柽柾栀栁栂栃栄栆栈栉栊栋栌栍栎栐旬栔栕栗"
+ "栘栙栚栛栜栝栞栟栠栢栣栤栥栦栧栨栩株栫栬栭栮栯栰栱栲栳栴栵栶核栺栻栽栾栿桀桁桂桄桅桇桉桊桋桍桎桏桒桕桖"
+ "桗桘桙桚桛桜桝桞桟桠桡桢档桤桦桧桨桩桪桫桬桭杯桯桰桱桲桳桴桵桶桷桸桹桺桻桼桽桾杆梀梁梂梃梄梅梆梇梈梉枣"
+ "梌梍梎梏梐梑梒梓梕梖梗枧梙梚梛梜梞梠梡梢梣梤梥梧梩梪梫梬梭梮梯械梲梴梵梶梷梸梹梺梻梼梽梾梿检棁棂棃棅棆"
+ "棇棈棉棊棋棌棍棎棏棐棒棓棔棕枨枣棘棙棚棛棜棝棞栋棠棡棢棣棤棥棦棨棩棪棫桊棭棯棰棱栖棳棴棵梾棷棸棹棺棻棼"
+ "棽棾棿椀椁椂椃椄椆椇椈椉椊椋椌椎桠椐椒椓椔椕椖椗椘椙椚椛検椝椞椟椠椡椢椣椤椥椦椧椨椩椪椫椬椭椮椯椰椱椲"
+ "椳椴椵椶椷椸椹椺椻椼椽椾椿楀楁楂楃楅楆楇楈楉杨楋楌楍楎楏楐楑楒楔楕楖楗楘楛楜楝楞楟楠楡楢楣楤楥楦楧桢楩"
+ "楪楫楬楮椑楯楰楱楲楳楴极楶榉榊榋榌楷楸楹楺楻楽楾楿榀榁榃榄榅榆榇榈榉榊榋榌榍槝搌榑榒榓榔榕榖榗榘榙榚榛"
+ "榜榝榞榟榠榡榢榣榤榥榧榨榩杩榫榬榭榯榰榱榲榳榴榵榶榷榸榹榺榻榼榽榾桤槀槁槂盘槄槅槆槇槈槉槊构槌枪槎槏槐"
+ "槑槒杠槔槕槖槗様槙槚槛槜槝槞槟槠槡槢槣槥槦椠椁槩槪槫槬槭槮槯槰槱槲桨槴槵槶槷槸槹槺槻槼槽槾槿樀桩樃樄枞"
+ "樆樇樈樉樊樋樌樍樎樏樐樒樔樕樖樗樘樚樛樜樝樟樠樢样樤樥樦樧樨権横樫樬樭樮樯樰樱樲樳樴樵樶樷朴树桦樻樼樽"
+ "樾樿橀橁橂橃橄橅橆橇桡橉橊桥橌橍橎橏橐橑橒橓橔橕橖橗橘橙橚橛橜橝橞橠橡椭橣橤橥橧橨橩橪橬橭橮橯橰橱橲橳"
+ "橴橵橶橷橸橹橺橻橼柜橿檀檩檂檃檄檅檆檇檈柽檊檋檌檍檎檏檐檑檒檓档檕檖檗檘檙檚檛桧檝檞槚檠檡检樯檤檥檦檧"
+ "檨檩檪檫檬檭梼檰檱檲槟檴檵檶栎柠檹檺槛檼檽桐檿櫀櫁棹柜櫄櫅櫆櫇櫈櫉櫊櫋櫌櫍櫎櫏累櫑櫒櫔櫕櫖櫗櫘櫙榈栉櫜"
+ "椟橼櫠櫡櫢櫣櫤橱櫦槠栌櫩枥橥榇櫭櫮櫯櫰櫱櫲栊櫴櫵櫶櫷榉櫹櫼櫽櫾櫿欀欁欂欃栏欅欆欇欈欉权欋欌欍欎椤欐欑栾"
+ "欓欔欕榄欗欘欙欚欛欜欝棂欟欤欥欦欨欩欪欫欬欭欮欯欰欱欳欴欵欶欷唉欹欻欼钦款欿歀歁歂歃歄歅歆歇歈歉歊歋歍"
+ "欧歑歒歓歔殓歗歘歙歚歛歜歝歞欤歠欢钦歧歨歩歫歬歭歮歯歰歱歳歴歵歶歾殁殁殂殃殄殅殆殇殈殉殌殍殎殏殐殑殒殓"
+ "殔殕殖殗残殙殚殛殜殝殒殟殠殡殢殣殇殥殦殧殨殩殪殚殬殰殱歼殶殸殹殾殿毂毃毄毅殴毇毈毉毊母毋毎毐毑毓坶拇毖"
+ "毗毘坒陛屁芘楷砒玭昆吡纰妣锴鈚秕庇沘毜毝毞毟毠毡毢毣毤毥毦毧毨毩毪毫毬毭毮毯毰毱毲毳毴毵毶毷毸毹毺毻毼"
+ "毽毾毵氀氁氂氃氋氄氅氆氇毡氉氊氍氎氒氐抵坻坁胝阍痻泜汦茋芪柢砥奃睧眡蚳蚔呧軧軝崏弤婚怟惛忯岻貾氕氖気氘"
+ "氙氚氜氝氞氟氠氡氢氤氥氦氧氨氩氪氭氮氯氰氱氲氶氷凼氺氻氼氽氾氿汀汃汄汅氽汈汊汋汌泛汏汐汑汒汓汔汕汖汘污"
+ "汚汛汜汞汢汣汥汦汧汨汩汫汬汭汮汯汰汱汲汳汴汵汶汷汸汹汻汼汾汿沀沂沃沄沅沆沇沊沋沌冱沎沏洓沓沔沕沗沘沚沛"
+ "沜沝沞沠沢沣沤沥沦沨沩沪沫沬沭沮沯沰沱沲沴沵沶沷沸沺沽泀泂泃泅泆泇泈泋泌泍泎泏泐泑泒泓泔泖泗泘泙泚泜溯"
+ "泞泟泠泤泦泧泩泫泬泭泮泯泱泲泴泵泶泷泸泹泺泾泿洀洂洃洄洅洆洇洈洉洊洌洍洎洏洐洑洒洓洔洕洖洘洙洚洜洝洠洡"
+ "洢洣洤洦洧洨洫洬洭洮洯洰洱洳洴洵洷洸洹洺洼洽洿浀浂浃浄浈浉浊浌浍浏浐浒浔浕浖浗浘浚浛浜浝浞浟浠浡浢浣浤"
+ "浥浦浧浨浫浭浯浰浱浲浳浵浶浃浺浻浼浽浾浿涀涁涂涃涄涅涆泾涊涋涍涎涐涑涒涓涔涖涗涘涙涚涜涝涞涟涠涡涢涣涤"
+ "涥涧涪涫涬涭涰涱涳涴涶涷涸涹涺涻凉涽涾涿淁淂淃淄淅淆淇淈淉淊淌淍淎淏淐淓淔淕淖淗淙淛淜淞淟淠淢淣淤渌淦"
+ "淧沦淬淭淯淰淲淳淴涞滍淾淿渀渁渂渃渄渆渇済渋渌渍渎渏渑渒渓渕渖渘渚渜渝渞渟沨渥渧渨渪渫渮渰渱渲渳渵渶渷"
+ "渹渻渼渽渿湀湁湂湄湅湆湇湈湉湋湌湍湎湏湐湑湒湓湔湕湗湙湚湜湝浈湟湠湡湢湤湥湦湨湩湪湫湬湭湮湰湱湲湳湴湵"
+ "湶湷湸湹湺湻湼湽満溁溂溄溆溇沩溉溊溋溌溍溎溏溑溒溓溔溕溗溘溙溚溛溞溟溠溡溣溤溥溦溧溨溩溬溭溯溰溱溲涢溴"
+ "溵溶溷溸溹溻溽溾溿滀滁滂滃沧滆滇滈滉滊涤滍荥滏滐滒滓滖滗滘滙滛滜滝滞滟滠滢滣滦滧滪滫沪滭滮滰滱渗滳滵滶"
+ "滹滺浐滼滽漀漃漄漅漈漉溇漋漌漍漎漐漑澙熹漗漘漙沤漛漜漝漞漟漡漤漥漦漧漨漪渍漭漮漯漰漱漳漴溆漶漷漹漺漻漼"
+ "漽漾浆潀颍潂潃潄潅潆潇潈潉潊潋潌潍潎潏潐潒潓洁潕潖潗潘沩潚潜潝潞潟潠潡潢潣润潥潦潧潨潩潪潫潬潭浔溃潱潲"
+ "潳潴潵潶滗潸潹潺潻潼潽潾涠澁澄澃澅浇涝澈澉澊澋澌澍澎澏湃澐澑澒澓澔澕澖涧澘澙澚澛澜澝澞澟渑澢澣泽澥滪澧"
+ "澨澪澫澬澭浍澯澰淀澲澳澴澵澶澷澸澹澺澻澼澽澾澿濂濄濅濆濇濈濉濊濋濌濍濎濏濐濑濒濓沵濖濗泞濙濚濛浕濝濞济"
+ "濠濡濢濣涛濥濦濧濨濩濪滥浚濭濮濯潍滨濲濳濴濵濶濷濸濹溅濻泺濽滤濿瀀漾瀂瀃灋渎瀇瀈泻瀊沈瀌瀍瀎浏瀐瀒瀓瀔"
+ "濒瀖瀗泸瀙瀚瀛瀜瀞潇潆瀡瀢瀣瀤瀥潴泷濑瀩瀪瀫瀬瀭瀮瀯弥瀱潋瀳瀴瀵瀶瀷瀸瀹瀺瀻瀼瀽澜瀿灀灁瀺灂沣滠灅灆灇"
+ "灈灉灊灋灌灍灎灏灐洒灒灓漓灖灗滩灙灚灛灜灏灞灟灠灡灢湾滦灥灦灧灨灪灮灱灲灳灴灷灸灹灺灻灼炀炁炂炃炄炅炆"
+ "炇炈炋炌炍炏炐炑炓炔炕炖炗炘炙炚炛炜炝炞炟炠炡炢炣炤炥炦炧炨炩炪炫炯炰炱炲炳炴炵炶炷炻炽炾炿烀烁烃烄烅"
+ "烆烇烉烊烋烌烍烎烐烑烒烓烔烕烖烗烙烚烜烝烞烠烡烢烣烥烩烪烯烰烱烲烳烃烵烶烷烸烹烺烻烼烾烿焀焁焂焃焄焇焈"
+ "焉焋焌焍焎焏焐焑焒焓焔焕焖焗焘焙焛焜焝焞焟焠焢焣焤焥焧焨焩焪焫焬焭焮焯焱焲焳焴焵焷焸焹焺焻焼焽焾焿煀煁"
+ "煂煃煄煅煇煈炼煊煋煌煍煎煏煐煑炜煓煔暖煗煘煚煛煜煝煞煟煠煡茕煣焕煦煨煪煫炀煭煯煰煱煲煳煴煵煶煷煸煹煺煻"
+ "煼煽煾煿熀熁熂熃熄熅熆熇熈熉熋熌熍熎熏熐熑荧熓熔熕熖炝熘熚熛熜熝熞熠熡熢熣熤熥熦熧熨熩熪熫熬熭熮熯熰颎"
+ "熳熴熵熶熷熸熹熺熻熼熽炽熿燀烨燂燅燆燇炖燊燋燌燍燎燏燐燑燓燔燖燗燘燚燛燝燞燠燡燢燣燤燥灿燧燨燩燪燫燮燯"
+ "燰燱燲燳烩燵燵燸燹燺薰燽焘燿爀爁爂爃爄爅爇爈爉爊爋爌烁爎爏爑爒爓爔爕爖爗爘爙爚烂爜爝爞爟爠爡爢爣爤爥爦"
+ "爧爨爩爮爯爰爳爴舀爷爻爼爽牀牁牂牃牄牅牊牉牋牍牎牏牐牑牒牓牔牕牖牗牚芽牜牝牞牟牣牤牥牦牨牪牫牬牭牮牯牰"
+ "牱牳牴牶牷牸牻牼牾牿犂犃犄犅犆犇犈犉犊犋犌犍犎犏犐犑犒犓犔犕荦犗犘犙犚牦犜犝犞犟犠犡犣犤犥犦牺犨犩犪犫"
+ "犭犰犱犲犳犴犵犷犸犹犺犻犼犽犾犿狘狁狃狄狅狆狇狉狊狋狌狍狎狏狑狒狓狔狕狖狙狚狛狜狝狞狟狡猯狢狣狤狥狦狧"
+ "狨狩狪狫狭狮狯狰狱狲狳狴狵狶狷狭狺狻狾狿猀猁猂猃猄猅猆猇猈猉猊猋猌猍猑猒猓猔猕猗猘狰猚猝猞猟猠猡猢猣猤"
+ "猥猦猧猨猬猭猰猱猲猳猵犹猷猸猹猺狲猼猽猾獀犸獂獆獇獈獉獊獋獌獍獏獐獑獒獓獔獕獖獗獘獙獚獛獜獝獞獟獠獡獢"
+ "獣獤獥獦獧獩狯猃獬獭狝獯狞獱獳獴獶獹獽獾獿猡玁玂玃")
}
} | 0 | Kotlin | 2 | 4 | 24ef998a28c3217dacc526722fc0782e42b38d2c | 11,808 | RandomGenerator | MIT License |
src/main/kotlin/me/nepnep/nepbot/music/MusicManager.kt | NepNep21 | 332,348,863 | false | null | package me.nepnep.nepbot.music
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers
object MusicManager {
val audioPlayerManager = DefaultAudioPlayerManager()
// Long is the guild
val players = mutableMapOf<Long, TrackScheduler>()
init {
AudioSourceManagers.registerRemoteSources(audioPlayerManager)
}
} | 0 | Kotlin | 1 | 2 | 9652ca68693218526660e12b1246643b59a7d120 | 421 | nepbot | MIT License |
lang/jap/src/main/kotlin/com/yandex/yatagan/lang/jap/JavaxTypeImpl.kt | yandex | 570,094,802 | false | {"Kotlin": 1455421} | /*
* Copyright 2022 Yandex LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yandex.yatagan.lang.jap
import com.yandex.yatagan.lang.Type
import com.yandex.yatagan.lang.TypeDeclaration
import com.yandex.yatagan.lang.common.NoDeclaration
import com.yandex.yatagan.lang.compiled.CtErrorType
import com.yandex.yatagan.lang.compiled.CtTypeBase
import com.yandex.yatagan.lang.compiled.CtTypeNameModel
import com.yandex.yatagan.lang.compiled.InvalidNameModel
import com.yandex.yatagan.lang.scope.FactoryKey
import com.yandex.yatagan.lang.scope.LexicalScope
import com.yandex.yatagan.lang.scope.caching
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
internal class JavaxTypeImpl private constructor(
lexicalScope: LexicalScope,
wrapped: TypeMirrorEquivalence,
) : CtTypeBase(), LexicalScope by lexicalScope {
val impl: TypeMirror = wrapped.get()
override val nameModel: CtTypeNameModel by lazy { CtTypeNameModel(impl) }
override val declaration: TypeDeclaration by lazy {
if (impl.kind == TypeKind.DECLARED) {
JavaxTypeDeclarationImpl(impl.asDeclaredType())
} else NoDeclaration(this)
}
override val isVoid: Boolean
get() = impl.kind == TypeKind.VOID
override fun asBoxed(): Type {
return Factory(if (impl.kind.isPrimitive) {
Utils.types.boxedClass(impl.asPrimitiveType()).asType()
} else impl)
}
override val typeArguments: List<Type> by lazy {
when (impl.kind) {
TypeKind.DECLARED -> impl.asDeclaredType().typeArguments.map { type ->
Factory(when(type.kind) {
TypeKind.WILDCARD -> type.asWildCardType().let {
it.extendsBound ?: it.superBound ?: Utils.objectType.asType()
}
else -> type
})
}
else -> emptyList()
}
}
override fun isAssignableFrom(another: Type): Boolean {
return when (another) {
is JavaxTypeImpl -> Utils.types.isAssignable(another.impl, impl)
else -> false
}
}
companion object Factory : FactoryKey<TypeMirror, Type> {
private object Caching : FactoryKey<TypeMirrorEquivalence, JavaxTypeImpl> {
override fun LexicalScope.factory() = caching(::JavaxTypeImpl)
}
override fun LexicalScope.factory() = fun LexicalScope.(impl: TypeMirror): Type {
return when (impl.kind) {
TypeKind.ERROR -> CtErrorType(
nameModel = InvalidNameModel.Unresolved(hint = impl.toString())
)
TypeKind.TYPEVAR -> CtErrorType(
nameModel = InvalidNameModel.TypeVariable(
typeVar = impl.asTypeVariable().asElement().simpleName.toString(),
)
)
TypeKind.DECLARED -> {
if (impl.asTypeElement().qualifiedName.contentEquals("error.NonExistentClass"))
CtErrorType(nameModel = InvalidNameModel.Unresolved(hint = "error.NonExistentClass"))
else Caching(TypeMirrorEquivalence(impl))
}
else -> Caching(TypeMirrorEquivalence(impl))
}
}
}
} | 11 | Kotlin | 10 | 231 | d0d7b823711c7f5a48cfd76d673ad348407fd904 | 3,836 | yatagan | Apache License 2.0 |
core/design/src/test/kotlin/cn/wj/android/cashbook/core/design/BackgroundScreenshotTests.kt | WangJie0822 | 365,932,300 | false | {"Kotlin": 1658612, "Java": 1405038, "Batchfile": 535} | /*
* Copyright 2021 The Cashbook Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.wj.android.cashbook.core.design
import androidx.activity.ComponentActivity
import androidx.compose.material3.Text
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import cn.wj.android.cashbook.core.design.component.CashbookBackground
import cn.wj.android.cashbook.core.design.component.CashbookGradientBackground
import cn.wj.android.cashbook.core.testing.util.captureMultiTheme
import dagger.hilt.android.testing.HiltTestApplication
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(application = HiltTestApplication::class, qualifiers = "480dpi")
@LooperMode(LooperMode.Mode.PAUSED)
class BackgroundScreenshotTests {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun cashbookBackground_multipleThemes() {
composeTestRule.captureMultiTheme(name = "Background") { description ->
CashbookBackground {
Text(text = "$description background")
}
}
}
@Test
fun cashbookGradientBackground_multipleThemes() {
composeTestRule.captureMultiTheme(
name = "Background",
overrideFileName = "GradientBackground",
) { description ->
CashbookGradientBackground {
Text(text = "$description background")
}
}
}
}
| 7 | Kotlin | 11 | 71 | 6c39b443a1e1e46cf3c4533db3ab270df1f1b9e8 | 2,247 | Cashbook | Apache License 2.0 |
core/design/src/test/kotlin/cn/wj/android/cashbook/core/design/BackgroundScreenshotTests.kt | WangJie0822 | 365,932,300 | false | {"Kotlin": 1658612, "Java": 1405038, "Batchfile": 535} | /*
* Copyright 2021 The Cashbook Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.wj.android.cashbook.core.design
import androidx.activity.ComponentActivity
import androidx.compose.material3.Text
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import cn.wj.android.cashbook.core.design.component.CashbookBackground
import cn.wj.android.cashbook.core.design.component.CashbookGradientBackground
import cn.wj.android.cashbook.core.testing.util.captureMultiTheme
import dagger.hilt.android.testing.HiltTestApplication
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(application = HiltTestApplication::class, qualifiers = "480dpi")
@LooperMode(LooperMode.Mode.PAUSED)
class BackgroundScreenshotTests {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun cashbookBackground_multipleThemes() {
composeTestRule.captureMultiTheme(name = "Background") { description ->
CashbookBackground {
Text(text = "$description background")
}
}
}
@Test
fun cashbookGradientBackground_multipleThemes() {
composeTestRule.captureMultiTheme(
name = "Background",
overrideFileName = "GradientBackground",
) { description ->
CashbookGradientBackground {
Text(text = "$description background")
}
}
}
}
| 7 | Kotlin | 11 | 71 | 6c39b443a1e1e46cf3c4533db3ab270df1f1b9e8 | 2,247 | Cashbook | Apache License 2.0 |
app/src/main/java/com/nuevo/gameness/ui/pages/personal/tournaments/detail/tournamentroom/refereechat/RefereeChatAdapter.kt | arbabkh | 873,814,880 | false | {"Kotlin": 538078} | package com.nuevo.gameness.ui.pages.personal.tournaments.detail.tournamentroom.refereechat
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.nuevo.gameness.data.model.tournamentrefereemessages.TournamentRefereeUserChatItem
import com.nuevo.gameness.databinding.ItemReceivedMessageBinding
import com.nuevo.gameness.databinding.ItemSendImageBinding
import com.nuevo.gameness.databinding.ItemSendMessageNoProfileBinding
import com.nuevo.gameness.utils.load
class RefereeChatAdapter(
private val itemList: ArrayList<TournamentRefereeUserChatItem> = arrayListOf()
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
private const val VIEW_TYPE_SEND_MESSAGE = 1
private const val VIEW_TYPE_SEND_IMAGE = 2
private const val VIEW_TYPE_RECEIVER = 3
}
class SendMessageViewHolder(
private val binding: ItemSendMessageNoProfileBinding
): RecyclerView.ViewHolder(binding.root) {
fun bind(item: TournamentRefereeUserChatItem) {
binding.apply {
root.rotation = 180F
textViewMessage.text = item.message
}
}
}
inner class SendImageViewHolder(
private val binding: ItemSendImageBinding,
private val context: Context
): RecyclerView.ViewHolder(binding.root) {
fun bind(item: TournamentRefereeUserChatItem) {
binding.apply {
root.rotation = 180F
imageViewMessage.load(context, item.message)
}
}
}
class ReceivedMessageViewHolder(
private val binding: ItemReceivedMessageBinding
): RecyclerView.ViewHolder(binding.root) {
fun bind(item: TournamentRefereeUserChatItem) {
binding.apply {
root.rotation = 180F
textViewMessage.text = item.message
}
}
}
override fun getItemViewType(position: Int): Int {
return if (itemList[position].isAdminResponse == false) {
if (itemList[position].messageType == 2) VIEW_TYPE_SEND_IMAGE
else VIEW_TYPE_SEND_MESSAGE
} else VIEW_TYPE_RECEIVER
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val context = parent.context
val inflater = LayoutInflater.from(context)
return when (viewType) {
VIEW_TYPE_SEND_MESSAGE -> SendMessageViewHolder(
ItemSendMessageNoProfileBinding.inflate(inflater, parent, false)
)
VIEW_TYPE_SEND_IMAGE -> SendImageViewHolder(
ItemSendImageBinding.inflate(inflater, parent, false),
context
)
else -> ReceivedMessageViewHolder(
ItemReceivedMessageBinding.inflate(inflater, parent, false)
)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when(holder) {
is SendMessageViewHolder -> holder.bind(itemList[position])
is SendImageViewHolder -> holder.bind(itemList[position])
is ReceivedMessageViewHolder -> holder.bind(itemList[position])
}
}
override fun getItemCount(): Int = itemList.size
fun updateAllData(newList: List<TournamentRefereeUserChatItem>) {
itemList.clear()
itemList.addAll(newList)
notifyDataSetChanged()
}
fun addData(position: Int, item: TournamentRefereeUserChatItem) {
itemList.add(position, item)
notifyItemInserted(position)
}
} | 0 | Kotlin | 0 | 0 | 80d7b04385a2cd516b8157dbea19dd821c30fcc9 | 3,668 | gameness-android | MIT License |
app/src/main/java/com/puntogris/posture/domain/repository/SyncRepository.kt | puntogris | 398,388,678 | false | null | package com.puntogris.posture.domain.repository
import com.puntogris.posture.domain.model.UserPrivateData
import com.puntogris.posture.utils.SimpleResult
interface SyncRepository {
suspend fun syncAccount(authUser: UserPrivateData?): SimpleResult
suspend fun syncAccountExperience()
}
| 0 | Kotlin | 2 | 7 | 099ba90c707c308047c43b1536f92f450f59c772 | 297 | posture-reminder | MIT License |
app/src/main/java/com/dreamit/androidquiz/utils/QuizRatesUtils.kt | mkAndroDev | 142,674,492 | false | null | package com.dreamit.androidquiz.utils
import com.dreamit.androidquiz.quizitem.model.Answer
import com.dreamit.androidquiz.quizitem.model.Rate
class QuizRatesUtils {
companion object {
fun getValidResultAsPercent(validQuestionsCount: Int, totalAnswers: Int): Int {
return validQuestionsCount * 100 / totalAnswers
}
fun getRateText(resultAsPercent: Int, rates: List<Rate>): String {
return rates.find {
resultAsPercent >= it.from && resultAsPercent <= it.to
}?.content ?: ""
}
fun isAnswerCorrect(userAnswerId: Int, answers: List<Answer>): Boolean {
return userAnswerId == answers.indexOf(answers.first { it.isCorrect == 1 })
}
}
} | 0 | Kotlin | 0 | 0 | eabf29df22080fcb6c4656b638ef1f6c5cc004f4 | 755 | AndroidQuiz | MIT License |
shared/src/commonMain/kotlin/by/game/binumbers/tutorial/domain/model/TutorialAction.kt | alexander-kulikovskii | 565,271,232 | false | {"Kotlin": 454229, "Swift": 3274, "Ruby": 2480, "Shell": 622} | package by.game.binumbers.tutorial.domain.model
import by.game.binumbers.base.BinumbersAction
sealed class TutorialAction : BinumbersAction {
object Load : TutorialAction()
object OnClickDone : TutorialAction()
}
| 0 | Kotlin | 0 | 10 | 66b1678b47a96a52ebef467111d1d4854a37486a | 223 | 2048-kmm | Apache License 2.0 |
lib/src/main/kotlin/org/konigsoftware/kontext/KonigKontext.kt | konigsoftware | 690,328,441 | false | {"Kotlin": 31037} | package org.konigsoftware.kontext
import io.grpc.Context
class KonigKontext<KontextValue> private constructor(
internal val konigKontextKey: KonigKontextKey<KontextValue>,
internal val konigKontextValue: KontextValue
) {
companion object {
@JvmStatic
fun <KontextValue> withValue(key: KonigKontextKey<KontextValue>, value: KontextValue): KonigKontext<KontextValue> =
KonigKontext(key, value)
@JvmStatic
fun <KontextValue> getValue(key: KonigKontextKey<KontextValue>): KontextValue = key.grpcContextKey.get() ?: key.defaultValue
}
fun run(r: Runnable) {
Context.current().withValue(konigKontextKey.grpcContextKey, konigKontextValue).run(r)
}
}
suspend fun <T, KontextValue> withKonigKontext(
konigKontext: KonigKontext<KontextValue>,
block: suspend () -> T
): T {
val context =
Context.current().withValue(konigKontext.konigKontextKey.grpcContextKey, konigKontext.konigKontextValue)
val oldContext: Context = context.attach()
return try {
block()
} finally {
context.detach(oldContext)
}
}
| 5 | Kotlin | 0 | 1 | cdfe2ab61f32625d5300c9dcd3c17c82079cc6ec | 1,122 | konig-kontext | MIT License |
main.kt | fpeterek | 138,159,931 | false | {"Kotlin": 2465} | package swing
import java.awt.*
import java.util.*
import javax.swing.*
fun main(args: Array<String>) {
val win = Window()
}
class Window: JFrame("Swing test") {
private val rand = Random()
private val panel = JPanel()
init {
panel.layout = GridLayout(3, 1)
contentPane.add(panel)
}
private val colorPanel = JPanel()
init {
colorPanel.layout = GridLayout(3, 2)
panel.add(colorPanel)
}
private var r = 0
private val rSlider = JSlider()
private var rLabel = Label()
init {
rSlider.minimum = 0
rSlider.maximum = 255
rSlider.addChangeListener { rValueChanged() }
colorPanel.add(rLabel)
colorPanel.add(rSlider)
}
private fun rValueChanged() {
r = rSlider.value
rLabel.text = "Red: $r"
colorChanged()
}
private var g = 0
private val gSlider = JSlider()
private var gLabel = Label()
init {
gSlider.minimum = 0
gSlider.maximum = 255
gSlider.addChangeListener { gValueChanged() }
colorPanel.add(gLabel)
colorPanel.add(gSlider)
}
private fun gValueChanged() {
g = gSlider.value
gLabel.text = "Green: $g"
colorChanged()
}
private var b = 0
private val bSlider = JSlider()
private var bLabel = Label()
init {
bSlider.minimum = 0
bSlider.maximum = 255
bSlider.addChangeListener { bValueChanged() }
colorPanel.add(bLabel)
colorPanel.add(bSlider)
}
private fun bValueChanged() {
b = bSlider.value
bLabel.text = "Blue: $b"
colorChanged()
}
private val canvas = Canvas()
init {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
canvas.background = Color(r, g, b)
panel.add(canvas)
randomColor()
size = Dimension(600, 400)
isVisible = true
println("Init")
}
private val button = Button()
init {
button.label = "Random Color"
button.addActionListener { randomColor() }
panel.add(button)
}
private fun randomColor() {
rSlider.value = rand.nextInt(255)
gSlider.value = rand.nextInt(255)
bSlider.value = rand.nextInt(255)
rValueChanged()
bValueChanged()
gValueChanged()
}
private fun colorChanged() {
canvas.background = Color(r, g, b)
}
} | 0 | Kotlin | 0 | 0 | b53c9be19a3b5cb842cb04999c751bf49a7eb352 | 2,465 | ColorPicker | MIT License |
library/src/commonMain/kotlin/dev/toastbits/ytmkt/endpoint/LikedArtistsEndpoint.kt | toasterofbread | 771,753,101 | false | {"Kotlin": 244150, "Nix": 2896} | package dev.toastbits.ytmkt.endpoint
import dev.toastbits.ytmkt.model.AuthenticatedApiEndpoint
import dev.toastbits.ytmkt.model.external.mediaitem.YtmArtist
abstract class LikedArtistsEndpoint: AuthenticatedApiEndpoint() {
/**
* Loads the authenticated user's liked artists.
*
* @return the list of liked artists.
*/
abstract suspend fun getLikedArtists(): Result<List<YtmArtist>>
}
| 2 | Kotlin | 6 | 8 | 51aaf1c093afb4fff09db8dcd493463b4228d6c9 | 414 | ytm-kt | Apache License 2.0 |
app/src/main/java/com/felipersn/itaurepositorylist/presentation/repositorylist/RepositoryListActivity.kt | FelipeRsN | 227,366,438 | false | null | package com.felipersn.itaurepositorylist.presentation.repositorylist
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.felipersn.itaurepositorylist.R
import com.felipersn.itaurepositorylist.common.extension.longToast
import com.felipersn.itaurepositorylist.common.utils.EndlessScrollEventListener
import com.felipersn.itaurepositorylist.common.utils.EndlessScrollEventListener.OnLoadMoreListener
import com.felipersn.itaurepositorylist.common.utils.Resource
import com.felipersn.itaurepositorylist.data.model.Repository
import com.felipersn.itaurepositorylist.presentation.pullrequest.PullRequestsActivity
import com.felipersn.itaurepositorylist.presentation.repositorylist.adapter.RepositoryListAdapter
import com.felipersn.itaurepositorylist.presentation.repositorylist.adapter.RepositoryListAdapterListener
import kotlinx.android.synthetic.main.activity_repository_list.*
import org.koin.android.ext.android.inject
import org.koin.android.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
class RepositoryListActivity : AppCompatActivity(), RepositoryListAdapterListener {
//injections
private val repositoryListAdapter: RepositoryListAdapter by inject { parametersOf(this) }
private val repositoryListViewModel: RepositoryListViewModel by viewModel()
private lateinit var endlessScrollEventListener: EndlessScrollEventListener
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_repository_list)
initView()
updateNumberOfResultsLabel(0)
repositoryListViewModel.getRepositoryList()
}
//init methods, variables and requests
private fun initView() {
setupRecyclerView()
setupListeners()
setupObservers()
}
private fun setupListeners() {
repositoryList_swipeRefresh?.setOnRefreshListener {
repositoryListViewModel.getRepositoryList(true)
repositoryListAdapter.clearList()
endlessScrollEventListener.reset()
updateNumberOfResultsLabel(0)
}
endlessScrollEventListener.mOnLoadMoreListener = object : OnLoadMoreListener {
override fun loadMore() {
repositoryListViewModel.getRepositoryList()
}
}
}
private fun setupRecyclerView() {
endlessScrollEventListener = EndlessScrollEventListener((repositoryList_list.layoutManager as LinearLayoutManager))
repositoryList_list?.adapter = repositoryListAdapter
repositoryList_list?.addOnScrollListener(endlessScrollEventListener)
}
private fun updateNumberOfResultsLabel(results: Int) {
repositoryList_listStatus?.text = String.format(getString(R.string.repositoryList_numberOfResults), results)
}
private fun setupObservers() {
repositoryListViewModel.repositoryListLiveData.observe(this, Observer { singleLiveEvent ->
singleLiveEvent.getContentIfNotHandled()?.let { resource ->
when (resource.status) {
Resource.Status.SUCCESS -> {
val response = resource.data
repositoryListAdapter.addList(response?.items!!)
updateNumberOfResultsLabel(repositoryListAdapter.itemCount)
toggleSwipeRefresh(false)
endlessScrollEventListener.isLoading = false
}
Resource.Status.LOADING -> {
toggleSwipeRefresh(true)
endlessScrollEventListener.isLoading = true
}
Resource.Status.ERROR -> {
toggleSwipeRefresh(false)
endlessScrollEventListener.isLoading = false
longToast(getString(R.string.repositoryList_error))
}
}
}
})
}
override fun onRepositoryClicked(repository: Repository) {
startActivity(PullRequestsActivity.providePullRequestIntent(this, repository.name, repository.owner?.login))
}
private fun toggleSwipeRefresh(show: Boolean) {
when (show) {
true -> {
if (!repositoryList_swipeRefresh?.isRefreshing!!) {
repositoryList_swipeRefresh?.isRefreshing = true
}
}
false -> {
if (repositoryList_swipeRefresh?.isRefreshing!!) {
repositoryList_swipeRefresh?.isRefreshing = false
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | a498396ecb75518763e3fd0588b87f87e2b5aae6 | 4,756 | Itau_RepositoryListTest | MIT License |
app/src/main/java/com/waryozh/simplestepcounter/services/StepCounter.kt | Waryozh | 202,525,623 | false | null | package com.waryozh.simplestepcounter.services
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.Transformations
import com.waryozh.simplestepcounter.App
import com.waryozh.simplestepcounter.R
import com.waryozh.simplestepcounter.injection.StepCounterServiceComponent
import com.waryozh.simplestepcounter.repositories.Repository
import com.waryozh.simplestepcounter.ui.MainActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import javax.inject.Inject
class StepCounter : LifecycleService(), SensorEventListener {
companion object {
private const val PRIMARY_CHANNEL_ID = "primary_notification_channel"
private const val NOTIFICATION_ID = 1234
}
@Inject lateinit var repository: Repository
private lateinit var notificationManager: NotificationManager
private lateinit var notificationBuilder: NotificationCompat.Builder
private lateinit var sensorManager: SensorManager
private val stepsTaken: LiveData<Int> by lazy {
Transformations.map(repository.today) { it?.steps ?: 0 }
}
private val stepCounterJob = Job()
private val stepCounterScope = CoroutineScope(Dispatchers.Main + stepCounterJob)
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
(application as App).appComponent
.plus(StepCounterServiceComponent.Module())
.inject(this)
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel =
NotificationChannel(PRIMARY_CHANNEL_ID, getString(R.string.notification_channel_name), NotificationManager.IMPORTANCE_LOW)
notificationManager.createNotificationChannel(notificationChannel)
}
val contentPendingIntent = PendingIntent.getActivity(
this,
NOTIFICATION_ID,
Intent(this, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
notificationBuilder = NotificationCompat.Builder(this, PRIMARY_CHANNEL_ID).apply {
setSmallIcon(R.drawable.ic_directions_run_white_24dp)
setContentIntent(contentPendingIntent)
setOngoing(true)
setAutoCancel(false)
setOnlyAlertOnce(true)
setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
priority = NotificationCompat.PRIORITY_LOW
color = ContextCompat.getColor(this@StepCounter, R.color.color_activity_background)
setColorized(true)
}
repository.setServiceRunning(true)
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
val stepCounterSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
if (stepCounterSensor != null) {
stepsTaken.observe(this, Observer {
notifyWithTitle(getString(R.string.steps_taken, stepsTaken.value))
})
repository.setStepCounterAvailable(true)
sensorManager.registerListener(this, stepCounterSensor, SensorManager.SENSOR_DELAY_UI)
startForeground(NOTIFICATION_ID, notifyWithTitle(getString(R.string.steps_taken, stepsTaken.value)))
} else {
repository.setStepCounterAvailable(false)
startForeground(NOTIFICATION_ID, notifyWithTitle(getString(R.string.notification_step_counter_not_available)))
stopSelf()
return START_NOT_STICKY
}
return START_STICKY
}
private fun notifyWithTitle(title: String): Notification {
notificationBuilder.setContentTitle(title)
val notification = notificationBuilder.build()
notificationManager.notify(NOTIFICATION_ID, notification)
return notification
}
override fun onDestroy() {
repository.setServiceRunning(false)
stepCounterJob.cancel()
sensorManager.unregisterListener(this)
super.onDestroy()
}
override fun onSensorChanged(event: SensorEvent?) {
stepCounterScope.launch {
repository.setStepsTaken(event!!.values[0].toInt())
}
notifyWithTitle(getString(R.string.steps_taken, stepsTaken.value))
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
}
| 0 | Kotlin | 0 | 0 | 9c1d619d51c2fcdc5f041ea3a84a6ed36771a4d1 | 5,034 | simple-step-counter | MIT License |
okhttp/src/main/java/com/lightningkite/rx/okhttp/WebSocketInterface.kt | lightningkite | 400,655,884 | false | null | package com.lightningkite.rx.okhttp
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.subjects.PublishSubject
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import okio.ByteString.Companion.toByteString
/**
* A live web socket connection.
*/
interface WebSocketInterface {
/**
* An observable representing the socket's connection. Will emit once it is fully connected.
*/
val ownConnection: Observable<WebSocketInterface>
/**
* Messages that come through the websocket.
*/
val read: Observable<WebSocketFrame>
/**
* Messages to send through the socket
*/
val write: Observer<WebSocketFrame>
} | 1 | Kotlin | 0 | 2 | 165fc0842698d1d6bbb7bc1e9f2ad73d2338edb4 | 826 | rxkotlin-plus | MIT License |
android/app/src/main/kotlin/com/hahafather007/flutterweather/utils/RxController.kt | hahafather007 | 154,427,119 | false | null | package com.hahafather007.flutterweather.utils
import io.reactivex.disposables.CompositeDisposable
/**
* Created by chenpengxiang on 2018/6/15
*/
interface RxController {
/**
* 在子类中这样写:
* override val rxComposite = CompositeDisposable()
*/
val rxComposite: CompositeDisposable
/**
* 继承的子类在activity销毁时调用该方法释放资源
*/
fun dispose() {
rxComposite.clear()
}
} | 1 | Dart | 18 | 64 | a5243eceb1b8a0722937352cf501c094af5a48a8 | 411 | flutter_weather | Apache License 2.0 |
feature-staking-impl/src/main/java/io/novafoundation/nova/feature_staking_impl/domain/staking/start/common/StakingStartedDetectionService.kt | novasamatech | 415,834,480 | false | {"Kotlin": 7668451, "Java": 14723, "JavaScript": 425} | package io.novafoundation.nova.feature_staking_impl.domain.staking.start.common
import io.novafoundation.nova.common.data.memory.ComputationalCache
import io.novafoundation.nova.feature_account_api.domain.interfaces.AccountRepository
import io.novafoundation.nova.feature_staking_api.domain.dashboard.model.MultiStakingOptionIds
import io.novafoundation.nova.feature_staking_impl.data.dashboard.model.StakingDashboardItem
import io.novafoundation.nova.feature_staking_impl.data.dashboard.repository.StakingDashboardRepository
import io.novafoundation.nova.feature_staking_impl.domain.staking.start.common.StakingStartedDetectionService.DetectionState
import io.novafoundation.nova.runtime.multiNetwork.ChainRegistry
import io.novafoundation.nova.runtime.multiNetwork.chain.model.Chain
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.transform
interface StakingStartedDetectionService {
enum class DetectionState {
ACTIVE, PAUSED
}
fun observeStatingStarted(stakingOptionIds: MultiStakingOptionIds, screenScope: CoroutineScope): Flow<Chain>
suspend fun setDetectionState(state: DetectionState, screenScope: CoroutineScope)
}
suspend fun StakingStartedDetectionService.activateDetection(screenScope: CoroutineScope) {
setDetectionState(DetectionState.ACTIVE, screenScope)
}
suspend fun StakingStartedDetectionService.pauseDetection(screenScope: CoroutineScope) {
setDetectionState(DetectionState.PAUSED, screenScope)
}
suspend fun StakingStartedDetectionService.awaitStakingStarted(stakingOptionIds: MultiStakingOptionIds, screenScope: CoroutineScope): Chain {
return observeStatingStarted(stakingOptionIds, screenScope).first()
}
private const val CACHE_KEY = "RealStakingStartedDetectionService.detectionActiveState"
class RealStakingStartedDetectionService(
private val stakingDashboardRepository: StakingDashboardRepository,
private val computationalCache: ComputationalCache,
private val accountRepository: AccountRepository,
private val chainRegistry: ChainRegistry,
) : StakingStartedDetectionService {
override fun observeStatingStarted(
stakingOptionIds: MultiStakingOptionIds,
screenScope: CoroutineScope
): Flow<Chain> {
return accountRepository.selectedMetaAccountFlow().flatMapLatest { account ->
stakingDashboardRepository.dashboardItemsFlow(account.id, stakingOptionIds)
.transform { dashboardItems ->
val hasAnyStake = dashboardItems.any { item -> item.stakeState is StakingDashboardItem.StakeState.HasStake }
if (hasAnyStake) {
val chain = chainRegistry.getChain(stakingOptionIds.chainId)
awaitDetectionActive(screenScope)
emit(chain)
}
}
}
}
override suspend fun setDetectionState(state: DetectionState, screenScope: CoroutineScope) {
detectionActiveState(screenScope).value = state
}
private suspend fun awaitDetectionActive(screenScope: CoroutineScope) {
detectionActiveState(screenScope).first { it == DetectionState.ACTIVE }
}
private suspend fun detectionActiveState(scope: CoroutineScope): MutableStateFlow<DetectionState> {
return computationalCache.useCache(CACHE_KEY, scope) {
MutableStateFlow(DetectionState.ACTIVE)
}
}
}
| 11 | Kotlin | 6 | 9 | b39307cb56302ce7298582dbd03f33f6b2e2a807 | 3,595 | nova-wallet-android | Apache License 2.0 |
app/src/main/java/com/e444er/cleanmovie/feature_home/data/dto/TvSeriesDto.kt | e444er | 597,756,971 | false | null | package com.e444er.cleanmovie.feature_home.data.dto
import com.e444er.cleanmovie.core.domain.models.TvSeries
import com.squareup.moshi.Json
data class TvSeriesDto(
val id: Int,
val popularity: Double,
val overview: String,
val name: String,
@Json(name = "original_name") val originalName: String,
@Json(name = "poster_path") val posterPath: String?,
@Json(name = "first_air_date") val firstAirDate: String?,
@Json(name = "origin_country") val originCountry: List<String>,
@Json(name = "genre_ids") val genreIds: List<Int>,
@Json(name = "original_language") val originalLanguage: String,
@Json(name = "vote_average") val voteAverage: Double,
@Json(name = "vote_count") val voteCount: Int,
)
fun List<TvSeriesDto>.toTvSeries(): List<TvSeries> {
return map {
TvSeries(
id = it.id,
overview = it.overview,
name = it.name,
originalName = it.originalName,
posterPath = it.posterPath,
firstAirDate = it.firstAirDate,
genreIds = it.genreIds,
voteCount = it.voteCount,
voteAverage = it.voteAverage
)
}
} | 0 | Kotlin | 0 | 0 | 1c939de424b4eb254fd4258f4e56e4399bdfb3cd | 1,177 | KinoGoClean | Apache License 2.0 |
app/src/main/java/com/fecostudio/faceguard/ChooseStyleFragment.kt | Fewing | 344,456,083 | false | null | package com.fecostudio.faceguard
import android.app.Dialog
import android.content.Context
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import com.google.mlkit.vision.face.Face
class ChooseStyleFragment(private val faceBitmap: Bitmap, private val face: Face) : DialogFragment() {
private lateinit var listener: ChooseStyleListener
interface ChooseStyleListener {
fun onStyleDialogClick(bitmap: Bitmap, face: Face, which: Int)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
// Use the Builder class for convenient dialog construction
val builder = AlertDialog.Builder(it)
val inflater = requireActivity().layoutInflater
val dialogLayout: View = inflater.inflate(R.layout.fragment_style_dialog, null)
val imageView = dialogLayout.findViewById<ImageView>(R.id.preview_image)
imageView.setImageBitmap(faceBitmap)
builder.setView(dialogLayout)
builder.setItems(
R.array.styles
) { _, which ->
// The 'which' argument contains the index position
// of the selected item
listener.onStyleDialogClick(faceBitmap, face, which)
}
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
override fun onAttach(context: Context) {
super.onAttach(context)
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
listener = context as ChooseStyleListener
} catch (e: ClassCastException) {
// The activity doesn't implement the interface, throw exception
throw ClassCastException(
(context.toString() +
" must implement NoticeDialogListener")
)
}
}
} | 0 | Kotlin | 1 | 1 | 0ff80b283598310241e0c79b1630d23f4f0a63be | 2,139 | FaceGuard | MIT License |
app/src/main/java/com/fecostudio/faceguard/ChooseStyleFragment.kt | Fewing | 344,456,083 | false | null | package com.fecostudio.faceguard
import android.app.Dialog
import android.content.Context
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import com.google.mlkit.vision.face.Face
class ChooseStyleFragment(private val faceBitmap: Bitmap, private val face: Face) : DialogFragment() {
private lateinit var listener: ChooseStyleListener
interface ChooseStyleListener {
fun onStyleDialogClick(bitmap: Bitmap, face: Face, which: Int)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
// Use the Builder class for convenient dialog construction
val builder = AlertDialog.Builder(it)
val inflater = requireActivity().layoutInflater
val dialogLayout: View = inflater.inflate(R.layout.fragment_style_dialog, null)
val imageView = dialogLayout.findViewById<ImageView>(R.id.preview_image)
imageView.setImageBitmap(faceBitmap)
builder.setView(dialogLayout)
builder.setItems(
R.array.styles
) { _, which ->
// The 'which' argument contains the index position
// of the selected item
listener.onStyleDialogClick(faceBitmap, face, which)
}
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
override fun onAttach(context: Context) {
super.onAttach(context)
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
listener = context as ChooseStyleListener
} catch (e: ClassCastException) {
// The activity doesn't implement the interface, throw exception
throw ClassCastException(
(context.toString() +
" must implement NoticeDialogListener")
)
}
}
} | 0 | Kotlin | 1 | 1 | 0ff80b283598310241e0c79b1630d23f4f0a63be | 2,139 | FaceGuard | MIT License |
web/widgets/src/commonMain/kotlin/Arrangement.kt | JetBrains | 293,498,508 | false | null | package org.jetbrains.compose.common.foundation.layout
import org.jetbrains.compose.common.ui.ExperimentalComposeWebWidgetsApi
@ExperimentalComposeWebWidgetsApi
object Arrangement {
@ExperimentalComposeWebWidgetsApi
interface Horizontal
@ExperimentalComposeWebWidgetsApi
interface Vertical
val End = object : Horizontal {}
val Start = object : Horizontal {}
val Top = object : Vertical {}
val Bottom = object : Vertical {}
}
| 422 | Kotlin | 398 | 6,759 | 5598db273feb44e95c7706662dd4ba18984d62f9 | 461 | compose-jb | Apache License 2.0 |
app/src/androidTest/java/io/sinzak/android/ExampleInstrumentedTest.kt | SINZAK | 567,559,091 | false | {"Kotlin": 482864} | package io.sinzak.android
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import dagger.hilt.android.AndroidEntryPoint
import io.sinzak.android.ui.main.home.viewmodel.HomeViewModel
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
import javax.inject.Inject
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("io.sinzak.android", appContext.packageName)
}
} | 0 | Kotlin | 0 | 3 | 3467e8ee8afeb6b91b51f3a454f7010bc717c436 | 806 | sinzak-android | MIT License |
src/main/kotlin/no/nav/bidrag/stønad/konfig/KafkaRetryListener.kt | navikt | 360,850,317 | false | {"Kotlin": 217028, "Dockerfile": 293} | package no.nav.bidrag.stønad.konfig
import no.nav.bidrag.stønad.SECURE_LOGGER
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.springframework.kafka.listener.RetryListener
class KafkaRetryListener : RetryListener {
override fun failedDelivery(record: ConsumerRecord<*, *>, exception: Exception, deliveryAttempt: Int) {
SECURE_LOGGER.error("Håndtering av kafkamelding ${record.value()} feilet. Dette er $deliveryAttempt. forsøk", exception)
}
override fun recovered(record: ConsumerRecord<*, *>, exception: java.lang.Exception) {
SECURE_LOGGER.error(
"Håndtering av kafkamelding ${record.value()} er enten suksess eller ignorert på grunn av ugyldig data",
exception,
)
}
override fun recoveryFailed(record: ConsumerRecord<*, *>, original: java.lang.Exception, failure: java.lang.Exception) {
}
}
| 1 | Kotlin | 0 | 0 | c6a6acdfd78c574d5411f207197d7317eecb675f | 889 | bidrag-stonad | MIT License |
lib/navigationsetup/src/main/java/se/gustavkarlsson/skylight/android/lib/navigationsetup/FragmentStateChanger.kt | wowselim | 288,922,417 | true | {"Kotlin": 316543} | package se.gustavkarlsson.skylight.android.lib.navigationsetup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.zhuinden.simplestack.StateChange
import com.zhuinden.simplestack.StateChanger
import se.gustavkarlsson.skylight.android.core.logging.logInfo
import se.gustavkarlsson.skylight.android.lib.navigation.BackstackListener
import se.gustavkarlsson.skylight.android.lib.navigation.Screen
// Stolen from https://github.com/Zhuinden/simple-stack/blob/a9adb03/simple-stack-example-basic-kotlin-fragment/src/main/java/com/zhuinden/simplestackexamplekotlinfragment/core/navigation/FragmentStateChanger.kt
internal class FragmentStateChanger(
private val fragmentManager: FragmentManager,
private val containerId: Int,
private val animationConfig: AnimationConfig,
private val backstackListeners: List<BackstackListener>
) : StateChanger {
override fun handleStateChange(
stateChange: StateChange,
completionCallback: StateChanger.Callback
) {
if (!stateChange.isTopNewKeyEqualToPrevious) perform(stateChange)
notifyListeners(stateChange)
log(stateChange)
completionCallback.stateChangeComplete()
}
private fun notifyListeners(stateChange: StateChange) {
val old = stateChange.getPreviousKeys<Screen>()
val new = stateChange.getNewKeys<Screen>()
backstackListeners.forEach { it.onBackstackChanged(old, new) }
}
private fun perform(stateChange: StateChange) {
fragmentManager.executePendingTransactions()
with(fragmentManager.beginTransaction()) {
setAnimations(stateChange)
cleanUpPreviousState(stateChange)
applyNewState(stateChange)
commitAllowingStateLoss()
}
}
private fun FragmentTransaction.setAnimations(stateChange: StateChange) {
val animations = when (stateChange.direction) {
StateChange.FORWARD -> animationConfig.forward
StateChange.BACKWARD -> animationConfig.backward
StateChange.REPLACE -> animationConfig.replace
else -> error("Unsupported direction: ${stateChange.direction}")
}
setAnimations(animations)
}
private fun FragmentTransaction.cleanUpPreviousState(stateChange: StateChange) {
val oldStack = stateChange.getPreviousKeys<Screen>()
val newStack = stateChange.getNewKeys<Screen>()
for (oldScreen in oldStack) {
val existingFragment = fragmentManager.findFragmentByTag(oldScreen.tag)
if (existingFragment != null) {
if (oldScreen !in newStack) {
remove(existingFragment)
} else if (!existingFragment.isDetached) {
detach(existingFragment)
}
}
}
}
private fun FragmentTransaction.applyNewState(stateChange: StateChange) {
val newStack = stateChange.getNewKeys<Screen>()
for (newScreen in newStack) {
val existingFragment = fragmentManager.findFragmentByTag(newScreen.tag)
if (newScreen == stateChange.topNewKey()) {
setNewTop(newScreen, existingFragment)
} else if (existingFragment?.isDetached == false) {
detach(existingFragment)
}
}
}
private fun FragmentTransaction.setNewTop(screen: Screen, existingFragment: Fragment?) {
when {
existingFragment == null -> {
val newFragment = screen.createFragment()
add(containerId, newFragment, screen.tag)
}
existingFragment.isRemoving -> {
val newFragment = screen.createFragment()
replace(containerId, newFragment, screen.tag)
}
existingFragment.isDetached -> attach(existingFragment)
}
}
}
private fun log(stateChange: StateChange) {
val direction = when (stateChange.direction) {
StateChange.FORWARD -> "forward"
StateChange.BACKWARD -> "backward"
else -> "replace"
}
logInfo { "Backstack set to ${stateChange.getNewKeys<Any>()} with direction: $direction" }
}
private fun FragmentTransaction.setAnimations(animations: Animations) {
setCustomAnimations(
animations.enter,
animations.exit,
animations.popEnter,
animations.popExit
)
}
| 0 | null | 0 | 0 | 4da1731aca92d4e6d4b0e8128ca504fc0b3820b9 | 4,473 | skylight-android | MIT License |
app/src/main/kotlin/com/ceh9/portfolio/features/calculator/presentation/ui/advanced/AdvancedCalcFragment.kt | CeH9 | 202,865,791 | false | null | package com.ceh9.portfolio.features.calculator.presentation.ui.advanced
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.ceh9.portfolio.R
import com.ceh9.portfolio.common.domain.entities.ErrorModel
import com.ceh9.portfolio.common.domain.entities.Target
import com.ceh9.portfolio.common.presentation.binding
import com.ceh9.portfolio.common.presentation.fragment.BaseFragment
import com.ceh9.portfolio.common.presentation.viewModel.ViewModelFactory
import com.ceh9.portfolio.common.presentation.hideKeyboard
import com.ceh9.portfolio.common.presentation.models.UiResource
import com.ceh9.portfolio.common.utils.Logger.log
import com.ceh9.portfolio.databinding.FragmentAdvancedCalcBinding
import kotlinx.android.synthetic.main.fragment_simple_calc.*
/**
* Created by CeH9 on 19.09.2019
*/
class AdvancedCalcFragment(
viewModelFactory: ViewModelFactory
) : BaseFragment<AdvancedCalcViewModel>(viewModelFactory) {
private lateinit var mBinding: FragmentAdvancedCalcBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
log("onCreateView")
mBinding = container!!.binding(R.layout.fragment_advanced_calc)
mBinding.lifecycleOwner = viewLifecycleOwner
mViewModel = viewModelFactory.instantiate(this, AdvancedCalcViewModel::class)
mBinding.vm = mViewModel
return mBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView()
}
//==============================================================================================
// *** UI ***
//==============================================================================================
private fun initView() {
materialToolbar.setNavigationOnClickListener {
mViewModel.onClickHome()
}
mViewModel.operationResult().observe(viewLifecycleOwner, Observer {
when (it) {
is UiResource.Success -> {
hideKeyboard()
clearErrors()
tvResult.setText(it.data)
}
is UiResource.Error -> {
tvResult.setText("")
handleError(it.error)
}
}
})
}
private fun handleError(error: ErrorModel) {
when (error) {
is ErrorModel.TargetErrors -> {
clearErrors()
for (message in error.messages) {
applyTargetError(message.target, message.text)
}
}
}
}
private fun applyTargetError(target: Target, text: String) {
when (target) {
Target.FirstOperand -> tilFirst.error = text
}
}
private fun clearErrors() {
tilFirst.error = null
}
} | 0 | Kotlin | 0 | 0 | d4efdcffbee64a02cdb82d73d4f707f322964c40 | 3,023 | Portfolio | MIT License |
app/src/main/java/com/sleewell/sleewell/reveil/DesactivationActivity.kt | TitouanFi | 427,797,671 | true | {"Kotlin": 554160, "HTML": 385717, "Java": 102120, "CSS": 12842, "JavaScript": 7278} | package com.sleewell.sleewell.reveil
import android.app.PendingIntent
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.sleewell.sleewell.R
import com.sleewell.sleewell.reveil.data.model.Alarm
import kotlinx.android.synthetic.main.activity_desactivation_alarm.*
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class DesactivationActivity : AppCompatActivity() {
/**
* Called to have the fragment instantiate its user interface view.
*
* @param savedInstanceState If non-null, this fragment is being re-constructed from a previous saved state as given here.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_desactivation_alarm)
val alarm: Alarm
val bundle = intent.getBundleExtra("ALARM")
if (bundle != null) {
alarm = bundle.getParcelable("alarm")!!
val currentDateTime = LocalDateTime.now()
val time = currentDateTime.format(DateTimeFormatter.ofPattern("HH:mm"))
time_desactivation.text = time
label_alarm.text = alarm.label
val stopIntent = Intent(applicationContext, GlobalReceiver::class.java).apply {
action = "Stop"
}
val stopBundle = Bundle()
stopBundle.putParcelable("alarm", alarm)
stopIntent.putExtra("ALARM", stopBundle)
val stopPendingIntent = PendingIntent.getBroadcast(
applicationContext,
alarm.id,
stopIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
swipe_button.setOnStateChangeListener {
stopPendingIntent.send()
finish()
}
val snoozeIntent = Intent(applicationContext, GlobalReceiver::class.java).apply {
action = "Snooze"
}
val snoozeBundle = Bundle()
snoozeBundle.putParcelable("alarm", alarm)
snoozeIntent.putExtra("ALARM", stopBundle)
val snoozePendingIntent = PendingIntent.getBroadcast(
applicationContext,
alarm.id,
snoozeIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
snooze_desactivation.setOnClickListener {
snoozePendingIntent.send()
finish()
}
}
}
} | 0 | Kotlin | 0 | 0 | e1980017127869159b0742b63273fa342ae0c9da | 2,532 | Sleewell-Android | MIT License |
app/src/main/java/org/simple/clinic/bp/history/BloodPressureHistoryScreenModel.kt | nikulsabhani | 235,044,934 | true | {"Kotlin": 2953763, "C": 680052, "Java": 8206, "Shell": 1878, "Makefile": 635} | package org.simple.clinic.bp.history
import org.simple.clinic.bp.BloodPressureMeasurement
import java.util.UUID
data class BloodPressureHistoryScreenModel(
val patientUuid: UUID,
val bloodPressures: List<BloodPressureMeasurement>?
) {
companion object {
fun create(patientUuid: UUID) = BloodPressureHistoryScreenModel(patientUuid, null)
}
val hasBloodPressures: Boolean
get() = bloodPressures.isNullOrEmpty().not()
fun historyLoaded(bloodPressures: List<BloodPressureMeasurement>): BloodPressureHistoryScreenModel =
copy(bloodPressures = bloodPressures)
}
| 0 | null | 0 | 0 | e37ae8f5a1c2ecf224bca4394eeefd62f1a497be | 591 | simple-android | MIT License |
src/test/kotlin/org/onliner/kafka/transforms/JsonDeserializeTest.kt | onliner | 682,631,795 | false | {"Kotlin": 34662} | package org.onliner.kafka.transforms
import com.fasterxml.jackson.databind.node.ObjectNode
import org.apache.kafka.connect.data.Schema
import org.apache.kafka.connect.data.SchemaBuilder
import org.apache.kafka.connect.data.Struct
import org.apache.kafka.connect.errors.DataException
import org.apache.kafka.connect.source.SourceRecord
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.*
import java.util.*
import kotlin.test.Test
import kotlin.test.assertNull
internal class JsonDeserializeTest {
private val xformKey: JsonDeserialize<SourceRecord> = JsonDeserialize.Key()
private val xformValue: JsonDeserialize<SourceRecord> = JsonDeserialize.Value()
@AfterEach
fun teardown() {
xformKey.close()
xformValue.close()
}
@Test
fun handlesNullValue() {
configure(xformValue)
val given = SourceRecord(
null,
null,
"topic",
0,
null,
null
)
val expected = null
val actual: Any? = xformValue.apply(given).value()
assertEquals(expected, actual)
}
@Test
fun handlesNullKey() {
configure(xformKey)
val given = SourceRecord(
null,
null,
"topic",
0,
null,
null,
null,
null
)
val expected = null
val actual: Any? = xformKey.apply(given).key()
assertEquals(expected, actual)
}
@Test
fun copyValueSchemaAndConvertFields() {
configure(xformValue, "payload")
val schema = SchemaBuilder
.struct()
.name("name")
.version(1)
.doc("doc")
.field("payload", Schema.STRING_SCHEMA)
.field("string", Schema.STRING_SCHEMA)
.build()
val value = Struct(schema)
.put("payload", "{\"foo\":\"bar\",\"baz\":false}")
.put("string", "string")
val original = SourceRecord(null, null, "test", 0, schema, value)
val transformed: SourceRecord = xformValue.apply(original)
val outputSchema = transformed.valueSchema()
val payloadStruct = (transformed.value() as Struct).getStruct("payload")
val payloadSchema = outputSchema.field("payload").schema()
assertEquals(schema.name(), outputSchema.name())
assertEquals(schema.version(), outputSchema.version())
assertEquals(schema.doc(), outputSchema.doc())
assertEquals(payloadSchema.field("foo").schema(), Schema.STRING_SCHEMA)
assertEquals("bar", payloadStruct.getString("foo"))
assertEquals(payloadSchema.field("baz").schema(), Schema.BOOLEAN_SCHEMA)
assertEquals(false, payloadStruct.getBoolean("baz"))
assertEquals(Schema.STRING_SCHEMA, outputSchema.field("string").schema())
assertEquals("string", (transformed.value() as Struct).getString("string"))
}
@Test
fun schemalessValueConvertField() {
configure(xformValue, "payload")
val original = mapOf(
"int32" to 42,
"payload" to "{\"foo\":\"bar\",\"baz\":false}"
)
val record = SourceRecord(null, null, "test", 0, null, original)
val transformed = xformValue.apply(record).value() as Map<*, *>
assertEquals(42, transformed["int32"])
assertInstanceOf(ObjectNode::class.java, transformed["payload"])
val payload = transformed["payload"] as ObjectNode
assertEquals("bar", payload.get("foo").textValue())
assertEquals(false, payload.get("baz").booleanValue())
}
@Test
fun schemalessValueConvertNullField() {
configure(xformValue, "payload")
val original = mapOf(
"int32" to 42,
"payload" to null
)
val record = SourceRecord(null, null, "test", 0, null, original)
val transformed = xformValue.apply(record).value() as Map<*, *>
assertEquals(42, transformed["int32"])
assertNull(transformed["payload"])
}
@Test
fun passUnknownSchemaFields() {
configure(xformValue, "unknown")
val schema = SchemaBuilder
.struct()
.name("name")
.version(1)
.doc("doc")
.field("int32", Schema.INT32_SCHEMA)
.build()
val expected = Struct(schema).put("int32", 42)
val original = SourceRecord(null, null, "test", 0, schema, expected)
val transformed: SourceRecord = xformValue.apply(original)
assertEquals(schema.name(), transformed.valueSchema().name())
assertEquals(schema.version(), transformed.valueSchema().version())
assertEquals(schema.doc(), transformed.valueSchema().doc())
assertEquals(Schema.INT32_SCHEMA, transformed.valueSchema().field("int32").schema())
assertEquals(42, (transformed.value() as Struct).getInt32("int32"))
}
@Test
fun topLevelStructRequired() {
configure(xformValue)
assertThrows(DataException::class.java) {
xformValue.apply(
SourceRecord(
null, null,
"topic", 0, Schema.INT32_SCHEMA, 42
)
)
}
}
@Test
fun topLevelMapRequired() {
configure(xformValue)
assertThrows(DataException::class.java) {
xformValue.apply(
SourceRecord(
null, null,
"topic", 0, null, 42
)
)
}
}
@Test
fun testOptionalStruct() {
configure(xformValue)
val builder = SchemaBuilder.struct().optional()
builder.field("opt_int32", Schema.OPTIONAL_INT32_SCHEMA)
val schema = builder.build()
val transformed: SourceRecord = xformValue.apply(
SourceRecord(
null, null,
"topic", 0,
schema, null
)
)
assertEquals(Schema.Type.STRUCT, transformed.valueSchema().type())
assertNull(transformed.value())
}
private fun configure(transform: JsonDeserialize<SourceRecord>, fields: String = "") {
val props: MutableMap<String, String> = HashMap()
props["fields"] = fields
transform.configure(props.toMap())
}
}
| 0 | Kotlin | 0 | 0 | 2466d5266732b6880222602e069d5155a485568c | 6,381 | kafka-smt | MIT License |
lib/src/main/java/quevedo/soares/leandro/blemadeeasy/typealiases/TypeAliases.kt | LeandroSQ | 341,048,778 | false | {"Kotlin": 101459} | package quevedo.soares.leandro.blemadeeasy.typealiases
internal typealias EmptyCallback = () -> Unit
internal typealias Callback <T> = (T) -> Unit
internal typealias PermissionRequestCallback = (granted: Boolean) -> Unit
| 3 | Kotlin | 28 | 87 | dfe096d08cec36a6f17271633e0197b9ef213f52 | 224 | android-ble-made-easy | MIT License |
rabbit-hole/src/main/kotlin/com/yonatankarp/rabbit_hole/retry/QueueFactory.kt | yonatankarp | 349,646,173 | false | null | package com.yonatankarp.rabbit_hole.retry
import com.yonatankarp.rabbit_hole.exception.ExchangeException.Companion.invalidExchangeNameException
import com.yonatankarp.rabbit_hole.exception.QueueConfigException
import com.yonatankarp.rabbit_hole.exception.QueueConfigException.Companion.emptyConfigurationException
import com.yonatankarp.rabbit_hole.exception.QueueConfigException.Companion.mixedExchangeTypesException
import com.yonatankarp.rabbit_hole.retry.exchanges.topic.TopicQueueConfig
import com.yonatankarp.rabbit_hole.retry.exchanges.topic.TopicRetryBuilder
import com.yonatankarp.rabbit_hole.utils.ContextUtils
import org.springframework.amqp.rabbit.connection.ConnectionFactory
import java.util.*
/** An interface represents a queue configuration object for RabbitMQ. */
interface QueueConfig
/**
* The interface of the integrators with this library. This factory is the only entry point to the
* library, and it should decide how to instantiate all beans according to the given queue
* configurations it receives.
*
* @param contextUtils - application context utilities class to register beans.
* @param connectionFactory - rabbitmq connection factory instance
*/
class QueueFactory constructor(
private val contextUtils: ContextUtils,
private val connectionFactory: ConnectionFactory,
) {
private val typeBuilder = mutableMapOf<Class<out QueueConfig>, RetryBuilder>()
init {
buildTypeBuilderMapping()
}
private fun buildTypeBuilderMapping() {
typeBuilder[TopicQueueConfig::class.java] = TopicRetryBuilder(contextUtils, connectionFactory)
}
/**
* Creates the retry mechanism according to the given configs.
*
* @param exchangeName - the name of the main exchange to create
* @param configs - a list of queues that needs to be created and associated with the exchange
* @throws QueueConfigException - if the configuration list
* is empty, null or mixed of multiple QueueConfig types
*/
fun createQueues(exchangeName: String?, configs: List<QueueConfig>?) {
exchangeName.validate()
configs.validate()
val clazz = typeBuilder[configs!!.first().javaClass]
val retryBuilder = Optional
.ofNullable(clazz)
.orElseThrow { IllegalArgumentException("Required QueueConfig $clazz is not supported") }
retryBuilder.createQueues(exchangeName!!, configs)
}
private fun String?.validate() =
if (this.isNullOrBlank()) invalidExchangeNameException()
else Unit
private fun List<QueueConfig>?.validate() {
if (this.isNullOrEmpty()) emptyConfigurationException()
val nonMatchingConfigs = this!!.stream()
.filter { this.first().javaClass != it.javaClass }
.count()
if (nonMatchingConfigs > 0) mixedExchangeTypesException()
}
}
| 4 | Kotlin | 2 | 0 | 2d0c1c1c05bfe09865e1f3c32db6294fb852d4cd | 2,864 | rabbit-hole | MIT License |
src/test/kotlin/adventofcode2019/Day13CarePackageTest.kt | n81ur3 | 484,801,748 | false | {"Kotlin": 467824, "Java": 275} | package adventofcode2019
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import utils.ResourceLoader
import java.io.File
class Day13CarePackageTest {
lateinit var file: File
@BeforeEach
fun setup() {
file = ResourceLoader.getFile("aoc2019/aoc2019_day13_input.txt")
}
@Test
fun solutionPart1() {
val program = file.readLines()[0]
val arcadeCabinet = ArcadeCabinet(program)
arcadeCabinet.play()
val blockCount = arcadeCabinet.tilesCountForType(2L)
Assertions.assertEquals(335, blockCount)
println("Solution for AoC2019-Day13-Part01: ${blockCount}")
}
@Test
fun solutionPart2() {
val program = file.readLines()[0]
val arcadeCabinet = ArcadeCabinet(program)
arcadeCabinet.enableFreePlay()
arcadeCabinet.play()
val finalScore = arcadeCabinet.currentScore
Assertions.assertEquals(15706, finalScore)
println("Solution for AoC2019-Day13-Part02: ${finalScore}")
}
} | 0 | Kotlin | 0 | 0 | ff5e3af6081fb0f872ad35b0437620aedc628f4c | 1,085 | kotlin-coding-challenges | MIT License |
shared/src/commonMain/kotlin/com/kkk/kopilot/presentation/component/buttons/PrimaryButton.kt | k-kertykamary | 708,003,499 | false | {"Kotlin": 100618, "Swift": 644, "Shell": 228} | package com.kkk.kopilot.presentation.component.buttons
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.height
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.kkk.kopilot.presentation.component.loader.loadingindicator.AnimationType
import com.kkk.kopilot.presentation.component.loader.loadingindicator.LoadingIndicator
import com.kkk.kopilot.presentation.component.loader.loadingindicator.LoadingIndicatorSize
import com.kkk.kopilot.presentation.theme.Dimensions
@Composable
fun PrimaryButton(
modifier: Modifier,
text: String,
loading: Boolean = false,
animationType: AnimationType = AnimationType.Bounce,
onClick: () -> Unit,
) {
Button(
modifier = modifier
.height(Dimensions.buttonHeight),
onClick = onClick,
shape = MaterialTheme.shapes.medium
) {
Box(
contentAlignment = Alignment.Center,
) {
if (loading) {
LoadingIndicator(
animationType = animationType,
color = MaterialTheme.colors.surface,
size = LoadingIndicatorSize.Small
)
} else {
Box {
Text(text = text, style = MaterialTheme.typography.button)
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 29c99211a40364ff7e40dd4ce08e5c32aedf4b30 | 1,549 | km2-ktofit | Apache License 2.0 |
im-access/src/main/kotlin/com/qingzhu/imaccess/service/AutoKickOutService.kt | linjinhai | 394,838,665 | true | {"Kotlin": 693654, "ANTLR": 281490, "Java": 48298, "Dockerfile": 375} | package com.qingzhu.imaccess.service
import com.qingzhu.common.domain.shared.msg.constant.CreatorType
import com.qingzhu.imaccess.domain.query.WebSocketRequest
import com.qingzhu.imaccess.socketio.constant.SocketEvent
import com.qingzhu.imaccess.socketio.sendWithCallback
import com.qingzhu.imaccess.util.Key
import com.qingzhu.imaccess.util.MapUtils
import org.springframework.boot.CommandLineRunner
import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.scheduler.Schedulers
import reactor.kotlin.core.publisher.toFlux
import java.time.Duration
/**
* 自动踢人,超时关闭人工会话
*/
@Service
class AutoKickOutService(
private val registerService: RegisterService,
) : CommandLineRunner {
override fun run(vararg args: String?) {
Flux.interval(Duration.ZERO, Duration.ofSeconds(10), Schedulers.boundedElastic())
.flatMapIterable {
// TODO 通过配置获取
MapUtils.Time.getExpiredKey(CreatorType.CUSTOMER, Duration.ofMinutes(15))
}
.doOnNext { MapUtils.Time.removeKey(it) }
.flatMapSequential { MapUtils.get(Key(it.organizationId, it.role, it.id)).map { socket -> it to socket } }
.map { (key, socket) ->
// TODO 消息通过配置获取
socket.sendWithCallback<Void>(
SocketEvent.IO.closed,
WebSocketRequest.createRequest(socket.sessionId.toString(), "连接超时断开")
) {
registerService.unRegisterCustomer(key.organizationId, key.id, CreatorType.SYS)
MapUtils.remove(Key(key.organizationId, CreatorType.CUSTOMER, key.id), socket)
socket.disconnect()
}
}
.thenMany(MapUtils.Time.getExpiredKey(CreatorType.STAFF, Duration.ofMinutes(2)).toFlux())
.doOnNext { MapUtils.Time.removeKey(it) }
.map {
TODO("客服离线超时,发送关闭信号给其客户")
}
.subscribe()
}
} | 0 | null | 0 | 0 | b4718991300746ccc627c735c79f478b3cfa0956 | 2,006 | contact-center | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/SquareBolt.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.SquareBolt: ImageVector
get() {
if (_squareBolt != null) {
return _squareBolt!!
}
_squareBolt = Builder(name = "SquareBolt", defaultWidth = 512.0.dp, defaultHeight =
512.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(15.75f, 11.61f)
curveToRelative(0.35f, 0.65f, 0.33f, 1.44f, -0.04f, 2.07f)
lineToRelative(-2.87f, 5.51f)
lineToRelative(-2.66f, -1.39f)
lineToRelative(2.24f, -4.31f)
horizontalLineToRelative(-2.3f)
curveToRelative(-0.67f, 0.0f, -1.3f, -0.32f, -1.7f, -0.85f)
curveToRelative(-0.4f, -0.54f, -0.52f, -1.23f, -0.33f, -1.87f)
lineToRelative(3.08f, -5.97f)
lineToRelative(2.66f, 1.39f)
lineToRelative(-2.24f, 4.31f)
horizontalLineToRelative(2.31f)
curveToRelative(0.78f, 0.0f, 1.49f, 0.42f, 1.85f, 1.11f)
close()
moveTo(24.0f, 3.5f)
lineTo(24.0f, 24.0f)
lineTo(0.0f, 24.0f)
lineTo(0.0f, 3.5f)
curveTo(0.0f, 1.57f, 1.57f, 0.0f, 3.5f, 0.0f)
lineTo(20.5f, 0.0f)
curveToRelative(1.93f, 0.0f, 3.5f, 1.57f, 3.5f, 3.5f)
close()
moveTo(21.0f, 3.5f)
curveToRelative(0.0f, -0.28f, -0.22f, -0.5f, -0.5f, -0.5f)
lineTo(3.5f, 3.0f)
curveToRelative(-0.28f, 0.0f, -0.5f, 0.22f, -0.5f, 0.5f)
lineTo(3.0f, 21.0f)
lineTo(21.0f, 21.0f)
lineTo(21.0f, 3.5f)
close()
}
}
.build()
return _squareBolt!!
}
private var _squareBolt: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,646 | icons | MIT License |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/PeopleMoney.kt | Konyaco | 574,321,009 | false | null |
package com.konyaco.fluent.icons.regular
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Regular.PeopleMoney: ImageVector
get() {
if (_peopleMoney != null) {
return _peopleMoney!!
}
_peopleMoney = fluentIcon(name = "Regular.PeopleMoney") {
fluentPath {
moveTo(5.5f, 7.0f)
arcToRelative(2.5f, 2.5f, 0.0f, true, true, 5.0f, 0.0f)
arcToRelative(2.5f, 2.5f, 0.0f, false, true, -5.0f, 0.0f)
close()
moveTo(8.0f, 3.0f)
arcToRelative(4.0f, 4.0f, 0.0f, true, false, 0.0f, 8.0f)
arcToRelative(4.0f, 4.0f, 0.0f, false, false, 0.0f, -8.0f)
close()
moveTo(15.5f, 8.0f)
arcToRelative(1.5f, 1.5f, 0.0f, true, true, 3.0f, 0.0f)
arcToRelative(1.5f, 1.5f, 0.0f, false, true, -3.0f, 0.0f)
close()
moveTo(17.0f, 5.0f)
arcToRelative(3.0f, 3.0f, 0.0f, true, false, 0.0f, 6.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, false, 0.0f, -6.0f)
close()
moveTo(11.75f, 13.0f)
curveToRelative(0.3f, 0.0f, 0.59f, 0.06f, 0.85f, 0.17f)
arcToRelative(2.5f, 2.5f, 0.0f, false, false, -1.4f, 1.33f)
lineTo(4.26f, 14.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.75f, 0.75f)
verticalLineToRelative(0.34f)
lineToRelative(0.06f, 0.33f)
curveToRelative(0.07f, 0.28f, 0.2f, 0.65f, 0.46f, 1.02f)
curveToRelative(0.5f, 0.71f, 1.56f, 1.56f, 3.98f, 1.56f)
curveToRelative(1.4f, 0.0f, 2.36f, -0.29f, 3.0f, -0.67f)
verticalLineToRelative(1.67f)
curveToRelative(-0.8f, 0.3f, -1.78f, 0.5f, -3.0f, 0.5f)
curveToRelative(-2.83f, 0.0f, -4.39f, -1.03f, -5.2f, -2.2f)
arcToRelative(4.49f, 4.49f, 0.0f, false, true, -0.8f, -2.27f)
verticalLineToRelative(-0.28f)
curveTo(2.0f, 14.01f, 3.0f, 13.0f, 4.25f, 13.0f)
horizontalLineToRelative(7.5f)
close()
moveTo(12.0f, 15.5f)
curveToRelative(0.0f, -0.83f, 0.67f, -1.5f, 1.5f, -1.5f)
horizontalLineToRelative(8.0f)
curveToRelative(0.83f, 0.0f, 1.5f, 0.67f, 1.5f, 1.5f)
verticalLineToRelative(4.0f)
curveToRelative(0.0f, 0.83f, -0.67f, 1.5f, -1.5f, 1.5f)
horizontalLineToRelative(-8.0f)
arcToRelative(1.5f, 1.5f, 0.0f, false, true, -1.5f, -1.5f)
verticalLineToRelative(-4.0f)
close()
moveTo(13.0f, 16.0f)
verticalLineToRelative(1.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 2.0f, -2.0f)
horizontalLineToRelative(-1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, 1.0f)
close()
moveTo(22.0f, 17.0f)
verticalLineToRelative(-1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f)
horizontalLineToRelative(-1.0f)
curveToRelative(0.0f, 1.1f, 0.9f, 2.0f, 2.0f, 2.0f)
close()
moveTo(20.0f, 20.0f)
horizontalLineToRelative(1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f)
verticalLineToRelative(-1.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, -2.0f, 2.0f)
close()
moveTo(13.0f, 18.0f)
verticalLineToRelative(1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f)
horizontalLineToRelative(1.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, -2.0f, -2.0f)
close()
moveTo(17.5f, 19.25f)
arcToRelative(1.75f, 1.75f, 0.0f, true, false, 0.0f, -3.5f)
arcToRelative(1.75f, 1.75f, 0.0f, false, false, 0.0f, 3.5f)
close()
}
}
return _peopleMoney!!
}
private var _peopleMoney: ImageVector? = null
| 1 | Kotlin | 3 | 83 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 4,414 | compose-fluent-ui | Apache License 2.0 |
app/src/main/java/com/example/cekongkir/di/UseCaseModule.kt | holis12821 | 382,658,929 | false | null | package com.example.cekongkir.di
import com.example.cekongkir.domain.usecase.UseCaseCekOngkir
import org.koin.dsl.module
val useCaseModule = module {
single { UseCaseCekOngkir(get()) }
} | 0 | Kotlin | 0 | 1 | 9b0149b020a2c8155806bef4228f8f885d98610c | 192 | cekongkir-repo | Apache License 2.0 |
kotlin-mui-icons/src/main/generated/mui/icons/material/ShuffleRounded.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/ShuffleRounded")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val ShuffleRounded: SvgIconComponent
| 12 | Kotlin | 145 | 983 | a99345a0160a80a7a90bf1adfbfdc83a31a18dd6 | 210 | kotlin-wrappers | Apache License 2.0 |
compiler/src/main/kotlin/edu/cornell/cs/apl/viaduct/backends/cleartext/LocalProtocolFactory.kt | apl-cornell | 169,159,978 | false | null | package edu.cornell.cs.apl.viaduct.backends.cleartext
import edu.cornell.cs.apl.viaduct.selection.ProtocolFactory
import edu.cornell.cs.apl.viaduct.syntax.Protocol
import edu.cornell.cs.apl.viaduct.syntax.intermediate.DeclarationNode
import edu.cornell.cs.apl.viaduct.syntax.intermediate.LetNode
import edu.cornell.cs.apl.viaduct.syntax.intermediate.ParameterNode
import edu.cornell.cs.apl.viaduct.syntax.intermediate.ProgramNode
class LocalProtocolFactory(val program: ProgramNode) : ProtocolFactory {
val protocols: Set<Protocol> = program.hosts.map(::Local).toSet()
override fun viableProtocols(node: LetNode): Set<Protocol> = protocols
override fun viableProtocols(node: DeclarationNode): Set<Protocol> = protocols
override fun viableProtocols(node: ParameterNode): Set<Protocol> = protocols
}
| 20 | Kotlin | 4 | 11 | 2352c676305c595d235bc9024770fc622efb8aa2 | 819 | viaduct | MIT License |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/CameraAdd.kt | Konyaco | 574,321,009 | false | null |
package com.konyaco.fluent.icons.filled
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Filled.CameraAdd: ImageVector
get() {
if (_cameraAdd != null) {
return _cameraAdd!!
}
_cameraAdd = fluentIcon(name = "Filled.CameraAdd") {
fluentPath {
moveTo(17.5f, 12.0f)
arcToRelative(5.5f, 5.5f, 0.0f, true, true, 0.0f, 11.0f)
arcToRelative(5.5f, 5.5f, 0.0f, false, true, 0.0f, -11.0f)
close()
moveTo(17.5f, 14.0f)
horizontalLineToRelative(-0.09f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.4f, 0.41f)
lineToRelative(-0.01f, 0.09f)
lineTo(17.0f, 17.0f)
horizontalLineToRelative(-2.6f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.4f, 0.41f)
verticalLineToRelative(0.18f)
curveToRelative(0.04f, 0.2f, 0.2f, 0.37f, 0.4f, 0.4f)
lineToRelative(0.1f, 0.01f)
lineTo(17.0f, 18.0f)
verticalLineToRelative(2.6f)
curveToRelative(0.05f, 0.2f, 0.2f, 0.36f, 0.41f, 0.4f)
horizontalLineToRelative(0.18f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.4f, -0.4f)
lineToRelative(0.01f, -0.1f)
lineTo(18.0f, 18.0f)
horizontalLineToRelative(2.6f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.4f, -0.4f)
verticalLineToRelative(-0.19f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.4f, -0.4f)
horizontalLineToRelative(-0.1f)
lineTo(18.0f, 17.0f)
verticalLineToRelative(-2.59f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.41f, -0.4f)
lineTo(17.5f, 14.0f)
close()
moveTo(13.92f, 2.5f)
curveToRelative(0.8f, 0.0f, 1.54f, 0.43f, 1.94f, 1.11f)
lineToRelative(0.82f, 1.4f)
horizontalLineToRelative(2.07f)
curveTo(20.55f, 5.0f, 22.0f, 6.45f, 22.0f, 8.24f)
verticalLineToRelative(4.56f)
arcToRelative(6.48f, 6.48f, 0.0f, false, false, -5.72f, -1.7f)
arcToRelative(4.5f, 4.5f, 0.0f, true, false, -5.25f, 5.79f)
arcToRelative(6.51f, 6.51f, 0.0f, false, false, 1.0f, 4.1f)
lineTo(5.24f, 20.99f)
arcTo(3.25f, 3.25f, 0.0f, false, true, 2.0f, 17.75f)
verticalLineToRelative(-9.5f)
curveTo(2.0f, 6.45f, 3.46f, 5.0f, 5.25f, 5.0f)
horizontalLineToRelative(2.08f)
lineToRelative(0.88f, -1.42f)
arcToRelative(2.25f, 2.25f, 0.0f, false, true, 1.91f, -1.08f)
horizontalLineToRelative(3.8f)
close()
moveTo(12.0f, 9.5f)
arcToRelative(3.0f, 3.0f, 0.0f, false, true, 2.85f, 2.06f)
arcToRelative(6.52f, 6.52f, 0.0f, false, false, -3.51f, 3.87f)
arcTo(3.0f, 3.0f, 0.0f, false, true, 12.0f, 9.5f)
close()
}
}
return _cameraAdd!!
}
private var _cameraAdd: ImageVector? = null
| 1 | Kotlin | 3 | 83 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 3,441 | compose-fluent-ui | Apache License 2.0 |
postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/parsers/MessageParsersRegistry.kt | KotlinPorts | 77,183,383 | false | null | /*
* Copyright 2013 <NAME>
*
* <NAME> licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.mauricio.async.db.postgresql.parsers
import com.github.mauricio.async.db.exceptions.ParserNotAvailableException
import com.github.mauricio.async.db.postgresql.messages.backend.ServerMessage
import com.github.mauricio.async.db.postgresql.messages.backend.*
import java.nio.charset.Charset
import io.netty.buffer.ByteBuf
class MessageParsersRegistry(charset: Charset) {
private val commandCompleteParser = CommandCompleteParser(charset)
private val errorParser = ErrorParser(charset)
private val noticeParser = NoticeParser(charset)
private val parameterStatusParser = ParameterStatusParser(charset)
private val rowDescriptionParser = RowDescriptionParser(charset)
private val notificationResponseParser = NotificationResponseParser(charset)
private fun parserFor(t: Byte): MessageParser =
when (t.toInt()) {
ServerMessage.Authentication -> AuthenticationStartupParser
ServerMessage.BackendKeyData -> BackendKeyDataParser
ServerMessage.BindComplete -> ReturningMessageParser.BindCompleteMessageParser
ServerMessage.CloseComplete -> ReturningMessageParser.CloseCompleteMessageParser
ServerMessage.CommandComplete -> this.commandCompleteParser
ServerMessage.DataRow -> DataRowParser
ServerMessage.Error -> this.errorParser
ServerMessage.EmptyQueryString -> ReturningMessageParser.EmptyQueryStringMessageParser
ServerMessage.NoData -> ReturningMessageParser.NoDataMessageParser
ServerMessage.Notice -> this.noticeParser
ServerMessage.NotificationResponse -> this.notificationResponseParser
ServerMessage.ParameterStatus -> this.parameterStatusParser
ServerMessage.ParseComplete -> ReturningMessageParser.ParseCompleteMessageParser
ServerMessage.RowDescription -> this.rowDescriptionParser
ServerMessage.ReadyForQuery -> ReadyForQueryParser
else -> throw ParserNotAvailableException(t)
}
fun parse(t: Byte, b: ByteBuf): ServerMessage =
this.parserFor(t).parseMessage(b)
} | 5 | Kotlin | 2 | 23 | 942ebfeee4601f9580916ed551fcfd2f8084d701 | 2,828 | pooled-client | Apache License 2.0 |
app/src/main/java/com/jerimkaura/contacts/receiver/AlarmReceiver.kt | jerimkaura | 520,493,196 | false | null | package com.jerimkaura.contacts.receiver
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.telephony.SmsManager
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.TaskStackBuilder
import com.jerimkaura.contacts.MainActivity
import com.jerimkaura.contacts.data.Contact
class AlarmReceiver :
BroadcastReceiver() {
private lateinit var mNotificationManager: NotificationManager
@RequiresApi(Build.VERSION_CODES.N)
override fun onReceive(context: Context, intent: Intent) {
val contact = intent.getStringExtra("contact")
val contacts = intent.getSerializableExtra("CONTACTS") as List<Contact?>
contacts.forEach {
if (it != null) {
sendSMS(it.phoneNumber, "Hi there ${it.name}")
}
}
mNotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
createNotification(context, contact)
}
@RequiresApi(Build.VERSION_CODES.N)
private fun createNotification(context: Context, contact: String?) {
val intent = Intent(context, MainActivity::class.java)
val pendingIntent = TaskStackBuilder.create(context).run {
addNextIntentWithParentStack(intent)
getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE)
}
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle("Contact")
.setContentText("Messages sent to all contacts. Tap to open and view saved contacts.")
.setSmallIcon(com.jerimkaura.contacts.R.drawable.logo2)
.setPriority(NotificationManager.IMPORTANCE_HIGH)
.setContentIntent(pendingIntent)
.build()
sendSMS(contact, "Hi there $contact")
mNotificationManager.notify(NOTIFICATION_ID, notification)
}
private fun sendSMS(phoneNo: String?, msg: String?) {
try {
val smsManager: SmsManager = SmsManager.getDefault()
smsManager.sendTextMessage(phoneNo, null, msg, null, null)
} catch (ex: Exception) {
ex.printStackTrace()
}
}
companion object {
const val CHANNEL_ID = "channel ID"
const val NOTIFICATION_ID = 0
}
} | 0 | Kotlin | 0 | 0 | 1e590768743984a979a59f29e0775cbae4f1a028 | 2,464 | Contacts | The Unlicense |
app/src/main/java/com/jerimkaura/contacts/receiver/AlarmReceiver.kt | jerimkaura | 520,493,196 | false | null | package com.jerimkaura.contacts.receiver
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.telephony.SmsManager
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.TaskStackBuilder
import com.jerimkaura.contacts.MainActivity
import com.jerimkaura.contacts.data.Contact
class AlarmReceiver :
BroadcastReceiver() {
private lateinit var mNotificationManager: NotificationManager
@RequiresApi(Build.VERSION_CODES.N)
override fun onReceive(context: Context, intent: Intent) {
val contact = intent.getStringExtra("contact")
val contacts = intent.getSerializableExtra("CONTACTS") as List<Contact?>
contacts.forEach {
if (it != null) {
sendSMS(it.phoneNumber, "Hi there ${it.name}")
}
}
mNotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
createNotification(context, contact)
}
@RequiresApi(Build.VERSION_CODES.N)
private fun createNotification(context: Context, contact: String?) {
val intent = Intent(context, MainActivity::class.java)
val pendingIntent = TaskStackBuilder.create(context).run {
addNextIntentWithParentStack(intent)
getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE)
}
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle("Contact")
.setContentText("Messages sent to all contacts. Tap to open and view saved contacts.")
.setSmallIcon(com.jerimkaura.contacts.R.drawable.logo2)
.setPriority(NotificationManager.IMPORTANCE_HIGH)
.setContentIntent(pendingIntent)
.build()
sendSMS(contact, "Hi there $contact")
mNotificationManager.notify(NOTIFICATION_ID, notification)
}
private fun sendSMS(phoneNo: String?, msg: String?) {
try {
val smsManager: SmsManager = SmsManager.getDefault()
smsManager.sendTextMessage(phoneNo, null, msg, null, null)
} catch (ex: Exception) {
ex.printStackTrace()
}
}
companion object {
const val CHANNEL_ID = "channel ID"
const val NOTIFICATION_ID = 0
}
} | 0 | Kotlin | 0 | 0 | 1e590768743984a979a59f29e0775cbae4f1a028 | 2,464 | Contacts | The Unlicense |
Barlom-Client-JS/src/main/kotlin/js/barlom/presentation/client/application/Application.kt | martin-nordberg | 82,682,055 | false | null | //
// (C) Copyright 2017-2018 <NAME>
// Apache 2.0 License
//
package js.barlom.presentation.client.application
import js.katydid.vdom.api.KatydidApplication
import js.katydid.vdom.api.KatydidApplicationCycle
import o.barlom.infrastructure.revisions.RevisionHistory
import o.barlom.presentation.client.ApplicationState
import js.barlom.presentation.client.messages.ActionMessage
import js.barlom.presentation.client.messages.Message
import js.barlom.presentation.client.views.leftpanels.browse.viewBrowsePanel
import js.barlom.presentation.client.views.leftpanels.favorites.viewFavoritesPanel
import js.barlom.presentation.client.views.leftpanels.search.viewSearchPanel
import js.barlom.presentation.client.views.leftpanels.viewLeftPanelNavItem
import js.barlom.presentation.client.views.listitems.viewFocusedElementPath
import js.barlom.presentation.client.views.rightpanels.forms.viewPropertiesForm
import js.barlom.presentation.client.views.rightpanels.links.viewRelatedElements
import js.barlom.presentation.client.views.rightpanels.viewRightPanelNavItem
import o.barlom.presentation.client.state.leftpanels.ELeftPanelType
import o.barlom.presentation.client.state.rightpanels.ERightPanelType
import o.katydid.vdom.builders.KatydidFlowContentBuilder
class Application : KatydidApplication<ApplicationState, Message> {
override fun initialize(): KatydidApplicationCycle<ApplicationState, Message> {
// Create the revision history for the application.
val revHistory = RevisionHistory("Initial model")
// Initialize the model.
lateinit var result: ApplicationState
revHistory.update {
result = ApplicationState()
val m = result.model
m.apply {
val root = rootPackage
val pkg1 = makePackage {
name = "pkg1"
makePackageContainment(root, this)
}
val pkg1a = makePackage {
name = "pkg1a"
makePackageContainment(pkg1, this)
}
val pkg1ai = makePackage {
name = "pkg1ai"
makePackageContainment(pkg1a, this)
}
val pkg1aii = makePackage {
name = "pkg1aii"
makePackageContainment(pkg1a, this)
}
val VertexTypeA = makeVertexType {
name = "VertexTypeA"
makeVertexTypeContainment(pkg1a, this)
}
val VertexTypeB = makeVertexType {
name = "VertexTypeB"
makeVertexTypeContainment(pkg1a, this)
}
val UndirectedEdgeTypeX = makeUndirectedEdgeType {
name = "UndirectedEdgeTypeX"
makeUndirectedEdgeTypeContainment(pkg1a, this)
}
makeUndirectedEdgeTypeConnectivity(UndirectedEdgeTypeX, VertexTypeA)
val UndirectedEdgeTypeY = makeUndirectedEdgeType {
name = "UndirectedEdgeTypeY"
makeUndirectedEdgeTypeContainment(pkg1a, this)
}
makeUndirectedEdgeTypeConnectivity(UndirectedEdgeTypeY, VertexTypeB)
val DirectedEdgeTypeP = makeDirectedEdgeType {
name = "DirectedEdgeTypeP"
makeDirectedEdgeTypeContainment(pkg1a, this)
}
makeDirectedEdgeTypeHeadConnectivity(DirectedEdgeTypeP, VertexTypeA)
makeDirectedEdgeTypeTailConnectivity(DirectedEdgeTypeP, VertexTypeB)
val DirectedEdgeTypeQ = makeDirectedEdgeType {
name = "DirectedEdgeTypeQ"
makeDirectedEdgeTypeContainment(pkg1a, this)
}
makeDirectedEdgeTypeHeadConnectivity(DirectedEdgeTypeQ, VertexTypeB)
makeDirectedEdgeTypeTailConnectivity(DirectedEdgeTypeQ, VertexTypeA)
val pkg1b = makePackage {
name = "pkg1b"
makePackageContainment(pkg1, this)
}
val pkg1bi = makePackage {
name = "pkg1bi"
makePackageContainment(pkg1b, this)
}
val pkg1bii = makePackage {
name = "pkg1bii"
makePackageContainment(pkg1b, this)
}
val pkg2 = makePackage {
name = "pkg2"
makePackageContainment(root, this)
}
val pkg3 = makePackage {
name = "pkg3"
makePackageContainment(root, this)
}
makePackageDependency(pkg2, pkg1)
makePackageDependency(pkg3, pkg1)
}
"Initialized application state."
}
return KatydidApplicationCycle(result)
}
override fun update(applicationState: ApplicationState, message: Message): KatydidApplicationCycle<ApplicationState, Message> {
if (message is ActionMessage) {
val actionDescription = message.executeAction(applicationState)
console.log(actionDescription)
return KatydidApplicationCycle(applicationState)
}
TODO("Update function not yet implemented for non-action messages")
}
override fun view(applicationState: ApplicationState): KatydidFlowContentBuilder<Message>.() -> Unit {
val m = applicationState.model
val ui = applicationState.uiState
val revHistory = applicationState.revHistory
return {
revHistory.review {
main("#BarlomMetamodelingEnvironment.o-grid.o-grid--no-gutter.o-panel.u-small") {
div("#left-panel-container.o-grid__cell--width-20.o-panel-container") {
nav("#left-navigation.c-nav.c-nav--inline") {
viewLeftPanelNavItem(this, ELeftPanelType.BROWSE, ui.leftPanelType)
viewLeftPanelNavItem(this, ELeftPanelType.FAVORITES, ui.leftPanelType)
viewLeftPanelNavItem(this, ELeftPanelType.SEARCH, ui.leftPanelType)
}
when (ui.leftPanelType) {
ELeftPanelType.BROWSE ->
viewBrowsePanel(this, m, ui.browsePanelState)
ELeftPanelType.FAVORITES ->
viewFavoritesPanel(this, m)
ELeftPanelType.SEARCH ->
viewSearchPanel(this, m)
}
}
div("#right-panel-container.o-grid__cell--width-80.o-panel-container") {
nav("#right-navigation.c-nav.c-nav--inline.c-nav--light") {
div("#focused-element-container.c-nav__content") {
viewFocusedElementPath(this, ui.focusedElement)
}
viewRightPanelNavItem(this, ERightPanelType.SETTINGS)
viewRightPanelNavItem(this, ERightPanelType.HELP)
}
if (ui.focusedElement != null) {
div("#right-forms-container.o-grid") {
div("#properties-form-container.o-grid__cell--width-60") {
viewPropertiesForm(this, ui.focusedElement!!)
}
div("#related-elements-container.o-grid__cell--width-40") {
viewRelatedElements(this, ui.relatedElementsPanelState,
ui.focusedElement!!)
}
}
}
}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 337b46f01f6eec6dfb3b86824c26f1c103e9d9a2 | 8,126 | ZZ-Barlom | Apache License 2.0 |
android/src/main/java/com/uvccamera/UVCCameraPackage.kt | and2long | 680,363,985 | false | null | package com.uvccamera
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class UVCCameraPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf(UVCCameraViewModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return listOf(UVCCameraViewManager())
}
}
| 2 | Kotlin | 0 | 0 | 80ed87fb461f14e61d183a33281f3b2b54272f3d | 557 | react-native-uvc-camera | MIT License |
app/src/main/java/fr/smarquis/fcm/data/services/FcmService.kt | tkstone | 370,204,426 | false | null | /*
* Copyright 2017 <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 fr.smarquis.fcm.data.services
import android.util.Log
import androidx.annotation.UiThread
import androidx.annotation.WorkerThread
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import fr.smarquis.fcm.data.model.Message
import fr.smarquis.fcm.data.model.Payload
import fr.smarquis.fcm.data.repository.MessageRepository
import fr.smarquis.fcm.utils.Notifications
import fr.smarquis.fcm.utils.asMessage
import fr.smarquis.fcm.utils.copyToClipboard
import fr.smarquis.fcm.utils.uiHandler
import fr.smarquis.fcm.viewmodel.PresenceLiveData
import kotlinx.coroutines.runBlocking
import org.koin.android.ext.android.inject
import java.lang.Boolean.parseBoolean
class FcmService : FirebaseMessagingService() {
private val repository: MessageRepository by inject()
override fun onNewToken(token: String) {
PresenceLiveData.instance(application).fetchToken()
}
@WorkerThread
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
val message = remoteMessage.asMessage()
val notification = remoteMessage.notification
Log.i("tkstone", "Fcm notification - title : ${notification?.title}, body : ${notification?.body}, image : ${notification?.imageUrl}")
Log.i("tkstone", "Fcm message : ${message.toString()}")
runBlocking { repository.insert(message) }
uiHandler.post { notifyAndExecute(message) }
}
@UiThread
private fun notifyAndExecute(message: Message) {
if (!parseBoolean(message.data["hide"])) {
Notifications.show(this, message)
}
val payload = message.payload
when {
payload is Payload.Text && payload.clipboard -> applicationContext.copyToClipboard(payload.text)
// payload is Payload.Text && payload.clipboard -> applicationContext.copyToClipboard("Test data")
}
}
} | 1 | Kotlin | 0 | 0 | 76276059ea9af82f68cca73294e4b89a486260ff | 2,550 | fcm_client | Apache License 2.0 |
src/test/kotlin/no/nav/tiltak/tiltaknotifikasjon/TiltakNotifikasjonApplicationTests.kt | navikt | 718,075,727 | false | {"Kotlin": 31691, "Dockerfile": 102} | package no.nav.tiltak.tiltaknotifikasjon
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.context.annotation.Profile
@SpringBootTest
@Profile("dockercompose")
class TiltakNotifikasjonApplicationTests {
@Test
fun contextLoads() {
}
}
| 0 | Kotlin | 0 | 0 | 991a13a6ef9764608bb86800e087665851051e4e | 312 | tiltak-notifikasjon | MIT License |
app/src/main/java/com/example/doitnow/data/repository/MainRepository.kt | HimashRajapaksha | 840,378,745 | false | {"Kotlin": 26095} | package com.example.doitnow.data.repository
import com.example.doitnow.data.database.TaskDao
import com.example.doitnow.data.model.TaskEntity
import javax.inject.Inject
class MainRepository @Inject constructor(private val dao: TaskDao) {
fun allTasks() = dao.getAllTasks()
fun searchTasks(search:String) = dao.searchTask(search)
fun filterTasks(filter:String) = dao.filetTask(filter)
suspend fun deleteTask(entity:TaskEntity) = dao.deleteTask(entity)
} | 0 | Kotlin | 0 | 1 | 71fabd65c3c6a7bd7243abd8d6bc87c3faa11430 | 473 | TaskBuddy | MIT License |
android-buddy-plugin/src/main/java/com/likethesalad/android/buddy/utils/FilesHolder.kt | LikeTheSalad | 289,290,234 | false | null | package com.likethesalad.android.buddy.utils
import java.io.File
data class FilesHolder(
val dirFiles: Set<File>,
val jarFiles: Set<File>,
val allFiles: Set<File>
) | 0 | Kotlin | 6 | 43 | 1089f89e1f8ad5fb9fdfb9195592cc8a7d04e299 | 178 | android-buddy | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.