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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
draw/src/main/java/com/dcxing/draw/tool/WatchTool.kt | dannycx | 740,734,778 | false | {"Kotlin": 78081, "Java": 30655, "HTML": 1578, "RenderScript": 980} | package com.dcxing.draw.tool
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import java.util.Calendar
import kotlin.math.cos
import kotlin.math.sin
object WatchTool {
// 表盘直径,宽,高
val len = 260
val watchWidth = 300
val watchHeight = 300
val calendar = Calendar.getInstance()
val watchPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.GRAY
style = Paint.Style.STROKE
strokeWidth = 1f
}
fun render(canvas: Canvas) {
val centerX = (watchWidth - len) / 2f
val centerY = (watchHeight - len) / 2f
canvas.translate(centerX, centerY)
// 表盘
drawPlate(canvas)
// 指针
drawPoint(canvas)
}
private fun drawPlate(canvas: Canvas) {
canvas.save()
watchPaint.style = Paint.Style.STROKE
watchPaint.strokeWidth = 2f
val radius = len / 2f
canvas.drawCircle(radius, radius, radius, watchPaint)
// 绘制刻度
for (i in 0 until 60) {
if (i % 5 == 0) {
// 整点刻度,长度半径1/10,起点:radius + 9 / 10 * radius,3点钟开始绘制
watchPaint.strokeWidth = 4f
watchPaint.color = Color.BLACK
canvas.drawLine(radius + 9 * radius / 10, radius, len.toFloat(), radius, watchPaint)
} else {
watchPaint.color = Color.GRAY
watchPaint.strokeWidth = 1f
canvas.drawLine(radius + 14 * radius / 15, radius, len.toFloat(), radius, watchPaint)
}
// 每个刻度间隔6°
canvas.rotate(6f, radius, radius)
}
canvas.restore()
}
private fun drawPoint(canvas: Canvas) {
// 获取设备时间:时分秒
calendar.timeInMillis = System.currentTimeMillis()
val hours = calendar.get(Calendar.HOUR) % 12 // 12小时制
val minute = calendar.get(Calendar.MINUTE)
val second = calendar.get(Calendar.SECOND)
watchPaint.color = Color.BLACK
// 转换弧度
val radius = len / 2f
val startX = radius
val startY = radius
canvas.save()
watchPaint.style = Paint.Style.FILL
canvas.drawCircle(startY, startY, 8f, watchPaint)
canvas.restore()
// 时分秒针
// 秒针
var degree = 360 * second / 60.0
var radians = Math.toRadians(degree)
var endX = startX + radius * cos(radians) * 0.8f
var endY = startY + radius * sin(radians) * 0.8f
canvas.save()
watchPaint.strokeWidth = 1f
// 0°从3点开始,移动至12点旋转-90°
canvas.rotate(-90f, radius, radius)
canvas.drawLine(startX, startY, endX.toFloat(), endY.toFloat(), watchPaint)
// 秒针尾部
radians = Math.toRadians(degree - 180)
endX = startX + radius * cos(radians) * 0.2f
endY = startY + radius * sin(radians) * 0.2f
canvas.drawLine(startX, startY, endX.toFloat(), endY.toFloat(), watchPaint)
canvas.restore()
// 分针
degree = 360 * minute / 60.0
radians = Math.toRadians(degree)
endX = startX + radius * cos(radians) * 0.6f
endY = startY + radius * sin(radians) * 0.6f
canvas.save()
watchPaint.strokeWidth = 3f
// 0°从3点开始,移动至12点旋转-90°
canvas.rotate(-90f, radius, radius)
canvas.drawLine(startX, startY, endX.toFloat(), endY.toFloat(), watchPaint)
canvas.restore()
// 时针:整点度数 + 分针对应时针的度数 1/12
degree = 360 * hours / 12.0 + degree / 12
radians = Math.toRadians(degree)
endX = startX + radius * cos(radians) * 0.4f
endY = startY + radius * sin(radians) * 0.4f
watchPaint.style = Paint.Style.STROKE
canvas.save()
watchPaint.strokeWidth = 5f
// 0°从3点开始,移动至12点旋转-90°
canvas.rotate(-90f, radius, radius)
canvas.drawLine(startX, startY, endX.toFloat(), endY.toFloat(), watchPaint)
canvas.restore()
}
}
| 0 | Kotlin | 0 | 0 | fd07fba5b446ecc28a486cb85480d9095263334a | 3,956 | XDemo | Apache License 2.0 |
src/test/kotlin/com/chromasgaming/ktweet/api/CountTweetsAPITest.kt | ChromasIV | 415,988,179 | false | {"Kotlin": 42956} | //package com.chromasgaming.ktweet.api
//
//import com.chromasgaming.ktweet.models.Granularity
//import com.chromasgaming.ktweet.oauth2.TwitterOauth2Authentication
//import kotlinx.coroutines.test.runTest
//import org.junit.jupiter.api.BeforeEach
//import org.junit.jupiter.api.Test
//
//internal class CountTweetsAPITest {
// private lateinit var countTweetsAPI: CountTweetsAPI
//
// @BeforeEach
// fun setUp() {
// countTweetsAPI = CountTweetsAPI()
// }
//
// @Test
// fun recentTweets() = runTest {
// val paramMap = LinkedHashMap<String, String>()
// paramMap["query"] = "from:250181762"
// paramMap["granularity"] = Granularity.DAY.value
//
// val bearerToken = TwitterOauth2Authentication().getAppOnlyBearerToken(
// System.getProperty("consumerKey"),
// System.getProperty("consumerSecret")
// )
//
// val tweetCount = countTweetsAPI.recent(paramMap, bearerToken)
//
// assert(tweetCount.data.isNotEmpty())
// assert(tweetCount.meta.total_tweet_count >= 0)
// }
//}
| 0 | Kotlin | 4 | 32 | 504dec2f740d9d2c64e47af3e9029c7a2d0945c2 | 1,079 | KTweet | Apache License 2.0 |
app/src/main/java/com/i_africa/shiftcalenderobajana/screens/viewmvc/viewmvcfactory/ViewMvcFactory.kt | iykeafrica | 395,050,451 | false | null | package com.i_africa.shiftcalenderobajana.screens.viewmvc.viewmvcfactory
import android.view.LayoutInflater
import android.view.ViewGroup
import com.i_africa.shiftcalenderobajana.screens.calculate_ot.CalculateOvertimeViewMvc
import com.i_africa.shiftcalenderobajana.screens.selectshift.SelectShiftViewMvc
import com.i_africa.shiftcalenderobajana.screens.shift.ShiftViewMvc
import com.i_africa.shiftcalenderobajana.screens.shift_materialcalender.ShiftMaterialCalendarViewMvc
import javax.inject.Inject
class ViewMvcFactory @Inject constructor(private val layoutInflater: LayoutInflater) {
fun newShiftViewMvc(parent: ViewGroup?) : ShiftViewMvc {
return ShiftViewMvc(layoutInflater, parent)
}
fun newSelectShiftViewMvc(parent: ViewGroup?) : SelectShiftViewMvc {
return SelectShiftViewMvc(layoutInflater, parent)
}
fun newCalculateOvertimeViewMvc(parent: ViewGroup?): CalculateOvertimeViewMvc {
return CalculateOvertimeViewMvc(layoutInflater, parent)
}
fun newShiftMaterialCalendarViewMvc(parent: ViewGroup?): ShiftMaterialCalendarViewMvc {
return ShiftMaterialCalendarViewMvc(layoutInflater, parent)
}
} | 0 | Kotlin | 0 | 0 | 571e23a5294f69282937d60bf9174174a3bad26d | 1,171 | OCPShiftSchedule | Apache License 2.0 |
src/main/kotlin/cz/richter/david/astroants/Application.kt | Dave562CZ | 103,682,625 | false | {"Kotlin": 29873, "Groovy": 12847, "Java": 7401} | package cz.richter.david.astroants
import com.fasterxml.jackson.databind.ObjectMapper
import cz.richter.david.astroants.parser.ConcurrentInputMapParser
import cz.richter.david.astroants.parser.MapLocationParserImpl
import cz.richter.david.astroants.parser.SequentialInputMapParser
import cz.richter.david.astroants.rest.SpringRestClient
import cz.richter.david.astroants.shortestpath.AStar
import cz.richter.david.astroants.shortestpath.ConcurrentHipsterGraphCreator
import cz.richter.david.astroants.shortestpath.Dijkstra
import cz.richter.david.astroants.shortestpath.SequentialHipsterGraphCreator
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringBootConfiguration
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.builder.SpringApplicationBuilder
import org.springframework.context.annotation.Bean
import org.springframework.web.client.RestTemplate
import java.net.URI
/**
* Runs the program :D
*/
fun main(args: Array<String>) {
@Suppress("UnnecessaryVariable")
val arguments = args
// val arguments = arrayOf(WARMUP_ARG)
SpringApplicationBuilder(Application::class.java)
.web(false)
.run(*arguments)
}
private val WARMUP_ARG = "warmup"
/**
* Class which start Spring boot application and solves the task of searching the shortest path for astroants
* using provided endpoints with input settings and solution verification
* By default system does not warm up JVM so results are not optimal.
* For better results you can pass argument warmup which does a little warmup
* by running the process of parsing input and 10 times before real run
*/
@SpringBootConfiguration
@EnableAutoConfiguration
open class Application() : CommandLineRunner {
override fun run(vararg args: String?) {
val runner = Runner(restClient(), concurrentInputMapParser(), aStarConcurrent(), consoleResultPrinter())
if (args.size > 0 && args[0] == WARMUP_ARG)
runner.warmup(objectMapper())
runner.run()
}
@Bean
open fun dijkstraSequential() = Dijkstra(sequentialGraphCreator())
@Bean
open fun dijkstraConcurrent() = Dijkstra(concurrentGraphCreator())
@Bean
open fun aStarSequential() = AStar(sequentialGraphCreator())
@Bean
open fun aStarConcurrent() = AStar(concurrentGraphCreator())
@Bean
open fun sequentialGraphCreator() = SequentialHipsterGraphCreator()
@Bean
open fun concurrentGraphCreator() = ConcurrentHipsterGraphCreator()
@Bean
open fun sequentialInputMapParser() = SequentialInputMapParser(mapLocationParser())
@Bean
open fun mapLocationParser() = MapLocationParserImpl()
@Bean
open fun concurrentInputMapParser() = ConcurrentInputMapParser(mapLocationParser())
@Bean
open fun endpointUri() = URI("http://tasks-rad.quadient.com:8080/task")
@Bean
open fun restTemplate() = RestTemplate()
@Bean
open fun restClient() = SpringRestClient(endpointUri(), restTemplate())
@Bean
open fun objectMapper() = ObjectMapper()
@Bean
open fun consoleResultPrinter() = ConsoleResultPrinter()
}
| 0 | Kotlin | 0 | 0 | fd51fcc5b7726cf4a2b94bb213a44e4b40d214ff | 3,180 | astroants | MIT License |
material/src/main/java/com/m3u/material/model/LocalHazeState.kt | realOxy | 592,741,804 | false | {"Kotlin": 734765} | package com.m3u.material.model
import androidx.compose.runtime.staticCompositionLocalOf
import dev.chrisbanes.haze.HazeState
val LocalHazeState = staticCompositionLocalOf { HazeState() } | 19 | Kotlin | 9 | 95 | 67e7185408a544094c7b4403f8309a52dad4aca0 | 188 | M3UAndroid | Apache License 2.0 |
loon/src/main/java/com/sirenartt/loon/core/AccessibilityChecker.kt | Zudoku | 609,994,763 | false | null | package com.sirenartt.loon.core
import android.graphics.Bitmap
import android.view.View
import com.google.android.apps.common.testing.accessibility.framework.*
import com.google.android.apps.common.testing.accessibility.framework.uielement.AccessibilityHierarchyAndroid
import com.google.android.apps.common.testing.accessibility.framework.utils.contrast.BitmapImage
import com.google.common.collect.ImmutableSet
class AccessibilityChecker {
fun runChecks(rootView: View): List<AccessibilityFinding> {
val hierarchy: AccessibilityHierarchyAndroid = AccessibilityHierarchyAndroid
.newBuilder(rootView)
.build()
val results: MutableList<AccessibilityHierarchyCheckResult> = ArrayList()
val (parameters, bitmap) = buildParameters(rootView)
for (check in getChecks()) {
results.addAll(check.runCheckOnHierarchy(hierarchy, null, parameters))
}
bitmap?.recycle()
val findings = AccessibilityCheckResultUtils.getResultsForTypes(
results, getAccessibilityFindingResultTypes()
)
return findings.map {
AccessibilityFinding.fromAccessibilityCheckResult(it)
}
}
private fun getAccessibilityFindingResultTypes(): Set<AccessibilityCheckResult.AccessibilityCheckResultType> {
return setOf(
AccessibilityCheckResult.AccessibilityCheckResultType.WARNING,
AccessibilityCheckResult.AccessibilityCheckResultType.ERROR,
AccessibilityCheckResult.AccessibilityCheckResultType.INFO
)
}
private fun buildParameters(rootView: View): Pair<Parameters, Bitmap?> {
val parameters = Parameters()
return if (AccessibilityLoon.config.useScreenshotsForAccessibilityChecks) {
val screenshotter = Screenshotter()
val screenshot: Bitmap = screenshotter.getScreenshot(rootView)
parameters.putScreenCapture(BitmapImage(screenshot))
parameters to screenshot
} else {
parameters to null
}
}
private fun getChecks(): ImmutableSet<AccessibilityHierarchyCheck> {
return AccessibilityCheckPreset.getAccessibilityHierarchyChecksForPreset(
AccessibilityLoon.config.accessibilityChecks
)
}
} | 2 | Kotlin | 0 | 0 | 215bc2cd3e2ca955960893c9622034e41ee6a19c | 2,301 | accessibility-loon | Apache License 2.0 |
src/main/kotlin/me/yaman/can/demo/exception/GlobalExceptionHandler.kt | canyaman | 352,449,602 | false | null | package me.yaman.can.demo.exception
import org.springframework.boot.autoconfigure.web.WebProperties
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler
import org.springframework.boot.web.error.ErrorAttributeOptions
import org.springframework.boot.web.reactive.error.ErrorAttributes
import org.springframework.context.ApplicationContext
import org.springframework.core.annotation.Order
import org.springframework.http.MediaType
import org.springframework.http.codec.ServerCodecConfigurer
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.BodyInserters
import org.springframework.web.reactive.function.server.RequestPredicates
import org.springframework.web.reactive.function.server.RouterFunction
import org.springframework.web.reactive.function.server.RouterFunctions
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import reactor.core.publisher.Mono
@Component
@Order(-2)
class GlobalExceptionHandler(
errorAttributes: ErrorAttributes?,
resources: WebProperties.Resources?,
applicationContext: ApplicationContext?,
serverCodecConfigurer: ServerCodecConfigurer
) : AbstractErrorWebExceptionHandler(errorAttributes, resources, applicationContext) {
init {
this.setMessageWriters(serverCodecConfigurer.writers)
}
override fun getRoutingFunction(errorAttributes: ErrorAttributes?): RouterFunction<ServerResponse> {
return RouterFunctions.route(RequestPredicates.all(), ::formatErrorResponse)
}
private fun formatErrorResponse(request: ServerRequest): Mono<ServerResponse> {
val errorAttributesMap: Map<String, Any> =
getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.MESSAGE))
val status = errorAttributesMap["status"] as? Int ?: 500
return ServerResponse
.status(status)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(errorAttributesMap))
}
}
| 0 | Kotlin | 0 | 0 | 010e5224759590a416e608f408be1d4e22c96c41 | 2,115 | spring-boot-gateway | MIT License |
contests/Kotlin Heroes Practice 4/Sum_of_round_numbers.kt | Razdeep | 151,215,612 | false | null | // https://codeforces.com/contest/1347/problem/C
fun main() {
var tc: Int
tc = readLine()!!.toInt()
while (tc-- > 0) {
var text: String = readLine()!!
var len: Int = text.length
var ans: MutableList<String> = arrayListOf()
for (i in 0..(len - 1)) {
if (text[i] != '0') {
var sb = StringBuilder()
sb.append(text[i])
for (j in 0..(len - i - 2)) {
sb.append("0")
}
ans.add(sb.toString())
}
}
println(ans.size)
for (i in 0..(ans.size - 1)) {
print(ans.get(i))
print(" ")
}
println()
}
} | 0 | C++ | 0 | 2 | 8a563f41bc31029ce030213f196b1e1355efc439 | 721 | Codeforces-Solutions | MIT License |
sample/src/main/java/com/lzh/nonview/router/demo/manager/DataManager.kt | yjfnypeu | 67,584,008 | false | null | package com.lzh.nonview.router.demo.manager
/**
* 一个本地的内存数据管理容器。提供登录状态进行使用。
* DATE: 2018/5/8
* AUTHOR: haoge
*/
object DataManager {
var username:String = "HaogeStudio"
var login:Boolean = false
} | 1 | Java | 88 | 747 | 3a7340ed0e2be0d434531ab30baafbc91f3f5237 | 209 | Router | Apache License 2.0 |
ir/src/main/kotlin/org/ksharp/ir/VariableIndex.kt | ksharp-lang | 573,931,056 | false | {"Kotlin": 1490588, "Java": 53036, "TypeScript": 3203} | package org.ksharp.ir
import org.ksharp.typesystem.attributes.Attribute
val NoCaptured: String? = null
enum class VarKind {
Var,
Arg
}
data class VarInfo(
val index: Int,
val kind: VarKind,
val attributes: Set<Attribute>,
val captureName: String? = NoCaptured
)
interface VariableIndex {
val size: Int
operator fun get(name: String): VarInfo?
}
class ClosureIndex(val arguments: VariableIndex, val context: VariableIndex) : VariableIndex {
override val size: Int
get() = arguments.size + 1
val captured = mutableMapOf<String, VarInfo>()
override operator fun get(name: String): VarInfo? {
val arg = arguments[name]
if (arg != null) return arg
val alreadyCaptured = captured[name]
if (alreadyCaptured != null) return alreadyCaptured.copy(captureName = name)
val captureVar = context[name]
if (captureVar != null) {
captured[name] = captureVar.copy(captureName = name)
}
return captured[name]
}
}
interface MutableVariableIndex : VariableIndex {
operator fun set(name: String, varInfo: VarInfo)
}
val emptyVariableIndex = object : VariableIndex {
override val size: Int = 0
override operator fun get(name: String): VarInfo? = null
}
fun argIndex(positions: Map<String, VarInfo>) = object : VariableIndex {
override val size: Int = 0
override operator fun get(name: String): VarInfo? = positions[name]
}
fun closureIndex(index: VariableIndex, parent: VariableIndex) = ClosureIndex(index, parent)
fun mutableVariableIndexes(parent: VariableIndex) = object : MutableVariableIndex {
private val repo = mutableMapOf<String, VarInfo>()
override fun set(name: String, varInfo: VarInfo) {
if (!repo.containsKey(name)) {
repo[name] = varInfo
} else error("Variable $name already exists")
}
override val size: Int
get() = repo.size + parent.size
override fun get(name: String): VarInfo? = repo[name] ?: parent[name]
}
| 4 | Kotlin | 0 | 0 | 688d0155a67cddba755ce23e65929fc3d532a721 | 2,037 | ksharp-kt | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/Eclipse.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.filled
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.rounded.Icons
public val Icons.Filled.Eclipse: ImageVector
get() {
if (_eclipse != null) {
return _eclipse!!
}
_eclipse = Builder(name = "Eclipse", 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(18.0f, 18.0f)
curveToRelative(-7.929f, -0.252f, -7.928f, -11.749f, 0.0f, -12.0f)
curveTo(25.929f, 6.252f, 25.928f, 17.749f, 18.0f, 18.0f)
close()
moveTo(10.0f, 12.0f)
arcToRelative(7.977f, 7.977f, 0.0f, false, true, 2.443f, -5.754f)
arcTo(1.913f, 1.913f, 0.0f, false, false, 13.0f, 4.863f)
lineTo(13.0f, 1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -2.0f, 0.0f)
lineTo(11.0f, 5.071f)
arcToRelative(6.913f, 6.913f, 0.0f, false, false, -1.6f, 0.43f)
lineTo(7.355f, 1.986f)
arcTo(1.0f, 1.0f, 0.0f, true, false, 5.627f, 2.992f)
lineTo(7.669f, 6.5f)
arcTo(7.08f, 7.08f, 0.0f, false, false, 6.522f, 7.646f)
lineTo(3.0f, 5.6f)
arcTo(1.0f, 1.0f, 0.0f, false, false, 2.0f, 7.326f)
lineTo(5.512f, 9.372f)
arcTo(6.94f, 6.94f, 0.0f, false, false, 5.071f, 11.0f)
lineTo(1.0f, 11.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f)
lineTo(5.071f, 13.0f)
arcToRelative(6.95f, 6.95f, 0.0f, false, false, 0.439f, 1.622f)
lineTo(2.0f, 16.662f)
arcTo(1.0f, 1.0f, 0.0f, false, false, 3.01f, 18.391f)
lineToRelative(3.509f, -2.042f)
arcToRelative(7.028f, 7.028f, 0.0f, false, false, 1.13f, 1.131f)
lineTo(5.6f, 21.0f)
arcTo(1.0f, 1.0f, 0.0f, false, false, 7.33f, 22.007f)
lineTo(9.376f, 18.49f)
arcTo(6.966f, 6.966f, 0.0f, false, false, 11.0f, 18.929f)
lineTo(11.0f, 23.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 2.0f, 0.0f)
lineTo(13.0f, 19.137f)
arcToRelative(1.913f, 1.913f, 0.0f, false, false, -0.557f, -1.383f)
arcTo(7.977f, 7.977f, 0.0f, false, true, 10.0f, 12.0f)
close()
}
}
.build()
return _eclipse!!
}
private var _eclipse: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,282 | icons | MIT License |
core/src/main/java/com/oscarg798/amiibowiki/core/extensions/ComposeImageTarget.kt | oscarg798 | 275,942,605 | false | null | /*
* Copyright 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
*/
package com.oscarg798.amiibowiki.core.extensions
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import com.squareup.picasso.Picasso
import com.squareup.picasso.Target
interface ImageCallbacks {
fun onLoaded(bitmap: Bitmap)
fun onFailure(error: Exception)
}
class ComposeImageTarget(private val imageCallbacks: ImageCallbacks) : Target {
override fun onBitmapLoaded(bitmap: Bitmap, from: Picasso.LoadedFrom?) {
imageCallbacks.onLoaded(bitmap)
}
override fun onBitmapFailed(error: Exception, errorDrawable: Drawable?) {
imageCallbacks.onFailure(error)
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
// DO_NOTHING
}
}
| 0 | Kotlin | 3 | 10 | e3f7f3f97af3ffb4998a3e8d4cb2144c82a5221c | 1,798 | AmiiboWiki | MIT License |
db/sqlite/src/commonMain/kotlin/pw/binom/db/sqlite/AsyncPreparedStatementAdapter.kt | caffeine-mgn | 182,165,415 | false | {"C": 13079003, "Kotlin": 1913743, "C++": 200, "Shell": 88} | package pw.binom.db.sqlite
import com.ionspin.kotlin.bignum.decimal.BigDecimal
import com.ionspin.kotlin.bignum.integer.BigInteger
import pw.binom.UUID
import pw.binom.concurrency.*
import pw.binom.coroutine.start
import pw.binom.date.Date
import pw.binom.db.async.AsyncConnection
import pw.binom.db.async.AsyncPreparedStatement
import pw.binom.db.async.AsyncResultSet
import pw.binom.db.sync.SyncPreparedStatement
import pw.binom.doFreeze
import pw.binom.neverFreeze
class AsyncPreparedStatementAdapter(
val ref: Reference<SyncPreparedStatement>,
val worker: Worker,
override val connection: AsyncConnection,
) : AsyncPreparedStatement {
init {
neverFreeze()
}
override suspend fun set(index: Int, value: BigInteger) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: BigDecimal) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: Double) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: Float) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: Int) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: Long) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: String) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: Boolean) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: ByteArray) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: Date) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun setNull(index: Int) {
val ref = ref
worker.start {
ref.value.setNull(index)
}
}
override suspend fun executeQuery(): AsyncResultSet {
val ref = ref
val out = worker.start {
val r = ref.value.executeQuery()
r.asReference() to r.columns
}
return AsyncResultSetAdapter(
ref = out.first,
worker = worker,
columns = out.second
)
}
override suspend fun setValue(index: Int, value: Any?) {
val ref = ref
worker.start {
ref.value.setValue(index, value)
}
}
override suspend fun executeQuery(vararg arguments: Any?): AsyncResultSet {
arguments.doFreeze()
val ref = ref
val out = worker.start {
val r = ref.value.executeQuery(*arguments)
r.asReference() to r.columns
}
return AsyncResultSetAdapter(
ref = out.first,
worker = worker,
columns = out.second
)
}
override suspend fun executeUpdate(vararg arguments: Any?): Long {
arguments.doFreeze()
val ref = ref
return worker.start {
ref.value.executeUpdate(*arguments)
}
}
override suspend fun set(index: Int, value: UUID) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun executeUpdate(): Long {
val ref = ref
return worker.start {
ref.value.executeUpdate()
}
}
override suspend fun asyncClose() {
val ref = ref
worker.start {
ref.value.close()
}
ref.close()
}
} | 7 | C | 2 | 59 | 580ff27a233a1384273ef15ea6c63028dc41dc01 | 4,066 | pw.binom.io | Apache License 2.0 |
db/sqlite/src/commonMain/kotlin/pw/binom/db/sqlite/AsyncPreparedStatementAdapter.kt | caffeine-mgn | 182,165,415 | false | {"C": 13079003, "Kotlin": 1913743, "C++": 200, "Shell": 88} | package pw.binom.db.sqlite
import com.ionspin.kotlin.bignum.decimal.BigDecimal
import com.ionspin.kotlin.bignum.integer.BigInteger
import pw.binom.UUID
import pw.binom.concurrency.*
import pw.binom.coroutine.start
import pw.binom.date.Date
import pw.binom.db.async.AsyncConnection
import pw.binom.db.async.AsyncPreparedStatement
import pw.binom.db.async.AsyncResultSet
import pw.binom.db.sync.SyncPreparedStatement
import pw.binom.doFreeze
import pw.binom.neverFreeze
class AsyncPreparedStatementAdapter(
val ref: Reference<SyncPreparedStatement>,
val worker: Worker,
override val connection: AsyncConnection,
) : AsyncPreparedStatement {
init {
neverFreeze()
}
override suspend fun set(index: Int, value: BigInteger) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: BigDecimal) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: Double) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: Float) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: Int) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: Long) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: String) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: Boolean) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: ByteArray) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun set(index: Int, value: Date) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun setNull(index: Int) {
val ref = ref
worker.start {
ref.value.setNull(index)
}
}
override suspend fun executeQuery(): AsyncResultSet {
val ref = ref
val out = worker.start {
val r = ref.value.executeQuery()
r.asReference() to r.columns
}
return AsyncResultSetAdapter(
ref = out.first,
worker = worker,
columns = out.second
)
}
override suspend fun setValue(index: Int, value: Any?) {
val ref = ref
worker.start {
ref.value.setValue(index, value)
}
}
override suspend fun executeQuery(vararg arguments: Any?): AsyncResultSet {
arguments.doFreeze()
val ref = ref
val out = worker.start {
val r = ref.value.executeQuery(*arguments)
r.asReference() to r.columns
}
return AsyncResultSetAdapter(
ref = out.first,
worker = worker,
columns = out.second
)
}
override suspend fun executeUpdate(vararg arguments: Any?): Long {
arguments.doFreeze()
val ref = ref
return worker.start {
ref.value.executeUpdate(*arguments)
}
}
override suspend fun set(index: Int, value: UUID) {
val ref = ref
worker.start {
ref.value.set(index, value)
}
}
override suspend fun executeUpdate(): Long {
val ref = ref
return worker.start {
ref.value.executeUpdate()
}
}
override suspend fun asyncClose() {
val ref = ref
worker.start {
ref.value.close()
}
ref.close()
}
} | 7 | C | 2 | 59 | 580ff27a233a1384273ef15ea6c63028dc41dc01 | 4,066 | pw.binom.io | Apache License 2.0 |
src/vision/alter/telekot/telegram/model/updates/WebhookInfo.kt | alter-vision | 261,156,045 | false | null | package vision.alter.telekot.telegram.model.updates
import kotlinx.serialization.Serializable
import vision.alter.telekot.telegram.model.markers.TelegramObject
/**
* Contains information about the current status of a webhook (https://core.telegram.org/bots/api#webhookinfo).
*/
@Serializable
data class WebhookInfo(
/**
* Webhook URL, may be empty if webhook is not set up
*/
val url: String = "",
/**
* True, if a custom certificate was provided for webhook certificate checks
*/
val hasCustomCertificate: Boolean = false,
/**
* Number of updates awaiting delivery
*/
val pendingUpdateCount: Int = 0,
/**
* Optional. Unix time for the most recent error that happened when trying to deliver an update via webhook
*/
val lastErrorDate: Int = -1,
/**
* Optional. Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook
*/
val lastErrorMessage: String? = null,
/**
* Optional. Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery
*/
val maxConnections: Int? = null,
/**
* Optional. A list of update types the bot is subscribed to. Defaults to all update types
*/
// @TODO: enum
val allowedUpdates: List<String>? = null
) : TelegramObject
| 10 | Kotlin | 0 | 2 | 28943db77d5ed7b0759ef180e61c1db78032a408 | 1,376 | telekot | Apache License 2.0 |
nav/editor/src/com/android/tools/idea/naveditor/scene/targets/NavScreenTargetProvider.kt | JetBrains | 60,701,247 | false | {"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19} | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.naveditor.scene.targets
import com.android.tools.idea.common.scene.SceneComponent
import com.android.tools.idea.common.scene.TargetProvider
import com.android.tools.idea.common.scene.target.Target
import com.android.tools.idea.naveditor.model.isDestination
import com.android.tools.idea.naveditor.model.supportsActions
/**
* [TargetProvider] for navigation screens.
*
* Notably, adds the actions going from this screen to others.
*/
object NavScreenTargetProvider : TargetProvider {
override fun createTargets(sceneComponent: SceneComponent): List<Target> {
if (!sceneComponent.nlComponent.isDestination || sceneComponent.parent == null) {
return listOf()
}
val result = mutableListOf<Target>(ScreenDragTarget(sceneComponent))
if (sceneComponent.nlComponent.supportsActions) {
result.add(ActionHandleTarget(sceneComponent))
}
return result
}
}
| 5 | Kotlin | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 1,544 | android | Apache License 2.0 |
src/main/kotlin/Main.kt | Victorov-I-A | 433,562,964 | false | {"Kotlin": 1869, "Dockerfile": 331} | fun main(args: Array<String>?) {
CurrencyConverter().start()
} | 0 | Kotlin | 0 | 0 | cd64a3e064231973239c74c6de779aa83bebe3eb | 66 | CurrencyConverter | MIT License |
app/src/main/java/com/astroscoding/jokesapp/presentation/screen/pun_jokes/PunJokesViewModel.kt | Astroa7m | 459,685,492 | false | {"Kotlin": 134726} | package com.astroscoding.jokesapp.presentation.screen.pun_jokes
import com.astroscoding.jokesapp.data.local.PreferencesManager
import com.astroscoding.jokesapp.domain.use_case.FavouriteJokesUseCase
import com.astroscoding.jokesapp.domain.use_case.GetJokesUseCase
import com.astroscoding.jokesapp.domain.use_case.UnFavouriteJokeUseCase
import com.astroscoding.jokesapp.presentation.core.BaseJokesViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class PunJokesViewModel @Inject constructor(
getAllJokes: GetJokesUseCase,
favouriteJokesUseCase: FavouriteJokesUseCase,
unFavouriteJokeUseCase: UnFavouriteJokeUseCase,
preferencesManager: PreferencesManager
) : BaseJokesViewModel(getAllJokes, favouriteJokesUseCase, unFavouriteJokeUseCase, preferencesManager) {
init {
getAllJokes(category = listOf("Pun"))
}
} | 0 | Kotlin | 2 | 5 | 691a420baf3b7be90d24f1bfdd988d944837a8d4 | 895 | clean_architecture_mvvm_jokes_app | MIT License |
src/main/kotlin/de/ebf/spring/jsonapi/errors/resolvers/WebServletExceptionResolver.kt | ebf | 193,854,358 | false | null | package de.ebf.spring.jsonapi.errors.resolvers
import de.ebf.spring.jsonapi.errors.messages.ErrorMessageResolvable
import org.springframework.core.Ordered
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.util.StringUtils
import org.springframework.web.HttpMediaTypeNotSupportedException
import org.springframework.web.HttpRequestMethodNotSupportedException
import org.springframework.web.HttpMediaTypeNotAcceptableException
import org.springframework.web.bind.MissingMatrixVariableException
import org.springframework.web.bind.MissingRequestCookieException
import org.springframework.web.bind.MissingRequestHeaderException
import org.springframework.web.bind.MissingServletRequestParameterException
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException
import org.springframework.web.multipart.support.MissingServletRequestPartException
import org.springframework.web.servlet.NoHandlerFoundException
import java.util.*
/**
* Implementation of an [ExceptionResolver] that is responsible for handling
* various web exceptions.
*/
class WebServletExceptionResolver: ExceptionResolver {
override fun getOrder(): Int {
return Ordered.LOWEST_PRECEDENCE
}
override fun resolve(throwable: Throwable): ResolvedException? {
if (throwable is HttpRequestMethodNotSupportedException) {
return handleHttpRequestMethodNotSupported(throwable)
}
if (throwable is HttpMediaTypeNotSupportedException) {
return handleHttpMediaTypeNotSupported(throwable)
}
if (throwable is HttpMediaTypeNotAcceptableException) {
return handleHttpMediaTypeNotAcceptableException(throwable)
}
if (throwable is MissingServletRequestPartException) {
return handleMissingServletRequestPartException(throwable)
}
if (throwable is MissingServletRequestParameterException) {
return handleMissingServletRequestParameterException(throwable)
}
if (throwable is MethodArgumentTypeMismatchException) {
return handleMethodArgumentTypeMismatchException(throwable)
}
if (throwable is MissingRequestHeaderException) {
return handleMissingRequestHeaderException(throwable)
}
if (throwable is MissingRequestCookieException) {
return handleMissingRequestCookieException(throwable)
}
if (throwable is MissingMatrixVariableException) {
return handleMissingMatrixVariableException(throwable)
}
if (throwable is NoHandlerFoundException) {
return handleNoHandlerFoundException(throwable)
}
return null
}
/**
* Handle the case where no request handler method was found for the particular HTTP request method.
*
* It sends an HTTP 405 error, sets the "Allow" header and returns an exception response
* object with a error message.
*
* @param ex the HttpRequestMethodNotSupportedException to be handled
* @return an exception response with a list of supported methods
*/
private fun handleHttpRequestMethodNotSupported(ex: HttpRequestMethodNotSupportedException): ResolvedException {
val headers = HttpHeaders()
headers.allow = ex.supportedHttpMethods!!
val errors = listOf(
ErrorMessageResolvable("exception.method-not-supported",
arrayOf(StringUtils.arrayToCommaDelimitedString(ex.supportedMethods))
)
)
return ResolvedException(status = HttpStatus.METHOD_NOT_ALLOWED, headers = headers, errors = errors)
}
/**
* Handle the case where the request handler cannot generate a response that is acceptable by the client
*
* It sends an HTTP 406 error, sets the "Allow" header and returns an exception response
* object with a error message.
*
* @param ex the HttpMediaTypeNotAcceptableException to be handled
* @return an exception response with a list of supported methods
*/
private fun handleHttpMediaTypeNotAcceptableException(ex: HttpMediaTypeNotAcceptableException): ResolvedException {
val headers = HttpHeaders()
headers.accept = ex.supportedMediaTypes
val errors = listOf(
ErrorMessageResolvable("exception.content-type-not-supported",
arrayOf(MediaType.toString(ex.supportedMediaTypes))
)
)
return ResolvedException(status = HttpStatus.NOT_ACCEPTABLE, headers = headers, errors = errors)
}
/**
* Handle the case where no [message converters][org.springframework.http.converter.HttpMessageConverter]
* were found for the PUT or POSTed content.
*
* It sends an HTTP 415 error, sets the "Accept" header and returns an exception response
* object with a error message.
*
* @param ex the HttpMediaTypeNotSupportedException to be handled
* @return an exception response with a list of supported media types
*/
private fun handleHttpMediaTypeNotSupported(ex: HttpMediaTypeNotSupportedException): ResolvedException {
val headers = HttpHeaders()
headers.accept = ex.supportedMediaTypes
val errors = listOf(
ErrorMessageResolvable("exception.content-type-not-supported",
arrayOf(MediaType.toString(ex.supportedMediaTypes))
)
)
return ResolvedException(status = HttpStatus.UNSUPPORTED_MEDIA_TYPE, headers = headers, errors = errors)
}
/**
* Handle the case where the file request parameter is missing.
*
* It sends an HTTP 400 error and returns an exception response
* object with a error message.
*
* @param ex the MissingServletRequestPartException to be handled
* @return an exception response with a list of supported media types
*/
private fun handleMissingServletRequestPartException(ex: MissingServletRequestPartException): ResolvedException {
val errors = listOf(
ErrorMessageResolvable("exception.missing_file_parameter", arrayOf(
ex.requestPartName
), mapOf(
Pair("parameter", ex.requestPartName)
))
)
return ResolvedException(status = HttpStatus.BAD_REQUEST, errors = errors)
}
/**
* Handle the case where the required request parameter is missing.
*
* It sends an HTTP 400 error and returns an exception response
* object with a error message.
*
* @param ex the MissingServletRequestParameterException to be handled
* @return an exception response with a list of supported media types
*/
private fun handleMissingServletRequestParameterException(ex: MissingServletRequestParameterException): ResolvedException {
val errors = listOf(
ErrorMessageResolvable("exception.missing_parameter", arrayOf(
ex.parameterName, ex.parameterType
), mapOf(
Pair("parameter", ex.parameterName)
))
)
return ResolvedException(status = HttpStatus.BAD_REQUEST, errors = errors)
}
/**
* Handle the case where the request parameter type could not be resolved
*
* It sends an HTTP 400 error and returns an exception response
* object with a error message.
*
* @param ex the MissingServletRequestParameterException to be handled
* @return an exception response with a list of supported media types
*/
private fun handleMethodArgumentTypeMismatchException(ex: MethodArgumentTypeMismatchException): ResolvedException {
val errors = listOf(
ErrorMessageResolvable("exception.invalid_parameter", arrayOf(
ex.name, Objects.toString(ex.requiredType)
), mapOf(
Pair("parameter", ex.name)
))
)
return ResolvedException(status = HttpStatus.BAD_REQUEST, errors = errors)
}
/**
* Handle the case where the required cookie in the request is missing.
*
* It sends an HTTP 400 error and returns an exception response
* object with a error message.
*
* @param ex the MissingRequestCookieException to be handled
* @return an exception response with a list of supported media types
*/
private fun handleMissingRequestCookieException(ex: MissingRequestCookieException): ResolvedException {
val errors = listOf(
ErrorMessageResolvable("exception.missing_cookie", arrayOf(
ex.cookieName, ex.parameter.parameterType.simpleName
))
)
return ResolvedException(status = HttpStatus.BAD_REQUEST, errors = errors)
}
/**
* Handle the case where the required header in the request is missing.
*
* It sends an HTTP 400 error and returns an exception response
* object with a error message.
*
* @param ex the MissingRequestHeaderException to be handled
* @return an exception response with a list of supported media types
*/
private fun handleMissingRequestHeaderException(ex: MissingRequestHeaderException): ResolvedException {
val errors = listOf(
ErrorMessageResolvable("exception.missing_header", arrayOf(
ex.headerName, ex.parameter.parameterType.simpleName
))
)
return ResolvedException(status = HttpStatus.BAD_REQUEST, errors = errors)
}
/**
* Handle the case where the request parameter is missing.
*
* It sends an HTTP 400 error and returns an exception response
* object with a error message.
*
* @param ex the MissingMatrixVariableException to be handled
* @return an exception response with a list of supported media types
*/
private fun handleMissingMatrixVariableException(ex: MissingMatrixVariableException): ResolvedException {
val errors = listOf(
ErrorMessageResolvable("exception.missing_matrix_variable", arrayOf(
ex.variableName, ex.parameter.parameterType.simpleName
))
)
return ResolvedException(status = HttpStatus.BAD_REQUEST, errors = errors)
}
/**
* Handle the case where the request handler can not be find for this request.
*
* It sends an HTTP 404 error and returns an exception response
* object with a error message.
*
* @param ex the NoHandlerFoundException to be handled
* @return an exception response with a list of supported media types
*/
private fun handleNoHandlerFoundException(ex: NoHandlerFoundException): ResolvedException {
val errors = listOf(
ErrorMessageResolvable("exception.not_found", arrayOf(ex.requestURL))
)
return ResolvedException(status = HttpStatus.NOT_FOUND, errors = errors)
}
} | 0 | null | 1 | 1 | 42adb68fe8dd837327139832d0a691eb267f5c10 | 10,984 | spring-json-api-errors | Apache License 2.0 |
common/src/main/kotlin/com/codeviking/kxg/gl/ProgramResource.kt | dwbullok | 153,008,678 | true | {"Kotlin": 925045} | package com.codeviking.kxg.gl
import com.codeviking.kxg.KxgContext
class ProgramResource private constructor(glRef: Any, ctx: KxgContext) : GlResource(glRef, Type.PROGRAM, ctx) {
companion object {
fun create(ctx: KxgContext): ProgramResource {
return ProgramResource(glCreateProgram(), ctx)
}
}
init {
ctx.memoryMgr.memoryAllocated(this, 1)
}
override fun delete(ctx: KxgContext) {
glDeleteProgram(this)
super.delete(ctx)
}
fun attachShader(shader: ShaderResource, ctx: KxgContext) {
glAttachShader(this, shader)
}
fun link(ctx: KxgContext): Boolean {
glLinkProgram(this)
return glGetProgrami(this, GL_LINK_STATUS) == GL_TRUE
}
fun getInfoLog(ctx: KxgContext): String {
return glGetProgramInfoLog(this)
}
} | 0 | Kotlin | 0 | 0 | 5121acb8d80480bf60624ae9ef87a39b97428e27 | 846 | kool | Apache License 2.0 |
hpc/AlanTuring.kt | efarsarakis | 145,103,833 | false | null | package com.example.studio.hpc
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class AlanTuring : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_alan_turing)
val actionbar = supportActionBar
actionbar!!.title = "Alan Turing"
actionbar.setDisplayHomeAsUpEnabled(true)
actionbar.setDisplayHomeAsUpEnabled(true)
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
}
| 0 | Kotlin | 1 | 0 | 4c97538e01d4379ba79562b2bcaf291690e6d3b0 | 599 | hpc-diversity-app | MIT License |
hpc/AlanTuring.kt | efarsarakis | 145,103,833 | false | null | package com.example.studio.hpc
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class AlanTuring : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_alan_turing)
val actionbar = supportActionBar
actionbar!!.title = "Alan Turing"
actionbar.setDisplayHomeAsUpEnabled(true)
actionbar.setDisplayHomeAsUpEnabled(true)
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
}
| 0 | Kotlin | 1 | 0 | 4c97538e01d4379ba79562b2bcaf291690e6d3b0 | 599 | hpc-diversity-app | MIT License |
compound/src/main/kotlin/io/element/android/compound/tokens/generated/SemanticColors.kt | element-hq | 722,917,923 | false | {"Kotlin": 196335, "Python": 3840, "Shell": 1975} | /*
* Copyright (c) 2024 New Vector Ltd
*
* 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.
*/
@file:Suppress("all")
package io.element.android.compound.tokens.generated
import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.Color
/**
* !!! WARNING !!!
*
* THIS IS AN AUTOGENERATED FILE.
* DO NOT EDIT MANUALLY.
*/
/**
* This class holds all the semantic tokens of the Compound theme.
*/
@Immutable
data class SemanticColors(
/** Background colour for accent or brand actions. State: Hover */
val bgAccentHovered: Color,
/** Background colour for accent or brand actions. State: Pressed */
val bgAccentPressed: Color,
/** Background colour for accent or brand actions. State: Rest. */
val bgAccentRest: Color,
/** Background colour for primary actions. State: Disabled. */
val bgActionPrimaryDisabled: Color,
/** Background colour for primary actions. State: Hover. */
val bgActionPrimaryHovered: Color,
/** Background colour for primary actions. State: Pressed. */
val bgActionPrimaryPressed: Color,
/** Background colour for primary actions. State: Rest. */
val bgActionPrimaryRest: Color,
/** Background colour for secondary actions. State: Hover. */
val bgActionSecondaryHovered: Color,
/** Background colour for secondary actions. State: Pressed. */
val bgActionSecondaryPressed: Color,
/** Background colour for secondary actions. State: Rest. */
val bgActionSecondaryRest: Color,
/** Default global background for the user interface.
Elevation: Default (Level 0) */
val bgCanvasDefault: Color,
/** Default background for disabled elements. There's no minimum contrast requirement. */
val bgCanvasDisabled: Color,
/** High-contrast background color for critical state. State: Hover. */
val bgCriticalHovered: Color,
/** High-contrast background color for critical state. State: Rest. */
val bgCriticalPrimary: Color,
/** Default subtle critical surfaces. State: Rest. */
val bgCriticalSubtle: Color,
/** Default subtle critical surfaces. State: Hover. */
val bgCriticalSubtleHovered: Color,
/** Decorative background (1, Lime) for avatars and usernames. */
val bgDecorative1: Color,
/** Decorative background (2, Cyan) for avatars and usernames. */
val bgDecorative2: Color,
/** Decorative background (3, Fuchsia) for avatars and usernames. */
val bgDecorative3: Color,
/** Decorative background (4, Purple) for avatars and usernames. */
val bgDecorative4: Color,
/** Decorative background (5, Pink) for avatars and usernames. */
val bgDecorative5: Color,
/** Decorative background (6, Orange) for avatars and usernames. */
val bgDecorative6: Color,
/** Subtle background colour for informational elements. State: Rest. */
val bgInfoSubtle: Color,
/** Medium contrast surfaces.
Elevation: Default (Level 2). */
val bgSubtlePrimary: Color,
/** Low contrast surfaces.
Elevation: Default (Level 1). */
val bgSubtleSecondary: Color,
/** Subtle background colour for success state elements. State: Rest. */
val bgSuccessSubtle: Color,
/** High-contrast border for critical state. State: Hover. */
val borderCriticalHovered: Color,
/** High-contrast border for critical state. State: Rest. */
val borderCriticalPrimary: Color,
/** Subtle border colour for critical state elements. */
val borderCriticalSubtle: Color,
/** Used for borders of disabled elements. There's no minimum contrast requirement. */
val borderDisabled: Color,
/** Used for the focus state outline. */
val borderFocused: Color,
/** Subtle border colour for informational elements. */
val borderInfoSubtle: Color,
/** Default contrast for accessible interactive element borders. State: Hover. */
val borderInteractiveHovered: Color,
/** Default contrast for accessible interactive element borders. State: Rest. */
val borderInteractivePrimary: Color,
/** ⚠️ Lowest contrast for non-accessible interactive element borders, <3:1. Only use for non-essential borders. Do not rely exclusively on them. State: Rest. */
val borderInteractiveSecondary: Color,
/** Subtle border colour for success state elements. */
val borderSuccessSubtle: Color,
/** Highest contrast accessible accent icons. */
val iconAccentPrimary: Color,
/** Lowest contrast accessible accent icons. */
val iconAccentTertiary: Color,
/** High-contrast icon for critical state. State: Rest. */
val iconCriticalPrimary: Color,
/** Use for icons in disabled elements. There's no minimum contrast requirement. */
val iconDisabled: Color,
/** High-contrast icon for informational elements. */
val iconInfoPrimary: Color,
/** Highest contrast icon color on top of high-contrast solid backgrounds like primary, accent, or destructive actions. */
val iconOnSolidPrimary: Color,
/** Highest contrast icons. */
val iconPrimary: Color,
/** Translucent version of primary icon. Refer to it for intended use. */
val iconPrimaryAlpha: Color,
/** ⚠️ Lowest contrast non-accessible icons, <3:1. Only use for non-essential icons. Do not rely exclusively on them. */
val iconQuaternary: Color,
/** Translucent version of quaternary icon. Refer to it for intended use. */
val iconQuaternaryAlpha: Color,
/** Lower contrast icons. */
val iconSecondary: Color,
/** Translucent version of secondary icon. Refer to it for intended use. */
val iconSecondaryAlpha: Color,
/** High-contrast icon for success state elements. */
val iconSuccessPrimary: Color,
/** Lowest contrast accessible icons. */
val iconTertiary: Color,
/** Translucent version of tertiary icon. Refer to it for intended use. */
val iconTertiaryAlpha: Color,
/** Accent text colour for plain actions. */
val textActionAccent: Color,
/** Default text colour for plain actions. */
val textActionPrimary: Color,
/** Text colour for destructive plain actions. */
val textCriticalPrimary: Color,
/** Decorative text colour (1, Lime) for avatars and usernames. */
val textDecorative1: Color,
/** Decorative text colour (2, Cyan) for avatars and usernames. */
val textDecorative2: Color,
/** Decorative text colour (3, Fuchsia) for avatars and usernames. */
val textDecorative3: Color,
/** Decorative text colour (4, Purple) for avatars and usernames. */
val textDecorative4: Color,
/** Decorative text colour (5, Pink) for avatars and usernames. */
val textDecorative5: Color,
/** Decorative text colour (6, Orange) for avatars and usernames. */
val textDecorative6: Color,
/** Use for regular text in disabled elements. There's no minimum contrast requirement. */
val textDisabled: Color,
/** Accent text colour for informational elements. */
val textInfoPrimary: Color,
/** Text colour for external links. */
val textLinkExternal: Color,
/** For use as text color on top of high-contrast solid backgrounds like primary, accent, or destructive actions. */
val textOnSolidPrimary: Color,
/** Use for placeholder text. Placeholder text should be non-essential. Do not rely exclusively on it. */
val textPlaceholder: Color,
/** Highest contrast text. */
val textPrimary: Color,
/** Lowest contrast text. */
val textSecondary: Color,
/** Accent text colour for success state elements. */
val textSuccessPrimary: Color,
/** True for light theme, false for dark theme. */
val isLight: Boolean,
)
| 7 | Kotlin | 3 | 3 | 8af20b639504614e9c74f88bce41794e9f563539 | 8,162 | compound-android | Apache License 2.0 |
src/main/kotlin/com/github/oowekyala/ijcc/ide/refs/PsiEltResolveResult.kt | oowekyala | 160,946,520 | false | {"Kotlin": 636577, "HTML": 12321, "Lex": 10654, "Shell": 1940, "Just": 101} | package com.github.oowekyala.ijcc.ide.refs
import com.intellij.psi.PsiElement
import com.intellij.psi.ResolveResult
data class PsiEltResolveResult<out T : PsiElement>(private val myElt: T) :
ResolveResult {
override fun getElement(): T = myElt
override fun isValidResult(): Boolean = true
} | 11 | Kotlin | 6 | 44 | c514083a161db56537d2473e42f2a1d4bf57eee1 | 305 | intellij-javacc | MIT License |
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/covidcertificate/valueset/ValueSetsRepositoryTest.kt | hd42 | 384,661,671 | false | null | package de.rki.coronawarnapp.covidcertificate.valueset
import de.rki.coronawarnapp.covidcertificate.vaccination.core.ValueSetTestData.testCertificateValueSetsDe
import de.rki.coronawarnapp.covidcertificate.vaccination.core.ValueSetTestData.testCertificateValueSetsEn
import de.rki.coronawarnapp.covidcertificate.vaccination.core.ValueSetTestData.vaccinationValueSetsDe
import de.rki.coronawarnapp.covidcertificate.vaccination.core.ValueSetTestData.vaccinationValueSetsEn
import de.rki.coronawarnapp.covidcertificate.vaccination.core.ValueSetTestData.valueSetsContainerDe
import de.rki.coronawarnapp.covidcertificate.vaccination.core.ValueSetTestData.valueSetsContainerEn
import de.rki.coronawarnapp.covidcertificate.valueset.server.CertificateValueSetServer
import de.rki.coronawarnapp.covidcertificate.valueset.valuesets.ValueSetsStorage
import de.rki.coronawarnapp.covidcertificate.valueset.valuesets.emptyValueSetsContainer
import io.kotest.matchers.shouldBe
import io.mockk.MockKAnnotations
import io.mockk.Ordering
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.just
import io.mockk.runs
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.first
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import testhelpers.BaseTest
import testhelpers.TestDispatcherProvider
import testhelpers.coroutines.runBlockingTest2
import java.util.Locale
class ValueSetsRepositoryTest : BaseTest() {
@MockK lateinit var certificateValueSetServer: CertificateValueSetServer
@MockK lateinit var valueSetsStorage: ValueSetsStorage
private val testDispatcherProvider = TestDispatcherProvider()
private fun createInstance(scope: CoroutineScope) = ValueSetsRepository(
certificateValueSetServer = certificateValueSetServer,
valueSetsStorage = valueSetsStorage,
scope = scope,
dispatcherProvider = testDispatcherProvider
)
@BeforeEach
fun setUp() {
MockKAnnotations.init(this)
coEvery { certificateValueSetServer.getVaccinationValueSets(any()) } returns
null
coEvery { certificateValueSetServer.getVaccinationValueSets(languageCode = Locale.ENGLISH) } returns
valueSetsContainerEn
coEvery { certificateValueSetServer.getVaccinationValueSets(languageCode = Locale.GERMAN) } returns
valueSetsContainerDe
every { certificateValueSetServer.clear() } just runs
every { valueSetsStorage.valueSetsContainer = any() } just runs
every { valueSetsStorage.valueSetsContainer } returns emptyValueSetsContainer
}
@Test
fun `successful update for de`() = runBlockingTest2(ignoreActive = true) {
createInstance(this).run {
triggerUpdateValueSet(languageCode = Locale.GERMAN)
latestVaccinationValueSets.first() shouldBe vaccinationValueSetsDe
latestTestCertificateValueSets.first() shouldBe testCertificateValueSetsDe
}
coVerify {
certificateValueSetServer.getVaccinationValueSets(languageCode = Locale.GERMAN)
valueSetsStorage.valueSetsContainer = valueSetsContainerDe
}
coVerify(exactly = 0) {
certificateValueSetServer.getVaccinationValueSets(languageCode = Locale.ENGLISH)
valueSetsStorage.valueSetsContainer = valueSetsContainerEn
}
}
@Test
fun `fallback to en`() = runBlockingTest2(ignoreActive = true) {
createInstance(this).run {
triggerUpdateValueSet(languageCode = Locale.FRENCH)
latestVaccinationValueSets.first() shouldBe vaccinationValueSetsEn
latestTestCertificateValueSets.first() shouldBe testCertificateValueSetsEn
}
coVerify(ordering = Ordering.ORDERED) {
certificateValueSetServer.getVaccinationValueSets(languageCode = Locale.FRENCH)
certificateValueSetServer.getVaccinationValueSets(languageCode = Locale.ENGLISH)
valueSetsStorage.valueSetsContainer = valueSetsContainerEn
}
}
@Test
fun `server returns nothing`() = runBlockingTest2(ignoreActive = true) {
coEvery { certificateValueSetServer.getVaccinationValueSets(languageCode = Locale.GERMAN) } returns null
coEvery { certificateValueSetServer.getVaccinationValueSets(languageCode = Locale.ENGLISH) } returns null
createInstance(this).run {
triggerUpdateValueSet(languageCode = Locale.GERMAN)
emptyValueSetsContainer.also {
latestVaccinationValueSets.first() shouldBe it.vaccinationValueSets
latestTestCertificateValueSets.first() shouldBe it.testCertificateValueSets
}
}
coVerify(ordering = Ordering.ORDERED) {
certificateValueSetServer.getVaccinationValueSets(languageCode = Locale.GERMAN)
certificateValueSetServer.getVaccinationValueSets(languageCode = Locale.ENGLISH)
}
}
@Test
fun `clear data of server and local storage`() = runBlockingTest2(ignoreActive = true) {
createInstance(this).run {
clear()
emptyValueSetsContainer.also {
latestVaccinationValueSets.first() shouldBe it.vaccinationValueSets
latestTestCertificateValueSets.first() shouldBe it.testCertificateValueSets
}
coVerify {
certificateValueSetServer.clear()
valueSetsStorage.valueSetsContainer = emptyValueSetsContainer
}
}
}
}
| 1 | null | 1 | 1 | ec812c6c409fd79852f75ea38a683ebeab823734 | 5,598 | cwa-app-android | Apache License 2.0 |
HacoMobile/app/src/main/java/com/example/haco/activities/ReportTool.kt | DeanORourke1996 | 321,971,010 | false | {"Python": 80387625, "Cython": 1350415, "CSS": 1100354, "JavaScript": 978991, "HTML": 925249, "C": 789556, "Jupyter Notebook": 640122, "Roff": 169593, "C++": 97021, "Jinja": 79129, "SCSS": 16281, "Shell": 11900, "Kotlin": 10488, "PowerShell": 10400, "Fortran": 8505, "Smarty": 4852, "Batchfile": 3579, "XSLT": 1196, "Xonsh": 1172} | package com.example.haco.activities
import androidx.appcompat.app.AppCompatActivity
class ReportTool : AppCompatActivity() {
} | 1 | Python | 1 | 0 | fc04d763735ca376c51e82e1f1be20b092ce751c | 129 | haco | MIT License |
library/jdbc/src/main/kotlin/io/github/ustudiocompany/uframework/jdbc/error/ErrorConverter.kt | uStudioCompany | 745,407,841 | false | {"Kotlin": 356468} | package io.github.ustudiocompany.uframework.jdbc.error
public typealias ErrorConverter<F> = (JDBCErrors) -> F
| 0 | Kotlin | 0 | 0 | 54b986bddde71660105d4135c52019a50a0ed7ec | 111 | u-framework | Apache License 2.0 |
engine/src/main/kotlin/kotli/engine/template/rule/ReplaceText.kt | kotlitecture | 741,006,904 | false | {"Kotlin": 99184} | package kotli.engine.template.rule
import kotli.engine.template.FileRule
import kotli.engine.template.TemplateFile
/**
* Replaces all occurrences of the given #text with the provided #replacer text.
*
* @param text The text to be replaced.
* @param replacer A function providing the text to be used as a replacement.
*/
data class ReplaceText(
private val text: String,
private val replacer: String
) : FileRule() {
override fun doApply(file: TemplateFile) {
val newText = replacer
file.lines.forEachIndexed { index, line ->
file.lines[index] = line.replace(text, newText)
}
}
} | 0 | Kotlin | 0 | 1 | abba606fd4505e3bf1019765a74ccb808738c130 | 639 | kotli-engine | MIT License |
pickerview/src/main/java/com/bigkoo/pickerview/adapter/NumericWheelAdapter.kt | neo-turak | 674,130,168 | false | null | package com.bigkoo.pickerview.adapter
import com.contrarywind.adapter.WheelAdapter
/**
* Numeric Wheel adapter.
*/
/**
* Constructor
* @param minValue the wheel min value
* @param maxValue the wheel max value
*/
class NumericWheelAdapter(private val minValue: Int, private val maxValue: Int) :
WheelAdapter<Any?> {
override fun getItem(index: Int): Any {
return if (index >= 0 && index < itemsCount()) {
minValue + index
} else 0
}
override fun itemsCount(): Int {
return maxValue - minValue + 1
}
override fun indexOf(o: Any?): Int {
return try {
o as Int - minValue
} catch (e: Exception) {
-1
}
}
} | 0 | Kotlin | 0 | 0 | f847ab8eef540b29770be1b2287311d4872ee256 | 723 | Android-PickerView | Apache License 2.0 |
mobile_app1/module346/src/main/java/module346packageKt0/Foo494.kt | uber-common | 294,831,672 | false | null | package module346packageKt0;
annotation class Foo494Fancy
@Foo494Fancy
class Foo494 {
fun foo0(){
module346packageKt0.Foo493().foo5()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
} | 6 | Java | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 297 | android-build-eval | Apache License 2.0 |
vscode/src/jsMain/kotlin/vscode/window/RegisterWebviewViewProviderOptions.kt | lppedd | 761,812,661 | false | {"Kotlin": 1887051} | package vscode.window
external interface RegisterWebviewViewProviderOptions {
/**
* Content settings for the webview created for this view.
*/
val webviewOptions: WebviewOptions?
}
| 0 | Kotlin | 0 | 3 | 0f493d3051afa3de2016e5425a708c7a9ed6699a | 192 | kotlin-externals | MIT License |
shared/src/commonMain/kotlin/com.sbga.sdgbapp/Net/VO/Mai2/UserFavorite.kt | NickJi2019 | 717,286,554 | false | {"Kotlin": 107919, "Ruby": 2257, "Swift": 1595, "JavaScript": 485, "HTML": 323} | package com.sbga.sdgbapp.VO.Mai2
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class UserFavorite(
@SerialName("userId") val userId: ULong,
@SerialName("itemKind") val itemKind: Int,
@SerialName("itemIdList") val itemIdList: IntArray
)
| 1 | Kotlin | 1 | 2 | de8bd85171f546f81fa4554a36b339ae7080f84b | 305 | SDGBApp | MIT License |
examples/sounds/src/barsoosayque/libgdxoboe/sounds/app/AppUi.kt | little-adam | 284,658,057 | true | {"C++": 77494, "Kotlin": 8292, "Shell": 7640, "CMake": 2088} | package barsoosayque.libgdxoboe.sounds.app
import barsoosayque.libgdxoboe.sounds.content.SoundAsset
import com.badlogic.gdx.assets.AssetManager
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.CheckBox
import com.badlogic.gdx.scenes.scene2d.ui.Slider
import com.badlogic.gdx.utils.viewport.ExtendViewport
import ktx.actors.onChange
import ktx.actors.onChangeEvent
import ktx.scene2d.*
import kotlin.math.pow
import com.badlogic.gdx.utils.Array as GdxArray
class AppUi(
sounds: Array<SoundAsset>,
assetManager: AssetManager
) : Stage(ExtendViewport(480f, 700f)) {
private lateinit var loopCheckBox: CheckBox
private lateinit var volumeSlider: Slider
private lateinit var panSlider: Slider
private lateinit var pitchSlider: Slider
private val volume: Float get() = volumeSlider.value
private val pan: Float get() = panSlider.value
private val pitch: Float get() = 2f.pow(pitchSlider.value)
private val isLooping: Boolean get() = loopCheckBox.isChecked
private var selectedSound: Sound = sounds.first().get(assetManager)
val root = table {
setFillParent(true)
pad(30f)
top()
label("libGDX Oboe: Sounds").cell(row = true, padBottom = 60f)
verticalGroup {
center()
space(30f)
verticalGroup {
label("Select one of the sounds:")
selectBoxOf<SoundAsset>(GdxArray(sounds)).onChangeEvent { _, selectBox ->
selectedSound = selectBox.selected.get(assetManager)
}
}
table {
defaults().pad(10f)
label("Soundpool controls: ")
horizontalGroup {
space(10f)
textButton("Play").onChange {
if (isLooping) selectedSound.loop(volume, pitch, pan)
else selectedSound.play(volume, pitch, pan)
}
textButton("Resume").onChange { selectedSound.resume() }
textButton("Pause").onChange { selectedSound.pause() }
textButton("Stop").onChange { selectedSound.stop() }
}
row()
label("Volume: ")
volumeSlider = slider { value = 1.0f }
row()
label("Loop: ")
loopCheckBox = checkBox("is looping")
row()
label("Pan: ")
panSlider = slider(-1f) { value = 0.0f }
row()
label("Pitch: ")
pitchSlider = slider(-1f) { value = 0.0f }
}
}.cell(grow = true)
}.let(::addActor)
} | 0 | C++ | 0 | 1 | 41831ecaf5b329ad5722421196c7b9d34f445def | 2,780 | libgdx-oboe | MIT License |
src/main/kotlin/Day01.kt | robert-iits | 573,124,643 | false | {"Kotlin": 21047} | import org.junit.jupiter.api.Assertions.assertEquals
import java.util.Collections.max
fun main() {
fun sumCaloriesPerElf(input: List<String>): MutableList<Int> {
val elves = mutableListOf<Int>()
var currentElvesCalories = 0
input.forEach {
if (it != "") {
currentElvesCalories += it.toInt()
} else {
elves.add(currentElvesCalories)
currentElvesCalories = 0
}
}
elves.add(currentElvesCalories)
return elves
}
fun part1(input: List<String>): Int {
val elves = sumCaloriesPerElf(input)
return max(elves)
}
fun part2(input: List<String>): Int {
return sumCaloriesPerElf(input).sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
assertEquals(24000, part1(testInput))
assertEquals(45000, part2(testInput))
val input = readInput("Day01")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 223017895e483a762d8aa2cdde6d597ab9256b2d | 1,082 | aoc2022 | Apache License 2.0 |
data/src/main/java/com/maciejmalak/data/db/Db.kt | xavarius | 373,149,697 | false | null | package com.maciejmalak.data.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
/**
* All of the implementation details hidden inside one, centralised module
*/
@Database(entities = [UserDto::class], version = 1)
abstract class Db : RoomDatabase() {
abstract fun usersDao(): UserDao
object DbInitializer {
private const val DB_NAME = "application_database"
private var instance: Db? = null
fun getInstance(context: Context): Db =
instance ?: buildDB(context).also { instance = it }
fun getUserDao(context: Context) = getInstance(context).usersDao()
private fun buildDB(context: Context): Db =
Room.databaseBuilder(context, Db::class.java, DB_NAME).build()
}
}
| 0 | Kotlin | 0 | 0 | e6ac5674ca2b73f84f6abf54763781a3bc178a4b | 817 | db-showoff-app | MIT License |
kotlin-reference-server/src/main/kotlin/org/stellar/reference/event/processor/AnchorEventProcessor.kt | stellar | 452,893,461 | false | {"Kotlin": 2211948, "Java": 1300419, "Smarty": 2448, "Makefile": 659, "Shell": 513, "Dockerfile": 483} | package org.stellar.reference.event.processor
import org.stellar.anchor.api.event.AnchorEvent
import org.stellar.anchor.api.platform.PlatformTransactionData
import org.stellar.reference.data.SendEventRequest
import org.stellar.reference.log
class AnchorEventProcessor(
private val sep6EventProcessor: Sep6EventProcessor,
private val noOpEventProcessor: NoOpEventProcessor,
) {
suspend fun handleEvent(event: SendEventRequest) {
val processor = getProcessor(event)
try {
when (event.type) {
AnchorEvent.Type.TRANSACTION_CREATED.type -> {
log.info("Received transaction created event")
processor.onTransactionCreated(event)
}
AnchorEvent.Type.TRANSACTION_STATUS_CHANGED.type -> {
log.info("Received transaction status changed event")
processor.onTransactionStatusChanged(event)
}
AnchorEvent.Type.TRANSACTION_ERROR.type -> {
log.info("Received transaction error event")
processor.onTransactionError(event)
}
AnchorEvent.Type.CUSTOMER_UPDATED.type -> {
log.info("Received customer updated event")
// Only SEP-6 listens to this event
sep6EventProcessor.onCustomerUpdated(event)
}
AnchorEvent.Type.QUOTE_CREATED.type -> {
log.info("Received quote created event")
processor.onQuoteCreated(event)
}
else -> {
log.warn(
"Received event of type ${event.type} which is not supported by the reference server"
)
}
}
} catch (e: Exception) {
log.error("Error processing event: $event", e)
}
}
private fun getProcessor(event: SendEventRequest): SepAnchorEventProcessor =
when (event.payload.transaction?.sep) {
PlatformTransactionData.Sep.SEP_6 -> sep6EventProcessor
else -> noOpEventProcessor
}
}
| 8 | Kotlin | 33 | 35 | 96a574b21d5a3c0fb992be8c65e5267cfdfb7c16 | 1,889 | java-stellar-anchor-sdk | Apache License 2.0 |
app/src/main/java/com/sneakers/sneakerschecker/api/AuthenticationApi.kt | LongJakeparker | 173,551,224 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 2, "Proguard": 1, "Kotlin": 88, "XML": 106, "Java": 77} | package com.sneakers.sneakerschecker.api
import com.sneakers.sneakerschecker.model.CheckPrivateKeyResultModel
import com.sneakers.sneakerschecker.model.SignIn
import com.sneakers.sneakerschecker.model.SignUp
import retrofit2.Call
import retrofit2.http.*
interface AuthenticationApi {
@POST("/user/")
fun signUpApi(@Body param: HashMap<String, String>): Call<SignUp>
@FormUrlEncoded
@POST("/user/signin/")
fun signInApi(@Header("Authorization") token:String,
@Field("grant_type") grant_type: String,
@Field("username") userIdentity: String,
@Field("password") password: String,
@Field("fcmToken") fcmToken: String): Call<SignIn>
@FormUrlEncoded
@POST("/oauth/token")
fun refreshTokenApi(@Header("Authorization") token:String,
@Field("grant_type") grant_type: String,
@Field("refresh_token") refresh_token: String): Call<SignIn>
@PATCH("/user/restoration/{networkAddress}")
fun restoration(@Path("networkAddress") userAddress: String,
@Body param: Map<String, String>): Call<CheckPrivateKeyResultModel>
} | 0 | Kotlin | 0 | 0 | 26c43b8c8bf6caa0e746bbcff3daefa8b5c79b9d | 1,187 | True-Grails | MIT License |
android/app-example/src/main/java/com/badoo/ribs/example/rib/switcher/Switcher.kt | journeyman | 205,386,527 | true | {"Kotlin": 593038, "Swift": 402146, "Java": 112878, "Shell": 2571, "Ruby": 1955, "Objective-C": 814} | package com.badoo.ribs.example.rib.switcher
import com.badoo.ribs.android.CanProvideActivityStarter
import com.badoo.ribs.android.CanProvidePermissionRequester
import com.badoo.ribs.core.Rib
import com.badoo.ribs.customisation.CanProvideRibCustomisation
import com.badoo.ribs.customisation.RibCustomisation
import com.badoo.ribs.dialog.CanProvideDialogLauncher
import com.badoo.ribs.example.rib.hello_world.HelloWorld
import com.badoo.ribs.example.util.CoffeeMachine
import io.reactivex.Single
interface Switcher : Rib {
interface Dependency :
CanProvideActivityStarter,
CanProvidePermissionRequester,
CanProvideDialogLauncher,
CanProvideRibCustomisation {
fun coffeeMachine(): CoffeeMachine
}
class Customisation(
val viewFactory: SwitcherView.Factory = SwitcherViewImpl.Factory()
) : RibCustomisation
interface Workflow {
fun attachHelloWorld(): Single<HelloWorld.Workflow>
fun testCrash(): Single<HelloWorld.Workflow>
fun waitForHelloWorld(): Single<HelloWorld.Workflow>
fun doSomethingAndStayOnThisNode(): Single<Switcher.Workflow>
}
}
| 0 | Kotlin | 0 | 0 | 6c4ae253ab1f052fd25b45f041744655041899fc | 1,151 | RIBs | Apache License 2.0 |
compiler/testData/codegen/box/secondaryConstructors/inlineIntoTwoConstructors.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | inline fun myRun(x: () -> String) = x()
fun <T> eval(fn: () -> T) = fn()
class C {
val x = myRun { eval { "OK" } }
constructor(y: Int)
constructor(y: String)
}
fun box(): String = C("").x
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 204 | kotlin | Apache License 2.0 |
hive-common/src/test/kotlin/com/amazon/ionhiveserde/configuration/PathExtractionConfigTest.kt | amazon-ion | 145,019,226 | false | {"Gradle": 3, "Java Properties": 5, "Markdown": 10, "Shell": 5, "Text": 1, "Ignore List": 1, "Batchfile": 1, "XML": 4, "Gradle Kotlin DSL": 9, "Kotlin": 51, "Java": 78, "INI": 1, "YAML": 2, "Dotenv": 1, "Dockerfile": 1} | package com.amazon.ionhiveserde.configuration
import com.amazon.ion.IonInt
import com.amazon.ion.IonSequence
import com.amazon.ion.IonStruct
import com.amazon.ion.system.IonReaderBuilder
import com.amazon.ionhiveserde.ION
import com.amazon.ionhiveserde.caseinsensitivedecorator.IonSequenceCaseInsensitiveDecorator
import com.amazon.ionhiveserde.caseinsensitivedecorator.IonStructCaseInsensitiveDecorator
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class PathExtractionConfigTest {
@Test
fun pathExtractor() {
val ionDocument = "{f1: 1, obj: {f2: 2}}"
val struct = ION.newEmptyStruct()
val configMap = mapOf(
"ion.c1.path_extractor" to "(f1)",
"ion.c2.path_extractor" to "(obj f2)")
val pathExtractor = PathExtractionConfig(
MapBasedRawConfiguration(configMap),
listOf("c1", "c2")
).pathExtractor()
assertTrue(struct.isEmpty)
pathExtractor.match(IonReaderBuilder.standard().build(ionDocument), struct)
assertEquals(2, struct.size())
assertEquals(1, (struct["c1"] as IonInt).intValue())
assertEquals(2, (struct["c2"] as IonInt).intValue())
}
@Test
fun caseInsensitiveNestedStruct() {
val ionDocument = "{f1: [{Foo: 2, foo:3}]}"
val rawStruct: IonStruct = ION.newEmptyStruct()
val struct = IonStructCaseInsensitiveDecorator(rawStruct)
val configMap = mapOf(
"ion.path_extractor.case_sensitive" to "false",
"ion.c1.path_extractor" to "(f1)",
)
val pathExtractor = PathExtractionConfig(
MapBasedRawConfiguration(configMap),
listOf("c1")
).pathExtractor()
assertTrue(struct.isEmpty)
pathExtractor.match(IonReaderBuilder.standard().build(ionDocument), struct)
assertTrue(struct.get("c1") is IonSequenceCaseInsensitiveDecorator)
assertTrue((struct.get("c1") as IonSequence)[0] is IonStructCaseInsensitiveDecorator)
}
@Test
fun caseInsensitiveNestedSequence() {
val ionDocument = "{f1: [{Foo: bar}]}"
val rawStruct: IonStruct = ION.newEmptyStruct()
val struct = IonStructCaseInsensitiveDecorator(rawStruct)
val configMap = mapOf(
"ion.path_extractor.case_sensitive" to "false",
"ion.c1.path_extractor" to "(f1)",
)
val pathExtractor = PathExtractionConfig(
MapBasedRawConfiguration(configMap),
listOf("c1")
).pathExtractor()
assertTrue(struct.isEmpty)
pathExtractor.match(IonReaderBuilder.standard().build(ionDocument), struct)
assertTrue(struct.get("c1") is IonSequenceCaseInsensitiveDecorator)
assertTrue((struct.get("c1") as IonSequence)[0] is IonStructCaseInsensitiveDecorator)
}
}
| 19 | Java | 12 | 28 | f8e9b0c0d7692c7dded75413ffe3f36fbc8fd2b0 | 2,907 | ion-hive-serde | Apache License 2.0 |
src/main/java/com/anatawa12/bintray2Central/LocalTracer.kt | anatawa12 | 338,053,110 | false | null | package com.anatawa12.bintray2Central
import java.io.File
import java.io.IOException
class LocalTracer(
private val base: File,
): AbstractTracer() {
/**
* relativePath requires ends with '/'
*/
override suspend fun getDirectory(relativePath: String): Entry.Directory {
val path = base.resolve(relativePath)
try {
val entries = path.listFiles()!!.map {
val name = it.name
if (it.isDirectory) {
DirectoryEntry.Directory(name)
} else {
DirectoryEntry.File(name)
}
}.toList()
return Entry.Directory(relativePath, entries)
} catch (ex: IOException) {
throw IOException("getting $path", ex)
}
}
override suspend fun getFile(relativePath: String): Entry.File {
val path = base.resolve(relativePath)
try {
return Entry.File(
relativePath,
path.readBytes(),
)
} catch (ex: IOException) {
throw IllegalStateException("getting $path", ex)
}
}
}
| 0 | Kotlin | 0 | 0 | dd809a2d2afad242ced5bf08c1f5220e39a7fc8e | 1,156 | bintray2central | MIT License |
app/src/main/java/com/pmpavan/githubpullrequests/viewmodel/binding/ListBindingAdapters.kt | pmpavan | 139,534,771 | false | null | package com.pmpavan.githubpullrequests.viewmodel.binding
import android.databinding.BindingAdapter
import android.support.v7.widget.RecyclerView
import android.view.View
import com.pmpavan.githubpullrequests.viewmodel.PullRequestListAdapter
import com.pmpavan.githubpullrequests.viewmodel.uistate.PullRequestListItemUiState
import java.util.ArrayList
object ListBindingAdapters {
@BindingAdapter("android:onClick")
@JvmStatic
fun View.setClickListener(handler: ClickHandler) {
setOnClickListener { _ -> handler.onClick() }
}
interface ClickHandler {
fun onClick()
}
@BindingAdapter("items")
@JvmStatic
fun RecyclerView.setChatAdapter(items: MutableList<PullRequestListItemUiState>?) {
if (adapter != null) {
val listAdapter = adapter as PullRequestListAdapter
listAdapter.clear()
if (items != null)
listAdapter.addAll(items)
listAdapter.notifyDataSetChanged()
}
}
@BindingAdapter("android:visibility")
@JvmStatic
fun View.setVisibility(visible: Boolean) {
visibility = if (visible) View.VISIBLE else View.GONE
}
} | 1 | null | 1 | 1 | 49fdbbd1ffccdf372b60774cfc249d9ebd29325f | 1,179 | GithubPullRequests | MIT License |
bukkit/rpk-drinks-bukkit/src/main/kotlin/com/rpkit/drinks/bukkit/drink/RPKDrinkImpl.kt | RP-Kit | 54,840,905 | false | null | /*
* Copyright 2021 <NAME>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.drinks.bukkit.drink
import com.rpkit.drink.bukkit.drink.RPKDrink
import com.rpkit.drink.bukkit.drink.RPKDrinkName
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.ShapelessRecipe
class RPKDrinkImpl(
override val name: RPKDrinkName,
override val item: ItemStack,
override val recipe: ShapelessRecipe,
override val drunkenness: Int
) : RPKDrink | 51 | Kotlin | 11 | 22 | aee4060598dc25cd8e4f3976ed5e70eb1bf874a2 | 1,000 | RPKit | Apache License 2.0 |
airbyte-integrations/connectors/destination-s3/src/test-integration/kotlin/io/airbyte/integrations/destination/s3/S3JsonlDestinationAcceptanceTest.kt | tim-werner | 511,419,970 | false | {"Java Properties": 8, "Shell": 57, "Markdown": 1170, "Batchfile": 1, "Makefile": 3, "JavaScript": 31, "CSS": 9, "Python": 4183, "Kotlin": 845, "Java": 723, "INI": 10, "Dockerfile": 27, "HTML": 7, "SQL": 527, "PLpgSQL": 8, "TSQL": 1, "PLSQL": 2} | /*
* Copyright (c) 2023 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.integrations.destination.s3
import com.fasterxml.jackson.databind.JsonNode
import io.airbyte.cdk.integrations.destination.s3.S3BaseJsonlDestinationAcceptanceTest
import io.airbyte.cdk.integrations.standardtest.destination.ProtocolVersion
class S3JsonlDestinationAcceptanceTest : S3BaseJsonlDestinationAcceptanceTest() {
override fun getProtocolVersion(): ProtocolVersion {
return ProtocolVersion.V1
}
override val baseConfigJson: JsonNode
get() = S3DestinationTestUtils.baseConfigJsonFilePath
}
| 1 | null | 1 | 1 | b2e7895ed3e1ca7c1600ae1c23578dd1024f20ff | 610 | airbyte | MIT License |
app/src/main/java/com/robyn/dayplus2/data/source/enums/EventCategory.kt | yifeidesu | 92,456,032 | false | {"Gradle": 3, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "JSON": 17, "Proguard": 1, "XML": 36, "Text": 1, "Java": 2, "Kotlin": 38} | package com.robyn.dayplus2.data.source.enums
/**
* Enum [MyEvent]'s category values.
*
* Implements [EventFilter] so that [MyEvent].category can act as filter when filter the list
*
* Created by yifei on 11/20/2017.
*/
enum class EventCategory : EventFilter {
CAKE_EVENTS,
LOVED_EVENTS,
FACE_EVENTS,
EXPLORE_EVENTS,
WORK_EVENTS
} | 1 | null | 1 | 1 | 788a1ef3cdf88b9e6e65f513148cda58bb43fef7 | 361 | DayPlus-Countdown | Apache License 2.0 |
malime.kitsu/src/main/java/com/chesire/malime/kitsu/KitsuConstants.kt | Chesire | 122,841,402 | false | null | package com.chesire.malime.kitsu
const val KITSU_ENDPOINT = "https://kitsu.io/"
| 1 | null | 1 | 5 | 3b9562e9e313ca7d426ae4c01cc0a5f40347252a | 81 | Malime | MIT License |
kotlin/코틀린 완벽 가이드/080250/Chapter14/KoTest/src/test/kotlin/NumbersTest4.kt | devYSK | 461,887,647 | false | {"Java": 3507759, "JavaScript": 659549, "Kotlin": 563136, "HTML": 455168, "CSS": 446825, "Shell": 57444, "Groovy": 54414, "Batchfile": 47890, "Go": 26805, "Python": 9963, "Handlebars": 8554, "Makefile": 7837, "Vue": 5706, "TypeScript": 5172, "Dockerfile": 436, "Vim Snippet": 362, "Assembly": 278, "Procfile": 199} | import io.kotest.matchers.shouldBe
import io.kotest.core.spec.style.DescribeSpec
class NumbersTest4 : DescribeSpec({
describe("Addition") {
context("1 + 2") {
it("should give 3") { (1 + 2) shouldBe 3 }
}
}
}) | 1 | null | 1 | 1 | 7a7c6b1bab3dc2c84527f8c528b06b9408872635 | 245 | study_repo | MIT License |
ui/src/main/java/com/sunblackhole/android/aliData/response/WireguardListResponse.kt | kunlunhundun | 197,153,365 | false | null | /*
* Copyright © 2020 WireGuard LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.sunblackhole.android.aliData.response
class WireguardListResponse : BaseResponseObject() {
val data = Body()
class Body {
var wireguardList: MutableList<VpnServiceObject> = mutableListOf();
}
data class VpnServiceObject (
var lineName: String? = null,
var wireguards: MutableList<VpnObject>? = null
)
data class VpnObject (
var id: String? = null,
var lineName: String? = null,
var serviceId: String? = null,
var privatekey: String? = null,
var address: String? = null,
var dns: String? = null,
var mtu: String? = null,
var publickey: String? = null,
var endpoint: String? = null,
var allowedIps: String? = null,
var persistentKeepalive: String? = null
)
} | 1 | null | 1 | 1 | 6007e09e0d3d4d081953145f413e8c0a9e239d70 | 962 | sonicdandroid | Apache License 2.0 |
UserCenter/src/main/java/com/kotlin/user/ui/activity/UserInfoActivity.kt | heisexyyoumo | 145,665,152 | false | null | package com.kotlin.user.ui.activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import com.bigkoo.alertview.AlertView
import com.bigkoo.alertview.OnItemClickListener
import com.jph.takephoto.app.TakePhoto
import com.jph.takephoto.app.TakePhotoImpl
import com.jph.takephoto.compress.CompressConfig
import com.jph.takephoto.model.TResult
import com.kotlin.base.common.BaseConstant
import com.kotlin.base.ext.onClick
import com.kotlin.base.ui.activity.BaseMvpActivity
import com.kotlin.base.utils.AppPrefsUtils
import com.kotlin.base.utils.DateUtils
import com.kotlin.base.utils.GlideUtils
import com.kotlin.provider.common.ProviderConstant
import com.kotlin.user.R
import com.kotlin.user.data.protocol.UserInfo
import com.kotlin.user.injection.component.DaggerUserComponent
import com.kotlin.user.injection.module.UserModule
import com.kotlin.user.presenter.UserInfoPresenter
import com.kotlin.user.presenter.view.UserInfoView
import com.kotlin.user.utils.UserPrefsUtils
import com.qiniu.android.http.ResponseInfo
import com.qiniu.android.storage.UpCompletionHandler
import com.qiniu.android.storage.UploadManager
import kotlinx.android.synthetic.main.activity_user_info.*
import org.jetbrains.anko.toast
import org.json.JSONObject
import java.io.File
import java.util.*
class UserInfoActivity : BaseMvpActivity<UserInfoPresenter>(), UserInfoView,
TakePhoto.TakeResultListener {
private lateinit var mTakePhoto: TakePhoto
private lateinit var mTempFile: File
private val mUploadManager: UploadManager by lazy { UploadManager() }
private var mLocalFileUrl: String? = null
private var mRemoteFileUrl: String? = null
private var mUserIcon: String? = null
private var mUserName: String? = null
private var mUserMobile: String? = null
private var mUserGender: String? = null
private var mUserSign: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_user_info)
mTakePhoto = TakePhotoImpl(this, this)
mTakePhoto.onCreate(savedInstanceState)
initView()
initData()
}
private fun initData() {
mUserIcon = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_ICON)
mUserName = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_NAME)
mUserMobile = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_MOBILE)
mUserGender = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_GENDER)
mUserSign = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_SIGN)
mRemoteFileUrl = mUserIcon
if (mUserIcon != "") {
GlideUtils.loadUrlImage(this, mUserIcon!!, mUserIconIv)
}
mUserNameEt.setText(mUserName)
mUserMobileTv.text = mUserMobile
if (mUserGender == "0") {
mGenderMaleRb.isChecked = true
} else {
mGenderFemaleRb.isChecked = true
}
mUserSignEt.setText(mUserSign)
}
private fun initView() {
mUserIconView.onClick {
showAlertView()
}
mHeaderBar.getRightView().onClick {
mPresenter.editUser(mRemoteFileUrl!!,
mUserNameEt.text?.toString() ?: "",
if (mGenderMaleRb.isChecked) "0" else "1",
mUserSignEt.text?.toString() ?: "")
}
}
private fun showAlertView() {
AlertView("选择图片", "", "取消", null,
arrayOf("拍照", "相册"), this, AlertView.Style.ActionSheet,
object : OnItemClickListener {
override fun onItemClick(o: Any?, position: Int) {
mTakePhoto.onEnableCompress(CompressConfig.ofDefaultConfig(),
false)
when (position) {
0 -> {
createTempFile()
mTakePhoto.onPickFromCapture(Uri.fromFile(mTempFile))
}
1 -> mTakePhoto.onPickFromGallery()
}
}
}).show()
}
override fun injectComponent() {
DaggerUserComponent.builder().activityComponent(activityComponent)
.userModule(UserModule()).build().inject(this)
mPresenter.mView = this
}
override fun takeSuccess(result: TResult?) {
mLocalFileUrl = result?.image?.compressPath
mPresenter.getUploadToken()
}
override fun takeCancel() {
}
override fun takeFail(result: TResult?, msg: String?) {
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
mTakePhoto.onActivityResult(requestCode, resultCode, data)
}
fun createTempFile() {
val tempFileName = "${DateUtils.curTime}.png"
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageDirectory())) {
this.mTempFile = File(Environment.getExternalStorageDirectory(), tempFileName)
return
}
this.mTempFile = File(filesDir, tempFileName)
}
override fun onGetUploadTokenResult(result: String) {
mUploadManager.put(mLocalFileUrl, null, result, object : UpCompletionHandler {
override fun complete(key: String?, info: ResponseInfo?, response: JSONObject?) {
mRemoteFileUrl = BaseConstant.IMAGE_SERVER_ADDRESS + response?.get("hash")
GlideUtils.loadUrlImage(this@UserInfoActivity, mRemoteFileUrl!!,
mUserIconIv)
}
}, null)
}
override fun onEditUserResult(result: UserInfo) {
toast("修改成功")
UserPrefsUtils.putUserInfo(result)
}
}
| 0 | Kotlin | 1 | 2 | 27fea0090cea5fb636f8db5025379d274693b1b4 | 5,895 | KotlinMall | Apache License 2.0 |
compiler/testData/diagnostics/testsWithStdLib/annotations/subclassOptInRequired/JavaKotlinInterop.fir.kt | JetBrains | 3,432,266 | false | {"Kotlin": 78346118, "Java": 6692370, "Swift": 4062767, "C": 2609482, "C++": 1962762, "Objective-C++": 169966, "JavaScript": 138328, "Python": 59488, "Shell": 35024, "TypeScript": 22800, "Lex": 18369, "Groovy": 17400, "Objective-C": 15578, "Batchfile": 11746, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9857, "EJS": 5241, "HTML": 4877, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FILE: one.java
package pcg;
import kotlin.ExperimentalMultiplatform;
import kotlin.SubclassOptInRequired;
@SubclassOptInRequired(markerClass = ExperimentalMultiplatform.class) public class Foo{}
// FILE: two.kt
import pcg.Foo
class Bar() : <!OPT_IN_USAGE_ERROR!>Foo<!>()
| 182 | Kotlin | 5617 | 47,637 | d257153a50bdaa761d54bbc9fd1c5d78a3769f0f | 279 | kotlin | Apache License 2.0 |
example-app/src/main/java/media/pixi/appkit/example/di/feature/DevelopModule.kt | NateWickstrom | 166,901,841 | false | null | package media.pixi.appkit.example.di.feature
import dagger.Binds
import dagger.Module
import dagger.android.ContributesAndroidInjector
import media.pixi.appkit.example.di.ActivityScoped
import media.pixi.appkit.example.di.FragmentScoped
import media.pixi.appkit.ui.develop.DevelopContract
import media.pixi.appkit.ui.develop.DevelopFragment
import media.pixi.appkit.ui.develop.DevelopNavigator
import media.pixi.appkit.ui.develop.DevelopPresenter
@Module
abstract class DevelopModule {
@FragmentScoped
@ContributesAndroidInjector
internal abstract fun developFragment(): DevelopFragment
@ActivityScoped
@Binds
internal abstract fun developPresenter(presenter: DevelopPresenter): DevelopContract.Presenter
@ActivityScoped
@Binds
internal abstract fun developNavigator(navigator: DevelopNavigator): DevelopContract.Navigator
}
| 0 | Kotlin | 0 | 0 | 67e3f5cb6e1d0d7ed12002408325823ce1772492 | 867 | android-rx-firebase-app-kit | Apache License 2.0 |
app/src/main/kotlin/org/eurofurence/connavigator/workers/PreloadImageFinishedWorker.kt | eurofurence | 50,885,645 | false | null | package org.eurofurence.connavigator.workers
import android.content.Context
import androidx.work.*
import org.eurofurence.connavigator.preferences.BackgroundPreferences
import org.eurofurence.connavigator.preferences.LoadingState
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
class PreloadImageFinishedWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams), AnkoLogger {
override fun doWork(): Result {
info {"Image preloading done"}
BackgroundPreferences.loadingState = LoadingState.SUCCEEDED
return Result.success()
}
companion object {
const val TAG = "IMAGE_LOADING_DONE"
fun create() = OneTimeWorkRequestBuilder<PreloadImageWorker>()
.setInputMerger(ArrayCreatingInputMerger::class)
.addTag(TAG)
.build()
}
} | 21 | null | 5 | 13 | 3da7b778cda0a9b39a5172bf48cb3cbc27604de8 | 877 | ef-app_android | MIT License |
wearsettings/src/main/java/com/thewizrd/wearsettings/actions/WifiAction.kt | SimpleAppProjects | 197,253,270 | false | {"Kotlin": 1136523, "Java": 53044} | package com.thewizrd.wearsettings.actions
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.net.wifi.IWifiManager
import android.net.wifi.WifiManager
import android.os.Build
import android.util.Log
import androidx.core.content.ContextCompat
import com.thewizrd.shared_resources.actions.Action
import com.thewizrd.shared_resources.actions.ActionStatus
import com.thewizrd.shared_resources.actions.ToggleAction
import com.thewizrd.shared_resources.utils.Logger
import com.thewizrd.wearsettings.Settings
import com.thewizrd.wearsettings.root.RootHelper
import com.topjohnwu.superuser.Shell
import rikka.shizuku.Shizuku
import rikka.shizuku.ShizukuBinderWrapper
import rikka.shizuku.SystemServiceHelper
object WifiAction {
fun executeAction(context: Context, action: Action): ActionStatus {
if (action is ToggleAction) {
val status = setWifiEnabled(context, action.isEnabled)
return if (status != ActionStatus.SUCCESS) {
// Note: could have failed due to Airplane mode restriction
// Try with root
if (Shizuku.pingBinder()) {
setWifiEnabledShizuku(context, action.isEnabled)
} else if (Settings.isRootAccessEnabled() && RootHelper.isRootEnabled()) {
setWifiEnabledRoot(action.isEnabled)
} else {
status
}
} else {
status
}
}
return ActionStatus.UNKNOWN
}
private fun setWifiEnabled(context: Context, enable: Boolean): ActionStatus {
if (ContextCompat.checkSelfPermission(
context,
Manifest.permission.CHANGE_WIFI_STATE
) == PackageManager.PERMISSION_GRANTED
) {
return try {
val wifiMan =
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
if (wifiMan.setWifiEnabled(enable))
ActionStatus.SUCCESS
else
ActionStatus.REMOTE_FAILURE
} catch (e: Exception) {
Logger.writeLine(Log.ERROR, e)
ActionStatus.REMOTE_FAILURE
}
}
return ActionStatus.REMOTE_PERMISSION_DENIED
}
private fun setWifiEnabledRoot(enable: Boolean): ActionStatus {
val arg = if (enable) "enable" else "disable"
val result = Shell.su("svc wifi $arg").exec()
return if (result.isSuccess) {
ActionStatus.SUCCESS
} else {
ActionStatus.REMOTE_FAILURE
}
}
private fun setWifiEnabledShizuku(context: Context, enable: Boolean): ActionStatus {
return runCatching {
val wifiMgr = SystemServiceHelper.getSystemService(Context.WIFI_SERVICE)
.let(::ShizukuBinderWrapper)
.let(IWifiManager.Stub::asInterface)
val ret = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
wifiMgr.setWifiEnabled("com.android.shell", enable)
} else {
wifiMgr.setWifiEnabled(enable)
}
if (ret) ActionStatus.SUCCESS else ActionStatus.REMOTE_FAILURE
}.getOrElse {
Logger.writeLine(Log.ERROR, it)
ActionStatus.REMOTE_FAILURE
}
}
} | 9 | Kotlin | 37 | 99 | f8df1f9b321130e3b7d031ed2e2e3bbe7d196c86 | 3,424 | SimpleWear | Apache License 2.0 |
src/test/kotlin/book/chapter1/section1/Exercise20KtTest.kt | rupeshsasne | 359,696,544 | false | {"Gradle": 2, "INI": 2, "Shell": 1, "Text": 2, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Kotlin": 42, "Java": 13, "XML": 7} | package book.chapter1.section1
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
class Exercise20KtTest {
@ParameterizedTest(name = "#{index} - Run test with arg = {0}")
@ValueSource(ints = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
fun testFactorial(n: Int) {
val fact: Int = (1..n).reduce { a, b -> a * b }
assertEquals(fact, factorial(n))
}
}
| 0 | Kotlin | 0 | 0 | e5a9b1f2d1c497ad7925fb38d9e4fc471688298b | 477 | algorithms-sedgewick-wayne | MIT License |
src/main/java/com/robohorse/robopojogenerator/delegates/RemoteTestCreatorDelegate.kt | arohim | 179,527,650 | false | null | package com.robohorse.robopojogenerator.delegates
import com.robohorse.robopojogenerator.controllers.CoreGeneratorActionController
import com.robohorse.robopojogenerator.errors.custom.PathException
import com.robohorse.robopojogenerator.models.*
import javax.inject.Inject
open class RemoteTestCreatorDelegate @Inject constructor() : CoreCreatorDelegate() {
@Inject
lateinit var pOJOGenerationDelegate: POJOGenerationDelegate
@Inject
lateinit var mapperTestGeneratorDelegate: MapperTestGeneratorDelegate
@Inject
lateinit var factoryGenerationDelegate: FactoryGeneratorDelegate
@Inject
lateinit var fileTemplateWriterDelegate: FileTemplateWriterDelegate
fun runGenerationTask(projectModel: ProjectModel, coreGeneratorModel: CoreGeneratorModel) {
generateMapperTest(projectModel, coreGeneratorModel)
generateFactory(projectModel, coreGeneratorModel)
generateRemoteImplTest(projectModel, coreGeneratorModel)
}
private fun generateRemoteImplTest(projectModel: ProjectModel, coreGeneratorModel: CoreGeneratorModel) {
val path = coreGeneratorModel.remoteTestPath ?: throw PathException()
val regenProjectModel = regenProjectModel(projectModel, path)
val fileTemplateManager = fileTemplateWriterDelegate.getInstance(regenProjectModel.project)
val className = coreGeneratorModel.rootClassName
val templateName = "RemoteImplTest"
val fileNameSuffix = "RemoteImplTest"
val templateProperties = fileTemplateManager.defaultProperties.also {
it["CLASS_NAME"] = className
}
fileTemplateWriterDelegate.writeTemplate(regenProjectModel.directory,
className + fileNameSuffix,
templateName, templateProperties)
}
private fun generateFactory(projectModel: ProjectModel, coreGeneratorModel: CoreGeneratorModel) {
val path = coreGeneratorModel.remoteTestPath + CoreGeneratorActionController.FACTORY_PATH
val regenProjectModel = regenProjectModel(projectModel, path)
val generationModel = GenerationModel.Builder()
.setContent(coreGeneratorModel.content)
.setRootClassName(coreGeneratorModel.rootClassName)
.build()
val factoryGeneratorModel = FactoryGeneratorModel(
fileNameSuffix = "Factory",
templateName = "RemoteFactory",
remote = true,
cache = false,
data = true,
domain = false
)
factoryGenerationDelegate.runGenerationTask(generationModel, regenProjectModel, factoryGeneratorModel)
}
private fun generateMapperTest(projectModel: ProjectModel, coreGeneratorModel: CoreGeneratorModel) {
val path = coreGeneratorModel.remoteTestPath + CoreGeneratorActionController.MAPPER_PATH
val regenProjectModel = regenProjectModel(projectModel, path)
val generationModel = GenerationModel.Builder()
.setContent(coreGeneratorModel.content)
.setRootClassName(coreGeneratorModel.rootClassName)
.build()
val fromMapperTestGeneratorModel = MapperTestGeneratorModel(
from = "model",
to = "entity",
fileNameSuffix = "EntityMapperTest",
templateName = "FromRemoteMapperTest",
classNameSuffix = "EntityMapper",
isNullable = true
)
mapperTestGeneratorDelegate.runGenerationTask(generationModel, regenProjectModel, fromMapperTestGeneratorModel)
val toMapperTestGeneratorModel = MapperTestGeneratorModel(
from = "entity",
to = "model",
fileNameSuffix = "ModelMapperTest",
templateName = "ToRemoteMapperTest",
classNameSuffix = "EntityMapper",
isNullable = false
)
mapperTestGeneratorDelegate.runGenerationTask(generationModel, regenProjectModel, toMapperTestGeneratorModel)
}
} | 4 | Kotlin | 1 | 18 | 45707fd1768bb3c6457a8122525c141dda05c81f | 4,065 | eddga | MIT License |
intellij-plugin-structure/structure-dotnet/src/main/kotlin/com/jetbrains/plugin/structure/dotnet/version/Version.kt | JetBrains | 3,686,654 | false | {"Kotlin": 2521867, "Java": 253600, "CSS": 1454, "JavaScript": 692} | package com.jetbrains.plugin.structure.dotnet.version
import com.jetbrains.plugin.structure.base.utils.Version
import kotlin.math.min
data class ReSharperVersion(val components: List<Int>, override val productCode: String): Version<ReSharperVersion> {
override fun compareTo(other: ReSharperVersion): Int {
val compareProductCodes = productCode.compareTo(other.productCode)
if (productCode.isNotEmpty() && other.productCode.isNotEmpty() && compareProductCodes != 0) {
return compareProductCodes
}
val c1 = components
val c2 = other.components
for (i in 0 until min(c1.size, c2.size)) {
val result = c1[i].compareTo(c2[i])
if (result != 0) {
return result
}
}
return c1.size.compareTo(c2.size)
}
override fun asString() = asString(true)
override fun asStringWithoutProductCode() = asString(false)
override fun toString() = asString()
companion object {
fun fromString(versionString: String): ReSharperVersion {
if (versionString.isBlank()) {
throw IllegalArgumentException("Version string must not be empty")
}
val productSeparator = versionString.indexOf('-')
val productCode: String
var versionNumber = versionString
if (productSeparator > 0) {
productCode = versionString.substring(0, productSeparator)
versionNumber = versionString.substring(productSeparator + 1)
} else {
productCode = ""
}
val components = versionNumber.trim().split('.').map { it.toIntOrNull() ?: throw IllegalArgumentException("Invalid version $versionNumber, should consists from numbers") }
require(components.size >= 2) { "Invalid version number $versionNumber, should be at least 2 parts" }
return ReSharperVersion(components, productCode)
}
}
private fun asString(includeProductCode: Boolean): String {
val builder = StringBuilder()
if (includeProductCode && productCode.isNotEmpty()) {
builder.append(productCode).append('-')
}
builder.append(components[0])
for (i in 1 until components.size) {
builder.append('.').append(components[i])
}
return builder.toString()
}
override fun setProductCodeIfAbsent(productCode: String) =
if (this.productCode.isEmpty())
fromString("$productCode-" + asStringWithoutProductCode())
else {
this
}
}
| 4 | Kotlin | 38 | 178 | 8be19a2c67854545d719fe56f3677122481b372f | 2,375 | intellij-plugin-verifier | Apache License 2.0 |
Plugins/Gradle/src/main/kotlin/com/shopify/testify/tasks/internal/ReportTask.kt | Shopify | 52,982,631 | false | {"Gradle": 8, "Markdown": 15, "INI": 5, "Shell": 3, "Text": 5, "Ignore List": 4, "Batchfile": 2, "Git Attributes": 1, "EditorConfig": 1, "Proguard": 2, "Kotlin": 147, "XML": 29, "CODEOWNERS": 1, "YAML": 9, "Java": 1, "Gradle Kotlin DSL": 2, "Java Properties": 1, "SVG": 8} | /*
* The MIT License (MIT)
*
* Copyright (c) 2021 Shopify Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.shopify.testify.tasks.internal
abstract class ReportTask : TestifyDefaultTask() {
override fun getGroup() = "Testify reports"
protected val reportName: String
get() {
return project.properties["reportFileName"]?.toString() ?: DEFAULT_REPORT_FILE_NAME
}
protected val destinationPath: String
get() {
return project.properties["reportPath"]?.toString() ?: project.file(".").absolutePath
}
}
internal const val DEFAULT_REPORT_FILE_NAME = "report.yml"
| 0 | Kotlin | 23 | 230 | a066819e7401dda888b60f041136d84acb3afc4b | 1,678 | android-testify | MIT License |
duplicates-android/app/src/main/java/com/github/duplicates/DuplicateProviderListener.kt | pnemonic78 | 74,286,607 | false | null | /*
* Copyright 2016, <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.duplicates
/**
* Listener for provider events.
*
* @author moshe.w
*/
interface DuplicateProviderListener<I : DuplicateItem, P : DuplicateProvider<I>> {
/**
* Notification that the provider has fetched an item.
*
* @param provider the provider.
* @param count the number of items fetched.
* @param item the item.
*/
fun onItemFetched(provider: P, count: Int, item: I)
/**
* Notification that the provider has deleted an item.
*
* @param provider the provider.
* @param count the number of items deleted.
* @param item the item.
*/
fun onItemDeleted(provider: P, count: Int, item: I)
/**
* Notification that the provider has deleted an item.
*
* @param provider the provider.
* @param count the number of items deleted.
* @param pair the items pair.
*/
fun onPairDeleted(provider: P, count: Int, pair: DuplicateItemPair<I>)
}
| 3 | null | 1 | 1 | 38a11ad1b3f6dde7224fed6203cea0e0a2792a92 | 1,578 | RemoveDuplicates | Apache License 2.0 |
app/src/main/java/com/yousef/mvvmflightinfo/di/module/ApiModule.kt | youseftaheri | 265,414,975 | false | {"Gradle": 3, "XML": 145, "Java Properties": 3, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "Kotlin": 51, "JSON": 1} | package com.yousef.mvvmflightinfo.di.module
import com.yousef.mvvmflightinfo.data.network.APIInterface
import dagger.Module
import dagger.Provides
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
@Module
class ApiModule {
@Provides
fun getApiInterface(retroFit: Retrofit): APIInterface {
return retroFit.create(APIInterface::class.java)
}
@Provides
fun getRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl("https://api.lufthansa.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build()
}
@Provides
fun getOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor?): OkHttpClient {
return OkHttpClient.Builder()
.connectTimeout(90, TimeUnit.SECONDS)
.writeTimeout(90, TimeUnit.SECONDS)
.readTimeout(90, TimeUnit.SECONDS)
.addInterceptor { chain: Interceptor.Chain ->
val request: Request = chain.request().newBuilder().addHeader("Accept", "application/json")
.build()
chain.proceed(request)
}
.addInterceptor(httpLoggingInterceptor)
.build()
}
@get:Provides
val httpLoggingInterceptor: HttpLoggingInterceptor
get() {
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
return httpLoggingInterceptor
}
}
| 0 | Kotlin | 0 | 0 | 9a1720d1487dd24b1c60ea45f76dd783e783ba92 | 1,932 | FlightInfoMVVM_kotlin | MIT License |
compiler/testData/diagnostics/tests/inference/cannotCompleteResolveWithFunctionLiterals.kt | GwanNg | 333,718,537 | false | {"Markdown": 70, "Gradle": 729, "Gradle Kotlin DSL": 570, "Java Properties": 15, "Shell": 10, "Ignore List": 12, "Batchfile": 9, "Git Attributes": 8, "Kotlin": 61867, "Protocol Buffer": 12, "Java": 6670, "Proguard": 12, "XML": 1607, "Text": 13214, "INI": 178, "JavaScript": 287, "JAR Manifest": 2, "Roff": 213, "Roff Manpage": 38, "AsciiDoc": 1, "HTML": 495, "SVG": 50, "Groovy": 33, "JSON": 186, "JFlex": 3, "Maven POM": 107, "CSS": 5, "JSON with Comments": 9, "Ant Build System": 50, "Graphviz (DOT)": 77, "C": 1, "Ruby": 5, "Objective-C": 8, "OpenStep Property List": 5, "Swift": 5, "Scala": 1, "YAML": 16} | // !WITH_NEW_INFERENCE
// !DIAGNOSTICS: -CONFLICTING_JVM_DECLARATIONS
package f
fun <R> h(<!UNUSED_PARAMETER!>f<!>: (Boolean) -> R) = 1
fun <R> h(<!UNUSED_PARAMETER!>f<!>: (String) -> R) = 2
fun test() = <!CANNOT_COMPLETE_RESOLVE{OI}, OVERLOAD_RESOLUTION_AMBIGUITY{NI}!>h<!>{ <!CANNOT_INFER_PARAMETER_TYPE{OI}, UNUSED_ANONYMOUS_PARAMETER!>i<!> -> getAnswer() }
fun getAnswer() = 42
| 1 | null | 1 | 1 | 836261ba6ee20f04eb09965424f8ad3d7811a7d2 | 386 | kotlin | Apache License 2.0 |
common/data/src/main/java/currencyconverter/common/data/model/CurrencyRate.kt | ShabanKamell | 235,781,240 | false | null | package currencyconverter.common.data.model
data class CurrencyRate(
var currency: String,
var rate: Double
) | 1 | Kotlin | 3 | 9 | 40cd5f4eae27217f7f36ed24f24e9d9bb94b4bfa | 126 | CurrencyConverter | Apache License 2.0 |
android/ares/src/main/java/com/xt/ares/commands/ARESCreatePatternCommand.kt | PonyCui | 159,524,730 | false | null | package com.xt.ares.commands
import com.xt.ares.ARESCommand
import com.xt.ares.ARESImage
class ARESCreatePatternCommand(val image: ARESImage, val repetition: String): ARESCommand() | 1 | null | 1 | 4 | af00835633914617e208b8108e66b503b105dcba | 182 | ares | MIT License |
viewmodelTests/src/jvmMain/kotlin/tech/skot/libraries/video/di/SKVideoViewInjectorMock.kt | useradgents | 470,094,397 | true | {"Kotlin": 17158} | package tech.skot.libraries.video.di
import tech.skot.core.di.InjectorMock
import tech.skot.core.di.module
import tech.skot.libraries.video.SKVideoViewMock
class SKVideoViewInjectorMock : SKVideoViewInjector {
override fun skVideo(url: String, playingInitial: Boolean, soundInitial: Boolean) =
SKVideoViewMock(url, playingInitial, soundInitial)
}
val skvideoModuleMock = module<InjectorMock> {
single<SKVideoViewInjector> { SKVideoViewInjectorMock() }
} | 0 | null | 0 | 0 | 8cc6608610e2dc5dced5d5d54f86ce073f7b97c0 | 472 | sk-video | Apache License 2.0 |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/appmesh/CfnVirtualRouterDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.appmesh
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.String
import kotlin.Unit
import software.amazon.awscdk.services.appmesh.CfnVirtualRouter
import software.amazon.awscdk.services.appmesh.CfnVirtualRouterProps
import software.constructs.Construct
@Generated
public fun Construct.cfnVirtualRouter(id: String, props: CfnVirtualRouterProps): CfnVirtualRouter =
CfnVirtualRouter(this, id, props)
@Generated
public fun Construct.cfnVirtualRouter(
id: String,
props: CfnVirtualRouterProps,
initializer: @AwsCdkDsl CfnVirtualRouter.() -> Unit,
): CfnVirtualRouter = CfnVirtualRouter(this, id, props).apply(initializer)
@Generated
public fun Construct.buildCfnVirtualRouter(id: String, initializer: @AwsCdkDsl
CfnVirtualRouter.Builder.() -> Unit): CfnVirtualRouter = CfnVirtualRouter.Builder.create(this,
id).apply(initializer).build()
| 1 | Kotlin | 0 | 0 | a1cf8fbfdfef9550b3936de2f864543edb76348b | 943 | aws-cdk-kt | Apache License 2.0 |
favourite-lyrics-domain/src/main/kotlin/org/jesperancinha/lyrics/domain/port/LyricsPersistencePort.kt | jesperancinha | 601,731,888 | false | {"Kotlin": 40679, "TypeScript": 10422, "Shell": 7332, "Makefile": 3902, "HTML": 1705, "CSS": 924, "Dockerfile": 604, "JavaScript": 358} | package org.jesperancinha.lyrics.domain.port
import org.jesperancinha.lyrics.domain.data.LyricsDto
import org.jesperancinha.lyrics.domain.data.LyricsFullDto
import java.util.*
interface LyricsPersistencePort {
fun addLyrics(lyricsDto: LyricsDto)
fun removeLyrics(lyricsDto: LyricsDto)
fun updateLyrics(lyricsDto: LyricsDto)
fun getAllLyrics(): List<LyricsDto>
fun getAllLFullLyrics(): List<LyricsFullDto>
fun getLyricsById(lyricsId: UUID): LyricsDto
} | 0 | Kotlin | 2 | 7 | b157f607472de517f4e6f4021a9a53df78491b66 | 477 | favourite-lyrics-app | Apache License 2.0 |
program/convert-miles-to-meters/ConvertMilesToMeters.kt | isyuricunha | 632,079,464 | true | {"YAML": 15, "Markdown": 207, "JSON": 3, "Ignore List": 1, "JavaScript": 207, "CODEOWNERS": 1, "Text": 1, "Python": 204, "Haskell": 60, "Dart": 99, "C": 197, "Ruby": 167, "Java": 195, "C++": 199, "C#": 187, "PHP": 183, "Go": 165, "Kotlin": 159, "Perl": 85, "Scala": 120, "R": 77, "F#": 73, "Rust": 81, "Swift": 122, "Julia": 109, "Raku": 8, "Rebol": 1} | import java.util.Scanner
fun main() {
print("Enter Miles : ")
println()
var miles = readLine()
println("$miles miles in meters : " + ConvertMilesToMeters(miles!!.toInt()))
}
private fun ConvertMilesToMeters(miles: Int): Double {
val meter = miles*1609.344;
return meter
} | 824 | Java | 174 | 6 | c3949d3d4bae20112e007af14d4657cc96142d69 | 301 | program | MIT License |
app/src/main/java/com/bytedance/ttgame/dagger2application/models/GlobalData1.kt | CreateChance | 725,986,477 | false | {"Kotlin": 23567} | package com.bytedance.ttgame.dagger2application.models
/**
* Application 级别的 data,全局唯一,和 application 生命周期同步
* 全局单例
*
* @author 高超(<EMAIL>)
* @since 2023/12/1
*/
class GlobalData1 {
} | 0 | Kotlin | 0 | 0 | 507abee830e8028a14ca96b39e2c15bec8b9c380 | 190 | Dagger2Application | Apache License 2.0 |
domain/src/main/java/com/example/domain/usecase/NoteAndTaskUseCase.kt | City-Zouitel | 576,223,915 | false | {"Kotlin": 435784} | package com.example.domain.usecase
import com.example.domain.model.NoteAndTask
import com.example.domain.repository.NoteAndTaskRepository
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
sealed class NoteAndTaskUseCase {
class GetAllNotesAndTask @Inject constructor(
private val repository: NoteAndTaskRepository
): NoteAndTaskUseCase() {
operator fun invoke() = repository.getAllNotesAndTask
}
class AddNoteAndTask @Inject constructor(
private val repository: NoteAndTaskRepository
): NoteAndTaskUseCase() {
suspend operator fun invoke(noteAndTask: NoteAndTask) = repository.addNoteAndTask(noteAndTask)
}
class DeleteNoteAndTask @Inject constructor(
private val repository: NoteAndTaskRepository
): NoteAndTaskUseCase() {
suspend operator fun invoke(noteAndTask: NoteAndTask) = repository.deleteNoteAndTask(noteAndTask)
}
}
| 27 | Kotlin | 10 | 67 | eddb26dd83a46123c36829efc47bf4f26eac2776 | 933 | JetNote | Apache License 2.0 |
lib/src/main/java/me/wsj/lib/net/parser/HeFengParser.kt | wsjAliYun | 283,814,909 | false | null | package me.wsj.lib.net.parser
import com.google.gson.Gson
import org.json.JSONObject
import java.lang.reflect.Type
/**
* 和风api解析器
*/
class HeFengParser<T>(val returnType: Type) : ResultParser<T> {
override fun parse(json: String): T {
return Gson().fromJson(json, returnType)
}
}
/**
* 风云api解析器
*/
class FengYunParser<T>(val returnType: Type) : ResultParser<T> {
override fun parse(json: String): T {
val jsonObject = JSONObject(json)
val data = jsonObject.get("result").toString()
return Gson().fromJson(data, returnType)
}
} | 3 | null | 74 | 514 | da4cba77a13cf10878c388bc67d96f9bc8a4230d | 581 | kms | Apache License 2.0 |
app/src/main/java/com/example/f0x/apibot/domain/repository/chat/ChatRepository.kt | theaspect | 110,525,955 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 2, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "YAML": 1, "Proguard": 1, "Java": 3, "XML": 25, "Kotlin": 51} | package com.example.f0x.apibot.domain.repository.chat
import com.example.f0x.apibot.domain.models.ai.chat.ChatMessage
import com.example.f0x.apibot.domain.repository.BaseRepository
import com.example.f0x.apibot.domain.repository.chat.local.IChatLocalStorage
import io.reactivex.subjects.ReplaySubject
class ChatRepository(val localStorage: IChatLocalStorage, val chatSubject: ReplaySubject<ChatMessage>) : BaseRepository(), IChatRepository {
override fun saveMessage(message: String, type: Int) {
val chatMessage = ChatMessage(System.currentTimeMillis(), message, type)
localStorage.saveMessage(chatMessage)
chatSubject.onNext(chatMessage)
}
override fun allMessages() {
localStorage.allMessages().forEach { chatSubject.onNext(it) }
}
override fun clearChatMessages() {
localStorage.clearChatMessages()
}
} | 0 | Kotlin | 0 | 1 | c4530a01e28bfda4a08c5a020411582a0ef52096 | 876 | api-bot | Apache License 2.0 |
core/src/main/kotlin/com/seventh_root/guildfordgamejam/component/LevelComponent.kt | alyphen | 72,883,027 | false | null | package com.seventh_root.guildfordgamejam.component
import com.badlogic.ashley.core.Component
import com.seventh_root.guildfordgamejam.level.Level
class LevelComponent(val level: Level): Component | 0 | Kotlin | 0 | 1 | a55ec8d4525d0e2c938d376b476eba6b5e32132b | 198 | guildford-game-jam-2016 | Apache License 2.0 |
fluentui_core/src/main/java/com/microsoft/fluentui/theme/token/controlTokens/BannerTokens.kt | microsoft | 257,221,908 | false | {"Kotlin": 3021107, "Shell": 8996} | package com.microsoft.fluentui.theme.token.controlTokens
import android.os.Parcelable
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.microsoft.fluentui.theme.FluentTheme.aliasTokens
import com.microsoft.fluentui.theme.token.ControlInfo
import com.microsoft.fluentui.theme.token.FluentAliasTokens
import com.microsoft.fluentui.theme.token.IControlToken
import kotlinx.parcelize.Parcelize
open class BannerInfo(
val isAccessoryButtonEnabled: Boolean = false
) : ControlInfo
@Parcelize
open class BannerTokens : IControlToken, Parcelable {
@Composable
open fun backgroundColor(bannerInfo: BannerInfo): Brush {
return SolidColor(aliasTokens.neutralBackgroundColor[FluentAliasTokens.NeutralBackgroundColorTokens.Background4].value())
}
@Composable
open fun textColor(bannerInfo: BannerInfo): Color {
return aliasTokens.neutralForegroundColor[FluentAliasTokens.NeutralForegroundColorTokens.Foreground1].value()
}
@Composable
open fun actionIconColor(bannerInfo: BannerInfo): Color {
return aliasTokens.neutralForegroundColor[FluentAliasTokens.NeutralForegroundColorTokens.Foreground2].value()
}
@Composable
open fun leadingIconColor(bannerInfo: BannerInfo): Color {
return aliasTokens.neutralForegroundColor[FluentAliasTokens.NeutralForegroundColorTokens.Foreground2].value()
}
@Composable
open fun actionButtonColor(bannerInfo: BannerInfo): Color {
return aliasTokens.brandForegroundColor[FluentAliasTokens.BrandForegroundColorTokens.BrandForeground1].value()
}
@Composable
open fun leadingIconSize(bannerInfo: BannerInfo): Dp = 24.dp
@Composable
open fun actionIconSize(bannerInfo: BannerInfo): Dp = 20.dp
@Composable
open fun padding(bannerInfo: BannerInfo): PaddingValues =
bannerInfo.isAccessoryButtonEnabled.let {
if (it) {
PaddingValues(horizontal = 16.dp, vertical = 8.dp)
} else {
PaddingValues(horizontal = 16.dp, vertical = 12.dp)
}
}
@Composable
open fun textTypography(bannerInfo: BannerInfo): TextStyle {
return aliasTokens.typography[FluentAliasTokens.TypographyTokens.Body2]
}
@Composable
open fun actionButtonTextTypography(bannerInfo: BannerInfo): TextStyle {
return aliasTokens.typography[FluentAliasTokens.TypographyTokens.Body2Strong]
}
@Composable
open fun leadingIconAndTextSpacing(bannerInfo: BannerInfo): Dp = 12.dp
@Composable
open fun textAndActionButtonSpacing(bannerInfo: BannerInfo): Dp = 12.dp
@Composable
open fun accessoryActionButtonsSpacing(bannerInfo: BannerInfo): Dp = 24.dp
@Composable
open fun textAndAccessoryButtonSpacing(bannerInfo: BannerInfo): Dp = 8.dp
} | 25 | Kotlin | 103 | 574 | 851a4989a4fce5db50a1818aa4121538c1fb4ad9 | 3,100 | fluentui-android | MIT License |
src/test/kotlin/aoc2019/TractorBeamTest.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2019
import komu.adventofcode.utils.readTestInput
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class TractorBeamTest {
@Test
fun `part 1`() {
assertEquals(129, tractorBeam1(readTestInput("/2019/TractorBeam.txt")))
}
@Test
fun `part 2`() {
assertEquals(14040699, tractorBeam2(readTestInput("/2019/TractorBeam.txt")))
}
}
| 0 | Kotlin | 0 | 0 | f07e74761d742c519fef4ba06fa474f1016bdbbd | 414 | advent-of-code | MIT License |
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/preferences/SettingsPreferences.kt | wigr11 | 132,491,533 | true | {"Kotlin": 932984, "Java": 251617} | package io.github.feelfreelinux.wykopmobilny.utils.preferences
import android.content.Context
interface SettingsPreferencesApi {
var notificationsSchedulerDelay : String?
var hotEntriesScreen : String?
var defaultScreen : String?
var linkImagePosition : String?
var linkShowImage : Boolean
var linkSimpleList : Boolean
var linkShowAuthor : Boolean
var showAdultContent : Boolean
var hideNsfw: Boolean
var useDarkTheme : Boolean
var useAmoledTheme : Boolean
var showNotifications : Boolean
var piggyBackPushNotifications : Boolean
var showMinifiedImages : Boolean
var cutLongEntries : Boolean
var cutImages : Boolean
var openSpoilersDialog : Boolean
var hideLowRangeAuthors : Boolean
var cutImageProportion : Int
var fontSize : String?
var hideLinkCommentsByDefault : Boolean
var hideBlacklistedViews : Boolean
var enableYoutubePlayer : Boolean
var enableEmbedPlayer : Boolean
}
class SettingsPreferences(context : Context) : Preferences(context, true), SettingsPreferencesApi {
override var notificationsSchedulerDelay by stringPref(defaultValue = "15")
override var showAdultContent by booleanPref(defaultValue = false)
override var hideNsfw: Boolean by booleanPref(defaultValue = true)
override var hideLowRangeAuthors: Boolean by booleanPref(defaultValue = false)
override var hotEntriesScreen by stringPref(defaultValue = "newest")
override var defaultScreen by stringPref(defaultValue = "mainpage")
override var fontSize by stringPref(defaultValue = "normal")
override var linkImagePosition by stringPref(defaultValue = "left")
override var linkShowImage by booleanPref(defaultValue = true)
override var linkSimpleList by booleanPref(defaultValue = false)
override var linkShowAuthor by booleanPref(defaultValue = false)
override var useDarkTheme by booleanPref(defaultValue = false)
override var useAmoledTheme by booleanPref(defaultValue = false)
override var showMinifiedImages by booleanPref(defaultValue = false)
override var piggyBackPushNotifications by booleanPref(defaultValue = false)
override var cutLongEntries by booleanPref(defaultValue = true)
override var cutImages by booleanPref(defaultValue = true)
override var cutImageProportion by intPref(defaultValue = 60)
override var openSpoilersDialog by booleanPref(defaultValue = true)
override var showNotifications by booleanPref(defaultValue = true)
override var hideLinkCommentsByDefault by booleanPref(defaultValue = false)
override var hideBlacklistedViews: Boolean by booleanPref(defaultValue = false)
override var enableEmbedPlayer by booleanPref(defaultValue = true)
override var enableYoutubePlayer by booleanPref(defaultValue = true)
} | 0 | Kotlin | 0 | 0 | ae3395fa96817628614b185e7cf84e81b4d44b47 | 2,810 | WykopMobilny | MIT License |
knear-sdk/src/main/java/com/knear/android/provider/response/viewaccountchanges/ChangeX.kt | near | 514,329,257 | false | {"Kotlin": 128819} | package com.knear.android.provider.response.viewaccountchanges
data class ChangeX(
val account_id: String,
val amount: String,
val code_hash: String,
val locked: String,
val storage_paid_at: Int,
val storage_usage: Int
)
| 5 | Kotlin | 2 | 20 | 42a2bbeed12257c310a96a4af1ffedda2ea719f1 | 246 | near-api-kotlin | MIT License |
skiko/src/jsMain/kotlin/org/jetbrains/skiko/SkiaLayer.js.kt | sellmair | 416,502,518 | true | {"C++": 1337733, "Kotlin": 1165199, "Objective-C++": 20873, "Dockerfile": 2426, "JavaScript": 929, "C": 704, "Shell": 555} | package org.jetbrains.skiko
actual open class SkiaLayer {
actual var renderApi: GraphicsApi = GraphicsApi.WEBGL
actual val contentScale: Float
get() = 1.0f
actual var fullscreen: Boolean
get() = false
set(value) = throw Exception("Fullscreen is not supported!")
actual var transparency: Boolean
get() = false
set(value) = throw Exception("Transparency is not supported!")
}
| 0 | null | 0 | 0 | 9ccc6234799558386ccfa00630600e02c8eb62f9 | 431 | skiko | Apache License 2.0 |
app/src/main/java/com/mitch/learnandroid/ui/fragment/SplashFragment.kt | MitchZhang | 468,718,415 | false | null | package com.mitch.learnandroid.ui.fragment
import android.os.Bundle
import android.view.View
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.kunminx.architecture.ui.page.BaseFragment
import com.kunminx.architecture.ui.page.DataBindingConfig
import com.mitch.learnandroid.BR
import com.mitch.learnandroid.R
import com.mitch.learnandroid.ui.state.SplashViewModel
/**
* @Class: SplashFragment
* @Description:
* @author: MitchZhang
* @Date: 2022/4/19
*/
class SplashFragment : BaseFragment() {
private lateinit var mState: SplashViewModel
override fun initViewModel() {
mState = SplashViewModel()
}
override fun getDataBindingConfig(): DataBindingConfig {
return DataBindingConfig(R.layout.fragment_splash, BR.vm, mState)
.addBindingParam(BR.click, object : View.OnClickListener {
override fun onClick(p0: View?) {
nav().navigate(R.id.goDispatch)
}
})
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycle.addObserver(mState.request)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//请求网络,view层持有ViewModel层
mState.request.getServerConfig()
//订阅 数据回调,非Mvp接口回调数据
mState.request.getDictLiveData().observe(viewLifecycleOwner) {
it?.let {
//todo 更加优雅的方式 获取list数据
if (it.success) {
ToastUtils.showShort("网络请求成功: 获取到${it.data?.size}条数据 !!!!!!!!!")
LogUtils.e("Banner数据:${it.data}")
} else {
ToastUtils.showShort("网络请求失败:${it.errorMsg}")
}
}
}
}
} | 1 | null | 1 | 1 | 25f91cdb993fdfdc461e615dd1b44c3cfdad2ef5 | 1,850 | LearnAndroid | Apache License 2.0 |
kotlin/src/main/java/io/github/caoshen/androidadvance/kotlin/oop/ObjectTest.kt | caoshen | 290,115,293 | false | null | package io.github.caoshen.androidadvance.kotlin.oop
fun testPerson() {
val person = Person("zhangsan", 30)
person.age = 31
println("${person.name} ${person.age} , is adult: ${person.isAdult}")
}
fun main() {
testPerson()
val person3 = Person3("<NAME>", 18)
val component1 = person3.component1()
val component2 = person3.component2()
println("component1:$component1, component2:$component2")
} | 0 | Kotlin | 0 | 2 | b128cdd72dd81ef2bc3f3510f808f198196ef889 | 428 | AndroidAdvance | MIT License |
ThumbArrowShape/src/main/kotlin/example/App.kt | aterai | 158,348,575 | false | null | package example
import java.awt.* // ktlint-disable no-wildcard-imports
import javax.swing.* // ktlint-disable no-wildcard-imports
fun makeUI(): Component {
val slider0 = JSlider(SwingConstants.VERTICAL)
val slider1 = JSlider(SwingConstants.VERTICAL)
val slider2 = JSlider(SwingConstants.VERTICAL)
val slider3 = JSlider(SwingConstants.HORIZONTAL)
val slider4 = JSlider(SwingConstants.HORIZONTAL)
val slider5 = JSlider(SwingConstants.HORIZONTAL)
val model = DefaultBoundedRangeModel(50, 0, 0, 100)
listOf(slider0, slider1, slider2, slider3, slider4, slider5).forEach {
it.model = model
}
slider1.majorTickSpacing = 20
slider1.paintTicks = true
val key = "Slider.paintThumbArrowShape"
slider2.putClientProperty(key, true)
slider4.majorTickSpacing = 20
slider4.paintTicks = true
slider5.putClientProperty(key, true)
val box1 = Box.createHorizontalBox().also {
it.border = BorderFactory.createEmptyBorder(20, 5, 20, 5)
it.add(slider0)
it.add(Box.createHorizontalStrut(20))
it.add(slider1)
it.add(Box.createHorizontalStrut(20))
it.add(slider2)
it.add(Box.createHorizontalGlue())
}
val box2 = Box.createVerticalBox().also {
it.border = BorderFactory.createEmptyBorder(20, 0, 20, 5)
it.add(makeTitledPanel("Default", slider3))
it.add(Box.createVerticalStrut(20))
it.add(makeTitledPanel("setPaintTicks", slider4))
it.add(Box.createVerticalStrut(20))
it.add(makeTitledPanel(key, slider5))
it.add(Box.createVerticalGlue())
}
return JPanel(BorderLayout()).also {
it.add(box1, BorderLayout.WEST)
it.add(box2)
val mb = JMenuBar()
mb.add(LookAndFeelUtil.createLookAndFeelMenu())
EventQueue.invokeLater { it.rootPane.jMenuBar = mb }
it.preferredSize = Dimension(320, 240)
}
}
private fun makeTitledPanel(title: String, c: Component) = JPanel(BorderLayout()).also {
it.border = BorderFactory.createTitledBorder(title)
it.add(c)
}
private object LookAndFeelUtil {
private var lookAndFeel = UIManager.getLookAndFeel().javaClass.name
fun createLookAndFeelMenu() = JMenu("LookAndFeel").also {
val lafRadioGroup = ButtonGroup()
for (lafInfo in UIManager.getInstalledLookAndFeels()) {
it.add(createLookAndFeelItem(lafInfo.name, lafInfo.className, lafRadioGroup))
}
}
private fun createLookAndFeelItem(
lafName: String,
lafClassName: String,
lafGroup: ButtonGroup
): JMenuItem {
val lafItem = JRadioButtonMenuItem(lafName, lafClassName == lookAndFeel)
lafItem.actionCommand = lafClassName
lafItem.hideActionText = true
lafItem.addActionListener { e ->
val m = lafGroup.selection
runCatching {
setLookAndFeel(m.actionCommand)
}.onFailure {
UIManager.getLookAndFeel().provideErrorFeedback(e.source as? Component)
}
}
lafGroup.add(lafItem)
return lafItem
}
@Throws(
ClassNotFoundException::class,
InstantiationException::class,
IllegalAccessException::class,
UnsupportedLookAndFeelException::class
)
private fun setLookAndFeel(lookAndFeel: String) {
val oldLookAndFeel = LookAndFeelUtil.lookAndFeel
if (oldLookAndFeel != lookAndFeel) {
UIManager.setLookAndFeel(lookAndFeel)
LookAndFeelUtil.lookAndFeel = lookAndFeel
updateLookAndFeel()
}
}
private fun updateLookAndFeel() {
for (window in Window.getWindows()) {
SwingUtilities.updateComponentTreeUI(window)
}
}
}
fun main() {
EventQueue.invokeLater {
runCatching {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
}.onFailure {
it.printStackTrace()
Toolkit.getDefaultToolkit().beep()
}
JFrame().apply {
defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
contentPane.add(makeUI())
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
}
| 0 | null | 3 | 9 | 47a0c684f64c3db2c8b631b2c20c6c7f9205bcab | 3,881 | kotlin-swing-tips | MIT License |
src/test/kotlin/uk/gov/justice/digital/hmpps/prisonerfromnomismigration/csip/CSIPApiMockServer.kt | ministryofjustice | 452,734,022 | false | {"Kotlin": 2035336, "Mustache": 1803, "Dockerfile": 1374} | package uk.gov.justice.digital.hmpps.prisonerfromnomismigration.csip
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.client.WireMock.aResponse
import com.github.tomakehurst.wiremock.client.WireMock.delete
import com.github.tomakehurst.wiremock.client.WireMock.get
import com.github.tomakehurst.wiremock.client.WireMock.post
import com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor
import com.github.tomakehurst.wiremock.client.WireMock.urlMatching
import org.junit.jupiter.api.extension.AfterAllCallback
import org.junit.jupiter.api.extension.BeforeAllCallback
import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.springframework.http.HttpStatus
import org.springframework.http.HttpStatus.CREATED
class CSIPApiExtension : BeforeAllCallback, AfterAllCallback, BeforeEachCallback {
companion object {
@JvmField
val csipApi = CSIPApiMockServer()
}
override fun beforeAll(context: ExtensionContext) {
csipApi.start()
}
override fun beforeEach(context: ExtensionContext) {
csipApi.resetAll()
}
override fun afterAll(context: ExtensionContext) {
csipApi.stop()
}
}
class CSIPApiMockServer : WireMockServer(WIREMOCK_PORT) {
companion object {
private const val WIREMOCK_PORT = 8088
}
fun stubHealthPing(status: Int) {
stubFor(
get("/health/ping").willReturn(
aResponse()
.withHeader("Content-Type", "application/json")
.withBody(if (status == 200) "pong" else "some error")
.withStatus(status),
),
)
}
fun stubCSIPMigrate(dpsCSIPId: String = "a1b2c3d4-e5f6-1234-5678-90a1b2c3d4e5") {
stubFor(
post("/migrate/csip-report").willReturn(
aResponse()
.withHeader("Content-Type", "application/json")
.withStatus(CREATED.value())
.withBody(
CSIPMigrateResponse(
dpsCSIPId = dpsCSIPId,
).toJson(),
),
),
)
}
fun stubCSIPInsert(dpsCSIPId: String = "a1b2c3d4-e5f6-1234-5678-90a1b2c3d4e5") {
stubFor(
post("/csip").willReturn(
aResponse()
.withHeader("Content-Type", "application/json")
.withStatus(CREATED.value())
.withBody(
CSIPSyncResponse(
dpsCSIPId = dpsCSIPId,
).toJson(),
),
),
)
}
fun stubCSIPDelete(dpsCSIPId: String = "a1b2c3d4-e5f6-1234-5678-90a1b2c3d4e5") {
stubFor(
delete("/csip/$dpsCSIPId").willReturn(
aResponse()
.withStatus(HttpStatus.NO_CONTENT.value()),
),
)
}
fun stubCSIPDeleteNotFound(status: HttpStatus = HttpStatus.NOT_FOUND) {
stubFor(
delete(WireMock.urlPathMatching("/csip/.*"))
.willReturn(
aResponse()
.withHeader("Content-Type", "application/json")
.withStatus(status.value()),
),
)
}
fun createCSIPMigrationCount() =
findAll(postRequestedFor(urlMatching("/migrate/csip-report"))).count()
fun createCSIPSyncCount() =
findAll(postRequestedFor(urlMatching("/csip"))).count()
}
private fun Any.toJson(): String = ObjectMapper().writeValueAsString(this)
| 2 | Kotlin | 1 | 2 | 081207d6f5fd7540e9af0fd6fc33f44a86deb689 | 3,364 | hmpps-prisoner-from-nomis-migration | MIT License |
composeApp/src/commonMain/kotlin/di/InitKoin.kt | abdallahmehiz | 830,308,163 | false | {"Kotlin": 449026, "Swift": 621} | package di
import com.liftric.kvault.KVault
import mehiz.abdallah.progres.domain.di.DomainModule
import org.koin.dsl.module
import utils.CredentialManager
import utils.PlatformUtils
fun initKoin(
datastorePath: String,
credentialManager: CredentialManager,
kVault: KVault,
platformUtils: PlatformUtils,
) = module {
includes(
PreferencesModule(datastorePath),
DomainModule,
ScreenModelsModule,
ApplicationModule(credentialManager, kVault, platformUtils)
)
}
| 1 | Kotlin | 0 | 8 | 331d3c6c8caa126fdc7df033f2574cd3aa8f8e80 | 488 | progres | MIT License |
libraries/tools/new-project-wizard/src/org/jetbrains/kotlin/tools/projectWizard/moduleConfigurators/NativeTargetConfigurator.kt | liuhuibin | 233,908,049 | true | {"Markdown": 61, "Gradle": 631, "Gradle Kotlin DSL": 357, "Java Properties": 13, "Shell": 10, "Ignore List": 11, "Batchfile": 9, "Git Attributes": 7, "Protocol Buffer": 11, "Java": 6450, "Kotlin": 54353, "Proguard": 8, "XML": 1566, "Text": 10603, "JavaScript": 270, "JAR Manifest": 2, "Roff": 211, "Roff Manpage": 36, "INI": 139, "AsciiDoc": 1, "SVG": 31, "HTML": 464, "Groovy": 31, "JSON": 46, "JFlex": 3, "Maven POM": 97, "CSS": 4, "JSON with Comments": 7, "Ant Build System": 50, "Graphviz (DOT)": 39, "C": 1, "YAML": 9, "Ruby": 2, "OpenStep Property List": 2, "Swift": 2, "Objective-C": 2, "Scala": 1} | package org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators
import org.jetbrains.kotlin.tools.projectWizard.core.buildList
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildSystemIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.CreateGradleValueIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.RawGradleIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.multiplatform.NativeTargetInternalIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.multiplatform.NonDefaultTargetConfigurationIR
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleSubType
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleType
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module
interface NativeTargetConfigurator : TargetConfigurator {
override fun createInnerTargetIrs(module: Module): List<BuildSystemIR> = buildList {
+NativeTargetInternalIR("MAIN CLASS")
}
}
class RealNativeTargetConfigurator private constructor(
override val moduleSubType: ModuleSubType
) : NativeTargetConfigurator, SimpleTargetConfigurator {
companion object {
val configurators = ModuleSubType.values()
.filter { it.moduleType == ModuleType.native }
.map(::RealNativeTargetConfigurator)
val configuratorsByModuleType = configurators.associateBy { it.moduleSubType }
}
}
object NativeForCurrentSystemTarget : NativeTargetConfigurator, SingleCoexistenceTargetConfigurator {
override val moduleType = ModuleType.native
override val id = "nativeForCurrentSystem"
override val text = "For Current System"
override fun createTargetIrs(module: Module): List<BuildSystemIR> {
val moduleName = module.name
return buildList {
+CreateGradleValueIR("hostOs", RawGradleIR { +"System.getProperty(\"os.name\")" })
+CreateGradleValueIR("isMingwX64", RawGradleIR { +"hostOs.startsWith(\"Windows\")" })
//TODO do not use RawGradleIR here
+RawGradleIR {
when (dsl) {
GradlePrinter.GradleDsl.KOTLIN -> {
+"val $DEFAULT_TARGET_VARIABLE_NAME = when "
inBrackets {
indent()
+"""hostOs == "Mac OS X" -> macosX64("$moduleName")"""; nlIndented()
+"""hostOs == "Linux" -> linuxX64("$moduleName")"""; nlIndented()
+"""isMingwX64 -> mingwX64("$moduleName")"""; nlIndented()
+"""else -> throw GradleException("Host OS is not supported in Kotlin/Native.")"""
}
}
GradlePrinter.GradleDsl.GROOVY -> {
+"""org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTargetWithTests $DEFAULT_TARGET_VARIABLE_NAME"""; nlIndented()
+"""if (hostOs == "Mac OS X") $DEFAULT_TARGET_VARIABLE_NAME = macosX64('$moduleName')"""; nlIndented()
+"""else if (hostOs == "Linux") $DEFAULT_TARGET_VARIABLE_NAME = linuxX64("$moduleName")"""; nlIndented()
+"""else if (isMingwX64) return $DEFAULT_TARGET_VARIABLE_NAME = mingwX64("$moduleName")"""; nlIndented()
+"""else throw new GradleException("Host OS is not supported in Kotlin/Native.")""";
}
}
nl()
}
+NonDefaultTargetConfigurationIR(
DEFAULT_TARGET_VARIABLE_NAME,
createInnerTargetIrs(module)
)
}
}
private const val DEFAULT_TARGET_VARIABLE_NAME = "nativeTarget"
}
| 0 | Kotlin | 0 | 0 | 6be72321d03e3a5ff761a65aea4b7fa51e29445c | 3,872 | kotlin | Apache License 2.0 |
common_component/src/main/java/com/xyoye/common_component/storage/platform/AndroidPlatform.kt | kaedei | 395,177,024 | true | {"Kotlin": 1300087, "Java": 542941} | package com.xyoye.common_component.storage.platform
import android.content.Context
import com.xyoye.common_component.storage.file_system.LollipopFileSystem
import com.xyoye.common_component.storage.utils.ExSdCardUtils
import com.xyoye.common_component.utils.PathHelper
import java.io.File
/**
* @author gubatron
* @author aldenml
*
* Created by xyoye on 2020/12/30.
*/
class AndroidPlatform private constructor() {
companion object {
@JvmStatic
fun getInstance() = Holder.instance
fun saf(context: Context, file: File): Boolean {
if (file.path.contains(PathHelper.PRIVATE_DIRECTORY_PATH)) {
return false
}
return ExSdCardUtils.getExtSdCardFolder(context, file) != null
}
}
private lateinit var fileSystem: LollipopFileSystem
private object Holder {
val instance = AndroidPlatform()
}
fun init(context: Context) {
if (this::fileSystem.isInitialized) {
throw IllegalStateException("Duplicate instantiation is not allowed")
}
fileSystem = LollipopFileSystem(context)
}
fun getFileSystem(): LollipopFileSystem {
if (!this::fileSystem.isInitialized) {
throw IllegalStateException("Wrong call timing, file system uninitialized")
}
return fileSystem
}
} | 0 | Kotlin | 1 | 8 | 1e2bbe520287c3ebf056ffdb3d00c07edf7946fb | 1,361 | DanDanPlayForAndroid | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/weather/HourlyWeatherDetails.kt | bherbst | 350,356,625 | 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.weather
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Navigation
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.R
import com.example.androiddevchallenge.data.AirQualityIndex
import com.example.androiddevchallenge.data.DegreesFahrenheit
import com.example.androiddevchallenge.data.Inches
import com.example.androiddevchallenge.data.MilesPerHour
import com.example.androiddevchallenge.data.Percent
import com.example.androiddevchallenge.data.Precipitation
import com.example.androiddevchallenge.data.PrecipitationType
import com.example.androiddevchallenge.data.WeatherAtTime
import com.example.androiddevchallenge.data.WeatherType
import com.example.androiddevchallenge.data.Wind
import com.example.androiddevchallenge.data.WindDirection
import com.example.androiddevchallenge.settings.WeatherUnits
import com.example.androiddevchallenge.ui.VerticalDivider
import com.example.androiddevchallenge.ui.theme.WeatherTheme
@Composable
fun HourlyWeatherDetails(
modifier: Modifier = Modifier,
weather: WeatherAtTime,
units: WeatherUnits
) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Precipitation(
modifier = Modifier.fillMaxWidth(.5f)
.padding(16.dp),
precipitation = weather.precipitation,
units = units
)
VerticalDivider(
modifier = Modifier.height(64.dp)
)
Wind(
modifier = Modifier.fillMaxWidth()
.padding(16.dp),
wind = weather.wind,
units = units
)
}
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Humidity(
modifier = Modifier.fillMaxWidth(.5f)
.padding(16.dp),
humidity = weather.humidity
)
VerticalDivider(
modifier = Modifier.height(64.dp)
)
AirQualityIndex(
modifier = Modifier.fillMaxWidth()
.padding(16.dp),
aqi = weather.airQuality
)
}
}
}
@Composable
private fun Precipitation(
modifier: Modifier = Modifier,
precipitation: Precipitation,
units: WeatherUnits
) {
val accumulation = units.formatAccumulation(precipitation.amount)
Column(
modifier = modifier.semantics(mergeDescendants = true) {},
horizontalAlignment = Alignment.CenterHorizontally
) {
Row {
PrecipitationIcon(precipitation.type)
Spacer(Modifier.width(4.dp))
Text(
text = "${precipitation.chance.value}%"
)
}
Spacer(Modifier.height(4.dp))
Text(accumulation)
}
}
@Composable
private fun PrecipitationIcon(type: PrecipitationType) {
when (type) {
PrecipitationType.Snow -> Icon(
painter = painterResource(R.drawable.ic_snowflake),
contentDescription = "snow"
)
PrecipitationType.Mixed -> Icon(
painter = painterResource(R.drawable.ic_snowflake_raindrop),
contentDescription = "rain and snow"
)
else -> Icon(
painter = painterResource(R.drawable.ic_raindrop),
contentDescription = "rain"
)
}
}
@Composable
private fun Wind(
modifier: Modifier = Modifier,
wind: Wind,
units: WeatherUnits
) {
Column(
modifier = modifier.semantics(mergeDescendants = true) {},
horizontalAlignment = Alignment.CenterHorizontally
) {
Row {
Icon(
painter = painterResource(R.drawable.ic_wind),
contentDescription = "Wind"
)
Spacer(Modifier.width(4.dp))
Text(units.formatSpeed(wind.speed))
}
Spacer(Modifier.height(4.dp))
Row {
Icon(
modifier = Modifier.rotate(wind.iconRotationDegrees()),
imageVector = Icons.Rounded.Navigation,
contentDescription = null // The text label will suffice
)
Spacer(Modifier.width(4.dp))
Text(wind.direction.shortText)
}
}
}
/**
* Get the amount in degrees to rotate the wind direction icon,
* which is pointing directly upward at zero rotation.
*/
private fun Wind.iconRotationDegrees(): Float = when (direction) {
WindDirection.North -> 0f
WindDirection.Northeast -> 45f
WindDirection.East -> 90f
WindDirection.Southeast -> 135f
WindDirection.South -> 180f
WindDirection.Southwest -> 225f
WindDirection.West -> 270f
WindDirection.Northwest -> 315f
}
@Composable
private fun AirQualityIndex(
modifier: Modifier = Modifier,
aqi: AirQualityIndex
) {
Column(
modifier = modifier.semantics(mergeDescendants = true) {
contentDescription = "Air Quality Index of ${aqi.value}, which is ${aqi.label().displayText}"
},
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "${aqi.value} ${aqi.label().displayText}")
Spacer(Modifier.height(4.dp))
Text(
text = "Air Quality",
style = MaterialTheme.typography.caption
)
}
}
@Composable
private fun Humidity(
modifier: Modifier = Modifier,
humidity: Percent
) {
Column(
modifier = modifier.semantics(mergeDescendants = true) {},
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("${humidity.value}%")
Spacer(Modifier.height(4.dp))
Text(
text = "Humidity",
style = MaterialTheme.typography.caption
)
}
}
@Preview
@Composable
private fun HourlyWeatherDetailsPreview() {
val weather = WeatherAtTime(
temp = DegreesFahrenheit(43),
humidity = Percent(81),
airQuality = AirQualityIndex(31),
wind = Wind(
speed = MilesPerHour(2),
direction = WindDirection.Northeast
),
precipitation = Precipitation(
chance = Percent(20),
type = PrecipitationType.Rain,
amount = Inches(0.2)
),
weatherType = WeatherType.Sunny
)
WeatherTheme {
Surface {
HourlyWeatherDetails(
modifier = Modifier.fillMaxWidth(),
weather = weather,
units = WeatherUnits.Imperial
)
}
}
}
| 0 | Kotlin | 0 | 0 | ed8f95988f711be62b591540307a99f5182393c5 | 8,392 | ComposeWeather | Apache License 2.0 |
app/src/main/java/com/mathews/codetracker/modules/splash/di/SplashScope.kt | marymathews | 307,809,066 | false | {"Gradle": 4, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "INI": 1, "Proguard": 2, "Kotlin": 63, "XML": 23, "Java": 1} | package com.mathews.codetracker.modules.splash.di
import javax.inject.Scope
@Scope annotation class SplashScope | 0 | Kotlin | 0 | 1 | 563bc7f8205e4b8a9a25856fcf74f67ed16f0584 | 113 | code-tracker | Apache License 2.0 |
app/src/main/java/com/sencent/qrcode/MainActivity.kt | qq2519157 | 162,520,464 | false | null | package com.sencent.qrcode
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.app.ActivityOptionsCompat
import android.support.v7.app.AppCompatActivity
import android.view.View
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun scan(view: View) {
val optionsCompat = ActivityOptionsCompat.makeCustomAnimation(this, R.anim.act_in, R.anim.act_out)
when (view.id) {
R.id.btn1 -> {
ActivityCompat.startActivity(
this@MainActivity,
Intent(this@MainActivity, TestActivity::class.java),
optionsCompat.toBundle()
)
}
else -> {
ActivityCompat.startActivity(
this@MainActivity,
Intent(this@MainActivity, TestFragmentActivity::class.java),
optionsCompat.toBundle()
)
}
}
}
}
| 0 | Kotlin | 1 | 7 | 2f4ef5cecc94cd760ef70cc4eeda3ec21f9e6012 | 1,159 | qrcode-view | Apache License 2.0 |
core/model/src/main/java/com/example/model/domain/DetailedModel.kt | KanuKim97 | 428,755,782 | false | {"Kotlin": 153590} | package com.example.model.domain
data class DetailedModel(
val placeId: String,
val placeName: String,
val placeRating: String,
val placeImgUrl: String,
val placeAddress: String,
val placePhoneNumber: String,
val placeLatitude: Double,
val placeLongitude: Double,
val isPlaceOpenNow: Boolean
) | 0 | Kotlin | 0 | 3 | 67d81baede597ccb19732a9c20868955be31bb5e | 330 | whats_eat | Apache License 2.0 |
core/model/src/main/java/com/example/model/domain/DetailedModel.kt | KanuKim97 | 428,755,782 | false | {"Kotlin": 153590} | package com.example.model.domain
data class DetailedModel(
val placeId: String,
val placeName: String,
val placeRating: String,
val placeImgUrl: String,
val placeAddress: String,
val placePhoneNumber: String,
val placeLatitude: Double,
val placeLongitude: Double,
val isPlaceOpenNow: Boolean
) | 0 | Kotlin | 0 | 3 | 67d81baede597ccb19732a9c20868955be31bb5e | 330 | whats_eat | Apache License 2.0 |
app/src/main/java/com/steven/movieapp/bean/Avaters.kt | StevenYan88 | 174,098,969 | false | null | package com.steven.movieapp.bean
import com.google.gson.annotations.SerializedName
/**
* Description: 演员信息
* Data:2019/1/28
* Actor:Steven
*/
data class Avaters(
//演员图片
@SerializedName("avatars")
val avatars: Images,
//英文名
@SerializedName("name_en")
val nameEn: String,
//中文名
@SerializedName("name")
val name: String,
//影人简介
@SerializedName("alt")
val alt: String,
//演员id
@SerializedName("id")
val id: Int
) | 1 | Kotlin | 23 | 76 | 7903af00677417a20cf1e06e8b647c762ed90585 | 475 | MovieApp | Apache License 2.0 |
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/api/stubs/ExecutionContextManagerStub.kt | JetBrains | 1,459,486 | false | null | /*
* Copyright 2003-2023 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.api.stubs
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.ExecutionContextManager
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.diagnostic.vimLogger
class ExecutionContextManagerStub : ExecutionContextManager {
init {
vimLogger<ExecutionContextManagerStub>().warn("ExecutionContextManagerStub is used. Please replace it with your own implementation of ExecutionContextManager.")
}
override fun onEditor(editor: VimEditor, prevContext: ExecutionContext?): ExecutionContext {
TODO("Not yet implemented")
}
override fun onCaret(caret: VimCaret, prevContext: ExecutionContext): ExecutionContext {
TODO("Not yet implemented")
}
override fun createCaretSpecificDataContext(context: ExecutionContext, caret: VimCaret): ExecutionContext {
TODO("Not yet implemented")
}
override fun createEditorDataContext(editor: VimEditor, context: ExecutionContext): ExecutionContext {
TODO("Not yet implemented")
}
}
| 6 | Kotlin | 679 | 7,221 | 9b56fbc3ed5d7558f37cd5c4661de4a2c6c9e001 | 1,289 | ideavim | MIT License |
FilmSearch/app/src/main/java/com/example/filmsearch/view/MainActivity.kt | skripkalisa | 442,273,516 | false | null | package com.example.filmsearch.view
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.example.filmsearch.R
import com.example.filmsearch.databinding.ActivityMainBinding
import com.example.filmsearch.data.entity.Film
import com.example.filmsearch.view.fragments.*
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//Инициализируем объект
binding = ActivityMainBinding.inflate(layoutInflater)
//Передаем его в метод
setContentView(binding.root)
navBarClicks()
//Зупускаем фрагмент при старте
supportFragmentManager
.beginTransaction()
.add(R.id.fragment_placeholder, HomeFragment())
.addToBackStack(null)
.commit()
}
fun launchDetailsFragment(film: Film) {
//Создаем "посылку"
val bundle = Bundle()
//Кладем наш фильм в "посылку"
bundle.putParcelable("film", film)
//Кладем фрагмент с деталями в перменную
val fragment = DetailsFragment()
//Прикрепляем нашу "посылку" к фрагменту
fragment.arguments = bundle
//Запускаем фрагмент
supportFragmentManager
.beginTransaction()
.replace(R.id.fragment_placeholder, fragment)
.addToBackStack(null)
.commit()
}
private fun navBarClicks() {
binding.bottomNavigation.setOnItemSelectedListener {
when (it.itemId) {
R.id.home -> {
val tag = "home"
val fragment = checkFragmentExistence(tag)
//В первом параметре, если фрагмент не найден и метод вернул null, то с помощью
//элвиса мы вызываем создание нового фрагмента
changeFragment(fragment ?: HomeFragment(), tag)
true
}
R.id.favorites -> {
val tag = "favorites"
val fragment = checkFragmentExistence(tag)
changeFragment(fragment ?: FavoritesFragment(), tag)
true
}
R.id.watch_later -> {
val tag = "watch_later"
val fragment = checkFragmentExistence(tag)
changeFragment(fragment ?: WatchLaterFragment(), tag)
true
}
R.id.selections -> {
val tag = "selections"
val fragment = checkFragmentExistence(tag)
changeFragment(fragment ?: SelectionsFragment(), tag)
true
}
R.id.settings -> {
val tag = "settings"
val fragment = checkFragmentExistence(tag)
changeFragment(fragment ?: SettingsFragment(), tag)
true
}
else -> false
}
}
}
//Ищем фрагмент по тегу, если он есть то возвращаем его, если нет, то null
private fun checkFragmentExistence(tag: String): Fragment? =
supportFragmentManager.findFragmentByTag(tag)
private fun changeFragment(fragment: Fragment, tag: String) {
supportFragmentManager
.beginTransaction()
.replace(R.id.fragment_placeholder, fragment, tag)
.addToBackStack(null)
.commit()
}
} | 0 | Kotlin | 0 | 0 | 1ce519b6d07a0c5ab37f10f5fe3b9cddf03ac964 | 3,605 | SF_Android_proc | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/ui/screens/StockBottomSheet.kt | ashrafi | 347,428,489 | 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.screens
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.db.CoStock
import com.example.androiddevchallenge.db.CoStocks
import com.example.androiddevchallenge.ui.theme.MyTheme
import com.example.androiddevchallenge.ui.theme.green
import com.example.androiddevchallenge.ui.theme.red
@Composable
fun StockBottomSheet() {
Surface() {
Column {
Text(
modifier = Modifier
.fillMaxWidth()
.paddingFromBaseline(top = 40.dp, bottom = 24.dp),
text = "Positions",
style = MaterialTheme.typography.subtitle1,
textAlign = TextAlign.Center
)
LazyColumn(modifier = Modifier.fillMaxHeight()) {
itemsIndexed(CoStocks) { index, stock ->
Divider()
StockRow(stock)
}
}
}
}
}
@Composable
fun StockRow(stock: CoStock) {
Row(
modifier = Modifier
.fillMaxWidth()
// .padding(horizontal = 16.dp)
// .paddingFromBaseline(,top = 24.dp, bottom = 16.dp)
// .height(40.dp),
.padding(horizontal = 16.dp)
.height(56.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column() {
Text(
stock.price,
modifier = Modifier.paddingFromBaseline(top = 24.dp),
style = MaterialTheme.typography.body1
)
Text(
"${stock.change}%",
modifier = Modifier.paddingFromBaseline(top = 16.dp, bottom = 16.dp),
color = if (stock.change > 0) green else red,
style = MaterialTheme.typography.body1
)
}
Spacer(Modifier.width(16.dp)) // small break
Column(modifier = Modifier.weight(1f)) {
Text(
stock.symbol,
modifier = Modifier.paddingFromBaseline(top = 24.dp),
style = MaterialTheme.typography.h3
)
Text(
stock.name,
modifier = Modifier.paddingFromBaseline(top = 16.dp, bottom = 16.dp),
style = MaterialTheme.typography.body1
)
}
Image(
modifier = Modifier
.background(color = Color.Black),
painter = painterResource(id = stock.chartImg),
contentDescription = "chart",
// contentScale = ContentScale.FillBounds
)
}
}
@Preview("Light Theme", widthDp = 360, heightDp = 640)
@Composable
fun SBSPreview() {
MyTheme {
StockBottomSheet()
}
}
@Preview("Dark Theme", widthDp = 360, heightDp = 640)
@Composable
fun SBSDarkPreview() {
MyTheme(darkTheme = true) {
StockBottomSheet()
}
}
| 0 | Kotlin | 0 | 0 | cf8b8b858cafca3ded7332773604485ed6f888c7 | 4,760 | AndDevChallengeWeTrade | Apache License 2.0 |
m3todo-data/src/commonMain/kotlin/models/Task.kt | MUKIVA | 805,780,262 | false | {"Kotlin": 6443, "Swift": 594} | package models
data class Task(
val id: Long,
val title: String
) | 0 | Kotlin | 0 | 0 | a862ef3f6b6d3b23b98efe2852de990981e0747a | 74 | m3todo | Apache License 2.0 |
app/src/main/java/xyz/teamgravity/manual_dependency_injection/presentation/viewmodel/MainViewModel.kt | raheemadamboev | 707,033,143 | false | {"Kotlin": 7560} | package xyz.teamgravity.manual_dependency_injection.presentation.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import xyz.teamgravity.manual_dependency_injection.data.repository.AuthRepository
class MainViewModel(
private val auth: AuthRepository
) : ViewModel() {
init {
viewModelScope.launch {
auth.login(
email = "2Pac",
password = "<PASSWORD>"
)
}
}
} | 0 | Kotlin | 0 | 0 | 031a90de36220d0b9bbf82293e20684d66103f49 | 516 | manual-dependency-injection | Apache License 2.0 |
app/src/main/java/com/alturino/calculator/ui/MainScreenViewModel.kt | Alturino | 814,595,409 | false | {"Kotlin": 34868} | package com.alturino.calculator.ui
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.alturino.calculator.domain.CalculatorUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import javax.inject.Inject
@HiltViewModel
class MainScreenViewModel @Inject constructor(
private val calculatorUseCase: CalculatorUseCase
) : ViewModel() {
private val _expressionStack = mutableListOf<String>()
private val _resultStack = mutableListOf<Double>()
private val _expression = MutableStateFlow("")
val expression = _expression.asStateFlow()
val result: StateFlow<Double?> = _expression
.drop(1)
.onEach { Log.d("MainScreenViewModel", "expression: $it") }
.map {
runCatching { calculatorUseCase.invoke(it) }
.getOrNull()
}
.onEach { Log.d("MainScreenViewModel", "result: $it") }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = null
)
fun onEvent(event: MainScreenEvent) {
when (event) {
is MainScreenEvent.OnButton0Clicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButton1Clicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButton2Clicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButton3Clicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButton4Clicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButton5Clicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButton6Clicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButton7Clicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButton8Clicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButton9Clicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
MainScreenEvent.OnButtonAcClicked -> {
_expressionStack.clear()
_expression.update { "" }
}
MainScreenEvent.OnButtonBackspaceClicked -> {
_expressionStack.removeLast()
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButtonDivClicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
MainScreenEvent.OnButtonEqualClicked -> {
runCatching { calculatorUseCase.invoke(expression.value) }
.onSuccess {
Log.d("MainScreenViewModel", "result: $it")
_resultStack.add(it)
}
.onFailure { Log.e("MainScreenViewModel", it.message.orEmpty()) }
}
is MainScreenEvent.OnButtonLeftParenthesesClicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButtonMinusClicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButtonPlusClicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButtonRightParenthesesClicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButtonTimesClicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
is MainScreenEvent.OnButtonDotClicked -> {
_expressionStack.add(event.value)
_expression.update { _expressionStack.joinToString("") }
}
}
Log.d(
"MainScreenViewModel",
"event: $event, _expression: $_expressionStack, _result: $_resultStack"
)
}
} | 0 | Kotlin | 0 | 0 | 242dc5dee1cc79e0a5d8b0c00bcaa3d74f896dfc | 5,705 | Calculator | Apache License 2.0 |
app/src/main/java/com/hulkrent/app/ui/host/HostFinalNavigator.kt | Hulk-Cars | 772,120,218 | false | {"Kotlin": 2511410, "Java": 358761} | package com.hulkrent.app.ui.host
import com.hulkrent.app.ui.base.BaseNavigator
interface HostFinalNavigator : BaseNavigator {
fun show404Screen()
fun showListDetails()
} | 0 | Kotlin | 0 | 0 | 9886a3455e3d404110a85cdaaf5bbff449390814 | 182 | Hulk-Rent-Android | Artistic License 1.0 w/clause 8 |
mobile_development/app/src/main/java/com/ajisaka/corak/ui/home/HomeFragment.kt | agusrachmadpurnama | 408,048,399 | true | {"Jupyter Notebook": 255421, "Kotlin": 103935, "JavaScript": 729} | package com.ajisaka.corak.ui.home
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ajisaka.corak.MainActivity
import com.ajisaka.corak.R
import com.ajisaka.corak.adapters.FavBatikHomeAdapter
import com.ajisaka.corak.application.FavBatikApplication
import com.ajisaka.corak.databinding.DialogCustomImageSelectionBinding
import com.ajisaka.corak.databinding.FragmentHomeBinding
import com.ajisaka.corak.model.entities.FavBatik
import com.ajisaka.corak.ui.detail.DetailActivity
import com.ajisaka.corak.ui.games.GamesFragment
import com.ajisaka.corak.ui.setting.SettingFragment
import com.ajisaka.corak.viewmodel.FavBatikViewModel
import com.ajisaka.corak.viewmodel.FavBatikViewModelFactory
import com.karumi.dexter.Dexter
import com.karumi.dexter.MultiplePermissionsReport
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionDeniedResponse
import com.karumi.dexter.listener.PermissionGrantedResponse
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.multi.MultiplePermissionsListener
import com.karumi.dexter.listener.single.PermissionListener
import java.io.*
import java.util.*
@Suppress("DEPRECATION", "UNREACHABLE_CODE")
class HomeFragment : Fragment() {
private lateinit var binding: FragmentHomeBinding
private val mBatikViewModel: FavBatikViewModel by viewModels {
FavBatikViewModelFactory((requireActivity().application as FavBatikApplication).repository)
}
private var mImagePath: String = ""
companion object {
private const val CAMERA = 1
private const val GALLERY = 2
private const val IMAGE_DIRECTORY = "FavBatikImages"
}
@SuppressLint("RestrictedApi")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentHomeBinding.inflate(inflater, container, false)
// Inflate the layout for this fragment
(activity as AppCompatActivity?)!!.supportActionBar!!.hide()
(activity as AppCompatActivity?)?.supportActionBar?.setShowHideAnimationEnabled(false)
binding.includeToolbar.btnSetting.setOnClickListener {
findNavController()
.navigate(HomeFragmentDirections.actionNavigationHomeToNavigationSetting())
}
binding.btnPlayGames.setOnClickListener {
findNavController()
.navigate(HomeFragmentDirections.actionNavigationHomeToNavigationGames())
}
val layoutManager: RecyclerView.LayoutManager = GridLayoutManager(activity, 2)
binding.rvList.layoutManager = layoutManager
val favBatikHomeAdapter = FavBatikHomeAdapter(this)
Log.d("Batik Home", favBatikHomeAdapter.toString())
mBatikViewModel.allBatikList.observe(viewLifecycleOwner) { batik ->
batik.let {
if (it.isNotEmpty()) {
binding.rvList.visibility = View.VISIBLE
binding.tvNoBatikAddedYet.visibility = View.GONE
favBatikHomeAdapter.batikList(batik)
binding.rvList.adapter = favBatikHomeAdapter
Log.d("BatikLIst Home", batik.toString())
} else {
binding.tvNoBatikAddedYet.visibility = View.VISIBLE
binding.rvList.visibility = View.GONE
}
}
}
// button Take Camera
binding.button.setOnClickListener{ customImageSelectionDialog() }
return binding.root
}
override fun onResume() {
super.onResume()
if (requireActivity() is MainActivity) {
(activity as MainActivity?)!!.showBottomNavigationView()
}
}
fun batikDetails(favBatik: FavBatik){
if (requireActivity() is MainActivity) {
(activity as MainActivity?)!!.hideBottomNavigationView()
}
findNavController()
.navigate(HomeFragmentDirections.actionNavigationHomeToNavigationBatikDetails(favBatik))
}
fun deleteStudent(batik: FavBatik) {
val builder = AlertDialog.Builder(requireContext())
//set title for alert dialog
builder.setTitle(resources.getString(R.string.title_delete_batik))
//set message for alert dialog
builder.setMessage(resources.getString(R.string.msg_delete_batik_dialog, batik.name))
builder.setIcon(android.R.drawable.ic_dialog_alert)
//performing positive action
builder.setPositiveButton(resources.getString(R.string.lbl_yes)) { dialogInterface, _ ->
mBatikViewModel.delete(batik)
dialogInterface.dismiss() // Dialog will be dismissed
}
//performing negative action
builder.setNegativeButton(resources.getString(R.string.lbl_no)) { dialogInterface, _ ->
dialogInterface.dismiss() // Dialog will be dismissed
}
// Create the AlertDialog
val alertDialog: AlertDialog = builder.create()
// Set other dialog properties
alertDialog.setCancelable(false) // Will not allow user to cancel after clicking on remaining screen area.
alertDialog.show() // show the dialog to UI
}
override fun onActivityResult(resultCode: Int, requestCode: Int, data: Intent?) {
super.onActivityResult(resultCode, requestCode, data)
Log.d("Image", "$resultCode $requestCode $data")
if (requestCode == Activity.RESULT_OK) {
if (resultCode == CAMERA) {
data?.extras?.let {
val thumbnail: Bitmap =
data.extras!!.get("data") as Bitmap // Bitmap from camera
mImagePath = saveImageToInternalStorage(thumbnail)
Log.d("ImagePath", mImagePath)
Log.d("Imagess",thumbnail.toString())
//Convert to byte array
// val stream = ByteArrayOutputStream()
// thumbnail.compress(Bitmap.CompressFormat.PNG, 100, stream)
// val byteArray: ByteArray = stream.toByteArray()
val sendImage = Intent(context, DetailActivity::class.java)
sendImage.putExtra("resultImage", mImagePath)
startActivity(sendImage)
}
} else if (resultCode == GALLERY) {
data?.let {
// Here we will get the select image URI.
val uri = data.data
Log.d("uriImageBeforSend", uri.toString())
// val thumbnail = MediaStore.Images.Media.getBitmap(this.contentResolver, uri)
// mImagePath = saveImageToInternalStorage(thumbnail)
// val stream = ByteArrayOutputStream()
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
// val byteArray: ByteArray = stream.toByteArray()
val sendImage = Intent(context, DetailActivity::class.java)
sendImage.putExtra("uriImage", uri.toString())
startActivity(sendImage)
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("Cancelled", "Cancelled")
}
}
private fun saveImageToInternalStorage(bitmap: Bitmap): String {
// Get the context wrapper instance
val wrapper = ContextWrapper(context)
// Initializing a new file
// The bellow line return a directory in internal storage
/**
* The Mode Private here is
* File creation mode: the default mode, where the created file can only
* be accessed by the calling application (or all applications sharing the
* same user ID).
*/
var file = wrapper.getDir(IMAGE_DIRECTORY, Context.MODE_PRIVATE)
// Mention a file name to save the image
file = File(file, "${UUID.randomUUID()}.jpg")
try {
// Get the file output stream
val stream: OutputStream = FileOutputStream(file)
// Compress bitmap
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
// Flush the stream
stream.flush()
// Close stream
stream.close()
} catch (e: IOException) { // Catch the exception
e.printStackTrace()
}
// Return the saved image absolute path
return file.absolutePath
}
private fun customImageSelectionDialog() {
val dialog = Dialog(requireContext())
val binding: DialogCustomImageSelectionBinding =
DialogCustomImageSelectionBinding.inflate(layoutInflater)
/*Set the screen content from a layout resource.
The resource will be inflated, adding all top-level views to the screen.*/
dialog.setContentView(binding.root)
binding.tvCamera.setOnClickListener {
Dexter.withContext(context)
.withPermissions(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
)
.withListener(object : MultiplePermissionsListener {
override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
report?.let {
// Here after all the permission are granted launch the CAMERA to capture an image.
if (report.areAllPermissionsGranted()) {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, CAMERA)
}
}
}
override fun onPermissionRationaleShouldBeShown(
permission: MutableList<PermissionRequest>?,
token: PermissionToken?
) {
showRationalDialogForPermissions()
}
}).onSameThread()
.check()
dialog.dismiss()
}
binding.tvGallery.setOnClickListener {
Dexter.withContext(context)
.withPermission(
Manifest.permission.READ_EXTERNAL_STORAGE
)
.withListener(object : PermissionListener {
override fun onPermissionGranted(response: PermissionGrantedResponse?) {
// Here after all the permission are granted launch the gallery to select and image.
val galleryIntent = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
startActivityForResult(galleryIntent, GALLERY)
}
override fun onPermissionDenied(response: PermissionDeniedResponse?) {
Toast.makeText(
context,
"You have denied the storage permission to select image.",
Toast.LENGTH_SHORT
).show()
}
override fun onPermissionRationaleShouldBeShown(
permission: PermissionRequest?,
token: PermissionToken?
) {
showRationalDialogForPermissions()
}
}).onSameThread()
.check()
dialog.dismiss()
}
//Start the dialog and display it on screen.
dialog.show()
}
private fun showRationalDialogForPermissions() {
AlertDialog.Builder(requireContext())
.setMessage("It Looks like you have turned off permissions required for this feature. It can be enabled under Application Settings")
.setPositiveButton(
"GO TO SETTINGS"
) { _, _ ->
try {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.fromParts("package", context?.packageName, null)
intent.data = uri
startActivity(intent)
} catch (e: ActivityNotFoundException) {
e.printStackTrace()
}
}
.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss()
}.show()
}
} | 0 | null | 0 | 0 | f0bbac80939c05705ed65c8c0fb4c9b5e81c3aaa | 13,447 | corak | Creative Commons Zero v1.0 Universal |
app/src/main/java/org/fnives/library/reloadable/module/hilt/ExampleApplication.kt | fknives | 391,189,260 | false | null | package org.fnives.library.reloadable.module.hilt
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class ExampleApplication : Application() | 6 | Kotlin | 0 | 0 | cd4994ae4a200b2bfd481c130bdd302d26889d2f | 181 | ReloadableHiltModule | Apache License 2.0 |
feature/home/src/main/java/soup/movie/home/di/HomeFragmentModule.kt | ashishkharcheiuforks | 246,956,919 | true | {"Kotlin": 383771, "Shell": 1169} | package soup.movie.home.di
import dagger.Module
import dagger.android.ContributesAndroidInjector
import soup.movie.home.favorite.HomeFavoriteFragment
import soup.movie.home.now.HomeNowFragment
import soup.movie.home.plan.HomePlanFragment
@Module
interface HomeFragmentModule {
@ContributesAndroidInjector
fun bindHomeNowFragment(): HomeNowFragment
@ContributesAndroidInjector
fun bindHomePlanFragment(): HomePlanFragment
@ContributesAndroidInjector
fun bindHomeFavoriteFragment(): HomeFavoriteFragment
}
| 0 | null | 0 | 0 | a7c6d9b372913241523cd36fdf04d1863ced9969 | 533 | Moop-Android | Apache License 2.0 |
src/main/kotlin/pl/edu/pk/hms/users/authentiation/AuthenticationService.kt | RaspberryCode | 711,198,092 | false | {"Kotlin": 77847} | package pl.edu.pk.hms.users.authentiation
import org.springframework.context.ApplicationEventPublisher
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import pl.edu.pk.hms.config.JwtService
import pl.edu.pk.hms.notifications.handlers.events.UserRegistered
import pl.edu.pk.hms.users.Role
import pl.edu.pk.hms.users.User
import pl.edu.pk.hms.users.authentiation.api.dto.AuthenticationRequest
import pl.edu.pk.hms.users.authentiation.dao.UserRepository
import pl.edu.pk.hms.users.details.dao.UserPreferences
import pl.edu.pk.hms.users.details.dao.UserProfile
const val NO_USER: String = "No user"
@Service
class AuthenticationService(
private val jwtService: JwtService,
private val userRepository: UserRepository,
private val authenticationManager: AuthenticationManager,
private val passwordEncoder: PasswordEncoder,
private val eventPublisher: ApplicationEventPublisher
) {
fun getUsername(): String {
return SecurityContextHolder.getContext().authentication.name ?: NO_USER
}
fun register(
email: String,
password: String,
phoneNumber: String?,
userPreferences: UserPreferences?
): String {
require(!userRepository.existsByProfile_Email(email)) {
throw IllegalArgumentException("Email address already assigned to account.")
}
val user = User(
encryptedPassword = passwordEncoder.encode(password),
role = Role.USER,
profile = null
)
val userProfile = UserProfile(
email = email,
phoneNumber = phoneNumber,
preferences = userPreferences ?: UserPreferences(),
user = user,
districts = emptySet()
)
user.profile = userProfile
val savedUser = userRepository.save(user)
eventPublisher.publishEvent(UserRegistered(this, savedUser.id!!))
return jwtService.generate(savedUser)
}
fun login(request: AuthenticationRequest): String {
authenticationManager.authenticate(
UsernamePasswordAuthenticationToken(
request.email,
request.password
)
)
val user = userRepository.findUserByProfile_Email(request.email)
.orElseThrow { IllegalArgumentException("Invalid email or password.") }
return jwtService.generate(user)
}
} | 0 | Kotlin | 0 | 1 | 585ab01e0ad8f10f0898aaba1a5824a4c3c42474 | 2,685 | hms | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.