path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/solutions/Day20GrovePositioningSystem.kt
aormsby
571,002,889
false
null
package solutions import utils.Input import utils.Solution // run only this day fun main() { Day20GrovePositioningSystem() } class Day20GrovePositioningSystem : Solution() { init { begin("Day 20 - Grove Positioning System") val input = Input.parseLines(filename = "/d20_encrypted_file.txt") .mapIndexed { i, n -> Pair(i, n.toLong()) } val sol1 = findGroveCoordinateSum(input) output("Sum of Grove Coordinates", sol1) val sol2 = findGroveCoordinateSum(input.map { Pair(it.first, it.second * 811_589_153) }, cycles = 10) output("Sum of Decrypted Grove Coordinates", sol2) } private fun findGroveCoordinateSum(input: List<Pair<Int, Long>>, cycles: Int = 1): Long { val switchList = input.toMutableList() val size = switchList.size for( c in 0 until cycles) { input.forEachIndexed { i, pair -> val oldI = switchList.indexOf(switchList.find { it.first == i }) var newI = (oldI + pair.second) % (size - 1) if (newI <= 0) { newI += size - 1 } switchList.removeAt(oldI) switchList.add(newI.toInt(), pair) } } val z = switchList.indexOf(switchList.find { it.second == 0L }) val a = switchList[(z + 1000) % size].second val b = switchList[(z + 2000) % size].second val c = switchList[(z + 3000) % size].second return a + b + c } }
0
Kotlin
0
0
1bef4812a65396c5768f12c442d73160c9cfa189
1,524
advent-of-code-2022
MIT License
container/src/main/kotlin/com/oneliang/ktx/frame/container/Container.kt
oneliang
262,052,605
false
{"Kotlin": 1458038, "Java": 255657, "C": 27979, "HTML": 3956}
package com.oneliang.ktx.frame.container interface Container { /** * start */ fun start() /** * stop */ fun stop() /** * restart, default stop first, start second */ fun restart() }
0
Kotlin
1
0
4063c05920b4906ebe2dc2cf78a0c5a076a7314a
239
frame-kotlin
Apache License 2.0
app/src/main/java/com/example/giphytestapp/navigation/NavGraph.kt
lusicom
611,414,117
false
null
package com.example.giphytestapp.navigation import android.content.Context import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import com.example.giphytestapp.ui.SharedViewModel import com.example.giphytestapp.ui.screens.master.MasterScreen @OptIn(ExperimentalFoundationApi::class) @Composable fun SetupNavGraph( context: Context, sharedViewModel: SharedViewModel, navController: NavHostController ){ NavHost( navController = navController, startDestination = Screen.Home.route){ composable( route = Screen.Home.route ) { MasterScreen(context = context, sharedViewModel = sharedViewModel, navController) } composable( route = Screen.Details.route ) { } } }
0
Kotlin
0
1
c4dec936964ca884ca9aa99c90c0a79fa1e9c6ae
964
GiphyApp
Apache License 2.0
omisego-core/src/test/kotlin/co/omisego/omisego/utils/OMGEncryptionTest.kt
omgnetwork
116,833,092
false
null
package co.omisego.omisego.utils /* * OmiseGO * * Created by <NAME> on 31/7/2018 AD. * Copyright © 2017-2018 OmiseGO. All rights reserved. */ import co.omisego.omisego.constant.enums.AuthScheme import co.omisego.omisego.constant.enums.AuthScheme.ADMIN import co.omisego.omisego.constant.enums.AuthScheme.Client import co.omisego.omisego.model.CredentialConfiguration import org.amshove.kluent.shouldEqualTo import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [23]) class OMGEncryptionTest { data class TestCredentialConfiguration( override val baseURL: String, override val authenticationToken: String, override val userId: String?, override val apiKey: String?, override val authScheme: AuthScheme ) : CredentialConfiguration private val clientConfiguration: TestCredentialConfiguration by lazy { TestCredentialConfiguration( "http://test.com/", "authenticationToken", null, "apiKey", Client ) } private val adminConfiguration: TestCredentialConfiguration by lazy { TestCredentialConfiguration( "http://test.com/", "authenticationToken", "userId", null, ADMIN ) } private val nullAPIKeyClientConfiguration: TestCredentialConfiguration by lazy { TestCredentialConfiguration( "http://test.com/", "authenticationToken", null, null, Client ) } private val emptyUserIdConfiguration: TestCredentialConfiguration by lazy { TestCredentialConfiguration( "http://test.com/", "authenticationToken", "", null, ADMIN ) } private val omgEncryption by lazy { OMGEncryption() } @Test fun `createAuthorizationHeader should return base64 of the apiKey and authenticationToken correctly`() { omgEncryption.createAuthorizationHeader(clientConfiguration) shouldEqualTo "<KEY> } @Test fun `createAuthorizationHeader should return base64 of the userId and authenticationToken correctly`() { omgEncryption.createAuthorizationHeader(adminConfiguration) shouldEqualTo "<KEY> } @Test fun `createAuthorizationHeader should return empty string if authScheme is OMGClient and apiKey is nullOrEmpty`() { omgEncryption.createAuthorizationHeader(nullAPIKeyClientConfiguration) shouldEqualTo "" omgEncryption.createAuthorizationHeader(nullAPIKeyClientConfiguration.copy(apiKey = "")) shouldEqualTo "" } @Test fun `createAuthorizationHeader should return empty string if authScheme is OMGAdmin and userId is nullOrEmpty`() { omgEncryption.createAuthorizationHeader(emptyUserIdConfiguration) shouldEqualTo "" omgEncryption.createAuthorizationHeader(emptyUserIdConfiguration.copy(userId = null)) shouldEqualTo "" } }
0
Kotlin
8
18
de12e344d6437b9c23df35d158fb247bac6c8055
3,124
android-sdk
Apache License 2.0
Camera/src/main/java/com/mx/camera/media/RecordUtil.kt
zhangmengxiong
234,220,945
false
null
package com.mx.camera.media import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import android.hardware.Camera import android.hardware.Camera.CameraInfo import android.media.MediaRecorder import android.os.Handler import android.view.SurfaceHolder import com.mx.camera.Log import com.mx.camera.config.CameraConfig import com.mx.camera.sensor.RotationWatch import java.io.File import kotlin.concurrent.thread import kotlin.math.abs import kotlin.math.max import kotlin.math.min class RecordUtil(private val mxSurfaceView: MXSurfaceView, private val rotationWatch: RotationWatch) { private val mHandler = Handler() private lateinit var cameraConfig: CameraConfig private var cameraIndex = CAMERA_BACK private var mCamera: Camera? = null private var mMediaRecorder: MediaRecorder? = null private var previewWidth: Int = 0 private var previewHeight: Int = 0 private var displayOrientation: Int = 0 private var isCameraLocked = true fun setConfig(config: CameraConfig) { cameraConfig = config } fun switchCamera() { cameraIndex = if (cameraIndex == CAMERA_FRONT) CAMERA_BACK else CAMERA_FRONT curState = STATE_INIT startPreview() } private fun createCamera(holder: SurfaceHolder?): Camera { val camera = Camera.open(cameraIndex) val info = CameraInfo() Camera.getCameraInfo(cameraIndex, info) displayOrientation = rotationWatch.calculateCameraPreviewOrientation(cameraIndex == CAMERA_FRONT, info.orientation) camera.setDisplayOrientation(displayOrientation) camera.setPreviewDisplay(holder) val params = camera.parameters //注意此处需要根据摄像头获取最优像素,//如果不设置会按照系统默认配置最低160x120分辨率 val bestWidth = max(cameraConfig.expectWidth, cameraConfig.expectHeight) val bestHeight = min(cameraConfig.expectWidth, cameraConfig.expectHeight) val previewSize = SizeBiz.getPreviewSize(camera, bestWidth, bestHeight) val pictureSize = SizeBiz.getPictureSize(camera, bestWidth, bestHeight) val previewFps = SizeBiz.chooseFixedPreviewFps(camera, cameraConfig.expectPreviewFps) params.apply { previewWidth = previewSize.width previewHeight = previewSize.height setPreviewSize(previewSize.width, previewSize.height) setPictureSize(pictureSize.width, pictureSize.height) previewFps?.let { Log("setPreviewFpsRange ${it.first}~${it.second}") setPreviewFpsRange(it.first, it.second) } jpegQuality = cameraConfig.jpegQuality pictureFormat = cameraConfig.pictureFormat try { if (supportedFocusModes?.contains(cameraConfig.focusMode) == true) { focusMode = cameraConfig.focusMode //对焦模式 } } catch (e: java.lang.Exception) { } } camera.parameters = params return camera } private var maxDurationLength: Int = -1 fun setMaxDuration(duration: Int) { maxDurationLength = duration } @Synchronized fun startPreview() { if (curState == STATE_PREVIEW) return try { mCamera?.apply { if (!isCameraLocked) { lock() } isCameraLocked = true stopPreview() setPreviewCallback(null) release() } mCamera = null } catch (e: Exception) { e.printStackTrace() } try { setState(STATE_INIT) mxSurfaceView.addSurfaceChange { val camera = createCamera(it) mCamera = camera camera.startPreview() camera.setErrorCallback { error, _ -> Log("setErrorCallback $error") } camera.setFaceDetectionListener { faces, _ -> Log("FaceDetectionListener") } isCameraLocked = true setState(STATE_PREVIEW) recordCall?.onStartPreview() } } catch (e: Exception) { e.printStackTrace() mCamera?.apply { try { if (!isCameraLocked) { lock() } isCameraLocked = true } catch (e: Exception) { } try { stopPreview() setPreviewCallback(null) release() } catch (e: Exception) { } mCamera = null } setState(STATE_ERROR) } } private var recordStartTime: Long = 0 fun startRecord() { try { if (curState != STATE_PREVIEW) { startPreview() } val camera = mCamera ?: throw Exception("启动摄像头失败!") if (isCameraLocked) { camera.unlock() } isCameraLocked = false mMediaRecorder = MediaRecorder().apply { reset() setOnErrorListener { mr, what, extra -> Log("MediaRecorder onError $what $extra") } setOnInfoListener { mr, what, extra -> if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) { Log("OnInfoListener onError $what $extra") stopRecord() } } setCamera(camera) // 设置音频源与视频源 这两项需要放在setOutputFormat之前 setAudioSource(cameraConfig.audioSource) setVideoSource(cameraConfig.videoSource) //设置输出格式 setOutputFormat(cameraConfig.videoOutputFormat) //这两项需要放在setOutputFormat之后 IOS必须使用ACC setAudioEncoder(cameraConfig.audioEncoder) //音频编码格式 //使用MPEG_4_SP格式在华为P20 pro上停止录制时会出现 //MediaRecorder: stop failed: -1007 //java.lang.RuntimeException: stop failed. // at android.media.MediaRecorder.stop(Native Method) setVideoEncoder(cameraConfig.videoEncoder) //视频编码格式 if (maxDurationLength > 0) { setMaxDuration(maxDurationLength * 1000) } if (cameraIndex == CAMERA_FRONT) { setOrientationHint(270) } else { setOrientationHint(90) } //设置记录会话的最大持续时间(毫秒) if (cameraConfig.maxDuration > 1000) { setMaxDuration(cameraConfig.maxDuration) } setOutputFile(cameraConfig.outputFile) //设置最终出片分辨率 setVideoSize(previewWidth, previewHeight) setVideoFrameRate(cameraConfig.videoFrameRate) setVideoEncodingBitRate(cameraConfig.videoEncodingBitRate) prepare() start() } recordStartTime = System.currentTimeMillis() setState(STATE_RECORDING) recordCall?.onStartRecord() mHandler.removeCallbacksAndMessages(null) mHandler.post(ticketRun) } catch (e: Exception) { e.printStackTrace() recordCall?.onError(e.message) } } private val ticketRun: Runnable by lazy { object : Runnable { override fun run() { if (curState != STATE_RECORDING) return try { val time = abs(recordStartTime - System.currentTimeMillis()) recordCall?.onRecordTimeTicket(time) } catch (e: Exception) { e.printStackTrace() } finally { mHandler.postDelayed(ticketRun, 300) } } } } private var curState = STATE_INIT private fun setState(state: Int) { curState = state } fun stopRecord() { if (curState != STATE_RECORDING) return val time = abs(recordStartTime - System.currentTimeMillis()) try { mMediaRecorder?.apply { stop() reset() release() mMediaRecorder = null } mCamera?.apply { if (!isCameraLocked) { lock() } isCameraLocked = true stopPreview() setPreviewCallback(null) release() mCamera = null } setState(STATE_INIT) mHandler.removeCallbacksAndMessages(null) recordCall?.onStopRecord(time) } catch (e: Exception) { e.printStackTrace() if (time < 2000) { recordCall?.onError("录制时间过短!") } else { recordCall?.onError(e.message ?: "录制错误!") } setState(STATE_ERROR) } } fun requestFocus() { if (curState != STATE_PREVIEW) return try { mCamera?.autoFocus { success, camera -> } } catch (e: java.lang.Exception) { } } fun takePicture() { if (curState == STATE_TAKE_PICTURE) return try { mMediaRecorder?.apply { reset() release() mMediaRecorder = null } startPreview() setState(STATE_TAKE_PICTURE) val camera = mCamera ?: throw Exception("启动摄像头失败!") camera.takePicture(null, null, Camera.PictureCallback { data, _ -> Log("takePicture ${data.size}") mCamera?.apply { lock() stopPreview() release() mCamera = null } setState(STATE_INIT) if (data == null) { recordCall?.onError("拍照失败!") return@PictureCallback } thread { try { val matrix = Matrix() val file = File(cameraConfig.outputFile) val rotation = (displayOrientation + rotationWatch.currentRotation()) % 360 if (cameraIndex == CAMERA_FRONT) { matrix.setRotate(((360 - rotation) % 360).toFloat()) matrix.postScale(-1f, 1f) } else { matrix.setRotate(rotation.toFloat()) } var bitmap = BitmapFactory.decodeByteArray(data, 0, data.size) bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true); BitmapBiz.saveBitmap(file, bitmap) mHandler.post { recordCall?.onTakePicture(file) } } catch (e: java.lang.Exception) { e.printStackTrace() } } }) setState(STATE_INIT) } catch (e: java.lang.Exception) { setState(STATE_ERROR) e.printStackTrace() recordCall?.onError(e.message ?: "拍照失败!") } } var recordCall: IRecordCall? = null fun setOnRecordCall(call: IRecordCall) { recordCall = call } fun release() { setState(STATE_INIT) try { mMediaRecorder?.apply { stop() reset() release() mMediaRecorder = null } } catch (e: Exception) { e.printStackTrace() } try { mCamera?.apply { if (!isCameraLocked) { lock() } isCameraLocked = true stopPreview() setPreviewCallback(null) release() mCamera = null } } catch (e: Exception) { e.printStackTrace() } mHandler.removeCallbacksAndMessages(null) } companion object { const val STATE_INIT = 0 const val STATE_PREVIEW = 1 const val STATE_RECORDING = 2 const val STATE_TAKE_PICTURE = 3 const val STATE_ERROR = 4 const val CAMERA_BACK = Camera.CameraInfo.CAMERA_FACING_BACK const val CAMERA_FRONT = Camera.CameraInfo.CAMERA_FACING_FRONT } }
0
Kotlin
0
0
61f26e2bc48fbbd25a24b210e4b8362ea7a9151f
12,778
MXCamera
Apache License 2.0
src/main/kotlin/pl/wendigo/chrome/api/accessibility/Operations.kt
zawodskoj
278,649,959
true
{"Kotlin": 1040926, "Go": 11831, "HTML": 7717, "Groovy": 1976, "Shell": 1808}
package pl.wendigo.chrome.api.accessibility /** * AccessibilityOperations represents Accessibility protocol domain request/response operations and events that can be captured. * * This API is marked as experimental in protocol definition and can change in the future. * @link Protocol [Accessibility](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility) domain documentation. */ @pl.wendigo.chrome.protocol.Experimental class AccessibilityOperations internal constructor(private val connection: pl.wendigo.chrome.protocol.ChromeDebuggerConnection) { /** * Disables the accessibility domain. * * @link Protocol [Accessibility#disable](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-disable) method documentation. */ fun disable() = connection.request("Accessibility.disable", null, pl.wendigo.chrome.protocol.ResponseFrame::class.java) /** * Enables the accessibility domain which causes `AXNodeId`s to remain consistent between method calls. This turns on accessibility for the page, which can impact performance until accessibility is disabled. * * @link Protocol [Accessibility#enable](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-enable) method documentation. */ fun enable() = connection.request("Accessibility.enable", null, pl.wendigo.chrome.protocol.ResponseFrame::class.java) /** * Fetches the accessibility node and partial accessibility tree for this DOM node, if it exists. * * @link Protocol [Accessibility#getPartialAXTree](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getPartialAXTree) method documentation. */ @pl.wendigo.chrome.protocol.Experimental fun getPartialAXTree(input: GetPartialAXTreeRequest) = connection.request("Accessibility.getPartialAXTree", input, GetPartialAXTreeResponse::class.java) /** * Fetches the entire accessibility tree * * @link Protocol [Accessibility#getFullAXTree](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getFullAXTree) method documentation. */ @pl.wendigo.chrome.protocol.Experimental fun getFullAXTree() = connection.request("Accessibility.getFullAXTree", null, GetFullAXTreeResponse::class.java) /** * Returns flowable capturing all Accessibility domains events. */ fun events(): io.reactivex.Flowable<pl.wendigo.chrome.protocol.Event> { return connection.allEvents().filter { it.protocolDomain() == "Accessibility" } } } /** * Represents request frame that can be used with [Accessibility#getPartialAXTree](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getPartialAXTree) operation call. * * Fetches the accessibility node and partial accessibility tree for this DOM node, if it exists. * @link [Accessibility#getPartialAXTree](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getPartialAXTree) method documentation. * @see [AccessibilityOperations.getPartialAXTree] */ data class GetPartialAXTreeRequest( /** * Identifier of the node to get the partial accessibility tree for. */ val nodeId: pl.wendigo.chrome.api.dom.NodeId? = null, /** * Identifier of the backend node to get the partial accessibility tree for. */ val backendNodeId: pl.wendigo.chrome.api.dom.BackendNodeId? = null, /** * JavaScript object id of the node wrapper to get the partial accessibility tree for. */ val objectId: pl.wendigo.chrome.api.runtime.RemoteObjectId? = null, /** * Whether to fetch this nodes ancestors, siblings and children. Defaults to true. */ val fetchRelatives: Boolean? = null ) /** * Represents response frame that is returned from [Accessibility#getPartialAXTree](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getPartialAXTree) operation call. * Fetches the accessibility node and partial accessibility tree for this DOM node, if it exists. * * @link [Accessibility#getPartialAXTree](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getPartialAXTree) method documentation. * @see [AccessibilityOperations.getPartialAXTree] */ data class GetPartialAXTreeResponse( /** * The `Accessibility.AXNode` for this DOM node, if it exists, plus its ancestors, siblings and children, if requested. */ val nodes: List<AXNode> ) /** * Represents response frame that is returned from [Accessibility#getFullAXTree](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getFullAXTree) operation call. * Fetches the entire accessibility tree * * @link [Accessibility#getFullAXTree](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getFullAXTree) method documentation. * @see [AccessibilityOperations.getFullAXTree] */ data class GetFullAXTreeResponse( /** * */ val nodes: List<AXNode> )
0
Kotlin
0
0
c7be8fcc1426229a26427466e3fc228e11b538aa
5,072
chrome-reactive-kotlin
Apache License 2.0
app/src/main/java/ru/maxim/unsplash/persistence/mapper/PhotoEntityMapper.kt
maximborodkin
406,747,572
false
{"Kotlin": 242939}
package ru.maxim.unsplash.persistence.mapper import kotlinx.coroutines.flow.first import ru.maxim.unsplash.domain.DomainMapper import ru.maxim.unsplash.domain.model.* import ru.maxim.unsplash.persistence.dao.TagDao import ru.maxim.unsplash.persistence.dao.UserDao import ru.maxim.unsplash.persistence.model.* import timber.log.Timber class PhotoEntityMapper( private val tagDao: TagDao, private val userDao: UserDao, private val locationEntityMapper: DomainMapper<LocationEntity, Location>, private val exifEntityMapper: DomainMapper<ExifEntity, Exif>, private val tagEntityMapper: DomainMapper<TagEntity, Tag>, private val userEntityMapper: DomainMapper<UserEntity, User>, private val urlsEntityMapper: DomainMapper<UrlsEntity, Urls>, private val linksEntityMapper: DomainMapper<LinksEntity, Links>, ) : DomainMapper<PhotoEntity, Photo> { @Throws(IllegalStateException::class) override suspend fun toDomainModel(model: PhotoEntity): Photo { val tags = tagEntityMapper.toDomainModelList(tagDao.getByPhotoId(model.id)) val user = userDao.getByUsername(model.userUsername).first()?.let { userEntity -> userEntityMapper.toDomainModel(userEntity) } ?: run { val exception = IllegalStateException( "User with username ${model.userUsername} for photo ${model.id} not found" ) Timber.w(exception) throw exception } return Photo( id = model.id, createdAt = model.createdAt, updatedAt = model.updatedAt, width = model.width, height = model.height, color = model.color, blurHash = model.blurHash, likes = model.likes, likedByUser = model.likedByUser, description = model.description, exif = model.exif?.let { exifEntity -> exifEntityMapper.toDomainModel(exifEntity) }, location = model.location?.let { locationEntity -> locationEntityMapper.toDomainModel(locationEntity) }, tags = tags, user = user, urls = urlsEntityMapper.toDomainModel(model.urls), links = linksEntityMapper.toDomainModel(model.links) ) } override suspend fun fromDomainModel(domainModel: Photo, vararg params: String): PhotoEntity { userDao.insertOrUpdate(userEntityMapper.fromDomainModel(domainModel.user)) return PhotoEntity( id = domainModel.id, createdAt = domainModel.createdAt, updatedAt = domainModel.updatedAt, width = domainModel.width, height = domainModel.height, color = domainModel.color, blurHash = domainModel.blurHash, likes = domainModel.likes, likedByUser = domainModel.likedByUser, description = domainModel.description, userUsername = domainModel.user.username, location = domainModel.location?.let { locationEntityMapper.fromDomainModel(it) }, exif = domainModel.exif?.let { exifEntityMapper.fromDomainModel(it) }, urls = urlsEntityMapper.fromDomainModel(domainModel.urls), links = linksEntityMapper.fromDomainModel(domainModel.links), System.currentTimeMillis() ) } }
0
Kotlin
0
2
06a7d3fb24badae12d42d1a6c45666434ec34d73
3,368
kts-android-unsplash
MIT License
src/main/java/miyucomics/hexical/casting/patterns/getters/types/OpGetItemTypeData.kt
miyucomics
757,094,041
false
{"Kotlin": 312812, "Java": 29755, "GLSL": 1353}
package miyucomics.hexical.casting.patterns.getters.types import at.petrak.hexcasting.api.spell.ConstMediaAction import at.petrak.hexcasting.api.spell.asActionResult import at.petrak.hexcasting.api.spell.casting.CastingContext import at.petrak.hexcasting.api.spell.iota.Iota import at.petrak.hexcasting.api.spell.mishaps.MishapInvalidIota import miyucomics.hexical.casting.iota.getIdentifier import net.minecraft.util.registry.Registry class OpGetItemTypeData(private val mode: Int) : ConstMediaAction { override val argc = 1 override fun execute(args: List<Iota>, ctx: CastingContext): List<Iota> { val id = args.getIdentifier(0, argc) if (!Registry.ITEM.containsId(id)) throw MishapInvalidIota.of(args[0], 0, "item_id") val item = Registry.ITEM.get(id) return when (mode) { 0 -> item.maxCount.asActionResult 1 -> item.maxDamage.asActionResult 2 -> item.isFood.asActionResult else -> throw IllegalStateException() } } }
0
Kotlin
1
1
8acff912fc3e4ccc1503576ab8a16fdfc3261184
950
hexical
MIT License
src/test/kotlin/org/andcoe/adf/core/AdbMonitorTest.kt
andcoe
157,694,100
false
null
package org.andcoe.adf.core import io.mockk.* import org.andcoe.adf.devices.Device import org.andcoe.adf.devices.DeviceId import org.andcoe.adf.devices.DevicesService import org.junit.Test import org.andcoe.adf.core.AdbOutput.* import org.andcoe.adf.core.AdbOutput.Companion.ADB_PIXEL import org.andcoe.adf.core.AdbOutput.Companion.ADB_SAMSUNG import org.andcoe.adf.core.AdbOutput.Companion.DEVICE_PIXEL import org.andcoe.adf.core.AdbOutput.Companion.DEVICE_SAMSUNG class AdbMonitorTest { private val commandRunner: CommandRunner = mockk() private val devicesService: DevicesService = mockk() private val adbMonitor = AdbMonitor( devicesService = devicesService, adb = Adb(commandRunner) ) @Test fun restartsAdbAndRunsCommands() { commandRunner.mockRestartAdb() adbMonitor.restartAdb() commandRunner.verifyRestartAdb() } @Test fun handlesNoDevices() { every { devicesService.devices() } returns emptyMap() adbMonitor.refreshDevicesWith(listOf()) verify { devicesService.devices() } } @Test fun handlesNewDeviceConnected() { commandRunner.mockAdbCommandsForDevice( deviceId = DEVICE_PIXEL.deviceId, tcpIpPort = 7777, adbModelResponse = ADB_DEVICE_MODEL_PIXEL, adbManufacturerResponse = ADB_DEVICE_MANUFACTURER_GOOGLE, adbAndroidVersionResponse = ADB_ANDROID_VERSION_PIXEL, adbApiLevelResponse = ADB_API_LEVEL_PIXEL ) every { devicesService.devices() } returns emptyMap() every { devicesService.create(ADB_PIXEL) } returns DEVICE_PIXEL adbMonitor.refreshDevicesWith(listOf(DEVICE_PIXEL.deviceId)) verify { devicesService.devices() } verify(exactly = 1) { devicesService.create(ADB_PIXEL) } commandRunner.verifyAdbCommandsForDevice(deviceId = DEVICE_PIXEL.deviceId, tcpIpPort = 7777) } @Test fun handlesMultipleNewDevicesConnected() { commandRunner.mockAdbCommandsForDevice( deviceId = DEVICE_PIXEL.deviceId, tcpIpPort = 7777, adbModelResponse = ADB_DEVICE_MODEL_PIXEL, adbManufacturerResponse = ADB_DEVICE_MANUFACTURER_GOOGLE, adbAndroidVersionResponse = ADB_ANDROID_VERSION_PIXEL, adbApiLevelResponse = ADB_API_LEVEL_PIXEL ) commandRunner.mockAdbCommandsForDevice( deviceId = DEVICE_SAMSUNG.deviceId, tcpIpPort = 7778, adbModelResponse = ADB_DEVICE_MODEL_S9, adbManufacturerResponse = ADB_DEVICE_MANUFACTURER_SAMSUNG, adbAndroidVersionResponse = ADB_ANDROID_VERSION_S9, adbApiLevelResponse = ADB_API_LEVEL_S9 ) every { devicesService.devices() } returns emptyMap() every { devicesService.create(ADB_PIXEL) } returns DEVICE_PIXEL every { devicesService.create(ADB_SAMSUNG) } returns DEVICE_SAMSUNG adbMonitor.refreshDevicesWith(listOf(DEVICE_PIXEL.deviceId, DEVICE_SAMSUNG.deviceId)) verify { devicesService.devices() } verify(exactly = 1) { devicesService.create(ADB_PIXEL) } verify(exactly = 1) { devicesService.create(ADB_SAMSUNG) } commandRunner.verifyAdbCommandsForDevice(deviceId = DEVICE_PIXEL.deviceId, tcpIpPort = 7777) commandRunner.verifyAdbCommandsForDevice(deviceId = DEVICE_SAMSUNG.deviceId, tcpIpPort = 7778) } @Test fun handlesDeviceRemoved() { every { devicesService.devices() } returns mapOf( DEVICE_PIXEL.deviceId to Device( DEVICE_PIXEL.deviceId, DEVICE_PIXEL.model, DEVICE_PIXEL.manufacturer, DEVICE_PIXEL.androidVersion, DEVICE_PIXEL.apiLevel, DEVICE_PIXEL.port ) ) every { devicesService.delete(DEVICE_PIXEL.deviceId) } just Runs adbMonitor.refreshDevicesWith(listOf()) verify { devicesService.devices() } verify { devicesService.delete(DEVICE_PIXEL.deviceId) } } @Test fun handlesDeviceRemovedAndKeepsExisting() { every { devicesService.devices() } returns mapOf( DEVICE_PIXEL.deviceId to DEVICE_PIXEL, DEVICE_SAMSUNG.deviceId to DEVICE_SAMSUNG ) every { devicesService.delete(DEVICE_PIXEL.deviceId) } just Runs adbMonitor.refreshDevicesWith(listOf(DEVICE_SAMSUNG.deviceId)) verify { devicesService.devices() } verify { devicesService.delete(DEVICE_PIXEL.deviceId) } } } fun CommandRunner.mockRestartAdb() { val commandRunner = this every { commandRunner.exec("adb kill-server") } returns ADB_KILL_SERVER.output every { commandRunner.exec("adb start-server") } returns ADB_START_SERVER.output } fun CommandRunner.verifyRestartAdb() { val commandRunner = this verify { commandRunner.exec("adb start-server") } verify { commandRunner.exec("adb kill-server") } } fun CommandRunner.mockAdbCommandsForDevice( deviceId: DeviceId, tcpIpPort: Int, adbModelResponse: AdbOutput, adbManufacturerResponse: AdbOutput, adbAndroidVersionResponse: AdbOutput, adbApiLevelResponse: AdbOutput ) { val commandRunner = this every { commandRunner.exec("adb -s ${deviceId.id} tcpip 5555") } returns ADB_TCP_IP.output every { commandRunner.exec("adb -s ${deviceId.id} wait-for-device") } returns ADB_WAIT_FOR_DEVICE.output every { commandRunner.exec("adb -s ${deviceId.id} forward tcp:$tcpIpPort tcp:5555") } returns AdbOutput.ADB_FORWARD_IP.output every { commandRunner.exec("adb -s ${deviceId.id} connect 127.0.0.1:$tcpIpPort") } returns AdbOutput.ADB_CONNECT_SUCCESS.output every { commandRunner.exec("adb -s ${deviceId.id} shell getprop ro.product.model") } returns adbModelResponse.output every { commandRunner.exec("adb -s ${deviceId.id} shell getprop ro.product.manufacturer") } returns adbManufacturerResponse.output every { commandRunner.exec("adb -s ${deviceId.id} shell getprop ro.build.version.release") } returns adbAndroidVersionResponse.output every { commandRunner.exec("adb -s ${deviceId.id} shell getprop ro.build.version.sdk") } returns adbApiLevelResponse.output } fun CommandRunner.verifyAdbCommandsForDevice(deviceId: DeviceId, tcpIpPort: Int) { val commandRunner = this verify { commandRunner.exec("adb -s ${deviceId.id} tcpip 5555") } verify { commandRunner.exec("adb -s ${deviceId.id} wait-for-device") } verify { commandRunner.exec("adb -s ${deviceId.id} forward tcp:$tcpIpPort tcp:5555") } verify { commandRunner.exec("adb -s ${deviceId.id} connect 127.0.0.1:$tcpIpPort") } verify { commandRunner.exec("adb -s ${deviceId.id} shell getprop ro.product.model") } verify { commandRunner.exec("adb -s ${deviceId.id} shell getprop ro.product.manufacturer") } verify { commandRunner.exec("adb -s ${deviceId.id} shell getprop ro.build.version.release") } verify { commandRunner.exec("adb -s ${deviceId.id} shell getprop ro.build.version.sdk") } }
0
Kotlin
0
3
700eb7a708a15977e603e0522604a79991938bbf
7,087
android-device-farm
Apache License 2.0
app/src/androidTest/java/com/aws/amazonlocation/ui/main/CheckRouteEstimatedTimeAndDistanceTest.kt
aws-geospatial
625,008,140
false
null
package com.aws.amazonlocation.ui.main import android.view.View import androidx.appcompat.widget.AppCompatTextView import androidx.recyclerview.widget.RecyclerView import androidx.test.core.app.ApplicationProvider import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.contrib.RecyclerViewActions import androidx.test.espresso.matcher.ViewMatchers.* // ktlint-disable no-wildcard-imports import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation import androidx.test.rule.ActivityTestRule import androidx.test.rule.GrantPermissionRule import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until import com.aws.amazonlocation.ACCESS_COARSE_LOCATION import com.aws.amazonlocation.ACCESS_FINE_LOCATION import com.aws.amazonlocation.AMAZON_MAP_READY import com.aws.amazonlocation.BaseTest import com.aws.amazonlocation.BuildConfig import com.aws.amazonlocation.DELAY_10000 import com.aws.amazonlocation.DELAY_15000 import com.aws.amazonlocation.DELAY_2000 import com.aws.amazonlocation.DELAY_5000 import com.aws.amazonlocation.R import com.aws.amazonlocation.TEST_FAILED import com.aws.amazonlocation.TEST_FAILED_CARD_DRIVE_GO import com.aws.amazonlocation.TEST_FAILED_DIRECTION_CARD import com.aws.amazonlocation.TEST_FAILED_DISTANCE_OR_TIME_EMPTY import com.aws.amazonlocation.TEST_FAILED_SEARCH_DIRECTION import com.aws.amazonlocation.TEST_WORD_10 import com.aws.amazonlocation.TEST_WORD_9 import com.aws.amazonlocation.di.AppModule import com.aws.amazonlocation.enableGPS import com.google.android.material.card.MaterialCardView import com.google.android.material.textfield.TextInputEditText import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import dagger.hilt.android.testing.UninstallModules import org.junit.Assert import org.junit.Rule import org.junit.Test @UninstallModules(AppModule::class) @HiltAndroidTest class CheckRouteEstimatedTimeAndDistanceTest : BaseTest() { @get:Rule var hiltRule = HiltAndroidRule(this) @get:Rule var permissionRule: GrantPermissionRule = GrantPermissionRule.grant( ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION, ) @get:Rule var mActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule(MainActivity::class.java) private val uiDevice = UiDevice.getInstance(getInstrumentation()) @Test fun showRouteEstimatedTimeAndDistanceTest() { try { enableGPS(ApplicationProvider.getApplicationContext()) uiDevice.wait(Until.hasObject(By.desc(AMAZON_MAP_READY)), DELAY_15000) Thread.sleep(DELAY_2000) val cardDirection = mActivityRule.activity.findViewById<MaterialCardView>(R.id.card_direction) if (cardDirection.visibility == View.VISIBLE) { val cardDirectionTest = onView(withId(R.id.card_direction)).check(matches(isDisplayed())) cardDirectionTest.perform(click()) uiDevice.wait( Until.hasObject(By.res("${BuildConfig.APPLICATION_ID}:id/edt_search_direction")), DELAY_5000, ) val edtSearchDirection = mActivityRule.activity.findViewById<TextInputEditText>(R.id.edt_search_direction) if (edtSearchDirection.visibility == View.VISIBLE) { onView(withId(R.id.edt_search_direction)).perform(ViewActions.typeText(TEST_WORD_9)) Thread.sleep(DELAY_2000) uiDevice.wait( Until.hasObject(By.res("${BuildConfig.APPLICATION_ID}:id/rv_search_places_suggestion_direction")), DELAY_15000, ) val rvSearchPlacesSuggestionDirection = mActivityRule.activity.findViewById<RecyclerView>(R.id.rv_search_places_suggestion_direction) rvSearchPlacesSuggestionDirection.adapter?.itemCount?.let { if (it > 0) { onView(withId(R.id.rv_search_places_suggestion_direction)).perform( RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>( 0, click(), ), ) } } onView(withId(R.id.edt_search_dest)).perform(ViewActions.typeText(TEST_WORD_10)) Thread.sleep(DELAY_2000) uiDevice.wait( Until.hasObject(By.res("${BuildConfig.APPLICATION_ID}:id/rv_search_places_suggestion_direction")), DELAY_15000, ) rvSearchPlacesSuggestionDirection.adapter?.itemCount?.let { if (it > 0) { onView(withId(R.id.rv_search_places_suggestion_direction)).perform( RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>( 0, click(), ), ) } } uiDevice.wait( Until.hasObject(By.res("${BuildConfig.APPLICATION_ID}:id/card_drive_go")), DELAY_15000, ) uiDevice.wait( Until.hasObject(By.res("${BuildConfig.APPLICATION_ID}:id/card_walk_go")), DELAY_15000, ) uiDevice.wait( Until.hasObject(By.res("${BuildConfig.APPLICATION_ID}:id/card_truck_go")), DELAY_15000, ) val cardDriveGo = mActivityRule.activity.findViewById<MaterialCardView>(R.id.card_drive_go) if (cardDriveGo.visibility == View.VISIBLE) { val tvDriveDistance = mActivityRule.activity.findViewById<AppCompatTextView>(R.id.tv_drive_distance) val tvDriveMinute = mActivityRule.activity.findViewById<AppCompatTextView>(R.id.tv_drive_minute) val tvWalkDistance = mActivityRule.activity.findViewById<AppCompatTextView>(R.id.tv_walk_distance) val tvWalkMinute = mActivityRule.activity.findViewById<AppCompatTextView>(R.id.tv_walk_minute) val tvTruckDistance = mActivityRule.activity.findViewById<AppCompatTextView>(R.id.tv_truck_distance) val tvTruckMinute = mActivityRule.activity.findViewById<AppCompatTextView>(R.id.tv_truck_minute) Assert.assertTrue( TEST_FAILED_DISTANCE_OR_TIME_EMPTY, tvDriveDistance.text.toString().isNotEmpty() && tvDriveMinute.text.toString().isNotEmpty() && tvWalkDistance.text.toString().isNotEmpty() && tvWalkMinute.text.toString().isNotEmpty() && tvTruckDistance.text.toString().isNotEmpty() && tvTruckMinute.text.toString().isNotEmpty(), ) } else { Assert.fail(TEST_FAILED_CARD_DRIVE_GO) } } else { Assert.fail(TEST_FAILED_SEARCH_DIRECTION) } } else { Assert.fail(TEST_FAILED_DIRECTION_CARD) } } catch (_: Exception) { Assert.fail(TEST_FAILED) } } }
4
Kotlin
1
0
8a31354f6b244ce55e7d50eb803625c212e690ab
8,123
amazon-location-features-demo-android
MIT No Attribution
src/main/kotlin/org/jetbrains/bio/span/coverage/NormalizedCoverageQuery.kt
JetBrains-Research
159,559,994
false
{"Kotlin": 396315}
package org.jetbrains.bio.span.coverage import org.apache.commons.math3.stat.correlation.PearsonsCorrelation import org.jetbrains.bio.dataframe.DataFrame import org.jetbrains.bio.genome.Chromosome import org.jetbrains.bio.genome.ChromosomeRange import org.jetbrains.bio.genome.GenomeQuery import org.jetbrains.bio.genome.coverage.Coverage import org.jetbrains.bio.genome.coverage.Fragment import org.jetbrains.bio.genome.query.Query import org.jetbrains.bio.genome.query.ReadsQuery import org.jetbrains.bio.span.fit.SpanConstants.SPAN_BETA_STEP import org.jetbrains.bio.span.fit.SpanConstants.SPAN_DEFAULT_BIN import org.jetbrains.bio.util.isAccessible import org.jetbrains.bio.util.reduceIds import org.jetbrains.bio.util.stemGz import org.slf4j.Logger import org.slf4j.LoggerFactory import java.nio.file.Path import kotlin.math.abs import kotlin.math.ceil import kotlin.math.max /** * A class representing a normalized coverage query. * * normCov = treatmentCov - controlCov * controlScale * beta * * beta is estimated as value between 0 and 1 minimizing absolute correlation between * normalized coverage and control coverage: * | correlation(treatmentCov - controlCov * controlScale * beta, controlCov) | * * Scaling is inspired by https://genomebiology.biomedcentral.com/articles/10.1186/gb-2008-9-9-r137 * Beta is inspired by https://www.cell.com/biophysj/fulltext/S0006-3495(17)30032-2#sec2 * * @property genomeQuery The genome query. * @property treatmentPath The path to the treatment file. * @property controlPath The path to the control file. * @property fragment The fragment. * @property unique Flag indicating whether to use unique reads. * @property binSize The bin size. * @property showLibraryInfo Flag indicating whether to show library information. */ class NormalizedCoverageQuery( val genomeQuery: GenomeQuery, val treatmentPath: Path, val controlPath: Path?, val fragment: Fragment, val unique: Boolean = true, val binSize: Int = SPAN_DEFAULT_BIN, val showLibraryInfo: Boolean = true, ) : Query<ChromosomeRange, Int> { override val id: String get() = reduceIds( listOfNotNull( treatmentPath.stemGz, controlPath?.stemGz, fragment.nullableInt, if (!unique) "keepdup" else null ).map { it.toString() } ) override val description: String get() = "Treatment: $treatmentPath, Control: $controlPath, " + "Fragment: $fragment, Keep-duplicates: ${!unique}" val treatmentReads by lazy { ReadsQuery(genomeQuery, treatmentPath, unique, fragment, showLibraryInfo = showLibraryInfo) } val controlReads by lazy { controlPath?.let { ReadsQuery(genomeQuery, it, unique, fragment, showLibraryInfo = showLibraryInfo) } } /** * Shows whether the relevant caches are present. */ fun areCachesPresent(): Boolean = treatmentReads.npzPath().isAccessible() && (controlReads?.npzPath()?.isAccessible() ?: true) /** * Cached value for treatment and control scales, see [analyzeCoverage] */ val coveragesNormalizedInfo by lazy { analyzeCoverage(genomeQuery, treatmentReads.get(), controlReads?.get(), binSize) } fun score(t: ChromosomeRange): Double { return treatmentReads.get().getBothStrandsCoverage(t).toDouble() } fun isControlAvailable(): Boolean { return controlReads != null } fun controlScore(chromosomeRange: ChromosomeRange): Double { require (controlReads != null) { "Control is not available" } return controlReads!!.get().getBothStrandsCoverage(chromosomeRange) * coveragesNormalizedInfo.controlScale } override fun apply(t: ChromosomeRange): Int { val treatmentCoverage = treatmentReads.get().getBothStrandsCoverage(t) if (controlPath == null) { return treatmentCoverage } val (controlScale, beta, _) = coveragesNormalizedInfo val controlCoverage = controlReads!!.get().getBothStrandsCoverage(t) return max(0.0, ceil(treatmentCoverage - controlCoverage * controlScale * beta)).toInt() } companion object { private val LOG: Logger = LoggerFactory.getLogger(NormalizedCoverageQuery::class.java) data class NormalizedCoverageInfo( val controlScale: Double, val beta: Double, val minCorrelation: Double ) /** * Compute coefficients to normalize coverage, see [NormalizedCoverageInfo]. * Whenever possible use [coveragesNormalizedInfo] cached value */ fun analyzeCoverage( genomeQuery: GenomeQuery, treatmentCoverage: Coverage, controlCoverage: Coverage?, binSize: Int ): NormalizedCoverageInfo { if (controlCoverage == null) { return NormalizedCoverageInfo(0.0, 0.0, 0.0) } val treatmentTotal = genomeQuery.get().sumOf { treatmentCoverage.getBothStrandsCoverage(it.chromosomeRange).toLong() } val controlTotal = genomeQuery.get().sumOf { controlCoverage.getBothStrandsCoverage(it.chromosomeRange).toLong() } // Scale control to treatment val controlScale = 1.0 * treatmentTotal / controlTotal val (beta, minCorrelation) = estimateBeta( genomeQuery, treatmentCoverage, controlCoverage, controlScale, binSize ) LOG.info( "Treatment ${"%,d".format(treatmentTotal)}, " + "control ${"%,d".format(controlTotal)} x ${"%.3f".format(controlScale)}, " + "min correlation ${"%.3f".format(minCorrelation)}, beta ${"%.3f".format(beta)}" ) return NormalizedCoverageInfo(controlScale, beta, minCorrelation) } private fun estimateBeta( genomeQuery: GenomeQuery, treatmentCoverage: Coverage, controlCoverage: Coverage, controlScale: Double, bin: Int, betaStep: Double = SPAN_BETA_STEP, ): Pair<Double, Double> { // Estimate beta corrected signal only on not empty chromosomes val chromosomeWithMaxSignal = genomeQuery.get() .maxByOrNull { treatmentCoverage.getBothStrandsCoverage(it.chromosomeRange) } ?: return 0.0 to 0.0 val binnedScaledTreatment = chromosomeWithMaxSignal.range.slice(bin).mapToDouble { treatmentCoverage.getBothStrandsCoverage(it.on(chromosomeWithMaxSignal)).toDouble() }.toArray() val binnedScaledControl = chromosomeWithMaxSignal.range.slice(bin).mapToDouble { controlCoverage.getBothStrandsCoverage(it.on(chromosomeWithMaxSignal)) * controlScale }.toArray() var b = 0.0 var minCorrelation = 1.0 var minB = 0.0 // Reuse array to reduce GC val binnedNorm = DoubleArray(binnedScaledTreatment.size) val pearsonCorrelation = PearsonsCorrelation() while (b < 1) { for (i in binnedNorm.indices) { binnedNorm[i] = binnedScaledTreatment[i] - binnedScaledControl[i] * b } val c = abs(pearsonCorrelation.correlation(binnedNorm, binnedScaledControl)) if (c <= minCorrelation) { minCorrelation = c minB = b } b += betaStep } if (minB == 0.0) { LOG.warn("Failed to estimate beta-value for control correction") } return minB to minCorrelation } } } /** * Calculates the binned coverage DataFrame for a list of normalized coverage queries. * Using clip percentile may slightly help to avoid out-of-range during model fit. */ fun List<NormalizedCoverageQuery>.binnedCoverageDataFrame( chromosome: Chromosome, binSize: Int, labels: Array<String>, ): DataFrame { var res = DataFrame() forEachIndexed { d, inputQuery -> val binnedCoverage = chromosome.range.slice(binSize).mapToInt { range -> inputQuery.apply(range.on(chromosome)) }.toArray() res = res.with(labels[d], binnedCoverage) } return res }
3
Kotlin
1
9
e80daaf0599363d74c1d96b4a2ddd9214d9b9489
8,449
span
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/Fork.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline 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.Outline.Fork: ImageVector get() { if (_fork != null) { return _fork!! } _fork = Builder(name = "Fork", 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(23.707f, 5.95f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.414f, 0.0f) lineToRelative(-5.172f, 5.171f) arcToRelative(3.074f, 3.074f, 0.0f, false, true, -3.4f, 0.568f) lineToRelative(6.982f, -6.982f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, -1.414f, -1.414f) lineTo(12.3f, 10.286f) arcToRelative(2.984f, 2.984f, 0.0f, false, true, 0.579f, -3.407f) lineTo(18.05f, 1.707f) arcTo(1.0f, 1.0f, 0.0f, false, false, 16.636f, 0.293f) lineTo(11.465f, 5.465f) arcToRelative(5.02f, 5.02f, 0.0f, false, false, -0.636f, 6.292f) lineTo(0.293f, 22.293f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.414f, 1.414f) lineTo(12.243f, 13.171f) arcToRelative(5.02f, 5.02f, 0.0f, false, false, 6.292f, -0.636f) lineToRelative(5.172f, -5.171f) arcTo(1.0f, 1.0f, 0.0f, false, false, 23.707f, 5.95f) close() } } .build() return _fork!! } private var _fork: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,287
icons
MIT License
bz/bz_xc/src/main/java/com/atmk/xc/patrolmap/v/PatrolMapActivity.kt
YangJian007
527,470,200
false
{"Kotlin": 650668, "Java": 293068}
package com.atmk.xc.patrolmap.v import android.os.Build import com.amap.api.maps.MapView import com.atmk.base.app.AppVMActivity import com.atmk.base.ui.dialog.MessageDialog import com.atmk.xc.databinding.XcActivityPatrolMapBinding import com.hjq.base.BaseDialog import com.hjq.permissions.OnPermissionCallback import com.hjq.permissions.Permission import com.hjq.permissions.XXPermissions /** * @author YJ * @date 2022-09-22 * @description */ class PatrolMapActivity : AppVMActivity<XcActivityPatrolMapBinding>() { override fun getViewBinding() = XcActivityPatrolMapBinding.inflate(layoutInflater) override fun initView() { } override fun initData() { } private val needPermissionsWithoutLocation = arrayOf( Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE, Permission.READ_PHONE_STATE ) //后台定位权限必须一组申请 com.hjq.permissions.PermissionChecker 192行 //ACCESS_BACKGROUND_LOCATION 这个权限只在版本号大于等于29(android 10)才需要申请 private val needLocationPermissions = mutableListOf( Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION ) override fun onStart() { super.onStart() //申请权限 if (Build.VERSION.SDK_INT >= 23) { checkPermissionsWithoutLocation(needPermissionsWithoutLocation) } } private fun checkPermissionsWithoutLocation(permissions: Array<String>) { XXPermissions.with(this) .permission(permissions) .request(object : OnPermissionCallback { override fun onGranted(permissions: MutableList<String>, all: Boolean) { if (all) { //假如大于28 ,就需要申请后台定位权限 if (Build.VERSION.SDK_INT > 28 && applicationContext.applicationInfo.targetSdkVersion > 28) { needLocationPermissions.add(Permission.ACCESS_BACKGROUND_LOCATION) } //判断位置权限是否已经授权 val isGranted = XXPermissions.isGranted(this@PatrolMapActivity, needLocationPermissions) if (!isGranted) { //全部申请成功后,再申请位置权限 showLocationRequestTipDialog() }else{ //已经授权,那就开始定位 } } } override fun onDenied(permissions: MutableList<String>, never: Boolean) { if (never) { showMissingPermissionDialog(permissions) } checkPermissionsWithoutLocation(permissions.toTypedArray()) } }) } /** * 申请位置权限除外 * 显示的提示信息 */ private fun showMissingPermissionDialog(permissions: MutableList<String>) { MessageDialog.Builder(this) .setTitle("提示") .setMessage("当前应用缺少必要权限,请手动设置权限。") .setConfirm("设置") .setCancel("取消") .setCancelable(false) .setListener(object : MessageDialog.OnListener { override fun onConfirm(dialog: BaseDialog?) { XXPermissions.startPermissionActivity(this@PatrolMapActivity, permissions) } override fun onCancel(dialog: BaseDialog?) { finish() } }) .show() } /** * 申请位置权限除外 * 显示的提示信息 */ private fun showLocationRequestTipDialog() { MessageDialog.Builder(this) .setTitle("提示") .setMessage("如果需要使用巡查功能,还需要授权定位权限。注意:在授权后台定位权限时,需要选择【始终允许】才可以!") .setConfirm("设置") .setCancel("取消") .setCancelable(false) .setListener(object : MessageDialog.OnListener { override fun onConfirm(dialog: BaseDialog?) { checkLocationPermission(needLocationPermissions.toTypedArray()) } override fun onCancel(dialog: BaseDialog?) { finish() } }) .show() } /** * 申请位置权限 */ private fun checkLocationPermission(permissions: Array<String>) { XXPermissions.with(this) .permission(permissions) .request(object : OnPermissionCallback { override fun onGranted(permissions: MutableList<String>, all: Boolean) { if (all) { //开始定位 } } override fun onDenied(permissions: MutableList<String>, never: Boolean) { if (never) { showMissingPermissionDialog(permissions) } checkLocationPermission(permissions.toTypedArray()) } }) } }
1
Kotlin
3
8
19e65fd5d22ebc1f5faded3d182fad25c9aa8627
4,915
AtmkArch
Apache License 2.0
src/main/kotlin/bsu/cc/schedule/Producers.kt
JordanPaoletti
167,065,523
false
null
package bsu.cc.schedule import bsu.cc.parser.getFromCellOrDefault import bsu.cc.parser.getFromCellOrThrow import org.apache.poi.ss.usermodel.Cell import org.apache.poi.ss.usermodel.Sheet import java.lang.IllegalArgumentException import java.time.DayOfWeek import java.time.LocalDate import java.time.LocalTime import java.time.format.DateTimeFormatter val CLASS_TIME_FORMATTER: DateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a") val MEETING_DATE_FORMATTER: DateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy") fun classScheduleProducer(rowMap: Map<String, Cell>): ClassSchedule { val meetingRangeSplit = getFromCellOrThrow<String>(rowMap["Meeting Time/Days"]).trim().toUpperCase().split("-") val startTimeString = meetingRangeSplit[0] val endTimeString = meetingRangeSplit[1].dropLastWhile { it != ' '}.dropLast(1) val daysString = meetingRangeSplit[1].takeLastWhile { it != ' ' } val meetingDatesString = getFromCellOrThrow<String>(rowMap["Meeting Dates"]).trim() val startDateString = meetingDatesString.takeWhile { it != '-' } val endDateString = meetingDatesString.takeLastWhile { it != '-' } val subject = getFromCellOrThrow<String>(rowMap["Subject"]) val catalogNumber = getFromCellOrThrow<Number>(rowMap["Catalog Nbr"]) val section = getFromCellOrThrow<Number>(rowMap["Class Section"]) val room = getFromCellOrDefault(rowMap["Room"], "") val instructors = stringToInstructorSet(getFromCellOrThrow(rowMap["Instructors"])) val description = getFromCellOrThrow<String>(rowMap["Descr"]) return ClassSchedule( startTime = LocalTime.parse(startTimeString, CLASS_TIME_FORMATTER), endTime = LocalTime.parse(endTimeString, CLASS_TIME_FORMATTER), meetingDays = daysString.chunked(2).map { stringToDayOfWeek(it) }.toSet(), meetingDates = DateInterval( LocalDate.parse(startDateString, MEETING_DATE_FORMATTER), LocalDate.parse(endDateString, MEETING_DATE_FORMATTER) ), subject = subject, catalogNumber = catalogNumber.toInt().toString(), section = section.toInt().toString(), room = room, instructors = instructors, description = description ) } fun classScheduleToRow(classSchedule: ClassSchedule, sheet: Sheet, rowIndex: Int, rowOffset: Int = 0) { val row = sheet.createRow(rowIndex) row.createCell(0 + rowOffset).setCellValue(classSchedule.subject) row.createCell(1 + rowOffset).setCellValue(classSchedule.catalogNumber.toDouble()) row.createCell(2 + rowOffset).setCellValue(classSchedule.description) row.createCell(3 + rowOffset).setCellValue(classSchedule.section.toDouble()) row.createCell(4 + rowOffset).setCellValue(meetingDatesToString(classSchedule.meetingDates)) row.createCell(5 + rowOffset).setCellValue(meetingTimeDaysToString(classSchedule.startTime, classSchedule.endTime, classSchedule.meetingDays)) row.createCell(6 + rowOffset).setCellValue(classSchedule.room) row.createCell(7 + rowOffset).setCellValue(classSchedule.instructors.joinToString { "${it.lastName},${it.firstName}" }) } private fun meetingDatesToString(meetingDates: DateInterval): String { return "${meetingDates.startDate.format(MEETING_DATE_FORMATTER)}-${meetingDates.endDate.format(MEETING_DATE_FORMATTER)}" } private fun meetingTimeDaysToString(startTime: LocalTime, endTime: LocalTime, meetingDays: Set<DayOfWeek>): String { return "${startTime.format(CLASS_TIME_FORMATTER)}-${endTime.format(CLASS_TIME_FORMATTER)} ${meetingDays.joinToString(""){ dayOfWeekToAbbr(it) }}" } private fun stringToInstructorSet(input: String): Set<Instructor> { val instructorStrings = input.split(", ") return instructorStrings.map{ it.trim() }.map { s -> Instructor(s.takeLastWhile { it != ',' } , s.takeWhile { it != ',' } ) }.toSet() } private fun stringToDayOfWeek(dayAbbreviation: String): DayOfWeek { return when(dayAbbreviation.toLowerCase()) { "su" -> DayOfWeek.SUNDAY "mo" -> DayOfWeek.MONDAY "tu" -> DayOfWeek.TUESDAY "we" -> DayOfWeek.WEDNESDAY "th" -> DayOfWeek.THURSDAY "fr" -> DayOfWeek.FRIDAY "sa" -> DayOfWeek.SATURDAY else -> throw IllegalArgumentException("Invalid day abbreviation") } } private fun dayOfWeekToAbbr(dayOfWeek: DayOfWeek): String { return when(dayOfWeek) { DayOfWeek.SUNDAY -> "Su" DayOfWeek.MONDAY -> "Mo" DayOfWeek.TUESDAY -> "Tu" DayOfWeek.WEDNESDAY -> "We" DayOfWeek.THURSDAY -> "Th" DayOfWeek.FRIDAY -> "Fr" DayOfWeek.SATURDAY -> "Sa" } }
4
Kotlin
1
0
0b17d34f45cb162e82c76546708dca0c739880ae
4,648
Conflict_Checker
MIT License
app/src/main/java/com/lubosoft/smsforwarder/utilities/DateUtils.kt
lbobowiec
201,331,114
false
null
package com.lubosoft.smsforwarder.utilities import android.content.Context import android.text.format.DateFormat import com.lubosoft.smsforwarder.R import com.lubosoft.smsforwarder.data.room.DayOfWeek import com.lubosoft.smsforwarder.data.room.LocalTime import com.lubosoft.smsforwarder.data.room.TimeOffRule import java.lang.IllegalArgumentException import java.util.* object DateUtils { private val daysOfWeekArray = arrayOf( DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY, DayOfWeek.SATURDAY, DayOfWeek.SUNDAY ) private val calendarToDayOfWeekMap = mapOf( Calendar.MONDAY to DayOfWeek.MONDAY, Calendar.TUESDAY to DayOfWeek.TUESDAY, Calendar.WEDNESDAY to DayOfWeek.WEDNESDAY, Calendar.THURSDAY to DayOfWeek.THURSDAY, Calendar.FRIDAY to DayOfWeek.FRIDAY, Calendar.SATURDAY to DayOfWeek.SATURDAY, Calendar.SUNDAY to DayOfWeek.SUNDAY ) private fun daysOfWeekToDayNames(context: Context, daysOfWeek: List<DayOfWeek>): List<String> { val result = mutableListOf<String>() for (day in daysOfWeek) { when (day) { DayOfWeek.MONDAY -> result.add(context.getString(R.string.monday)) DayOfWeek.TUESDAY -> result.add(context.getString(R.string.tuesday)) DayOfWeek.WEDNESDAY -> result.add(context.getString(R.string.wednesday)) DayOfWeek.THURSDAY -> result.add(context.getString(R.string.thursday)) DayOfWeek.FRIDAY -> result.add(context.getString(R.string.friday)) DayOfWeek.SATURDAY -> result.add(context.getString(R.string.saturday)) DayOfWeek.SUNDAY -> result.add(context.getString(R.string.sunday)) } } return result } fun daysOfWeekToString(context: Context, daysOfWeek: List<DayOfWeek>): String { val result = daysOfWeekToDayNames(context, daysOfWeek) return result.joinToString { it } } fun isDateWithinTimeIntervals(date: Date, timeOffRules: List<TimeOffRule>, is24Clock: Boolean = false): Boolean { for (timeOffRule in timeOffRules) { if (isWithinDateRanges(date, timeOffRule, is24Clock)) { return true } } return false } fun isWithinDateRanges(date: Date, timeOffRule: TimeOffRule, is24Clock: Boolean = false): Boolean { val startTime = timeOffRule.startTime val endTime = timeOffRule.endTime for (dayOfWeek in timeOffRule.daysOfWeek) { if (isBetween(date, dayOfWeek, startTime, endTime, is24Clock)) { return true } } return false } fun isBetween(date: Date, dayOfWeek: DayOfWeek, startTime: LocalTime, endTime: LocalTime, is24Clock: Boolean = false): Boolean { val calendar = Calendar.getInstance() calendar.time = date val day= calendar.get(Calendar.DAY_OF_WEEK); val currentDayOfWeek = calendarToDayOfWeekMap[day] ?: throw IllegalArgumentException("$day is out of range of days of week") val currentHour = if (is24Clock) calendar.get(Calendar.HOUR_OF_DAY) else calendar.get(Calendar.HOUR) val currentMinute = calendar.get(Calendar.MINUTE) if (isLessOrEqual(startTime, endTime)) { if (currentDayOfWeek == dayOfWeek && (startTime.hour < currentHour || (startTime.hour == currentHour && startTime.minute <= currentMinute)) && (currentHour < endTime.hour || (currentHour == endTime.hour && currentMinute <= endTime.minute))) { return true } } else { if ((currentDayOfWeek == dayOfWeek && (startTime.hour < currentHour || (startTime.hour == currentHour && startTime.minute <= currentMinute))) || (currentDayOfWeek == nextDayOfWeek(dayOfWeek) && (currentHour < endTime.hour || (currentHour == endTime.hour && currentMinute <= endTime.minute)))) { return true } } return false } fun isLessOrEqual(startTime: LocalTime, endTime: LocalTime, is24Clock: Boolean = false): Boolean { if (is24Clock) { return lessOrEqual(startTime, endTime) } else { return if (startTime.amPm == endTime.amPm) lessOrEqual(startTime, endTime) else (endTime.amPm == "PM") } } private fun lessOrEqual(startTime: LocalTime, endTime: LocalTime): Boolean { return (startTime.hour < endTime.hour || (startTime.hour == endTime.hour && startTime.minute <= endTime.minute)) } private fun nextDayOfWeek(dayOfWeek: DayOfWeek) = daysOfWeekArray[dayOfWeek.ordinal + 1 % 7] fun adjustTimeToDefaultLocale(context: Context, localTime: LocalTime): LocalTime { val result = localTime if (DateFormat.is24HourFormat(context)) { if (localTime.amPm.isNotEmpty()) { if (localTime.amPm == "PM") { result.hour += 12 } result.amPm = "" } } else { if (localTime.amPm.isEmpty()) { result.amPm = "AM" if (localTime.hour > 11) { result.hour -= 12 result.amPm = "PM" } } } return result } }
0
Kotlin
0
0
947975c8b1d42c15e01b2b936e47042169472195
5,454
SmsForwarder
MIT License
core/src/main/java/id/shaderboi/anilist/core/domain/use_case/anime/SearchAnimeUseCase.kt
andraantariksa
471,877,514
false
{"Kotlin": 95740}
package id.shaderboi.anilist.core.domain.use_case.anime import androidx.paging.PagingData import id.shaderboi.anilist.core.domain.model.anime.Anime import id.shaderboi.anilist.core.domain.repository.AnimeRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject class SearchAnimeUseCase @Inject constructor( val animeRepository: AnimeRepository ) { operator fun invoke(query: String): Flow<PagingData<Anime>> = animeRepository.searchAnime(query) }
0
Kotlin
0
2
b9ac622737b9eccab0918b0e952316f96ada5825
481
anilist
MIT License
runner/src/main/kotlin/com/intellij/idea/Utils.kt
schoolptor
130,823,474
true
{"Kotlin": 76362, "HTML": 3458, "Java": 194}
package com.intellij.idea fun createCommandLineApplication(isInternal: Boolean, isUnitTestMode: Boolean, isHeadless: Boolean) = CommandLineApplication.ourInstance ?: run { CommandLineApplication(isInternal, isUnitTestMode, isHeadless) }
0
Kotlin
0
0
8af2b06e95333ebbb8cbeb686e61ee7c70e50981
265
inspection-plugin
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/manageoffencesapi/service/PrisonApiUserClient.kt
ministryofjustice
460,455,417
false
{"Kotlin": 396525, "Shell": 1564, "Dockerfile": 1558}
package uk.gov.justice.digital.hmpps.manageoffencesapi.service import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Qualifier import org.springframework.core.ParameterizedTypeReference import org.springframework.stereotype.Service import org.springframework.web.reactive.function.client.WebClient import uk.gov.justice.digital.hmpps.manageoffencesapi.model.external.prisonapi.OffenceActivationDto import uk.gov.justice.digital.hmpps.manageoffencesapi.model.external.prisonapi.OffenceToScheduleMappingDto // To be used when passing through the users token - rather than using system credentials @Service class PrisonApiUserClient(@Qualifier("prisonApiUserWebClient") private val webClient: WebClient) { private inline fun <reified T> typeReference() = object : ParameterizedTypeReference<T>() {} private val log = LoggerFactory.getLogger(this::class.java) fun changeOffenceActiveFlag(offenceActivationDto: OffenceActivationDto) { log.info("Making prison-api call to change offence active flag") webClient.put() .uri("/api/offences/update-active-flag") .bodyValue(offenceActivationDto) .retrieve() .toBodilessEntity() .block() } fun linkToSchedule(offenceToScheduleMappingDtos: List<OffenceToScheduleMappingDto>) { log.info("Making prison-api call to link offences to schedules") webClient.post() .uri("/api/offences/link-to-schedule") .bodyValue(offenceToScheduleMappingDtos) .retrieve() .toBodilessEntity() .block() } fun unlinkFromSchedule(offenceToScheduleMappingDtos: List<OffenceToScheduleMappingDto>) { log.info("Making prison-api call to unlink offences from schedules") webClient.post() .uri("/api/offences/unlink-from-schedule") .bodyValue(offenceToScheduleMappingDtos) .retrieve() .toBodilessEntity() .block() } }
2
Kotlin
0
0
215386ffdc32fb2ee84877e42c7f5d35b5e69630
1,888
hmpps-manage-offences-api
MIT License
app/src/main/java/com/example/thrones/utils/DummyContent.kt
RobinKeya
646,498,988
false
null
package com.example.thrones.utils import com.example.thrones.data.remote.CharacterInfoDto import com.example.thrones.domain.data.models.CharacterInfo object DummyContent { val characters = listOf<CharacterInfo>( CharacterInfo(1,"title1","family1","fullName1","imageURL"), CharacterInfo(2,"title2","family2","fullName2","imageURL"), CharacterInfo(3,"title3","family3","fullName3","imageURL"), CharacterInfo(4,"title4","family4","fullName4","imageURL"), CharacterInfo(5,"title5","family5","fullName5","imageURL"), CharacterInfo(6,"title6","family6","fullName6","imageURL"), ) fun getDomainCharacters(): List<CharacterInfo>{ return characters } fun getCharacterInfoDto(): List<CharacterInfoDto>{ return characters.map { item-> CharacterInfoDto( id = item.id, title = item.title, family = item.family, fullName = item.fullName, imageUrl = item.imageUrl, firstName = "", lastName = "", image = "" ) } } }
0
Kotlin
0
0
9c02870758434366649c0e51ee3c6c6e4a146881
1,149
ThronesApp
MIT License
connectors/ktor/network/src/commonMain/kotlin/com/river/connector/ktor/network/internal/ServerTcpExtensions.kt
River-Kt
539,201,163
false
{"Kotlin": 450835, "Shell": 268, "Python": 126}
package com.river.connector.ktor.network.internal import com.river.connector.ktor.network.use import com.river.core.collectAsync import com.river.core.poll import com.river.core.withPromise import io.ktor.network.selector.* import io.ktor.network.sockets.* import io.ktor.utils.io.core.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext internal interface ServerTcpExtensions { context(CoroutineScope) suspend fun bindAsync( hostname: String, port: Int, maxConnections: Int = 10, builder: SocketOptions.AcceptorOptions.() -> Unit = {}, dispatcher: CoroutineContext = EmptyCoroutineContext, handle: suspend Connection.() -> Unit ): ServerSocket = withPromise { promise -> bindAsFlow(hostname, port, maxConnections, builder, dispatcher) .collect { (socket, connections) -> promise.complete(socket) coroutineScope { val bindingJob = launch { connections .collectAsync(maxConnections) { connection -> connection.use { handle(it) } } } socket.awaitClosed() bindingJob.cancelAndJoin() } } } suspend fun bind( hostname: String, port: Int, maxConnections: Int = 10, builder: SocketOptions.AcceptorOptions.() -> Unit = {}, dispatcher: CoroutineContext = EmptyCoroutineContext, handle: suspend Connection.() -> Unit ): Unit = bindAsFlow(hostname, port, maxConnections, builder, dispatcher) .collect { (_, connections) -> connections.collectAsync(maxConnections) { connection -> connection.use { handle(it) } } } fun bindAsFlow( hostname: String, port: Int, maxConnections: Int = 10, builder: SocketOptions.AcceptorOptions.() -> Unit = {}, dispatcher: CoroutineContext = EmptyCoroutineContext, ): Flow<Pair<ServerSocket, Flow<Connection>>> = flow { SelectorManager(dispatcher) .use { selectorManager -> aSocket(selectorManager) .tcp() .bind(hostname, port, builder) .use { serverSocket -> emit(serverSocket to serverSocket.acceptAsFlow()) serverSocket.awaitClosed() } } } fun ServerSocket.acceptAsFlow(): Flow<Connection> = poll(stopOnEmptyList = true) { if (isClosed) emptyList() else runCatching { listOf(accept().connection()) }.getOrElse { emptyList() } } }
30
Kotlin
3
79
9841047b27268172a42e0e1ec74b095c0202a2cc
3,125
river
MIT License
MarsRealeState/app/src/main/java/com/example/android/marsrealestate/detail/DetailFragment.kt
ChaMinZi
357,587,849
false
null
package com.example.android.marsrealestate.detail import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.example.android.marsrealestate.databinding.FragmentDetailBinding /** * This [Fragment] will show the detailed information about a selected piece of Mars real estate. */ class DetailFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @Suppress("UNUSED_VARIABLE") val application = requireNotNull(activity).application val binding = FragmentDetailBinding.inflate(inflater) binding.lifecycleOwner = this // !!은 null일 경우 nullpointexception을 throw 실제 프러덕트에서는 에러처리를 해주는게 좋음 val marsProperty = DetailFragmentArgs.fromBundle(arguments!!).selectedProperty val viewModelFactory = DetailViewModelFactory(marsProperty, application) binding.viewModel = ViewModelProvider(this, viewModelFactory).get(DetailViewModel::class.java) return binding.root } }
0
Kotlin
0
0
3db9315d032e0e3d5977d5c747d7bbebe78bcb10
1,199
Android_Basic_Sample
Apache License 2.0
src/test/kotlin/org/rgadmin/UIToServerTest.kt
jussijartamo
52,715,110
false
null
package org.rgadmin import org.junit.Before import org.junit.Test import org.mockito.Mockito import org.openqa.selenium.By import org.openqa.selenium.Keys import org.rgadmin.nashorn.NashornExecutor import org.rgadmin.server.ServerTestBase import org.rgadmin.servlet.api.v1.Result import java.util.* import java.util.concurrent.TimeUnit import java.util.function.Consumer import java.util.regex.Pattern class UIToServerTest : ServerTestBase() { @Test fun es7Test() { val inputElement = driver().findElementById("codearea") val textinput = inputElement.findElement(By.tagName("textarea")) textinput.sendKeys(clean(""" const i = (items) => { return "jee " + items; }; print(i); """)) textinput.sendKeys(Keys.chord(Keys.CONTROL, Keys.ENTER)); waitUntilExecutionDone() val print = Mockito.mock(Consumer::class.java) NashornExecutor().script { it.put("print", print) }.execute(captureExecuteScript()) //Mockito.verify(print, Mockito.atLeast(1)).accept(Mockito.anyObject()) } }
0
Kotlin
0
0
f04448b29f349f26835e5f19b0af67f5754d0613
1,117
rgadmin
Apache License 2.0
app/src/main/kotlin/it/scoppelletti/spaceship/preference/sample/CreditsActivity.kt
dscoppelletti
288,121,395
false
null
package it.scoppelletti.spaceship.preference.sample import android.os.Bundle import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import it.scoppelletti.spaceship.app.tryFinish import it.scoppelletti.spaceship.html.app.HtmlViewFragment import it.scoppelletti.spaceship.preference.sample.databinding.CreditsActivityBinding class CreditsActivity : AppCompatActivity() { private lateinit var binding: CreditsActivityBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = CreditsActivityBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) val actionBar = supportActionBar!! actionBar.setDisplayHomeAsUpEnabled(true) supportFragmentManager.beginTransaction() .replace(R.id.contentFrame, HtmlViewFragment.newInstance( HtmlViewFragment.URL_ASSET + "credits.html")) .commit() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { tryFinish() return true } } return super.onOptionsItemSelected(item) } }
0
Kotlin
0
0
c2110bacd06b7687c5a527eba8786b7cf227fe9f
1,292
spaceship-preference
Apache License 2.0
app/src/main/java/com/vignesh/todo/common/repository/TDTodoRepository.kt
vigneshsskv
486,442,436
false
null
package com.vignesh.todo.common.repository import com.vignesh.todo.common.repository.local.db.dao.TDTodoDao import com.vignesh.todo.common.repository.model.TDTodoData import javax.inject.Inject class TDTodoRepository @Inject constructor(private val database: TDTodoDao) : TDRepositoryImpl<TDTodoData>() { override suspend fun insert(data: TDTodoData) = database.insertTODO(data) override suspend fun update(data: TDTodoData) = database.updateTODO(data) override suspend fun delete(data: TDTodoData) = database.updateTODO(data) override fun fetch() = database.fetchTodo() }
0
Kotlin
0
0
00d977f0c7f53b2053424ee6bf97b9ea4797056b
597
Todo-Android-hilt
MIT License
app/src/main/java/com/chocolate/triviatitans/presentation/SplashScreen.kt
team-chocolate-cake
661,943,976
false
null
package com.chocolate.triviatitans.presentation import android.window.SplashScreen import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.constraintlayout.compose.ConstraintLayout import androidx.navigation.NavController import coil.compose.AsyncImage import com.chocolate.triviatitans.R import com.chocolate.triviatitans.composables.ImageView import com.chocolate.triviatitans.presentation.screens.home.navigateToHome import com.chocolate.triviatitans.presentation.theme.TriviaTitansTheme import com.chocolate.triviatitans.presentation.theme.customColor import kotlinx.coroutines.delay @Composable fun SplashScreen(navController: NavController) { LaunchedEffect(key1 = true) { delay(2000) navController.popBackStack() navController.navigateToHome() } TriviaTitansTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.customColor().background ) { ConstraintLayout(modifier = Modifier.fillMaxSize()) { val (Image , text) = createRefs() val guideline = createGuidelineFromTop(0.3f) Box(contentAlignment = Alignment.Center, modifier = Modifier .fillMaxWidth() .constrainAs(Image) { top.linkTo(guideline) }) { ImageView( ImageResource = R.drawable.app_icon, modifier = Modifier .size(150.dp) .padding(bottom = 16.dp) ) } Box(contentAlignment = Alignment.Center, modifier = Modifier .fillMaxWidth() .constrainAs(text) { top.linkTo(Image.bottom) }, ) { Text( fontSize = 32.sp, text = "Trivia\n\nTitans", color = MaterialTheme.customColor().onBackground87, fontWeight = FontWeight.SemiBold, fontStyle = FontStyle.Italic ) } } } } }
0
Kotlin
3
1
94e74e9943f25d94a64311d898baf4b07fabfc63
3,095
TriviaTitans
MIT License
app/src/main/java/com/chocolate/triviatitans/presentation/SplashScreen.kt
team-chocolate-cake
661,943,976
false
null
package com.chocolate.triviatitans.presentation import android.window.SplashScreen import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.constraintlayout.compose.ConstraintLayout import androidx.navigation.NavController import coil.compose.AsyncImage import com.chocolate.triviatitans.R import com.chocolate.triviatitans.composables.ImageView import com.chocolate.triviatitans.presentation.screens.home.navigateToHome import com.chocolate.triviatitans.presentation.theme.TriviaTitansTheme import com.chocolate.triviatitans.presentation.theme.customColor import kotlinx.coroutines.delay @Composable fun SplashScreen(navController: NavController) { LaunchedEffect(key1 = true) { delay(2000) navController.popBackStack() navController.navigateToHome() } TriviaTitansTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.customColor().background ) { ConstraintLayout(modifier = Modifier.fillMaxSize()) { val (Image , text) = createRefs() val guideline = createGuidelineFromTop(0.3f) Box(contentAlignment = Alignment.Center, modifier = Modifier .fillMaxWidth() .constrainAs(Image) { top.linkTo(guideline) }) { ImageView( ImageResource = R.drawable.app_icon, modifier = Modifier .size(150.dp) .padding(bottom = 16.dp) ) } Box(contentAlignment = Alignment.Center, modifier = Modifier .fillMaxWidth() .constrainAs(text) { top.linkTo(Image.bottom) }, ) { Text( fontSize = 32.sp, text = "Trivia\n\nTitans", color = MaterialTheme.customColor().onBackground87, fontWeight = FontWeight.SemiBold, fontStyle = FontStyle.Italic ) } } } } }
0
Kotlin
3
1
94e74e9943f25d94a64311d898baf4b07fabfc63
3,095
TriviaTitans
MIT License
test/org/jetbrains/r/rinterop/RDebuggerTestHelper.kt
JetBrains
214,212,060
false
{"Kotlin": 2657533, "Java": 558927, "R": 37082, "Lex": 14307, "HTML": 10063, "Rez": 70, "Rebol": 47}
/* * Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.r.rinterop import com.intellij.execution.process.ProcessOutputType import com.intellij.testFramework.PlatformTestUtil import junit.framework.TestCase import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.r.blockingGetAndDispatchEvents class RDebuggerTestHelper(rInterop: RInterop) { private var promise = AsyncPromise<Boolean>() init { rInterop.asyncEventsStartProcessing() val textPromise = AsyncPromise<Unit>() rInterop.addAsyncEventsListener(object : RInterop.AsyncEventsListener { override fun onPrompt(isDebug: Boolean) { promise.setResult(isDebug) } override fun onText(text: String, type: ProcessOutputType) { if (READY_STR in text) { promise = AsyncPromise<Boolean>() textPromise.setResult(Unit) } } }) invokeAndWait(false) { rInterop.replExecute("cat('$READY_STR\\n')") textPromise.blockingGet(DEFAULT_TIMEOUT) } } fun <R> invokeAndWait(expectedDebug: Boolean? = null, f: () -> R): R { PlatformTestUtil.dispatchAllEventsInIdeEventQueue() val result = f() val isDebug = promise.blockingGetAndDispatchEvents(DEFAULT_TIMEOUT) if (expectedDebug != null) { TestCase.assertEquals(expectedDebug, isDebug) } promise = AsyncPromise() return result } companion object { private const val DEFAULT_TIMEOUT = 3000 private const val READY_STR = "__READY__" } }
2
Kotlin
13
62
9225567ed712f54d019ce5ab712016acdb6fc98e
1,606
Rplugin
Apache License 2.0
app/src/main/java/bg/zahov/app/mediators/SettingsManager.kt
HauntedMilkshake
698,074,119
false
{"Kotlin": 52409}
package bg.zahov.app.mediators import android.app.Application import android.content.Context import android.util.Log import androidx.lifecycle.MutableLiveData import bg.zahov.app.data.* import java.util.concurrent.TimeUnit class SettingsManager(application: Application) { companion object { const val PERSISTENCE_STORE_NAME = "UserSettings" const val PERSISTENCE_LANGUAGE = "Language" const val PERSISTENCE_WEIGHT = "Weight" const val PERSISTENCE_DISTANCE = "Distance" const val PERSISTENCE_SOUND_EFFECTS = "SoundEffects" const val PERSISTENCE_THEME = "Theme" const val PERSISTENCE_REST_TIMER = "RestTimer" const val PERSISTENCE_VIBRATION = "Vibration" const val PERSISTENCE_SOUND_SETTINGS = "SoundSettings" const val PERSISTENCE_UPDATE_TEMPLATE = "UpdateTemplate" const val PERSISTENCE_SYNC = "Sync" const val PERSISTENCE_FIT = "Fit" @Volatile private var settingsInstance: SettingsManager? = null fun getInstance(application: Application) = settingsInstance ?: synchronized(this) { settingsInstance ?: SettingsManager(application).also { settingsInstance = it } } } private val sharedPreferences = application.getSharedPreferences(PERSISTENCE_STORE_NAME, Context.MODE_PRIVATE) private val _language = MutableLiveData(Language.valueOf(sharedPreferences.getString(PERSISTENCE_LANGUAGE, Language.English.name) ?: Language.English.name)) private val _weight = MutableLiveData(Units.valueOf(sharedPreferences.getString(PERSISTENCE_WEIGHT, Units.Normal.name) ?: Units.Normal.name)) private val _distance = MutableLiveData(Units.valueOf(sharedPreferences.getString(PERSISTENCE_DISTANCE, Units.Normal.name) ?: Units.Normal.name)) private val _soundEffects = MutableLiveData(sharedPreferences.getBoolean(PERSISTENCE_SOUND_EFFECTS, true)) private val _theme = MutableLiveData(Theme.valueOf(sharedPreferences.getString(PERSISTENCE_THEME, Theme.Dark.name) ?: Theme.Dark.name)) private val _restTimer = MutableLiveData((sharedPreferences.getInt(PERSISTENCE_REST_TIMER, 30))) private val _vibration = MutableLiveData(sharedPreferences.getBoolean(PERSISTENCE_VIBRATION, true)) private val _soundSettings = MutableLiveData(Sound.valueOf(sharedPreferences.getString(PERSISTENCE_SOUND_SETTINGS, Sound.SOUND_1.name) ?: Sound.SOUND_1.name)) private val _updateTemplate = MutableLiveData(sharedPreferences.getBoolean(PERSISTENCE_UPDATE_TEMPLATE, true)) private val _sync = MutableLiveData(sharedPreferences.getBoolean(PERSISTENCE_SYNC, true)) private val _fit = MutableLiveData(sharedPreferences.getBoolean(PERSISTENCE_FIT, false)) fun getSettings(): Settings{ return Settings( language = Language.valueOf(sharedPreferences.getString(PERSISTENCE_LANGUAGE, Language.English.name) ?: Language.English.name), weight = Units.valueOf(sharedPreferences.getString(PERSISTENCE_WEIGHT, Units.Normal.name) ?: Units.Normal.name), distance = Units.valueOf(sharedPreferences.getString(PERSISTENCE_DISTANCE, Units.Normal.name) ?: Units.Normal.name), soundEffects = sharedPreferences.getBoolean(PERSISTENCE_SOUND_EFFECTS, true), theme = Theme.valueOf(sharedPreferences.getString(PERSISTENCE_THEME, Theme.Dark.name) ?: Theme.Dark.name), restTimer = sharedPreferences.getInt(PERSISTENCE_REST_TIMER, 30), vibration = sharedPreferences.getBoolean(PERSISTENCE_VIBRATION, true), soundSettings = Sound.valueOf(sharedPreferences.getString(PERSISTENCE_SOUND_SETTINGS, Sound.SOUND_1.name) ?: Sound.SOUND_1.name), updateTemplate = sharedPreferences.getBoolean(PERSISTENCE_UPDATE_TEMPLATE, true), sync = sharedPreferences.getBoolean(PERSISTENCE_SYNC, true), fit = sharedPreferences.getBoolean(PERSISTENCE_FIT, false) ) } fun setLanguage(language: Language) { sharedPreferences.edit().putString(PERSISTENCE_LANGUAGE, language.name).apply() _language.value = language Log.d("New Language", _language.value.toString()) } fun setWeight(weight: Units) { sharedPreferences.edit().putString(PERSISTENCE_WEIGHT, weight.name).apply() _weight.value = weight } fun setDistance(distance: Units) { sharedPreferences.edit().putString(PERSISTENCE_DISTANCE, distance.name).apply() _distance.value = distance } fun setSoundEffects(enable: Boolean) { sharedPreferences.edit().putBoolean(PERSISTENCE_SOUND_EFFECTS, enable).apply() _soundEffects.value = enable } fun setTheme(theme: Theme) { sharedPreferences.edit().putString(PERSISTENCE_THEME, theme.name).apply() _theme.value = theme } fun setRestTimer(seconds: Int) { sharedPreferences.edit().putInt(PERSISTENCE_REST_TIMER, seconds).apply() _restTimer.value = seconds } fun setVibration(enable: Boolean) { sharedPreferences.edit().putBoolean(PERSISTENCE_VIBRATION, enable).apply() _vibration.value = enable } fun setSoundSettings(sound: Sound) { sharedPreferences.edit().putString(PERSISTENCE_SOUND_SETTINGS, sound.name).apply() _soundSettings.value = sound } fun setUpdateTemplate(enable: Boolean) { sharedPreferences.edit().putBoolean(PERSISTENCE_UPDATE_TEMPLATE, enable).apply() _updateTemplate.value = enable } fun setSync(enable: Boolean) { sharedPreferences.edit().putBoolean(PERSISTENCE_SYNC, enable).apply() _sync.value = enable } fun setFit(enable: Boolean) { sharedPreferences.edit().putBoolean(PERSISTENCE_FIT, enable).apply() _fit.value = enable } }
0
Kotlin
0
1
e1e93feddac745fef305ebcf60657f618d42b2a4
5,800
fitness_app
MIT License
app/src/main/java/com/example/zierulesguru/list_data/ListTugas.kt
Apechi
680,068,900
false
{"Kotlin": 64121, "Java": 19162}
package com.example.zierulesguru.list_data data class ListTugas( val status: Int, val dataTask: ArrayList<dataTask> ) data class dataTask( val id: Int, val name: String, )
0
Kotlin
0
0
d844c095c50502937c290ea9b1a5a99554e04b28
191
ZieRulesGuru
Apache License 2.0
src/main/kotlin/com/github/nikolaisviridov/testtask/intentions/AddAnnotation.kt
NikolaiSviridov
294,978,511
false
null
package com.github.nikolaisviridov.testtask.intentions import com.intellij.codeInsight.CodeInsightUtilCore import com.intellij.codeInsight.FileModificationService import com.intellij.codeInsight.hint.HintManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.containers.ContainerUtil import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil import com.jetbrains.python.codeInsight.intentions.PyBaseIntentionAction import com.jetbrains.python.codeInsight.intentions.PyTypeHintGenerationUtil import com.jetbrains.python.codeInsight.intentions.PyTypeHintGenerationUtil.AnnotationInfo import com.jetbrains.python.codeInsight.intentions.PyTypeHintGenerationUtil.Pep484IncompatibleTypeException import com.jetbrains.python.documentation.doctest.PyDocstringFile import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyBuiltinCache import com.jetbrains.python.psi.impl.PyPsiUtils import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.types.PyClassTypeImpl import com.jetbrains.python.psi.types.PyType import com.jetbrains.python.psi.types.TypeEvalContext import one.util.streamex.StreamEx import java.util.function.Predicate class AddAnnotation : PyBaseIntentionAction() { override fun getText(): String = "TestTask Add stub-annotation" override fun getFamilyName(): String = "Test Task FamilyName" override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean { if (file !is PyFile || file is PyDocstringFile || editor == null) { return false } val resolvedVars = findSuitableTargets(project, file) val resolvedFunctions = traversePsiTreeFunctions(file) return resolvedVars.isNotEmpty() || resolvedFunctions.isNotEmpty() } override fun doInvoke(project: Project, editor: Editor?, file: PsiFile?) { if (editor == null || file == null) return val targets = findSuitableTargets(project, file) for (annotationTarget in targets) { try { insertVariableAnnotation(annotationTarget) } catch (e: Pep484IncompatibleTypeException) { e.message?.let { HintManager.getInstance().showErrorHint(editor, it) } } } val functions = traversePsiTreeFunctions(file) for (function in functions) { annotateFunction(editor, function) } } override fun startInWriteAction(): Boolean = false /** * Template for future function */ private fun getParameterType(): String = "Any" /** * Template for future function */ private fun getFunctionType(): String = "Any" /** * Template for future function */ private fun getVariableType(target: PyTypedElement): PyType? = PyBuiltinCache.getInstance(target).getObjectType("Any") /** * Template for future function */ private fun getVariableAnnotationText(): String = "Any" /** * Get all PyTargetExpression's recursively from psi tree */ private fun traversePsiTreeVariables(element: PsiElement, result: MutableList<PyTargetExpression> = arrayListOf()) : List<PyTargetExpression> { if (element is PyTargetExpression) { result.add(element) } for (child in element.children) { traversePsiTreeVariables(child, result) } return result } /** * Get all PyFunction's recursively from psi tree */ private fun traversePsiTreeFunctions(element: PsiElement, result: MutableList<PyFunction> = arrayListOf()) : List<PyFunction> { val index = ProjectFileIndex.getInstance(element.project) if (element is PyFunction) { if (!index.isInLibraryClasses(element.containingFile.virtualFile)) { result.add(element) } } for (child in element.children) { traversePsiTreeFunctions(child, result) } return result } /** * Find PyTargetExpression's which can be annotated */ private fun findSuitableTargets(project: Project, file: PsiFile): List<PyTargetExpression> { val index = ProjectFileIndex.getInstance(project) val typeEvalContext = TypeEvalContext.codeAnalysis(project, file) return traversePsiTreeVariables(file) .filter { !index.isInLibraryClasses(it.containingFile.virtualFile) } .filter { canBeAnnotated(it) } .filter { !isAnnotated(it, typeEvalContext) } } private fun canBeAnnotated(target: PyTargetExpression): Boolean { val directParent = target.parent return if (directParent is PyImportElement || directParent is PyComprehensionForComponent || directParent is PyGlobalStatement || directParent is PyNonlocalStatement) { false } else PsiTreeUtil.getParentOfType(target, PyWithItem::class.java, PyAssignmentStatement::class.java, PyForPart::class.java) != null } private fun isAnnotated(target: PyTargetExpression, context: TypeEvalContext): Boolean { val scopeOwner = ScopeUtil.getScopeOwner(target) ?: return false val name = target.name ?: return false if (!target.isQualified) { if (target.annotationValue != null) return true var candidates: StreamEx<PyTargetExpression>? = null when { context.maySwitchToAST(target) -> { val scope = ControlFlowCache.getScope(scopeOwner) candidates = StreamEx.of(scope.getNamedElements(name, false)).select(PyTargetExpression::class.java) } scopeOwner is PyFile -> candidates = StreamEx.of(scopeOwner.topLevelAttributes).filter { name == it.name } scopeOwner is PyClass -> candidates = StreamEx.of(scopeOwner.classAttributes).filter { name == it.name } } if (candidates != null) return candidates.anyMatch(Predicate { it.annotationValue != null }) } else if (isInstanceAttribute(target, context)) { val classLevelDefinitions = findClassLevelDefinitions(target, context) return ContainerUtil.exists(classLevelDefinitions) { it.annotationValue != null } } return false } private fun findClassLevelDefinitions(target: PyTargetExpression, context: TypeEvalContext) : List<PyTargetExpression> { assert(target.containingClass != null) assert(target.name != null) val classType = PyClassTypeImpl(target.containingClass!!, true) val resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context) val classAttrs = classType.resolveMember(target.name!!, target, AccessDirection.READ, resolveContext, true) ?: return emptyList() return StreamEx.of(classAttrs) .map { it.element } .select(PyTargetExpression::class.java) .filter { ScopeUtil.getScopeOwner(it) is PyClass } .toList() } private fun isInstanceAttribute(target: PyTargetExpression, context: TypeEvalContext): Boolean { val scopeOwner = ScopeUtil.getScopeOwner(target) return if (target.isQualified && target.containingClass != null && scopeOwner is PyFunction) { if (context.maySwitchToAST(target)) { val resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context) StreamEx.of(PyUtil.multiResolveTopPriority(target.qualifier!!, resolveContext)) .select(PyParameter::class.java) .filter { it.isSelf } .anyMatch { PsiTreeUtil.getParentOfType(it, PyFunction::class.java) === scopeOwner } } else { PyUtil.isInstanceAttribute(target) } } else false } private fun insertVariableAnnotation(target: PyTargetExpression) { val context = TypeEvalContext.userInitiated(target.project, target.containingFile) val inferredType = getVariableType(target) PyTypeHintGenerationUtil.checkPep484Compatibility(inferredType, context) val info = AnnotationInfo(getVariableAnnotationText(), inferredType) if (isInstanceAttribute(target, context)) { val classLevelAttrs = findClassLevelDefinitions(target, context) if (classLevelAttrs.isEmpty()) { PyTypeHintGenerationUtil.insertStandaloneAttributeAnnotation(target, context, info, false) } else { PyTypeHintGenerationUtil.insertVariableAnnotation(classLevelAttrs[0], context, info, false) } } else { PyTypeHintGenerationUtil.insertVariableAnnotation(target, context, info, false) } } private fun annotateFunction(editor: Editor?, function: PyFunction) { if (editor == null) return if (!FileModificationService.getInstance().preparePsiElementForWrite(function)) return WriteAction.run<RuntimeException> { generatePy3kTypeAnnotations(function.project, editor, function) } } private fun annotateParameter(project: Project?, editor: Editor, parameter: PyNamedParameter): PyNamedParameter? { @Suppress("NAME_SHADOWING") var parameter = parameter val defaultParamValue = parameter.defaultValue val paramName = StringUtil.notNullize(parameter.name) val elementGenerator = PyElementGenerator.getInstance(project) val defaultParamText = defaultParamValue?.text val paramType = getParameterType() val namedParameter = elementGenerator.createParameter(paramName, defaultParamText, paramType, LanguageLevel.forElement(parameter))!! parameter = parameter.replace(namedParameter) as PyNamedParameter parameter = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(parameter) editor.caretModel.moveToOffset(parameter.textOffset) return parameter } private fun annotateReturnType(function: PyFunction): PyExpression? { val returnType = getFunctionType() val annotationText = "-> $returnType" val annotatedFunction = PyUtil.updateDocumentUnblockedAndCommitted<PyFunction>(function) { document: Document -> val oldAnnotation = function.annotation if (oldAnnotation != null) { val oldRange = oldAnnotation.textRange document.replaceString(oldRange.startOffset, oldRange.endOffset, annotationText) } else { val prevElem = PyPsiUtils.getPrevNonCommentSibling(function.statementList, true)!! val range = prevElem.textRange if (prevElem.node.elementType === PyTokenTypes.COLON) { document.insertString(range.startOffset, " $annotationText") } else { document.insertString(range.endOffset, " $annotationText:") } } CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(function) } ?: return null val annotation = annotatedFunction.annotation!! return annotation.value ?: error("Generated function must have annotation") } private fun generatePy3kTypeAnnotations(project: Project, editor: Editor, function: PyFunction) { annotateReturnType(function) val params = function.parameterList.parameters for (i in params.indices.reversed()) { if (params[i] is PyNamedParameter && !params[i].isSelf) { annotateParameter(project, editor, (params[i] as PyNamedParameter)) } } } }
0
Kotlin
0
0
efa0cd0189a1a0b9e69a1bc51def849ebd85a913
12,387
Add-Stub-Annotation
Apache License 2.0
composeApp/src/desktopMain/kotlin/nl/mdsystems/ui/screens/configurationScreen.kt
MikeDirven
866,569,963
false
{"Kotlin": 100228}
package nl.mdsystems.ui.screens import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import nl.mdsystems.domain.enums.ConfigurationSteps import nl.mdsystems.model.Configuration import nl.mdsystems.ui.screens.components.GeneralConfig import nl.mdsystems.ui.screens.components.InstallerConfig import nl.mdsystems.ui.screens.components.LauncherConfig import nl.mdsystems.ui.screens.components.PackageConfig @Composable fun configurationScreen( modifier: Modifier = Modifier, packageConfig: Configuration, activeStep: ConfigurationSteps, onConfigChange: (Configuration) -> Unit ){ Column( modifier = modifier, verticalArrangement = Arrangement.spacedBy(10.dp) ) { Column( modifier = Modifier.padding(horizontal = 8.dp) ) { when(activeStep){ ConfigurationSteps.GENERAL -> { GeneralConfig( config = packageConfig, onConfigChange = onConfigChange ) } ConfigurationSteps.PACKAGE -> { PackageConfig( config = packageConfig, onConfigChange = onConfigChange ) } ConfigurationSteps.LAUNCHER -> { LauncherConfig( config = packageConfig, onConfigChange = onConfigChange ) } ConfigurationSteps.INSTALLER -> { InstallerConfig( config = packageConfig, onConfigChange = onConfigChange ) } } } } }
17
Kotlin
0
1
95fdf5b088c5790efcc9be1d3db64fa34f7f3078
1,978
jpackager
Apache License 2.0
src/main/kotlin/fr/vahren/engine/GameContext.kt
baaleze
242,791,456
false
null
package fr.vahren.engine import fr.vahren.GameEntity import fr.vahren.engine.type.Player import fr.vahren.world.World import org.hexworks.amethyst.api.Context import org.hexworks.zircon.api.screen.Screen import org.hexworks.zircon.api.uievent.UIEvent data class GameContext(val world: World, val screen: Screen, val uiEvent: UIEvent, val player: GameEntity<Player>) : Context
0
Kotlin
0
0
37a42e7e66a246d0891d69582a40830dca7fa086
446
tactiks
Apache License 2.0
tibiakt-core/src/main/kotlin/com/galarzaa/tibiakt/core/utils/ListExtensions.kt
Galarzaa90
285,669,589
false
{"Kotlin": 531360, "Dockerfile": 1445}
/* * Copyright © 2022 <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.galarzaa.tibiakt.core.utils import kotlin.math.min /** * Get a sublist from the receiver, starting at a certain [offset]. * * If the offset is bigger than the list's size, the same list is returned. */ public fun <T> List<T>.offsetStart(offset: Int): List<T> = subList(min(offset, size), size)
0
Kotlin
1
1
a06455074717eb53642128de70919c9310e97624
905
TibiaKt
Apache License 2.0
feature/login/src/main/kotlin/com/espressodev/gptmap/feature/login/LoginNavigation.kt
f-arslan
714,072,263
false
{"Kotlin": 226952, "Dockerfile": 852}
package com.espressodev.gptmap.feature.login import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavOptions import androidx.navigation.compose.composable const val loginRoute = "login_route" fun NavController.navigateToLogin(navOptions: NavOptions? = null) { navigate(loginRoute, navOptions) } fun NavGraphBuilder.loginScreen( navigateToMap: () -> Unit, navigateToRegister: () -> Unit, navigateToForgotPassword: () -> Unit ) { composable(loginRoute) { LoginRoute( navigateToMap = navigateToMap, navigateToRegister = navigateToRegister, navigateToForgotPassword = navigateToForgotPassword ) } }
0
Kotlin
0
2
51522d23757a7ef2b8421652a9eba57a6bf6133d
732
GptMap
MIT License
compiler-processing/src/main/java/com/paulrybitskyi/hiltbinder/compiler/processing/ksp/KspAnnotationValue.kt
mars885
332,237,059
false
{"Kotlin": 487350, "Java": 429825, "Shell": 593}
/* * Copyright 2021 <NAME>, <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.paulrybitskyi.hiltbinder.compiler.processing.ksp import com.google.devtools.ksp.symbol.KSType import com.paulrybitskyi.hiltbinder.common.utils.safeCast import com.paulrybitskyi.hiltbinder.common.utils.unsafeCast import com.paulrybitskyi.hiltbinder.compiler.processing.XAnnotationValue import com.paulrybitskyi.hiltbinder.compiler.processing.XType import com.paulrybitskyi.hiltbinder.compiler.processing.factories.XTypeFactory import com.paulrybitskyi.hiltbinder.compiler.processing.ksp.utils.simpleName internal class KspAnnotationValue( private val env: KspProcessingEnv, private val value: Any? ): XAnnotationValue { override fun getAsBoolean(default: Boolean): Boolean { return (value?.safeCast() ?: default) } override fun <T : Enum<*>> getAsEnum(valueOf: (String) -> T, default: T): T { return try { when(value) { is Enum<*> -> value.unsafeCast() is KSType -> valueOf(value.simpleName) else -> default } } catch(error: Throwable) { default } } override fun getAsType(default: XType?): XType? { return value?.safeCast<KSType>() ?.let { XTypeFactory.createKspType(env, it) } ?: default } }
3
Kotlin
4
69
5070ab91501e04eb6f77b0aefd357e2b6d96b8d2
1,894
hilt-binder
Apache License 2.0
src/me/anno/video/formats/gpu/Y4Frame.kt
AntonioNoack
456,513,348
false
null
package me.anno.video.formats.gpu import me.anno.gpu.GFX import me.anno.gpu.texture.Texture2D import me.anno.utils.Sleep import me.anno.utils.types.InputStreams.readNBytes2 import java.io.InputStream class Y4Frame(w: Int, h: Int) : RGBFrame(w, h) { override fun load(input: InputStream) { val s0 = w * h val data = input.readNBytes2(s0, Texture2D.bufferPool) Sleep.acquire(true, creationLimiter) GFX.addGPUTask("Y4", w, h) { rgb.createMonochrome(data, true) creationLimiter.release() } } }
0
Kotlin
1
9
b2532f7d40527eb2c9e24e3659dd904aa725a1aa
565
RemsEngine
Apache License 2.0
compose-material/src/main/java/com/google/android/horologist/compose/material/Icon.kt
google
451,563,714
false
{"Kotlin": 3151160, "Shell": 5169, "Java": 708, "Starlark": 361}
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.google.android.horologist.compose.material import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.Color import androidx.wear.compose.material.Icon import androidx.wear.compose.material.LocalContentAlpha import androidx.wear.compose.material.LocalContentColor import com.google.android.horologist.annotations.ExperimentalHorologistApi import com.google.android.horologist.images.base.paintable.PaintableIcon /** * This component is an alternative to [Icon], providing the following: * - a API for different image loaders; */ @ExperimentalHorologistApi @Composable public fun Icon( paintable: PaintableIcon, contentDescription: String?, modifier: Modifier = Modifier, tint: Color = LocalContentColor.current.copy(alpha = LocalContentAlpha.current), ) { Icon( painter = paintable.rememberPainter(), contentDescription = contentDescription, tint = tint, modifier = modifier, ) } @Composable internal fun Modifier.autoMirrored(autoMirror: Boolean): Modifier = scale( scaleX = if (autoMirror) -1f else 1f, scaleY = 1f, )
16
Kotlin
93
565
bde87db14f63338904550fc1827d0141ebe24d9a
1,813
horologist
Apache License 2.0
src/main/kotlin/dk/cachet/carp/webservices/file/config/LoggerConfig.kt
cph-cachet
674,650,033
false
{"Kotlin": 671905, "TypeScript": 111037, "HTML": 14219, "Shell": 4202, "CSS": 1656, "Dockerfile": 1264, "JavaScript": 706}
package dk.cachet.carp.webservices.file.config import dk.cachet.carp.webservices.common.configuration.internationalisation.service.MessageBase import dk.cachet.carp.webservices.common.environment.EnvironmentProfile import dk.cachet.carp.webservices.common.environment.EnvironmentUtil import dk.cachet.carp.webservices.common.exception.file.FileStorageException import dk.cachet.carp.webservices.file.util.FileUtil import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger import org.springframework.context.annotation.Configuration import java.io.IOException import java.nio.file.Path import java.nio.file.Paths /** * The Configuration Class [LoggerConfig]. * The [LoggerConfig] enables application to create a logger storage on application start. */ @Configuration class LoggerConfig( private val environmentUtil: EnvironmentUtil, private val fileUtil: FileUtil, private val validationMessages: MessageBase ) { companion object { private val LOGGER: Logger = LogManager.getLogger() } init { createLoggerStorageOnStart() } /** * The function [createLoggerStorageOnStart] creates a storage on application startup. */ @Throws(IOException::class, FileStorageException::class) final fun createLoggerStorageOnStart() { val rootFolder: Path = when(environmentUtil.profile) { EnvironmentProfile.LOCAL -> Paths.get(fileUtil.filePath.toString()).toAbsolutePath().normalize() else -> Paths.get(fileUtil.storageDirectory.toString()).toAbsolutePath().normalize() } ?: throw FileStorageException(validationMessages.get("file.directory.empty", "logging")) val directory: Path = fileUtil.isDirectoryOrElseCreate(rootFolder) if (!fileUtil.isDirectory(directory)) throw FileStorageException(validationMessages.get("file.directory.exists", "logging")) if (!fileUtil.isWritable(directory)) { if (!fileUtil.setStoragePermission(directory)) { LOGGER.warn("Logger directory cannot be created.") throw FileStorageException(validationMessages.get("file.directory.error", "logging")) } else if (fileUtil.setStoragePermission(directory)) { LOGGER.info("Logging storage was created: {}", directory) } } else LOGGER.info("Logging storage: {}", directory) } }
27
Kotlin
1
3
6f16c3c5f1b5b8bdd7abc30fd312c0cad973473c
2,474
carp-webservices-spring
MIT License
app/src/main/java/com/example/dropy/network/models/getWaterPoints/Owner.kt
dropyProd
705,360,878
false
{"Kotlin": 3916897, "Java": 20617}
package com.example.dropy.network.models.getWaterPoints data class Owner( val first_name: String, val id: String, val last_name: String, val phone_number: Any? )
0
Kotlin
0
0
6d994c9c61207bac28c49717b6c250656fe4ae6b
178
DropyLateNights
Apache License 2.0
neuro_router_core/src/main/java/com/victor/neuro/router/core/data/RouteType.kt
Victor2018
538,359,659
false
{"Kotlin": 69455}
package com.victor.neuro.router.core.data /* * ----------------------------------------------------------------- * Copyright (C) 2018-2028, by Victor, All rights reserved. * ----------------------------------------------------------------- * File: RouteType * Author: Victor * Date: 2022/9/30 14:18 * Description: * ----------------------------------------------------------------- */ object RouteType { const val ACTIVITY = 0 const val SERVICE = 1 const val PROVIDER = 2 const val CONTENT_PROVIDER = 3 const val BOARDCAST = 4 const val FRAGMENT = -1 const val UNKNOWN = -2 }
0
Kotlin
0
0
76abc8151196ca7f4ab0665b0a314a6c98007b5c
615
NRouter
Apache License 2.0
android/src/main/java/org/reactnative/camera/tasks/ExposureChangeDelegate.kt
equinoxventures
389,917,793
true
{"Java": 439273, "Objective-C": 254803, "C++": 89515, "Kotlin": 77497, "C#": 58176, "JavaScript": 45801, "Ruby": 1415, "C": 1132, "CSS": 907, "Dockerfile": 148}
package org.reactnative.camera.tasks import com.facebook.react.bridge.WritableMap interface ExposureChangeDelegate { fun onExposeChange(response: WritableMap) }
0
Java
0
0
306cf162eba8bc5939c5e34a37321d2e0e233627
166
react-native-camera
MIT License
src/main/kotlin/com/github/widarlein/kavanza/model/OrderbookModels.kt
widarlein
208,076,108
false
null
package com.github.widarlein.kavanza.model data class OrderbookListItem ( val priceThreeMonthsAgo : Double, val currency : String, val highestPrice : Double, val lowestPrice : Double, val lastPrice : Double, val change : Double, val changePercent : Double, val updated : String, val totalVolumeTraded : Int, val flagCode : String, val tradable : Boolean, val instrumentType : String, val name : String, val id : String )
0
Kotlin
0
1
2aafede39e552305d87e503c1bb0788b764e8879
477
kavanza
MIT License
src/test/kotlin/org/lexem/angmar/parser/functional/statements/loops/LoopClausesStmtNodeTest.kt
lexemlang
184,409,059
false
{"Kotlin": 3049940}
package org.lexem.angmar.parser.functional.statements.loops import org.junit.jupiter.api.* import org.junit.jupiter.params.* import org.junit.jupiter.params.provider.* import org.lexem.angmar.* import org.lexem.angmar.errors.* import org.lexem.angmar.io.readers.* import org.lexem.angmar.parser.* import org.lexem.angmar.parser.functional.statements.* import org.lexem.angmar.utils.* import java.util.stream.* import kotlin.streams.* internal class LoopClausesStmtNodeTest { // PARAMETERS ------------------------------------------------------------- companion object { const val testExpression = "${LoopClausesStmtNode.lastKeyword} ${BlockStmtNodeTest.testExpression}" @JvmStatic private fun provideCorrectLoopClauses(): Stream<Arguments> { val sequence = sequence { for (hasElse in listOf(false, true)) { for (hasLast in listOf(false, true)) { // Avoid none of them if (!hasElse && !hasLast) { continue } val list = mutableListOf<String>() if (hasLast) { list += "${LoopClausesStmtNode.lastKeyword} ${BlockStmtNodeTest.testExpression}" } if (hasElse) { list += "${LoopClausesStmtNode.elseKeyword} ${BlockStmtNodeTest.testExpression}" } yield(Arguments.of(list.joinToString(" "), hasLast, hasElse)) // Without whitespaces list.clear() if (hasLast) { list += "${LoopClausesStmtNode.lastKeyword}${BlockStmtNodeTest.testExpression}" } if (hasElse) { list += "${LoopClausesStmtNode.elseKeyword}${BlockStmtNodeTest.testExpression}" } yield(Arguments.of(list.joinToString(""), hasLast, hasElse)) } } } return sequence.asStream() } // AUX METHODS -------------------------------------------------------- fun checkTestExpression(node: ParserNode) { Assertions.assertTrue(node is LoopClausesStmtNode, "The node is not a LoopClausesStmtNode") node as LoopClausesStmtNode Assertions.assertNotNull(node.lastBlock, "The lastBlock property cannot be null") BlockStmtNodeTest.checkTestExpression(node.lastBlock!!) Assertions.assertNull(node.elseBlock, "The elseBlock property must be null") } } // TESTS ------------------------------------------------------------------ @ParameterizedTest @MethodSource("provideCorrectLoopClauses") fun `parse correct loop clauses`(text: String, hasLast: Boolean, hasElse: Boolean) { val parser = LexemParser(IOStringReader.from(text)) val res = LoopClausesStmtNode.parse(parser, ParserNode.Companion.EmptyParserNode, 0) Assertions.assertNotNull(res, "The input has not been correctly parsed") res as LoopClausesStmtNode if (hasLast) { Assertions.assertNotNull(res.lastBlock, "The lastBlock property cannot be null") BlockStmtNodeTest.checkTestExpression(res.lastBlock!!) } else { Assertions.assertNull(res.lastBlock, "The lastBlock property must be null") } if (hasElse) { Assertions.assertNotNull(res.elseBlock, "The elseBlock property cannot be null") BlockStmtNodeTest.checkTestExpression(res.elseBlock!!) } else { Assertions.assertNull(res.elseBlock, "The elseBlock property must be null") } Assertions.assertEquals(text.length, parser.reader.currentPosition(), "The parser did not advance the cursor") } @Test @Incorrect fun `parse incorrect loop clauses with last but without block`() { TestUtils.assertParserException(AngmarParserExceptionType.LastLoopClauseWithoutBlock) { val text = LoopClausesStmtNode.lastKeyword val parser = LexemParser(IOStringReader.from(text)) LoopClausesStmtNode.parse(parser, ParserNode.Companion.EmptyParserNode, 0) } } @Test @Incorrect fun `parse incorrect loop clauses with else but without block`() { TestUtils.assertParserException(AngmarParserExceptionType.ElseLoopClauseWithoutBlock) { val text = LoopClausesStmtNode.elseKeyword val parser = LexemParser(IOStringReader.from(text)) LoopClausesStmtNode.parse(parser, ParserNode.Companion.EmptyParserNode, 0) } } @ParameterizedTest @ValueSource(strings = [""]) fun `not parse the node`(text: String) { val parser = LexemParser(IOStringReader.from(text)) val res = LoopClausesStmtNode.parse(parser, ParserNode.Companion.EmptyParserNode, 0) Assertions.assertNull(res, "The input has incorrectly parsed anything") Assertions.assertEquals(0, parser.reader.currentPosition(), "The parser must not advance the cursor") } }
0
Kotlin
0
2
45fb563507a00c3eada89be9ab6e17cfe1701958
5,276
angmar
MIT License
core-ui/src/main/java/com/anytypeio/anytype/core_ui/tools/SlashHelper.kt
anyproto
647,371,233
false
{"Kotlin": 11623123, "Java": 69306, "Shell": 11350, "Makefile": 1334}
package com.anytypeio.anytype.core_ui.tools import com.anytypeio.anytype.core_ui.tools.SlashTextWatcher.Companion.NO_SLASH_POSITION import com.anytypeio.anytype.core_ui.tools.SlashTextWatcher.Companion.SLASH_CHAR object SlashHelper { fun getSlashPosition(text: CharSequence, start: Int, count: Int): Int { val position = start + count - 1 return if (count > 0 && start < text.length && text.getOrNull(position) == SLASH_CHAR) { position } else { NO_SLASH_POSITION } } fun isSlashDeleted(start: Int, slashPosition: Int): Boolean = slashPosition != NO_SLASH_POSITION && start <= slashPosition }
45
Kotlin
43
528
c708958dcb96201ab7bb064c838ffa8272d5f326
672
anytype-kotlin
RSA Message-Digest License
SnackBarToast/app/src/main/java/cn/xwj/snackbartoast/MainActivity.kt
jxiaow
141,072,576
false
{"Kotlin": 82977, "Java": 12342}
package cn.xwj.snackbartoast import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mToastBtn.setOnClickListener(this::click) mSnackBtn.setOnClickListener(this::click) } private fun click(v: View) { when (v.id) { R.id.mToastBtn -> customView() R.id.mSnackBtn -> { Snackbar.make(v, "你使用的是SnackBar", Snackbar.LENGTH_LONG).setAction("确定") { customView() }.show() } } } /** * 自定义吐司 */ private fun customView() { val toast = Toast(this) val inflater: LayoutInflater = LayoutInflater.from(this) val view = inflater.inflate(R.layout.custom_view, null) toast.view = view toast.setGravity(Gravity.TOP, 0, 0) toast.show() } }
0
Kotlin
0
0
6c9e3fd453a10025e432de278aff4b729bf8c5de
1,248
AndroidUIStudio
Apache License 2.0
drag-drop-swipe-recyclerview/src/main/java/com/ernestoyaquello/dragdropswiperecyclerview/ScrollAwareRecyclerView.kt
ernestoyaquello
153,335,440
false
null
package com.ernestoyaquello.dragdropswiperecyclerview import android.content.Context import androidx.recyclerview.widget.RecyclerView import android.util.AttributeSet import com.ernestoyaquello.dragdropswiperecyclerview.listener.OnListScrollListener /** * Extension of RecyclerView that detects when the user scrolls. */ open class ScrollAwareRecyclerView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RecyclerView(context, attrs, defStyleAttr) { /** * Listener for the scrolling events. */ var scrollListener: OnListScrollListener? = null private val internalListScrollListener = object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) when (newState) { SCROLL_STATE_IDLE -> scrollListener?.onListScrollStateChanged(OnListScrollListener.ScrollState.IDLE) SCROLL_STATE_DRAGGING -> scrollListener?.onListScrollStateChanged(OnListScrollListener.ScrollState.DRAGGING) SCROLL_STATE_SETTLING -> scrollListener?.onListScrollStateChanged(OnListScrollListener.ScrollState.SETTLING) } } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) when { dy > 0 -> scrollListener?.onListScrolled(OnListScrollListener.ScrollDirection.DOWN, dy) dy < 0 -> scrollListener?.onListScrolled(OnListScrollListener.ScrollDirection.UP, -dy) dx > 0 -> scrollListener?.onListScrolled(OnListScrollListener.ScrollDirection.RIGHT, dx) dx < 0 -> scrollListener?.onListScrolled(OnListScrollListener.ScrollDirection.LEFT, -dx) } } } init { super.addOnScrollListener(internalListScrollListener) } @Deprecated("Use the property scrollListener instead.", ReplaceWith("scrollListener")) override fun addOnScrollListener(listener: OnScrollListener) { throw UnsupportedOperationException( "Only the property scrollListener can be used to add a scroll listener here.") } }
0
Kotlin
96
844
0ab79d9eecdc8c829a22903673a1ba6c2c746627
2,427
DragDropSwipeRecyclerview
Apache License 2.0
app/src/main/java/com/jdagnogo/welovemarathon/home/di/HomeModule.kt
jdagnogo
424,252,162
false
{"Kotlin": 625180}
package com.jdagnogo.welovemarathon.home.di import com.jdagnogo.welovemarathon.beach.domain.GetBeachesUseCase import com.jdagnogo.welovemarathon.common.banner.GetBannerUseCase import com.jdagnogo.welovemarathon.home.domain.HomeUseCases import com.jdagnogo.welovemarathon.home.presentation.HomeReducer import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object HomeModule { @Provides @Singleton fun provideHomeReducer() = HomeReducer() @Singleton @Provides fun provideRunDao( bannerUseCase: GetBannerUseCase, getBeachesUseCase: GetBeachesUseCase, ): HomeUseCases = HomeUseCases(bannerUseCase, getBeachesUseCase) }
0
Kotlin
0
0
e82d9fb221b605ce996a68dc938692273279f662
814
WeLoveMArathon
The Unlicense
modules/LoadingView/src/main/java/com/loading/view/space/system/LinesSystem.kt
siarheisinelnikau
337,195,832
false
null
package com.loading.view.space.system import com.badlogic.ashley.core.Entity import com.badlogic.ashley.core.Family import com.badlogic.ashley.systems.IteratingSystem import com.loading.view.ecs.util.VectorFloat import com.loading.view.space.component.LineComponent import com.loading.view.space.component.SizeComponent import com.loading.view.space.component.TransformComponent class LinesSystem(private val proximity: Float) : IteratingSystem(family) { companion object { private val family = Family .all( TransformComponent::class.java, SizeComponent::class.java, LineComponent::class.java ) .get() } override fun update(deltaTime: Float) { // super.update ignored val size = entities.size() for (i: Int in 0 until size) { LineComponent.from(entities[i]).active = false } for (i: Int in 0 until size - 1) { for (e: Int in i + 1 until size) { checkLine(entities[i], entities[e], proximity) } } } @Suppress("NOTHING_TO_INLINE") private inline fun checkLine(a: Entity, b: Entity, proximity: Float) { val p1 = TransformComponent.from(a).position val p2 = TransformComponent.from(b).position val aType = SizeComponent.from(a).big val bType = SizeComponent.from(b).big if (aType == bType) { val line = LineComponent.from(a) if (VectorFloat.distanceSquared(p1, p2) < proximity * proximity) { line.position.set(p2) line.active = true } } } override fun processEntity(entity: Entity?, deltaTime: Float) { // empty, not used } }
0
Kotlin
0
0
ed59d1e4c1f67c1e70cadd8e37a52882fe879912
1,787
LoadingView
Apache License 2.0
server/src/jp/gree/techcon/server/task/InitializeDB.kt
hitomi-sasaki
235,529,484
false
null
package jp.gree.techcon.server.task import io.ktor.server.engine.commandLineEnvironment import io.ktor.util.KtorExperimentalAPI import jp.gree.techcon.server.dao.* import jp.gree.techcon.server.entity.* import jp.gree.techcon.server.service.DatabaseFactory import org.jetbrains.exposed.sql.SchemaUtils import org.jetbrains.exposed.sql.SizedCollection import org.jetbrains.exposed.sql.transactions.transaction @KtorExperimentalAPI fun main(args: Array<String>) { val config = commandLineEnvironment(args).config DatabaseFactory.init(config) InitializeDB.setupSchema() InitializeDB.setupInitialRecords() } object InitializeDB { const val DATABASE = "techcon" val TABLES = arrayOf( Sessions, SpeakerRelations, Speakers, TagRelations, Tags, Articles, Bookmarks, Tracks, TrackSessions, Booths ) fun setupSchema() { transaction { SchemaUtils.createMissingTablesAndColumns(*TABLES) } } fun setupInitialRecords() { transaction { val TAG_ANDROID = DatabaseFactory.upsert(Tag.Companion, 1) { name = "Android" } val TAG_APACHEBEAM = DatabaseFactory.upsert(Tag.Companion, 2) { name = "ApacheBeam" } val TAG_AWS = DatabaseFactory.upsert(Tag.Companion, 3) { name = "AWS" } val TAG_BIGQUERY = DatabaseFactory.upsert(Tag.Companion, 4) { name = "BigQuery" } val TAG_DEEPLEARNING = DatabaseFactory.upsert(Tag.Companion, 5) { name = "DeepLearning" } val TAG_DEVOPS = DatabaseFactory.upsert(Tag.Companion, 6) { name = "DevOps" } val TAG_FIREBASE = DatabaseFactory.upsert(Tag.Companion, 7) { name = "Firebase" } val TAG_GAMEENGINE = DatabaseFactory.upsert(Tag.Companion, 8) { name = "GameEngine" } val TAG_GCP = DatabaseFactory.upsert(Tag.Companion, 9) { name = "GCP" } val TAG_GRAPHQL = DatabaseFactory.upsert(Tag.Companion, 10) { name = "GraphQL" } val TAG_INFRA = DatabaseFactory.upsert(Tag.Companion, 11) { name = "Infra" } val TAG_IOS = DatabaseFactory.upsert(Tag.Companion, 12) { name = "iOS" } val TAG_KUBERNETES = DatabaseFactory.upsert(Tag.Companion, 13) { name = "Kubernetes" } val TAG_LAMP = DatabaseFactory.upsert(Tag.Companion, 14) { name = "LAMP" } val TAG_LUA = DatabaseFactory.upsert(Tag.Companion, 15) { name = "Lua" } val TAG_MACHINELEANING = DatabaseFactory.upsert(Tag.Companion, 16) { name = "MachineLeaning" } val TAG_MOTIONCAPTURE = DatabaseFactory.upsert(Tag.Companion, 17) { name = "MotionCapture" } val TAG_NATIVEAPP = DatabaseFactory.upsert(Tag.Companion, 18) { name = "NativeApp" } val TAG_NUXTJS = DatabaseFactory.upsert(Tag.Companion, 19) { name = "NuxtJS" } val TAG_PHP = DatabaseFactory.upsert(Tag.Companion, 20) { name = "PHP" } val TAG_REALTIMESERVER = DatabaseFactory.upsert(Tag.Companion, 21) { name = "RealtimeServer" } val TAG_RPG = DatabaseFactory.upsert(Tag.Companion, 22) { name = "RPG" } val TAG_UNITY = DatabaseFactory.upsert(Tag.Companion, 23) { name = "Unity" } val TAG_UNREALENGINE4 = DatabaseFactory.upsert(Tag.Companion, 24) { name = "UnrealEngine4" } val TAG_VOICECONVERSION = DatabaseFactory.upsert(Tag.Companion, 25) { name = "VoiceConversion" } val TAG_VUEJS = DatabaseFactory.upsert(Tag.Companion, 26) { name = "Vue.js" } val TAG_WFLE = DatabaseFactory.upsert(Tag.Companion, 27) { name = "WFLE" } val TAG_WFS = DatabaseFactory.upsert(Tag.Companion, 28) { name = "WFS" } val TAG_ENGINEER = DatabaseFactory.upsert(Tag.Companion, 29) { name = "エンジニア" } val TAG_ENGINEERING = DatabaseFactory.upsert(Tag.Companion, 30) { name = "エンジニアリング" } val TAG_SOCIALGAME = DatabaseFactory.upsert(Tag.Companion, 31) { name = "ソーシャルゲーム" } val TAG_DATAPIPELINE = DatabaseFactory.upsert(Tag.Companion, 32) { name = "データパイプライン" } val TAG_FRONTEND = DatabaseFactory.upsert(Tag.Companion, 33) { name = "フロントエンド" } val TAG_MOBILEGAME = DatabaseFactory.upsert(Tag.Companion, 34) { name = "モバイルゲーム" } val TAG_LIVE = DatabaseFactory.upsert(Tag.Companion, 35) { name = "ライブ配信" } val TAG_LEGACY = DatabaseFactory.upsert(Tag.Companion, 36) { name = "レガシー" } val TAG_INFRASTRUCTURE = DatabaseFactory.upsert(Tag.Companion, 37) { name = "基盤" } val TAG_MIGRATION = DatabaseFactory.upsert(Tag.Companion, 38) { name = "移管" } val TAG_ORGANIZATION = DatabaseFactory.upsert(Tag.Companion, 39) { name = "組織" } val TAG_RUN = DatabaseFactory.upsert(Tag.Companion, 40) { name = "運営" } val TAG_OPERATION = DatabaseFactory.upsert(Tag.Companion, 41) { name = "運用" } val TAG_LONGTERM = DatabaseFactory.upsert(Tag.Companion, 42) { name = "運用10年" } val TAG_LONGHIT = DatabaseFactory.upsert(Tag.Companion, 43) { name = "長寿タイトル" } val TAG_DEVELOPMENT = DatabaseFactory.upsert(Tag.Companion, 44) { name = "開発" } val SPEAKER_01 = DatabaseFactory.upsert(Speaker.Companion, 1) { name = "紙谷 憲" title = "部長" githubId = "" twitterId = "" description = "" } val SPEAKER_02 = DatabaseFactory.upsert(Speaker.Companion, 2) { name = "西田 綾佑" title = "ウルトラスーパーエンジニア" githubId = "" twitterId = "" description = "" } val SPEAKER_03 = DatabaseFactory.upsert(Speaker.Companion, 3) { name = "山内 洋典" title = "エンジニア" githubId = "youten" twitterId = "youten_redo" description = "組み込み系SIerの会社で十数年ほど働いた後、飽きたので退職。\n" + "1年ほど無職を堪能した後、VTuberにハマり「モバイルでバーチャルアバター配信アプリを本気でやるよ」という話が楽しそうだったのでWFLEに2018年に入社。\n" + "REALITYアプリのUnity・アバター部を担当。" } val SPEAKER_04 = DatabaseFactory.upsert(Speaker.Companion, 4) { name = "増住 啓吾" title = "エンジニア" githubId = "" twitterId = "" description = "" } val SPEAKER_05 = DatabaseFactory.upsert(Speaker.Companion, 5) { name = "安川 貴志" title = "エンジニア" githubId = "" twitterId = "" description = "" } val SPEAKER_06 = DatabaseFactory.upsert(Speaker.Companion, 6) { name = "髙橋 悠" title = "エンジニア" githubId = "" twitterId = "" description = "フィーチャーフォン向けのコンテンツ・ゲームエンジンの開発を3年。\n" + "スマートフォン向けゲームエンジン開発を9年。\n" + "並行して VR コンテンツ開発を 3 年。\n" + "2018年にグリー入社。ライブエンターテインメント事業にて、主にモーションキャプチャーを担当。" } val SPEAKER_07 = DatabaseFactory.upsert(Speaker.Companion, 7) { name = "覚張 泰幸" title = "エンジニアマネージャー" githubId = "" twitterId = "" description = "『SINoALICE -シノアリス-』リードエンジニアとして立ち上げから参画。\n" + "現在もリードエンジニアとしてエンジニアを統括している。\n" + "\n" + "ポケラボで携わったタイトル :\n" + "・戦乱のサムライキングダム [エンジニア -> リードエンジニア]\n" + "・新規アクションRPG(未リリース) [リードエンジニア]\n" + "・SINoALICE -シノアリス- [リードエンジニア]\n" + "\n" + "2013年ポケラボ入社" } val SPEAKER_08 = DatabaseFactory.upsert(Speaker.Companion, 8) { name = "天野 雄太" title = "エンジニアチームマネージャ" githubId = "" twitterId = "" description = "2012年にグリー株式会社に入社。2014年より携帯ソーシャルゲーム運用・開発のチームに配属。2018年より同チームのエンジニアチームマネージャに就任。現在まで約6年間、長期運用タイトルにエンジニアとして携わる。趣味はテレビゲーム、動画鑑賞、英語の勉強。剣道四段、英検4級。" } val SPEAKER_09 = DatabaseFactory.upsert(Speaker.Companion, 9) { name = "大谷 俊平" title = "シニアマネージャー" githubId = "" twitterId = "" description = "" } val SPEAKER_10 = DatabaseFactory.upsert(Speaker.Companion, 10) { name = "村田 翔" title = "エンジニアチームマネージャ" githubId = "sakurahigashi2" twitterId = "" description = "" } val SPEAKER_11 = DatabaseFactory.upsert(Speaker.Companion, 11) { name = "田畠 知弥" title = "エンジニア" githubId = "" twitterId = "" description = "" } val SPEAKER_12 = DatabaseFactory.upsert(Speaker.Companion, 12) { name = "矢﨑 雄人" title = "エンジニア" githubId = "" twitterId = "" description = "" } val SPEAKER_13 = DatabaseFactory.upsert(Speaker.Companion, 13) { name = "駒﨑 拓斗" title = "エンジニア" githubId = "" twitterId = "" description = "" } val SPEAKER_14 = DatabaseFactory.upsert(Speaker.Companion, 14) { name = "石原 達馬" title = "データエンジニア" githubId = "" twitterId = "" description = "" } val SESSION_01 = DatabaseFactory.upsert(Session.Companion, 1) { startTime = 1574157622 endTime = 1574163622 title = "WFSエンジニア組織の振り返りとこれから〜コンテンツ開発に集中するために取り組んだこと〜" description = "WFSはスタジオ立ち上げから6年、「いかにゲームを面白くするか、どのように魅力的なゲームを作るか」のみを考えられるような開発体制を常に模索し続けてきた。内外の環境変化や組織の成熟度とともにその組織構成も徐々に変えてきているが、その中でも「挑戦する、何度でも。」のValueを体現すべく、主に組織横断的に取り組んできた事例について紹介する。また、今後のWFSのエンジニアリングの展望についても一部紹介する。" slideUrl = "" movieUrl = "" speakers = SizedCollection(SPEAKER_01) tags = SizedCollection(TAG_WFS, TAG_ORGANIZATION, TAG_INFRASTRUCTURE) } val SESSION_02 = DatabaseFactory.upsert(Session.Companion, 2) { startTime = 1574157622 endTime = 1574163622 title = "Lua過激派!WFSにおけるイベントスクリプト活用法 〜すべてはより良いコンテンツ制作のために〜" description = "kms : イベントスクリプト活用例\n" + "ららマジ : Excelでのアドベンチャーパート作成法と、改善案\n" + "UnityによるLua活用例 : 新規製作中のゲームにおけるスクリプトエンジンの進化と展望" slideUrl = "" movieUrl = "" speakers = SizedCollection(SPEAKER_02) tags = SizedCollection(TAG_WFS, TAG_GAMEENGINE, TAG_LUA, TAG_RPG) } val SESSION_03 = DatabaseFactory.upsert(Session.Companion, 3) { startTime = 1574157622 endTime = 1574163622 title = "バーチャルライブ配信アプリREALITYの3Dアバターシステムの全容について" description = "REALITYは、3Dアバターをパーツ毎にカスタマイズし、フェイストラッキングを適用し、音声・チャット・3Dバーチャルアイテムのギフティングを用いて視聴者とコミュニケーションをとることがスマホ1台でできる、バーチャルライブ配信アプリです。\n" + "そのREALITYにおける、3Dアバターシステムの全容について、「Unityにおける着せ替えの基本の仕組み」「OS別フェイストラッキングライブラリとアバターへの適用」「アップデートの歴史と対応してきた課題」の3テーマについて発表します。" slideUrl = "" movieUrl = "" speakers = SizedCollection(SPEAKER_03) tags = SizedCollection(TAG_UNITY, TAG_ANDROID, TAG_IOS) } val SESSION_04 = DatabaseFactory.upsert(Session.Companion, 4) { startTime = 1574157622 endTime = 1574163622 title = "REALITY低遅延モード配信を支えるリアルタイムサーバとデータパイプライン" description = "バーチャル配信アプリ「REALITY」の低遅延モード配信機能が2020年1月8日に正式リリースされました。\n" + "本機能の開発にあたり、「ラグなし・ギガ安・高画質」の配信・視聴体験を実現した上で、バックエンドのスケーラビリティと安定性を追求するために新規に構築したライブ配信基盤において、\n" + "その中核をなすふたつのコンポーネントである「コンテナベースのリアルタイムサーバ」と「Apache Beamによるストリーミングデータパイプライン」についてご紹介します。" slideUrl = "" movieUrl = "" speakers = SizedCollection(SPEAKER_04) tags = SizedCollection(TAG_LIVE, TAG_REALTIMESERVER, TAG_KUBERNETES, TAG_DATAPIPELINE, TAG_APACHEBEAM) } val SESSION_05 = DatabaseFactory.upsert(Session.Companion, 5) { startTime = 1574157622 endTime = 1574163622 title = "RealityStudio Motion Engineについて" description = "「連絡取れないですね」\n" + "時は年末、某開発スタジオ。\n" + "モーションキャプチャーを稼働させるために必要不可欠としてきたミドルウェアが突如サービス停止との一報が届く。\n" + "「リミットはあと3ヶ月か…」\n" + "サービス停止とは即ちキャプチャーシステムの停止である。\n" + "「ミドルウェアを独自開発するしかない」\n" + "ミドルウェアの多機能化、多すぎる設定項目見直し、高度に複雑化していく番組内容、さいげんなく増えていく端末管理、、、これらもまとめて解消したいという思い。\n" + "限られた時間に反するように項目だけが増えていく、、、\n" + "REALITY Studioが所持しているキャプチャーシステムの停止だけは絶対に阻止しなければならない。\n" + "そしてミドルウェア「REALITY Studio Motion Engine」は完成した。\n" + "そこで本日は「REALITY Studio Motion Engine」について紹介を致します。" slideUrl = "" movieUrl = "" speakers = SizedCollection(SPEAKER_05, SPEAKER_06) tags = SizedCollection(TAG_UNITY, TAG_UNREALENGINE4, TAG_MOTIONCAPTURE, TAG_WFLE) } val SESSION_06 = DatabaseFactory.upsert(Session.Companion, 6) { startTime = 1574157622 endTime = 1574163622 title = "大規模タイトルの長期運営におけるエンジニアリング的工夫 - ソーシャルアプリで世界と人を変える為にエンジニアが出来るコト -" description = "設立から10年を越え、数々のHitタイトルに恵まれ弊社ポケラボには様々なエンジニアリングノウハウが蓄積されております。過去, 運用中のタイトルで行った様々な工夫を今回ご紹介させて頂きます。" slideUrl = "" movieUrl = "" speakers = SizedCollection(SPEAKER_07) tags = SizedCollection(TAG_PHP, TAG_OPERATION) } val SESSION_07 = DatabaseFactory.upsert(Session.Companion, 7) { startTime = 1574157622 endTime = 1574163622 title = "長寿タイトルの運営の歴史" description = "10年もの歴史を刻んできたソーシャルゲーム内製タイトルを運用しつづけている私たち。技術的な観点において、10年の道のりは平坦ではなかった。歴史あるレガシーアプリケーションに対し、私たちが直面した問題とそれをどう乗り越えたかを紹介する。また、今後さらに長期間運用を続ける上で現在抱えている課題や、生き残り続けるための展望も一部紹介する。" slideUrl = "" movieUrl = "" speakers = SizedCollection(SPEAKER_08) tags = SizedCollection(TAG_SOCIALGAME, TAG_LAMP, TAG_LONGHIT, TAG_LONGTERM, TAG_LEGACY) } val SESSION_08 = DatabaseFactory.upsert(Session.Companion, 8) { startTime = 1574157622 endTime = 1574163622 title = "モバイルゲーム。移管と運営のエンジニア" description = "ファンプレックス株式会社ではモバイルゲーム運営事業を行っています。\n" + "ゲーム運営のプロフェッショナルとして、開発会社からゲームタイトルを移管し運営を行う上で必要な事・ファンプレックスが大事にしていることをエンジニア視点にて紹介させていただきます。" slideUrl = "" movieUrl = "" speakers = SizedCollection(SPEAKER_09) tags = SizedCollection( TAG_SOCIALGAME, TAG_MOBILEGAME, TAG_DEVELOPMENT, TAG_MIGRATION, TAG_RUN, TAG_ENGINEER, TAG_ENGINEERING ) } val SESSION_09 = DatabaseFactory.upsert(Session.Companion, 9) { startTime = 1574157622 endTime = 1574163622 title = "NuxtJS + REST APIで運用中サービスをNuxt.js + GraphQLに変更したことによる光と影" description = "アウモ株式会社では記事メディア「aumo」だけではなく、横断比較できるサービスの開発を行なっています。\n" + "REST APIで実装していたところを一部サービスについては全面的にGraphQLに書き換えを行い、そこで得た知見について紹介します。" slideUrl = "" movieUrl = "" speakers = SizedCollection(SPEAKER_10) tags = SizedCollection(TAG_FRONTEND, TAG_VUEJS, TAG_NUXTJS, TAG_GRAPHQL) } val SESSION_10 = DatabaseFactory.upsert(Session.Companion, 10) { startTime = 1574157622 endTime = 1574163622 title = "LIMIAアプリにおける行動履歴を用いたコンテンツ配信の最適化" description = "「おてがる工夫で家事上手」をコンセプトにした、家事情報のアプリ「LIMIA」では、毎日ユーザーさんに楽しんでもらうために、様々なコンテンツを配信しています。ユーザーさんに喜ばれるコンテンツを配信するためには、ユーザーさんのアプリ内の行動を正しく知る必要があります。\n" + "このセッションでは、アプリ内でユーザーさんがどのようなコンテンツに興味を持ったのかをトラッキングする仕組みから、実際にそのトラッキングデータを元にユーザーに最適なコンテンツの配信するシステムまでを紹介します。\n" + "具体的には、アプリ内でのユーザーのトラッキングに関しては、コンテンツのvCTRを計測するライブラリの開発、Firebase Analyticsを利用したイベント送信についてを、\n" + "コンテンツの配信システムに関しては、配信するコンテンツを決めるレコメンド処理のパイプラインの紹介、実際の業務でどうやってレコメンドの改善を行うかについてお話しします。\n" slideUrl = "" movieUrl = "" speakers = SizedCollection(SPEAKER_11, SPEAKER_12) tags = SizedCollection( TAG_FIREBASE, TAG_BIGQUERY, TAG_NATIVEAPP, TAG_IOS, TAG_ANDROID, TAG_MACHINELEANING, TAG_AWS ) } val SESSION_11 = DatabaseFactory.upsert(Session.Companion, 11) { startTime = 1574157622 endTime = 1574163622 title = "ホストベースからコンテナベースへのワークロード移行に求められるインフラエンジニアの役割" description = "オンプレミス時代、クラウド活用時代、クラウドネイティブ時代といった Web技術の変遷に伴い、グリーグループのサービスを提供するインフラは変化を続けています。インフラ部門のアプリケーション開発サイドに向き合うチームとして、ゲームタイトルのリリースと運用に関わってきた経験を元に、急激な変化を続けているインフラエンジニアの役割と課題について発表します。" slideUrl = "" movieUrl = "" speakers = SizedCollection(SPEAKER_13) tags = SizedCollection(TAG_DEVOPS, TAG_ORGANIZATION, TAG_INFRA, TAG_AWS, TAG_GCP, TAG_KUBERNETES) } val SESSION_12 = DatabaseFactory.upsert(Session.Companion, 12) { startTime = 1574157622 endTime = 1574163622 title = "任意話者間声質変換の研究開発" description = "任意の話者から任意の話者への声質変換をニューラルネットを用いて実装する。特に入力話者に関して事前に発話が入手できず、対象話者の音声サンプルが1発話しかない場合でも動作するように学習の設定を工夫する。" slideUrl = "" movieUrl = "" speakers = SizedCollection(SPEAKER_14) tags = SizedCollection(TAG_DEEPLEARNING, TAG_VOICECONVERSION) } val ARTICLE_01 = DatabaseFactory.upsert(Article.Companion, 1) { title = "GREE Tech Conference 2020 公式アプリをダウンロードいただきありがとうございます。" description = "GREE Tech Conference 2020 公式アプリへようこそ。" + "セッションをブックマークすることでマイスケジュールが作成できます。" + "アプリを活用して GREE Tech Conference 2020 をお楽しみください。" + "プライバシーポリシー" + "https://techcon.gree.jp/xxxx" + "利用規約" + "https://techcon.gree.jp/xxxx" publishedAt = 1574157622 } val ARTICLE_02 = DatabaseFactory.upsert(Article.Companion, 2) { title = "ブース情報追加しました" description = "" publishedAt = 1574157622 } val ARTICLE_03 = DatabaseFactory.upsert(Article.Companion, 3) { title = "いよいよ今週末です" description = "いよいよ今週末です" publishedAt = 1574157622 } val TRACK_01 = DatabaseFactory.upsert(Track.Companion, 1) { trackName = "メイン" sessions = SizedCollection(SESSION_01, SESSION_02) } val TRACK_02 = DatabaseFactory.upsert(Track.Companion, 2) { trackName = "ショートトラック" sessions = SizedCollection(SESSION_03) } val BOOTH_01 = DatabaseFactory.upsert(Booth.Companion, 1) { title = "コーヒースタンド" description = "無料のコーヒーが置いてあります" } val BOOTH_02 = DatabaseFactory.upsert(Booth.Companion, 2) { title = "Make部" description = "グリーグループの有志で作ったガジェットを展示します。" } val BOOTH_03 = DatabaseFactory.upsert(Booth.Companion, 3) { title = "技術書典部" description = "グリーグループの有志で作った技術書を頒布します。" } val BOOKMARK_01 = DatabaseFactory.upsert(Bookmark.Companion, 1) { firebaseUid = "1111-1111-1111-1111" session = SESSION_01 } val BOOKMARK_02 = DatabaseFactory.upsert(Bookmark.Companion, 2) { firebaseUid = "2222-2222-2222-2222" session = SESSION_02 } val BOOKMARK_03 = DatabaseFactory.upsert(Bookmark.Companion, 2) { firebaseUid = "2222-2222-2222-2222" session = SESSION_03 } } } }
1
Kotlin
0
0
da8d30a38e4e9f97c1dbcf97427a751de3ac4638
22,633
techcon-app
MIT License
core/models/src/commonMain/kotlin/ly/david/musicsearch/core/models/artist/CollaboratingArtistAndRecording.kt
lydavid
458,021,427
false
{"HTML": 1735273, "Kotlin": 1608241, "Swift": 4205, "Python": 3527, "Shell": 1541, "Ruby": 955}
package ly.david.musicsearch.core.models.artist data class CollaboratingArtistAndRecording( val artistId: String, val artistName: String, val recordingId: String, val recordingName: String, )
102
HTML
0
22
94228bfad5473e3a3d86c1f3b8273689df7a4421
209
MusicSearch
Apache License 2.0
graph/graph-core-model/src/main/kotlin/org/orkg/graph/domain/PredicateUsageCount.kt
TIBHannover
197,416,205
false
{"Kotlin": 2966676, "Cypher": 216833, "Python": 4881, "Groovy": 1936, "Shell": 1803, "HTML": 240}
package org.orkg.graph.domain import org.orkg.common.ThingId data class PredicateUsageCount( val id: ThingId, val count: Long )
0
Kotlin
1
5
f9de52bdf498fdc200e7f655a52cecff215c1949
138
orkg-backend
MIT License
server/src/test/kotlin/com/tomaszezula/makker/server/SetModuleDataV1Test.kt
zezutom
521,502,658
false
null
package com.tomaszezula.makker.server import com.tomaszezula.makker.common.MakeAdapter import com.tomaszezula.makker.common.model.Blueprint import com.tomaszezula.makker.common.model.Scenario import com.tomaszezula.makker.common.model.SetModuleDataContext import com.tomaszezula.makker.common.model.UpdateResult import com.tomaszezula.makker.server.model.RequestContext import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.server.testing.* import io.mockk.every import io.mockk.mockk import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import kotlin.test.Test import kotlin.test.assertEquals class SetModuleDataV1Test { @Test fun success() { asAnonymous { setModuleData(it) } } @Test fun successAuthenticated() { asAuthenticated { setModuleData(it) } } @Test fun failure() { asAnonymous { setModuleData(it, false) } } @Test fun failureAuthenticated() { asAuthenticated { setModuleData(it, false) } } private fun setModuleData(requestContext: RequestContext, shouldSucceed: Boolean = true) = testApplication { val makeAdapter = mockk<MakeAdapter>() val scenarioId = Scenario.Id(1) val moduleId = Blueprint.Module.Id(1) val key = "json" val value = "{}" val result = result(UpdateResult.Success, shouldSucceed) every { runBlocking { makeAdapter.setModuleData(key, value, SetModuleDataContext(authToken, scenarioId, moduleId)) } } returns result withApplication(makeAdapter, requestContext) val response = client.put("/v1/scenarios/${scenarioId.value}/data") { setHeaders() setBody(buildJsonObject { put("modules", buildJsonArray { add(buildJsonObject { put("moduleId", moduleId.value) put("key", key) put("value", value) }) }) }.toString()) } if (shouldSucceed) { assertEquals(HttpStatusCode.OK, response.status) assertEquals( """ {"result":true} """.trim(), response.bodyAsText() ) } else { assertFailure(response, result, "Operation failed for one or more fields.") } } }
1
Kotlin
1
0
b6fb828fe9f57e09980d010fb6abb3562b760e18
2,588
makker
MIT License
simplesettings/src/main/java/com/chillibits/simplesettings/core/elements/PreferenceHeader.kt
marcauberer
263,408,016
false
null
package com.chillibits.simplesettings.core.elements import android.content.Context import androidx.annotation.LayoutRes /** * Page element for page headers / setting screen headers. * More information: https://github.com/marcauberer/simple-settings/wiki/PreferenceHeader */ class PreferenceHeader( context: Context, iconSpaceReservedByDefault: Boolean ): PreferenceElement(context, iconSpaceReservedByDefault) { // Attributes @LayoutRes var layoutResource: Int? = null }
10
Kotlin
6
35
ee00a389dbc0dccfb3e1000ac8248535765fd806
504
simple-settings
MIT License
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/TLMessageMediaUnsupported.kt
Miha-x64
436,587,061
true
{"Kotlin": 3919807, "Java": 75352}
package com.github.badoualy.telegram.tl.api /** * messageMediaUnsupported#9f84f49e * * @author <NAME> <EMAIL> * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ class TLMessageMediaUnsupported : TLAbsMessageMedia() { private val _constructor: String = "messageMediaUnsupported#9f84f49e" override val constructorId: Int = CONSTRUCTOR_ID override fun toString() = _constructor override fun equals(other: Any?): Boolean { if (other !is TLMessageMediaUnsupported) return false if (other === this) return true return true } companion object { const val CONSTRUCTOR_ID: Int = 0x9f84f49e.toInt() } }
1
Kotlin
2
3
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
711
kotlogram-resurrected
MIT License
commands/src/main/kotlin/tech/carcadex/kotlinbukkitkit/commands/exceptions/LeafCommandHasNotExecutorException.kt
CarcadeX
681,093,300
false
{"Kotlin": 301127, "Java": 26805}
package tech.carcadex.kotlinbukkitkit.commands.exceptions class LeafCommandHasNotExecutorException(commandName: String) : IllegalArgumentException("Command $commandName has not subcommands or default executor!") { }
0
Kotlin
1
2
95edc90da4b6d703e46ef589dbcfbc58b16bff46
220
KotlinBukkitKIT
MIT License
android/app-newm/src/main/java/io/newm/screens/profile/view/ProfileReadOnlyViewModel.kt
projectNEWM
435,674,758
false
{"Kotlin": 326567, "Swift": 233616}
package io.newm.screens.profile.view import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import co.touchlab.kermit.Logger import io.newm.Logout import io.newm.shared.public.models.User import io.newm.shared.public.usecases.UserProfileUseCase import io.newm.shared.public.usecases.ConnectWalletUseCase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch class ProfileReadOnlyViewModel( private val userProviderUserCase: UserProfileUseCase, private val connectWalletUseCase: ConnectWalletUseCase, private val logout: Logout ) : ViewModel() { private var _state = MutableStateFlow<ProfileViewState>(ProfileViewState.Loading) val state: StateFlow<ProfileViewState> get() = _state.asStateFlow() init { println("NewmAndroid - ProfileViewModel") viewModelScope.launch { val user = userProviderUserCase.getCurrentUser() Logger.d { "NewmAndroid - ProfileViewModel user: $user" } _state.value = ProfileViewState .Content( profile = user, isWalletConnected = connectWalletUseCase.isConnected() ) } } fun logout() { viewModelScope.launch(Dispatchers.IO) { logout.call() } } fun disconnectWallet() { viewModelScope.launch(Dispatchers.IO) { connectWalletUseCase.disconnect() _state.value = ProfileViewState .Content( profile = (state.value as ProfileViewState.Content).profile, isWalletConnected = false ) } } fun connectWallet(xpubKey: String) { viewModelScope.launch(Dispatchers.IO) { connectWalletUseCase.connect(xpubKey) _state.value = ProfileViewState .Content( profile = (state.value as ProfileViewState.Content).profile, isWalletConnected = true ) } } } sealed class ProfileViewState { object Loading : ProfileViewState() data class Content(val profile: User, val isWalletConnected: Boolean) : ProfileViewState() }
1
Kotlin
8
9
98b9e2d2dfe9ce29d53cf31f73a5a0172f742717
2,344
newm-mobile
Apache License 2.0
src/test/kotlin/com/jacobhyphenated/advent2022/day8/Day8Test.kt
jacobhyphenated
573,603,184
false
null
package com.jacobhyphenated.advent2022.day8 import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day8Test { @Test fun testPart1() { val input = """ 30373 25512 65332 33549 35390 """.trimIndent() .lines() .map { line -> line.toCharArray().map { it.digitToInt() } } val day = Day8() assertEquals(21, day.part1(input)) } @Test fun testPart2() { val input = """ 30373 25512 65332 33549 35390 """.trimIndent() .lines() .map { line -> line.toCharArray().map { it.digitToInt() } } val day = Day8() assertEquals(8, day.part2(input)) } }
0
Kotlin
0
0
9f4527ee2655fedf159d91c3d7ff1fac7e9830f7
810
advent2022
The Unlicense
src/test/kotlin/com/jacobhyphenated/advent2022/day8/Day8Test.kt
jacobhyphenated
573,603,184
false
null
package com.jacobhyphenated.advent2022.day8 import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day8Test { @Test fun testPart1() { val input = """ 30373 25512 65332 33549 35390 """.trimIndent() .lines() .map { line -> line.toCharArray().map { it.digitToInt() } } val day = Day8() assertEquals(21, day.part1(input)) } @Test fun testPart2() { val input = """ 30373 25512 65332 33549 35390 """.trimIndent() .lines() .map { line -> line.toCharArray().map { it.digitToInt() } } val day = Day8() assertEquals(8, day.part2(input)) } }
0
Kotlin
0
0
9f4527ee2655fedf159d91c3d7ff1fac7e9830f7
810
advent2022
The Unlicense
oop-lab-1/CanonicBook.kt
stonefacead
695,912,890
false
{"Kotlin": 14858}
class CanonicBook(bname: String, year: String, author : String) : Book(bname, year, author) { override var canonicity = CanonicEnums.CANONIC override var annotation = "$name is a canonic book written by $author and published in year $year. Book includes this characters: " override fun showBookData() { println(annotation) printCharacters() } }
0
Kotlin
0
0
2d7c36c56c72758bc273c5a47fd5a3559cc6f1ba
377
university-stuff
MIT License
secdra-data/src/main/kotlin/com/junjie/secdradata/database/collect/entity/PixivError.kt
fuzeongit
154,359,683
false
null
package com.junjie.secdradata.database.collect.entity import com.junjie.secdradata.database.base.BaseEntity import org.hibernate.annotations.GenericGenerator import org.springframework.data.annotation.CreatedDate import org.springframework.data.annotation.LastModifiedDate import org.springframework.data.jpa.domain.support.AuditingEntityListener import java.io.Serializable import java.util.* import javax.persistence.* @Entity @EntityListeners(AuditingEntityListener::class) @Table(name = "pixiv_error") class PixivError() : BaseEntity(), Serializable { @Column(name = "pixiv_id", length = 32) lateinit var pixivId: String @Column(name = "status") var status: Int? = null @Column(columnDefinition = "text") var message: String? = null @Column(name = "record") var record: Boolean = false constructor(pixivId: String, status: Int, message: String?) : this() { this.pixivId = pixivId this.status = status this.message = message } }
1
Kotlin
4
11
f75c32e5fb834d456a3182f71aee08029a1629d3
1,001
secdra
MIT License
src/main/kotlin/ch/icken/csvtoolkit/transform/condition/AndCondition.kt
Thijsiez
369,554,595
false
{"Kotlin": 306396}
package ch.icken.csvtoolkit.transform.condition import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.VerticalScrollbar import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollbarAdapter import androidx.compose.material.DropdownMenu import androidx.compose.material.DropdownMenuItem import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.window.rememberDialogState import ch.icken.csvtoolkit.flatMapToSet import ch.icken.csvtoolkit.transform.EditDialog import ch.icken.csvtoolkit.transform.Transform.ConditionFosterParent import ch.icken.csvtoolkit.transform.Transform.ConditionParentTransform import ch.icken.csvtoolkit.transform.condition.AndCondition.AndSerializer import ch.icken.csvtoolkit.transform.condition.Condition.ConditionParent import ch.icken.csvtoolkit.ui.Confirmation import ch.icken.csvtoolkit.ui.DeleteConditionConfirmation import ch.icken.csvtoolkit.ui.reorderableItemModifier import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import org.burnoutcrew.reorderable.move import org.burnoutcrew.reorderable.rememberReorderState import org.burnoutcrew.reorderable.reorderable @Serializable(with = AndSerializer::class) class AndCondition( override val parentTransform: ConditionParentTransform, override val parentCondition: ConditionParent? ) : ConditionParent(), ConditionCustomItemView { override val description get() = buildAnnotatedString { append("All of the following") } override val surrogate get() = AndSurrogate(conditions) override val usesFiles get() = conditions.flatMapToSet { it.usesFiles } constructor(surrogate: AndSurrogate) : this(ConditionFosterParent, null) { conditions.addAll(surrogate.conditions) } override suspend fun prepareChecks() = conditions.all { it.prepareChecks() } override fun check(row: Map<String, String>) = conditions.all { it.check(row) } override fun isValid(context: Context): Boolean { if (!conditions.all { it.isValid(context) }) { invalidMessage = "One or more conditions are invalid" return false } return true } @OptIn(ExperimentalFoundationApi::class) @Composable override fun CustomItemView( context: Context, onEditCondition: (Condition) -> Unit, modifier: Modifier ) { Column( modifier = modifier .clickable( enabled = context.allowChanges, onClick = { onEditCondition(this) } ) .fillMaxWidth() .padding(start = 16.dp) ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = description, modifier = Modifier.weight(1f) .padding(vertical = 8.dp), style = MaterialTheme.typography.body1 ) Row( modifier = Modifier.requiredHeight(48.dp) .padding(horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically ) { DefaultConditionStateContent(context, this@AndCondition) } } if (conditions.isEmpty()) { Box( modifier = Modifier.fillMaxWidth() .height(48.dp) .padding(start = 16.dp), contentAlignment = Alignment.CenterStart ) { Text("None") } } else { conditions.forEach { ConditionItemView( context = context, condition = it, onEditCondition = onEditCondition ) } } } } @Composable override fun Dialog( context: Context, onHide: () -> Unit, onDelete: () -> Unit ) { var expanded by remember { mutableStateOf(false) } val reorderState = rememberReorderState() var showEditConditionDialogFor: Condition? by remember { mutableStateOf(null) } var showConfirmationDialogFor: Confirmation? by remember { mutableStateOf(null) } EditDialog( titleText = "And", onHide = onHide, onDelete = onDelete, state = rememberDialogState( size = DpSize(360.dp, Dp.Unspecified) ) ) { Column( modifier = Modifier.fillMaxWidth() .height(320.dp), verticalArrangement = Arrangement.spacedBy(4.dp) ) { Text( text = "Conditions", fontWeight = FontWeight.Bold ) Box( modifier = Modifier.weight(1f) ) { LazyColumn( modifier = Modifier.reorderable( state = reorderState, onMove = { from, to -> conditions.move(from.index, to.index) } ), state = reorderState.listState ) { items(conditions, { it }) { condition -> ConditionItemView( context = context, condition = condition, onEditCondition = { showEditConditionDialogFor = it }, modifier = Modifier.reorderableItemModifier(reorderState, condition) ) } } VerticalScrollbar( adapter = rememberScrollbarAdapter(reorderState.listState), modifier = Modifier.align(Alignment.CenterEnd) ) } Box { TextButton( onClick = { expanded = true } ) { Text("ADD CONDITION") } DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false } ) { Type.values().forEach { DropdownMenuItem( onClick = { val condition = it.create(parentTransform, this@AndCondition) conditions.add(condition) showEditConditionDialogFor = condition expanded = false } ) { Text(it.uiName) } } } } } } showEditConditionDialogFor?.let { condition -> condition.Dialog( context = context, onHide = { showEditConditionDialogFor = null }, onDelete = { showConfirmationDialogFor = DeleteConditionConfirmation( condition = condition, onHide = { showConfirmationDialogFor = null } ) } ) } showConfirmationDialogFor?.Dialog() } @Serializable @SerialName("and") class AndSurrogate( override val conditions: List<Condition> ) : ConditionParentSurrogate object AndSerializer : KSerializer<AndCondition> { override val descriptor = AndSurrogate.serializer().descriptor override fun serialize(encoder: Encoder, value: AndCondition) { encoder.encodeSerializableValue(AndSurrogate.serializer(), value.surrogate) } override fun deserialize(decoder: Decoder): AndCondition { return AndCondition(decoder.decodeSerializableValue(AndSurrogate.serializer())) } } override fun postDeserialization(context: Context) { conditions.forEach { it.postDeserialization(context) } } override fun adopt(parentTransform: ConditionParentTransform, parentCondition: ConditionParent?): Condition { return AndCondition(parentTransform, parentCondition).also { copy -> copy.conditions.addAll(conditions.map { it.adopt(parentTransform, this) }) } } }
0
Kotlin
0
1
086741bddea99b8377065c73762a9629559ca605
10,128
csvtoolkit
The Unlicense
library/src/test/java/library/view/lib/NetStatusViewCustomizedPropertiesUnitTest.kt
XinyueZ
118,283,171
false
null
package library.view.lib import androidx.core.content.res.ResourcesCompat import io.kotlintest.properties.Gen import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(shadows = [(ShadowSignalStrength::class)]) class NetStatusViewCustomizedPropertiesUnitTest : AbstractNetStatusViewUnitTest() { override fun config(netStatusView: NetStatusView) { with(context()) { with(netStatusView) { setUp( R.array.ic_net_strength_levels.apply { netStrengthLevelRes = this }, ResourcesCompat.getColor( resources, R.color.ns_view_text_color, null ).apply { [email protected] = this }, R.dimen.ns_view_text_size.apply { [email protected] = this }, R.string.net_status_wifi.apply { netWifi = getString(this) }, R.string.net_status_2g.apply { net2g = getString(this) }, R.string.net_status_3g.apply { net3g = getString(this) }, R.string.net_status_4g.apply { net4g = getString(this) }, R.string.net_status_unknown.apply { netUnknown = getString(this) } ) } } } @Test fun testStrengthLevelResShouldNotBeNull() { with(context()) { with(netStatusView) { assertNotNull(netStrengthLevelResIds) } } } @Test fun test2G_HaveNetworkTypeAndStrength() { val cellStrength = Gen.choose(0, 3).generate() with(context()) { with(netStatusView) { withNetworkTest( false, true, false, FULL_LIST_OF_NET_2G, cellStrength ) { // net's type assertEquals( net2g, getNetworkStatus().type ) // net's strength assertEquals( cellStrength, getNetworkStatus().strength ) } } } } @Test fun test3G_HaveNetworkTypeAndStrength() { val cellStrength = Gen.choose(0, 3).generate() with(context()) { with(netStatusView) { withNetworkTest( false, true, false, FULL_LIST_OF_NET_3G, cellStrength ) { // net's type assertEquals( net3g, getNetworkStatus().type ) // net's strength assertEquals( cellStrength, getNetworkStatus().strength ) } } } } @Test fun test4G_HaveNetworkTypeAndStrength() { val cellStrength = Gen.choose(0, 3).generate() with(context()) { with(netStatusView) { withNetworkTest( false, true, false, FULL_LIST_OF_NET_4G, cellStrength ) { // net's type assertEquals( net4g, getNetworkStatus().type ) // net's strength assertEquals( cellStrength, getNetworkStatus().strength ) } } } } }
0
Kotlin
0
1
2f97bfb2f2d3bf1dee79803ecd2cc62bca8b3267
4,154
net-status-view
The Unlicense
build-logic/src/main/kotlin/batect/dockerclient/buildtools/formatting/FormattingConventionPlugin.kt
batect
401,175,530
false
{"Kotlin": 691076, "Go": 150124, "C": 61485, "Shell": 8058, "Dockerfile": 3979}
/* Copyright 2017-2022 <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 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 batect.dockerclient.buildtools.formatting import com.diffplug.gradle.spotless.SpotlessExtension import com.diffplug.gradle.spotless.SpotlessPlugin import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.artifacts.VersionCatalogsExtension import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.getByType import java.nio.file.Files class FormattingConventionPlugin : Plugin<Project> { override fun apply(target: Project) { applySpotless(target) configureSpotless(target) } private fun applySpotless(target: Project) { target.plugins.apply(SpotlessPlugin::class.java) } private fun configureSpotless(target: Project) { val licenseText = Files.readString(target.rootProject.projectDir.resolve("gradle").resolve("license.txt").toPath())!! val isKotlinProject = target.plugins.hasPlugin("org.jetbrains.kotlin.multiplatform") val kotlinLicenseHeader = "/*\n${licenseText.trimEnd().lines().joinToString("\n") { " $it".trimEnd() }}\n*/\n\n" val ktlintVersion = getKtlintVersion(target) target.configure<SpotlessExtension> { encoding("UTF-8") kotlinGradle { it.ktlint(ktlintVersion) .setEditorConfigPath(target.rootProject.file(".editorconfig")) .editorConfigOverride(mapOf("max_line_length" to "285")) // ktlint doesn't seem to respect the value set in .editorconfig it.licenseHeader(kotlinLicenseHeader, "plugins|rootProject|import") } if (isKotlinProject) { kotlin { it.target(target.fileTree("src").include("**/*.kt")) it.ktlint(ktlintVersion) .setEditorConfigPath(target.rootProject.file(".editorconfig")) .editorConfigOverride(mapOf("max_line_length" to "285")) // ktlint doesn't seem to respect the value set in .editorconfig it.licenseHeader(kotlinLicenseHeader, "package |@file|// AUTOGENERATED") it.endWithNewline() } } } } private fun getKtlintVersion(target: Project): String { val catalogs = target.extensions.getByType<VersionCatalogsExtension>() val libs = catalogs.named("libs") return libs.findVersion("ktlint").get().requiredVersion } }
5
Kotlin
0
9
a78b8c7c80500848fa4aae460557947ceea5a6d5
3,028
docker-client
Apache License 2.0
app/src/main/java/com/example/plantcareai/dashboard/Plant.kt
mmweru
778,368,746
false
{"Kotlin": 172718}
package com.example.plantcareai.dashboard data class Plant(val imageId: Int, val name: String)
2
Kotlin
0
0
03aec21802286934f690b6a6564a2aba0d9fd3fe
96
PlantCare
MIT License
sunrise-sunset-org/src/main/java/dev/drewhamilton/skylight/sunrise_sunset_org/network/ApiConstants.kt
drewhamilton
165,543,758
false
null
package dev.drewhamilton.skylight.sunrise_sunset_org.network internal object ApiConstants { internal const val BASE_URL = "https://api.sunrise-sunset.org/" internal const val DATE_TIME_NONE = "1970-01-01T00:00:00+00:00" internal const val DATE_TIME_ALWAYS_DAY = "1970-01-01T00:00:01+00:00" }
1
Kotlin
0
2
7cc77a889afff7c3a9d2f0ac09f7cd271b850813
307
Skylight
Apache License 2.0
app/src/main/java/com/example/nifasku/deskripsiA/DescNutrisi.kt
mochasep
213,590,667
false
null
package com.example.nifasku.deskripsiA import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import com.example.nifasku.OnClickRuleListener import com.example.nifasku.R import com.example.nifasku.RuleAdapter import com.example.nifasku.RuleContent import kotlinx.android.synthetic.main.activity_desc_mobilisasi_dini.* class DescNutrisi : AppCompatActivity(), OnClickRuleListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_desc_nutrisi) setComponentListener() } override fun onClick(position: Int) { // Toast.makeText(applicationContext, "Rule Clicked", Toast.LENGTH_LONG).show() } private fun setComponentListener() { val ruleData = arrayListOf( RuleContent("", resources.getString(R.string.nutrisi_pertama), null, "nutrisi_1.png"), RuleContent("", resources.getString(R.string.nutrisi_kedua), null, "nutrisi_2.png"), RuleContent("", resources.getString(R.string.nutrisi_ketiga), null, "nutrisi_3.png"), RuleContent("", resources.getString(R.string.nutrisi_keempat), null, "nutrisi_4.png"), RuleContent("", resources.getString(R.string.nutrisi_kelima), null, "nutrisi_5.png"), RuleContent("", resources.getString(R.string.nutrisi_keenam), null, "nutrisi_6.png") ) rule_list.apply { layoutManager = LinearLayoutManager(applicationContext) adapter = RuleAdapter( applicationContext, ruleData, this@DescNutrisi ) } } }
0
Kotlin
0
0
837d5ef6d7c2d3d658ab10d31d6a0980756afe1e
1,717
Nifasku
MIT License
rtron-transformer/src/main/kotlin/io/rtron/transformer/modifiers/opendrive/remover/OpendriveObjectRemoverParameters.kt
tum-gis
258,142,903
false
{"Kotlin": 1490806, "C": 12590, "Dockerfile": 511, "CMake": 399, "Shell": 99}
/* * Copyright 2019-2024 Chair of Geoinformatics, Technical University of Munich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.rtron.transformer.modifiers.opendrive.remover import io.rtron.model.opendrive.objects.EObjectType import kotlinx.serialization.Serializable @Serializable data class OpendriveObjectRemoverParameters( /** remove road objects without type */ val removeRoadObjectsWithoutType: Boolean, /** remove road objects of type */ val removeRoadObjectsOfTypes: Set<EObjectType>, ) { companion object { val DEFAULT_REMOVE_ROAD_OBJECTS_WITHOUT_TYPE = false val DEFAULT_REMOVE_ROAD_OBJECTS_OF_TYPES = emptySet<EObjectType>() } }
7
Kotlin
12
46
6add55fcd0836a2bd14622d3fd55e6f9e8902056
1,210
rtron
Apache License 2.0
net/craftventure/audioserver/packet/PacketReload.kt
Craftventure
770,049,457
false
{"Kotlin": 3656616, "Java": 684034}
package net.craftventure.audioserver.packet import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class PacketReload : BasePacket(PacketID.RELOAD)
0
Kotlin
1
21
015687ff6687160835deacda57121480f542531b
165
open-plugin-parts
MIT License
app/src/main/java/com/example/recyclerview_with_video_images/viewModels/viewTrailerViewModel.kt
kennedylinzie
626,782,906
false
null
package com.example.recyclerview_with_video_images.viewModels import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class viewTrailerViewModel : ViewModel() { private val _video = MutableLiveData<String>() val video: LiveData<String> = _video fun setVideo(video: String) { _video.value = video } }
0
Kotlin
0
0
738177f93f25a0a782c6ba5730c7dbc37753c42e
383
RecyclerView_with_video_images_mvvm
MIT License
app/src/main/kotlin/me/zhiyao/waterever/ui/tag/TagsActivity.kt
WangZhiYao
243,558,800
false
null
package me.zhiyao.waterever.ui.tag import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.activity.viewModels import androidx.recyclerview.widget.LinearLayoutManager import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.input.input import dagger.hilt.android.AndroidEntryPoint import me.zhiyao.waterever.R import me.zhiyao.waterever.data.db.model.Tag import me.zhiyao.waterever.databinding.ActivityTagsBinding import me.zhiyao.waterever.exts.showSnackBar import me.zhiyao.waterever.ui.base.BaseActivity import me.zhiyao.waterever.ui.tag.adapter.TagAdapter /** * * @author WangZhiYao * @date 2020/8/27 */ @AndroidEntryPoint class TagsActivity : BaseActivity(), TagAdapter.OnItemLongClickListener { private lateinit var binding: ActivityTagsBinding private val viewModel by viewModels<TagsViewModel>() private lateinit var adapter: TagAdapter companion object { fun start(context: Context) { val intent = Intent(context, TagsActivity::class.java) context.startActivity(intent) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityTagsBinding.inflate(layoutInflater) setContentView(binding.root) initView() initData() } override fun showBack(): Boolean = true private fun initView() { binding.rvTags.layoutManager = LinearLayoutManager(this) adapter = TagAdapter() adapter.setOnItemLongClickListener(this) binding.rvTags.adapter = adapter } private fun initData() { viewModel.tags.observe(this, { tags -> adapter.setTags(tags) setSelectionMode(false) }) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_tags_new, menu) return true } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { menu?.clear() if (adapter.isSelectionMode()) { menuInflater.inflate(R.menu.menu_tags_edit, menu) } else { menuInflater.inflate(R.menu.menu_tags_new, menu) } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_tag_new -> { showNewTagDialog() true } R.id.menu_tag_delete -> { viewModel.deleteTags(adapter.getSelectedItem()) true } else -> super.onOptionsItemSelected(item) } } private fun showNewTagDialog() { MaterialDialog(this).show { title(R.string.dialog_tags_new) input(allowEmpty = false) { _, charSequence -> val tagName = charSequence.toString() if (adapter.isTagExist(tagName)) { binding.root.showSnackBar(R.string.tags_already_exist) } else { viewModel.addTag(Tag(tagName, System.currentTimeMillis())) } } positiveButton(R.string.dialog_tags_add) } } override fun onLongClicked() { if (!adapter.isSelectionMode()) { setSelectionMode(true) } } override fun onBackPressed() { if (adapter.isSelectionMode()) { setSelectionMode(false) return } else { super.onBackPressed() } } private fun setSelectionMode(isSelectionMode: Boolean) { adapter.setSelectionMode(isSelectionMode) invalidateOptionsMenu() } }
0
Kotlin
0
0
232f20d623209eb2b9fb889aeb05af6ec3fee535
3,769
WaterEver
Apache License 2.0
cinescout/details/presentation/src/main/kotlin/cinescout/details/presentation/sample/ScreenPlayRatingsUiModelSample.kt
fardavide
280,630,732
false
null
package cinescout.details.presentation.sample import cinescout.details.presentation.model.ScreenplayRatingsUiModel import cinescout.rating.domain.sample.ScreenplayPersonalRatingSample import cinescout.screenplay.domain.sample.ScreenplaySample internal object ScreenPlayRatingsUiModelSample { val BreakingBad = ScreenplayRatingsUiModel( publicAverage = ScreenplaySample.BreakingBad.rating.average.value.toString(), publicCount = ScreenplaySample.BreakingBad.rating.voteCount.toString(), personal = ScreenplayPersonalRatingSample.BreakingBad.toOption().fold( ifEmpty = { ScreenplayRatingsUiModel.Personal.NotRated }, ifSome = { rating -> ScreenplayRatingsUiModel.Personal.Rated( rating = rating, stringValue = rating.value.toInt().toString() ) } ) ) val Grimm = ScreenplayRatingsUiModel( publicAverage = ScreenplaySample.Grimm.rating.average.value.toString(), publicCount = ScreenplaySample.Grimm.rating.voteCount.toString(), personal = ScreenplayPersonalRatingSample.Grimm.toOption().fold( ifEmpty = { ScreenplayRatingsUiModel.Personal.NotRated }, ifSome = { rating -> ScreenplayRatingsUiModel.Personal.Rated( rating = rating, stringValue = rating.value.toInt().toString() ) } ) ) val Inception = ScreenplayRatingsUiModel( publicAverage = ScreenplaySample.Inception.rating.average.value.toString(), publicCount = ScreenplaySample.Inception.rating.voteCount.toString(), personal = ScreenplayPersonalRatingSample.Inception.toOption().fold( ifEmpty = { ScreenplayRatingsUiModel.Personal.NotRated }, ifSome = { rating -> ScreenplayRatingsUiModel.Personal.Rated( rating = rating, stringValue = rating.value.toInt().toString() ) } ) ) val TheWolfOfWallStreet = ScreenplayRatingsUiModel( publicAverage = ScreenplaySample.TheWolfOfWallStreet.rating.average.value.toString(), publicCount = ScreenplaySample.TheWolfOfWallStreet.rating.voteCount.toString(), personal = ScreenplayPersonalRatingSample.TheWolfOfWallStreet.toOption().fold( ifEmpty = { ScreenplayRatingsUiModel.Personal.NotRated }, ifSome = { rating -> ScreenplayRatingsUiModel.Personal.Rated( rating = rating, stringValue = rating.value.toInt().toString() ) } ) ) }
11
Kotlin
2
6
f2e3993816452afaf6c3f1e7c7a384eb9a66c06e
2,716
CineScout
Apache License 2.0
app/src/main/java/com/exorabeveragefsm/features/myjobs/api/MyJobRepoProvider.kt
DebashisINT
614,840,078
false
null
package com.exorabeveragefsm.features.myjobs.api import android.content.Context import android.net.Uri import android.util.Log import com.exorabeveragefsm.app.FileUtils import com.exorabeveragefsm.base.BaseResponse import com.exorabeveragefsm.features.activities.model.ActivityImage import com.exorabeveragefsm.features.activities.model.AddActivityInputModel import com.exorabeveragefsm.features.myjobs.model.WIPSubmit import com.fasterxml.jackson.databind.ObjectMapper import io.reactivex.Observable import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.RequestBody import java.io.File object MyJobRepoProvider { fun jobRepoProvider(): MyJobRepo { return MyJobRepo(MyJobApi.create()) } fun jobMultipartRepoProvider(): MyJobRepo { return MyJobRepo(MyJobApi.createMultiPart()) } }
0
Kotlin
0
0
4df01290a7f38cf9d446d5295c4733e30b827093
830
ExoraBeverage
Apache License 2.0
datasource-remote/src/main/java/cmm/apps/esmorga/datasource_remote/user/AuthRemoteDatasourceImpl.kt
cmm-apps-android
797,188,002
false
{"Kotlin": 296464}
package cmm.apps.esmorga.datasource_remote.user import android.content.SharedPreferences import cmm.apps.esmorga.data.user.datasource.AuthDatasource import cmm.apps.esmorga.datasource_remote.api.EsmorgaApi import cmm.apps.esmorga.datasource_remote.api.EsmorgaAuthApi import cmm.apps.esmorga.datasource_remote.api.authenticator.AuthorizationConstants.REFRESH_TOKEN_KEY import cmm.apps.esmorga.datasource_remote.api.authenticator.AuthorizationConstants.SHARED_AUTH_TOKEN_KEY import cmm.apps.esmorga.datasource_remote.api.authenticator.AuthorizationConstants.SHARED_REFRESH_TOKEN_KEY import cmm.apps.esmorga.datasource_remote.api.authenticator.AuthorizationConstants.SHARED_TTL class AuthRemoteDatasourceImpl( private val api: EsmorgaAuthApi, private val sharedPreferences: SharedPreferences ) : AuthDatasource { override suspend fun refreshTokens(refreshToken: String): String? { return try { val refreshedTokens = api.refreshAccessToken(mapOf(REFRESH_TOKEN_KEY to refreshToken)) sharedPreferences.edit().run { putString(SHARED_REFRESH_TOKEN_KEY, refreshedTokens.remoteRefreshToken) putString(SHARED_AUTH_TOKEN_KEY, refreshedTokens.remoteAccessToken) putLong(SHARED_TTL, System.currentTimeMillis() + refreshedTokens.ttl * 1000) }.apply() return refreshedTokens.remoteAccessToken } catch (e: Exception) { null } } }
0
Kotlin
0
0
3494b5bfaea0520855d8209aef504aec31b1895f
1,462
EsmorgaAndroid
The Unlicense
cachek_room/src/main/java/com/mozhimen/cachek/room/temps/CacheKRMVarPropertyInt.kt
mozhimen
762,721,622
false
{"Kotlin": 80928}
package com.mozhimen.cachek.room.temps import com.mozhimen.cachek.basic.bases.BaseCacheKVarPropertyInt import com.mozhimen.cachek.room.CacheKRM /** * @ClassName CacheKRMDelegateInt * @Description TODO * @Author Mozhimen & <NAME> * @Date 2023/3/13 15:17 * @Version 1.0 */ class CacheKRMVarPropertyInt( cacheKRMProvider: CacheKRM, key: String, default: Int = 0 ) : BaseCacheKVarPropertyInt<CacheKRM>(cacheKRMProvider, key, default)
0
Kotlin
0
0
268c1d08947b39f97271394a8cbf77895486224c
442
ACacheKit
Apache License 2.0
source/app/src/main/java/com/apion/apionhome/data/source/remote/UserRemoteDatasource.kt
ApionTech
386,238,144
false
null
package com.apion.apionhome.data.source.remote import com.apion.apionhome.data.model.User import com.apion.apionhome.data.source.UserDatasource import com.apion.apionhome.data.source.remote.utils.UserAPIService import com.apion.apionhome.utils.ApiEndPoint import com.google.gson.Gson import com.google.gson.JsonObject import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Maybe import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.HttpException import java.io.File import java.lang.Exception import java.lang.IllegalArgumentException import java.util.* class UserRemoteDatasource(private val backend: UserAPIService) : UserDatasource.Remote { override fun getAllUsers(): Maybe<List<User>> = backend.geUsers().map { it.users } override fun getUserById(id: Int): Maybe<User> = backend.geUserById(id).map { it.user } @Throws(IllegalArgumentException::class) override fun createUser(user: User): Maybe<User> { return try { backend.createUser(user).map { if (it.isSuccess) it.user else throw IllegalArgumentException(it.message) } } catch (exception: Exception) { Maybe.error(exception) } } @Throws(IllegalArgumentException::class) override fun updateUser(user: User): Maybe<User> { return try { backend.updateUser(user.id, user).map { if (it.isSuccess) it.user else throw IllegalArgumentException(it.message) } } catch (exception: Exception) { Maybe.error(exception) } } override fun uploadAvatar(id: Int, image: String): Maybe<User> { val file = File(image) return if (file.isFile) { val end = file.name.split(".").last() val currentTime = Date().time.toString() val fileName = "$currentTime.$end" val imageRequestBody = RequestBody.create(MediaType.parse("image/*"), file) val imagePart = MultipartBody.Part.createFormData( ApiEndPoint.PART_ATTACHMENT, fileName, imageRequestBody ) backend.uploadAvatar(id, imagePart).map { it.user } } else { Maybe.error(IllegalArgumentException("No such file $image")) } } @Throws(IllegalArgumentException::class) override fun login(phone: String, pinCode: String): Maybe<User> { val json = JsonObject().apply { addProperty("phone", phone) } val body = RequestBody.create( MediaType.parse("application/json; charset=utf-8"), Gson().toJson(json) ) return try { backend.login(body).map { if (it.isSuccess) { if (it.user.pincode == pinCode) { it.user } else { throw IllegalArgumentException(AUTHEN_EXCEPTION) } } else { throw IllegalArgumentException(it.message) } } } catch (exception: Exception) { Maybe.error(exception) } } override fun logout(id: Int, phone: String): Maybe<User> { val json = JsonObject().apply { addProperty("phone", phone) } val body = RequestBody.create( MediaType.parse("application/json; charset=utf-8"), Gson().toJson(json) ) return try { backend.logout(id, body).map { if (it.isSuccess) { it.user } else { throw IllegalArgumentException(it.message) } } } catch (exception: HttpException) { Maybe.error(exception) } } companion object { const val AUTHEN_EXCEPTION = "Password isn't valid" } }
0
Kotlin
1
0
24ddb088ffd985dcd34e3e8deeb5edcc1d717558
3,957
apion_home
Apache License 2.0
src/commonMain/kotlin/com/severett/kemver/processor/GreaterThanOrEqualZeroProcessor.kt
severn-everett
788,089,454
false
{"Kotlin": 80398}
package com.severett.kemver.processor import com.severett.kemver.Range import com.severett.kemver.Semver import com.severett.kemver.processor.RangesUtils.ASTERISK /** * Processor for translating `latest`, `latest.internal`, and `*` strings into a classic range. * * Translates: * * All ranges to `>=0.0.0` */ object GreaterThanOrEqualZeroProcessor : Processor { private const val LATEST = "latest" private const val LATEST_INTEGRATION = "$LATEST.integration" private val ALL_RANGE = "${Range.RangeOperator.GTE.asString}${Semver.ZERO}" override fun process(range: String): String { return if (range.isEmpty() || range == LATEST || range == LATEST_INTEGRATION || range == ASTERISK) { ALL_RANGE } else { range } } }
0
Kotlin
0
0
99ca3fdaea45386d66eb021513e272040250d998
788
kemver
MIT License
src/main/kotlin/io/github/trainb0y/fabrihud/elements/LatencyElement.kt
trainb0y
524,534,291
false
{"Kotlin": 20569, "Java": 1358}
package io.github.trainb0y.fabrihud.elements import net.minecraft.client.MinecraftClient // HUD element displaying the client-server latency (ping) class LatencyElement : TextElement() { override fun getArgs(client: MinecraftClient): List<Any?> { var ping = -1 if (client.networkHandler != null) { if (client.networkHandler!!.getPlayerListEntry(client.player?.uuid) != null) { ping = client.networkHandler!!.getPlayerListEntry(client.player!!.uuid)!!.latency } } return listOf(ping) } override val key = "element.fabrihud.latency" }
1
Kotlin
0
5
9b7b25213c6463c6a0579b6cf5fb9ebab5d568e1
556
FabriHUD
MIT License
app/src/main/java/com/avocadochif/nerdzmagicbottomnavigation/enums/BottomNavigationPage.kt
avocadochif-core
281,013,936
false
null
package com.avocadochif.nerdzmagicbottomnavigation.enums enum class BottomNavigationPage { TAB_HOME, TAB_EVENTS, TAB_LIBRARY }
0
Kotlin
0
0
f4b571da14dd70aa5cec0cb8f286d95ef89d7321
143
nerdz-magic-bottom-navigation
MIT License
data/src/main/java/com/ragdroid/data/entity/Mappers.kt
ragdroid
113,446,060
false
null
package com.ragdroid.data.entity import com.ragdroid.api.entity.TCharacterMarvel import javax.inject.Inject /** * base mapper interface for mapping * Created by garimajain on 18/11/17. */ interface Mapper<in I, out O> { fun map(input: I): O } class CharacterMapper @Inject constructor(): Mapper<TCharacterMarvel, CharacterMarvel> { override fun map(input: TCharacterMarvel): CharacterMarvel { val character = input.let { CharacterMarvel(it.id, it.name, it.description, "${it.thumbnail.path}.${it.thumbnail.extension}".replace("http:", "https:")) } return character; } }
3
Kotlin
7
82
b4b8faa15cffe48c985da1da0463a8a2b67c21a4
691
klayground
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/ClockUpArrow.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.ClockUpArrow: ImageVector get() { if (_clockUpArrow != null) { return _clockUpArrow!! } _clockUpArrow = Builder(name = "ClockUpArrow", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(11.0f, 6.0f) horizontalLineToRelative(2.0f) verticalLineToRelative(6.437f) lineToRelative(-4.887f, 2.989f) lineToRelative(-1.043f, -1.707f) lineToRelative(3.93f, -2.403f) verticalLineToRelative(-5.315f) close() moveTo(2.0f, 12.0f) curveTo(2.0f, 6.486f, 6.486f, 2.0f, 12.0f, 2.0f) curveToRelative(3.559f, 0.0f, 6.878f, 1.916f, 8.663f, 5.001f) curveToRelative(0.707f, 1.224f, 1.13f, 2.591f, 1.271f, 3.999f) horizontalLineToRelative(2.0f) curveToRelative(-0.147f, -1.759f, -0.657f, -3.473f, -1.541f, -5.001f) curveTo(20.253f, 2.299f, 16.271f, 0.0f, 12.0f, 0.0f) curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f) curveToRelative(0.0f, 3.076f, 1.162f, 6.002f, 3.273f, 8.236f) curveToRelative(0.449f, 0.475f, 0.937f, 0.896f, 1.444f, 1.286f) lineToRelative(1.423f, -1.423f) curveToRelative(-0.501f, -0.365f, -0.977f, -0.773f, -1.414f, -1.236f) curveToRelative(-1.758f, -1.862f, -2.727f, -4.3f, -2.727f, -6.863f) close() moveTo(22.0f, 13.0f) horizontalLineToRelative(-4.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(2.568f) lineToRelative(-4.693f, 4.692f) lineToRelative(-3.25f, -3.25f) lineToRelative(-6.063f, 6.062f) lineToRelative(1.414f, 1.414f) lineToRelative(4.648f, -4.648f) lineToRelative(3.25f, 3.25f) lineToRelative(6.125f, -6.124f) verticalLineToRelative(2.604f) horizontalLineToRelative(2.0f) verticalLineToRelative(-4.0f) curveToRelative(0.0f, -1.103f, -0.897f, -2.0f, -2.0f, -2.0f) close() } } .build() return _clockUpArrow!! } private var _clockUpArrow: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,268
icons
MIT License
src/main/kotlin/com/bolyartech/forge/server/response/builders/ResponseBuilder.kt
ogrebgr
530,584,692
false
null
package com.bolyartech.forge.server.response.builders import com.bolyartech.forge.server.response.HttpHeader import com.bolyartech.forge.server.response.Response import jakarta.servlet.http.Cookie interface ResponseBuilder { fun build(): Response fun status(status: Int) fun getStatus(): Int fun addCookie(c: Cookie): ResponseBuilder fun cookieExists(cookieName: String): Boolean fun getCookies(): List<Cookie> fun removeCookie(cookieName: String): ResponseBuilder fun headerExists(headerName: String): Boolean fun addHeader(header: HttpHeader): ResponseBuilder fun getHeaders(): List<HttpHeader> fun removeHeader(headerName: String): ResponseBuilder // fun gzipSupport(enable: Boolean) : ResponseBuilder } abstract class AbstractResponseBuilder constructor() : ResponseBuilder { private var enableGzipSupport = true private val cookies: MutableMap<String, Cookie> = mutableMapOf<String, Cookie>() private val headers: MutableMap<String, HttpHeader> = mutableMapOf<String, HttpHeader>() private var status: Int = -1 override fun status(status: Int) { if (this.status != -1) { throw java.lang.IllegalStateException("Status already set") } this.status = status } override fun getStatus(): Int { return status } override fun getCookies(): List<Cookie> { return cookies.values.toList() } @Throws(CookieAlreadyExistException::class) override fun addCookie(c: Cookie): ResponseBuilder { if (cookies[c.name.lowercase()] != null) { throw CookieAlreadyExistException(c.name) } cookies[c.name.lowercase()] = c return this } override fun cookieExists(cookieName: String): Boolean { return cookies[cookieName.lowercase()] != null } override fun removeCookie(cookieName: String): ResponseBuilder { cookies.remove(cookieName.lowercase()) return this } override fun getHeaders(): List<HttpHeader> { return headers.values.toList() } override fun removeHeader(headerName: String): ResponseBuilder { headers.remove(headerName.lowercase()) return this } @Throws(HeaderAlreadyExistException::class) override fun addHeader(header: HttpHeader): ResponseBuilder { if (headers[header.header] != null) { throw HeaderAlreadyExistException(header.header) } return this } override fun headerExists(headerName: String): Boolean { return cookies[headerName] != null } class CookieAlreadyExistException(cookieName: String) : Exception("Cookie already exist: $cookieName") class HeaderAlreadyExistException(headerName: String) : Exception("Header already exist: $headerName") }
0
Kotlin
0
0
ba0ab4247f96ae84d127e20bb84976bc17c3e30e
2,816
forge-server-ktl
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/ExternalHardDrive.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.ExternalHardDrive: ImageVector get() { if (_externalHardDrive != null) { return _externalHardDrive!! } _externalHardDrive = Builder(name = "ExternalHardDrive", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(15.0f, 19.5f) curveToRelative(0.0f, 0.83f, -0.67f, 1.5f, -1.5f, 1.5f) reflectiveCurveToRelative(-1.5f, -0.67f, -1.5f, -1.5f) reflectiveCurveToRelative(0.67f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.67f, 1.5f, 1.5f) close() moveTo(9.5f, 18.0f) curveToRelative(-0.83f, 0.0f, -1.5f, 0.67f, -1.5f, 1.5f) reflectiveCurveToRelative(0.67f, 1.5f, 1.5f, 1.5f) reflectiveCurveToRelative(1.5f, -0.67f, 1.5f, -1.5f) reflectiveCurveToRelative(-0.67f, -1.5f, -1.5f, -1.5f) close() moveTo(24.0f, 10.0f) verticalLineToRelative(6.0f) horizontalLineToRelative(-4.0f) verticalLineToRelative(-6.0f) horizontalLineToRelative(1.0f) lineTo(21.0f, 3.0f) curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f) horizontalLineToRelative(-9.0f) curveToRelative(-0.551f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f) verticalLineToRelative(1.0f) horizontalLineToRelative(5.0f) curveToRelative(1.654f, 0.0f, 3.0f, 1.346f, 3.0f, 3.0f) verticalLineToRelative(17.0f) lineTo(0.0f, 24.0f) lineTo(0.0f, 7.0f) curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f) horizontalLineToRelative(5.0f) verticalLineToRelative(-1.0f) curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f) horizontalLineToRelative(9.0f) curveToRelative(1.654f, 0.0f, 3.0f, 1.346f, 3.0f, 3.0f) verticalLineToRelative(7.0f) horizontalLineToRelative(1.0f) close() moveTo(16.0f, 22.0f) verticalLineToRelative(-5.0f) lineTo(2.0f, 17.0f) verticalLineToRelative(5.0f) horizontalLineToRelative(14.0f) close() moveTo(3.0f, 6.0f) curveToRelative(-0.551f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f) verticalLineToRelative(8.0f) horizontalLineToRelative(14.0f) lineTo(16.0f, 7.0f) curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f) lineTo(3.0f, 6.0f) close() } } .build() return _externalHardDrive!! } private var _externalHardDrive: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,790
icons
MIT License
app/src/main/java/priv/muchia/practice/model/HotKeyData.kt
MuChia
501,616,479
false
{"Kotlin": 81632, "Java": 1827}
package priv.muchia.practice.model data class HotKeyData( val id: Int, val link: String, val name: String, val order: Int, val visible: Int )
0
Kotlin
0
0
b5474d36a4b9bf44b34c5d0169a967694aa46671
187
Practice
Apache License 2.0
app/src/main/java/com/andrehaueisen/listadejanot/views/IndicatorViewFlipper.kt
AndreHaueisen
88,384,506
false
null
package com.andrehaueisen.listadejanot.views import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.support.v4.content.ContextCompat import android.util.AttributeSet import android.widget.ViewFlipper import com.andrehaueisen.listadejanot.R /** * Created by andre on 10/10/2017. */ class IndicatorViewFlipper : ViewFlipper { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) private val paint = Paint() override fun dispatchDraw(canvas: Canvas) { super.dispatchDraw(canvas) val width = width val margin = 3F val radius = 6F var cx: Float = (width / 2F) - ((radius+margin) * 2F * childCount / 2F) val cy: Float = height - 20F canvas.save() for (i in 0 until childCount) { if (i == displayedChild) { paint.color = ContextCompat.getColor(context, R.color.colorAccent) canvas.drawCircle(cx, cy, radius, paint) } else { paint.color = ContextCompat.getColor(context, R.color.colorPrimary) canvas.drawCircle(cx, cy, radius, paint) } cx += 2 * (radius + margin) } canvas.restore() } }
0
Kotlin
0
0
f477e5520e5037bf019133051139adba4d61c962
1,328
TheList
Apache License 2.0
app/src/main/java/com/kaustavjaiswal/omdbsampleapp/ui/SearchShowsActivity.kt
tapriandi
462,808,078
true
{"Kotlin": 37519}
package com.kaustavjaiswal.omdbsampleapp.ui import android.content.Context import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.KeyEvent import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import androidx.core.widget.doAfterTextChanged import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import androidx.paging.LoadState import androidx.recyclerview.widget.GridLayoutManager import com.kaustavjaiswal.omdbsampleapp.databinding.ActivitySearchShowsBinding import com.kaustavjaiswal.omdbsampleapp.utilities.ConnectionUtils import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.InternalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import timber.log.Timber @InternalCoroutinesApi @ExperimentalCoroutinesApi @AndroidEntryPoint class SearchShowsActivity : AppCompatActivity() { private lateinit var binding: ActivitySearchShowsBinding private val viewModel: SearchViewModel by viewModels() private val adapter = ShowsAdapter() private var searchJob: Job? = null private var connected = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySearchShowsBinding.inflate(layoutInflater) val view = binding.root setContentView(view) initConnectionCheck() initAdapter() val query = savedInstanceState?.getString(LAST_SEARCH_QUERY) ?: DEFAULT_QUERY search(query) initSearch(query) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(LAST_SEARCH_QUERY, (binding.searchOmdb.text?.trim() ?: "").toString()) } private fun initConnectionCheck() { ConnectionUtils.getConnectionLiveData(applicationContext) .observe(this, Observer { connectionStatus -> this.connected = connectionStatus if (connected.not()) { setInternetError() } else { setConnectionEstablished() } }) } private fun setConnectionEstablished() { viewModel.forceRefresh = true updateShows() binding.inputLayout.isErrorEnabled = false } private fun setInternetError() { connectionToast() binding.inputLayout.isErrorEnabled = true binding.inputLayout.error = "Please Check Internet Connection" } private fun initAdapter() { binding.list.layoutManager = GridLayoutManager(this, 2) adapter.addLoadStateListener { loadState -> if (loadState.refresh is LoadState.Loading) { handleLoadingScenario() } else { displayRecyclerViewDataIfAvailable() // getting the error val error = when { loadState.prepend is LoadState.Error -> loadState.prepend as LoadState.Error loadState.append is LoadState.Error -> loadState.append as LoadState.Error loadState.refresh is LoadState.Error -> loadState.refresh as LoadState.Error else -> null } error?.let { Timber.e(error.toString()) } } } binding.list.adapter = adapter } private fun displayRecyclerViewDataIfAvailable() { handlerWithDelay(300) { if (binding.list.adapter?.itemCount ?: 0 > 0) { handleNotLoadingScenario() } else { handleErrorScenario() } } } @OptIn(FlowPreview::class) private fun initSearch(query: String) { binding.searchOmdb.setText(query) binding.inputLayout.setEndIconOnClickListener { updateShows() } binding.searchOmdb.doAfterTextChanged { lifecycleScope.launch { delay(300) //debounce timeOut updateShows(false) } } binding.searchOmdb.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_SEARCH) { binding.searchOmdb.clearFocus() updateShows() true } else { false } } binding.searchOmdb.setOnKeyListener { _, keyCode, event -> if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) { binding.searchOmdb.clearFocus() updateShows() true } else { false } } binding.retryButton.setOnClickListener { if (connected.not()) { connectionToast() } adapter.retry() } } private fun search(query: String) { // Make sure we cancel the previous job before creating a new one searchJob?.cancel() searchJob = lifecycleScope.launch { viewModel.searchShows(query).collectLatest { adapter.submitData(it) } } } private fun updateShows(dismissKeyBoard: Boolean = true) { if (dismissKeyBoard) dismissKeyboard() val searchText = (binding.searchOmdb.text?.trim() ?: "").toString() if (searchText.isNotEmpty()) { search(searchText) } } private fun handleErrorScenario() { binding.list.isVisible = false binding.progressBar.isVisible = false binding.retryButton.isVisible = true binding.animationView.isVisible = true } private fun handleNotLoadingScenario() { binding.list.isVisible = true binding.retryButton.isVisible = false binding.progressBar.isVisible = false binding.animationView.isVisible = false } private fun handleLoadingScenario() { binding.progressBar.isVisible = true binding.retryButton.isVisible = false binding.animationView.isVisible = false } private fun connectionToast() { Toast.makeText( this, "Issue detected with internet connection!", Toast.LENGTH_SHORT ).show() } private fun dismissKeyboard() { binding.searchOmdb.clearFocus() val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(binding.searchOmdb.windowToken, 0) } inline fun handlerWithDelay(duration: Long, crossinline action: () -> Unit) { val handler = Handler(Looper.getMainLooper()) handler.postDelayed({ action() }, duration) } companion object { private const val LAST_SEARCH_QUERY: String = "last_search_query" private const val DEFAULT_QUERY = "Android" } }
0
null
0
0
1e44e5227652871adbe496c0dd4c66e694ab980a
7,277
OmdbSample
The Unlicense
app/src/main/java/pk/farimarwat/anrspyexample/MainActivity.kt
farimarwat
579,959,968
false
null
package pk.farimarwat.anrspyexample import android.content.Intent import android.content.IntentFilter import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import pk.farimarwat.AnrSpy.ANRSpyAgent import pk.farimarwat.AnrSpy.ANRSpyListener import pk.farimarwat.AnrSpy.TAG import pk.farimarwat.anrspyexample.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { val binding by lazy { ActivityMainBinding.inflate(layoutInflater) } lateinit var mReceiver:AirPlanMode override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) mReceiver = AirPlanMode() IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also { registerReceiver(mReceiver,it) } val anrSpyAgent = ANRSpyAgent.Builder() .setSpyListener(object : ANRSpyListener { override fun onWait(ms: Long) { //Log.e(TAG,"Waited: $ms") } override fun onAnrStackTrace(stackstrace: Array<StackTraceElement>) { Log.e(TAG,"Stack:\n ${stackstrace}") } override fun onAnrDetected(details: String, stackTrace: Array<StackTraceElement>) { Log.e(TAG,details) Log.e(TAG,"${stackTrace}") } }) .setThrowException(true) .setTimeOut(5000) .build() anrSpyAgent.start() initGui() } fun initGui(){ binding.btnMain.setOnClickListener { for(i in 1..10){ Log.e(TAG,"Number: $i") Thread.sleep(1000) } } binding.btnService.setOnClickListener { startService(Intent(this,MyService::class.java)) } } override fun onDestroy() { super.onDestroy() unregisterReceiver(mReceiver) } }
0
Kotlin
4
14
7bc11c3180042edef44a1a00c3e1220e106fcd36
1,984
ANR-Spy
Apache License 2.0
Hermes/Logger/src/main/java/com/spartancookie/hermeslogger/filters/FilterSet.kt
RafaelsRamos
352,183,568
false
null
package com.spartancookie.hermeslogger.filters import com.spartancookie.hermeslogger.core.models.EventDataHolder internal class FilterSet<T: Filter> { private val _filters = mutableListOf<T>() val filters get() = _filters.toList() /** * Filter the [events] into a List that results from the current filters. */ fun filterResults(events: List<EventDataHolder>) = filters.filter(events) /** * Override [_filters] with the given [filters]. */ fun overrideFilters(filters: Collection<T>) { clear() _filters.addAll(filters) } /** * Check if the current filters contains [filter]. */ fun contains(filter: T) : Boolean = filters.contains(filter) /** * Add [filter] to the current filters, if it doesn't exist already. */ fun addFilter(filter: T) { if (!filters.contains(filter)) { _filters.add(filter) } } /** * Remove [filter] if it already exists in [_filters]. */ fun removeFilter(filter: T) { if (filters.contains(filter)) { _filters.remove(filter) } } /** * Clear all current filters. */ fun clear() { _filters.clear() } private fun List<Filter>.filter(events: List<EventDataHolder>): List<EventDataHolder> { if (isEmpty()) { return events } // Filter 1st layer (by Type) val eventsFilteredByType = mutableListOf<EventDataHolder>() return eventsFilteredByType.apply { [email protected] { addAll(it.filter(events)) } } } }
6
null
0
3
12007ddb2110f8585e50a86ede897366f4df3dff
1,655
HermesLogger
Apache License 2.0
src/test/kotlin/pl/org/pablo/slack/money/MoneyApplicationTests.kt
pablow91
110,442,981
false
null
package pl.org.tosio.slack.money import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit.jupiter.SpringExtension @ExtendWith(SpringExtension::class) @SpringBootTest class MoneyApplicationTests { @Test fun contextLoads() { } }
4
Kotlin
2
1
efde0f75af9286cb65cb9b6f5d0e60632fab9e66
376
money-dispatcher
Apache License 2.0
src/test/kotlin/pl/org/pablo/slack/money/MoneyApplicationTests.kt
pablow91
110,442,981
false
null
package pl.org.tosio.slack.money import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit.jupiter.SpringExtension @ExtendWith(SpringExtension::class) @SpringBootTest class MoneyApplicationTests { @Test fun contextLoads() { } }
4
Kotlin
2
1
efde0f75af9286cb65cb9b6f5d0e60632fab9e66
376
money-dispatcher
Apache License 2.0
fsmlib/src/main/kotlin/org/suggs/fsm/behavior/builders/PseudoStateBuilder.kt
suggitpe
158,869,057
false
null
package org.suggs.fsm.behavior.builders import org.suggs.fsm.behavior.PseudoState import org.suggs.fsm.behavior.PseudoStateKind import org.suggs.fsm.behavior.Region class PseudoStateBuilder(name: String, val pseudoStateKind: PseudoStateKind) : VertexBuilder(name) { constructor(pseudoStateKind: PseudoStateKind) : this(pseudoStateKind.toString(), pseudoStateKind) override fun withDeferrableTriggers(vararg newTriggers: TriggerBuilder): VertexBuilder { throw IllegalStateException("You cannot define deferrable triggers on a pseudo state") } override fun withEntryBehavior(behavior: BehaviorBuilder): VertexBuilder { throw IllegalStateException("You cannot define entry and exit behaviors on pseudo states") } override fun withExitBehavior(behavior: BehaviorBuilder): VertexBuilder { throw IllegalStateException("You cannot define entry and exit behaviors on pseudo states") } override fun build(container: Region): PseudoState { return PseudoState(name, container, pseudoStateKind) } }
0
Kotlin
0
0
874dd36add564ca968f334c6e9aa050c5e495b64
1,093
fsm
Apache License 2.0
core/src/test/kotlin/snitch/parameters/ParametersTest.kt
memoizr
322,370,926
false
null
package snitch.parameters import snitch.validation.ofNonEmptySingleLineString import snitch.validation.ofNonNegativeInt import snitch.documentation.Visibility import snitch.dsl.InlineSnitchTest import snitch.parsers.GsonJsonParser.serialized import snitch.parsing.Parser import snitch.request.parsing import snitch.types.Sealed import snitch.types.ErrorResponse import snitch.validation.Validator import org.junit.Test import java.text.SimpleDateFormat import java.util.* val stringParam by path(ofNonEmptySingleLineString) val intParam by path(ofNonNegativeInt) val q by query() val int by query(ofNonNegativeInt, emptyAsMissing = true) private val offset by optionalQuery(ofNonNegativeInt, default = 30) val limit by optionalQuery(ofNonNegativeInt) val qHead by header(ofNonEmptySingleLineString, name = "q") val intHead by header(ofNonNegativeInt, name = "int") val offsetHead by optionalHeader(ofNonNegativeInt, emptyAsMissing = true, default = 666) val limitHead by optionalHeader(ofNonNegativeInt, emptyAsMissing = true) val queryParam by optionalQuery(ofNonEmptySingleLineString, name = "param", default = "hey") val headerParam by optionalHeader( ofNonEmptySingleLineString, name = "param", default = "hey", visibility = Visibility.INTERNAL ) val pathParam by path(ofNonEmptySingleLineString, name = "param") val time by query(DateValidator) object DateValidator : Validator<Date, Date> { override val description: String = "An iso 8601 format date" override val regex: Regex = """^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)-02-29)T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:Z|[+-][01]\d:[0-5]\d)$""".toRegex() override val parse: Parser.(Collection<String>) -> Date = { it.first().let { SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").parse(it) } } } data class IntTestResult(val result: Int) data class NullableIntTestResult(val result: Int?) data class DateResult(val date: Date) data class BodyParam(val int: Int, val string: String, val sealed: SealedClass) data class BodyTestResult(val a: Int, val b: Int) data class TestErrorHttpResponse<T, E>(val statusCode: Int, val details: E) sealed class SealedClass : Sealed() { data class One(val oneInt: Int) : SealedClass() object Two : SealedClass() } data class TestResult(val string: String) class ParametersTest : InlineSnitchTest() { @Test fun `supports typed path parameters`() { given { GET("stringpath" / stringParam) isHandledBy { TestResult(request[stringParam]).ok } GET("intpath" / intParam) isHandledBy { IntTestResult(request[intParam]).ok } } then { GET("/stringpath/hellothere").expectBodyJson(TestResult("hellothere")) GET("/intpath/300").expectBodyJson(IntTestResult(300)) } } @Test fun `validates path parameters`() { given { GET("intpath2" / intParam / "end") isHandledBy { IntTestResult(request[intParam]).ok } } then { GET("/intpath2/4545/end").expectBody(IntTestResult(4545).serialized) GET("/intpath2/hello/end").expectBody( ErrorResponse( 400, listOf("Path parameter `intParam` is invalid, expecting non negative integer, got `hello`") ).serialized ) } } @Test fun `supports query parameters`() { given { GET("queriespath") inSummary "does a foo" withQuery q isHandledBy { TestResult(request[q]).ok } GET("queriespath2") with queries(int) isHandledBy { IntTestResult(request[int]).ok } } then { GET("/queriespath?q=foo").expectBodyJson(TestResult("foo")) GET("/queriespath?q=foo%0Abar").expectBodyJson(TestResult("foo\nbar")) GET("/queriespath?q=").expectBodyJson( TestErrorHttpResponse<TestResult, List<String>>( 400, listOf("Query parameter `q` is invalid, expecting non empty string, got ``") ) ) GET("/queriespath").expectBodyJson( TestErrorHttpResponse<TestResult, List<String>>( 400, listOf("Required Query parameter `q` is missing") ) ) GET("/queriespath2?int=3434").expectBodyJson(IntTestResult(3434)) GET("/queriespath2?int=").expectBodyJson( TestErrorHttpResponse<TestResult, List<String>>( 400, listOf("Required Query parameter `int` is missing") ) ) GET("/queriespath2?int=hello").expectBodyJson( TestErrorHttpResponse<TestResult, List<String>>( 400, listOf("Query parameter `int` is invalid, expecting non negative integer, got `hello`") ) ) GET("/queriespath2?int=-34").expectBodyJson( TestErrorHttpResponse<TestResult, List<String>>( 400, listOf("Query parameter `int` is invalid, expecting non negative integer, got `-34`") ) ) } } @Test fun `supports default values for query parameters`() { given { GET("queriespath3") with queries(offset) isHandledBy { IntTestResult(request[offset]).ok } GET("queriespath4") with queries(limit) isHandledBy { NullableIntTestResult(request[limit]).ok } } then { GET("/queriespath3?offset=42").expectBody(IntTestResult(42).serialized) GET("/queriespath3").expectBody(IntTestResult(30).serialized) GET("/queriespath4?limit=42").expectBody(NullableIntTestResult(42).serialized) GET("/queriespath4").expectBody("""{}""") } } @Test fun `supports header parameters`() { given { GET("headerspath") with headers(qHead) isHandledBy { TestResult(request[qHead]).ok } GET("headerspath2") with headers(intHead) isHandledBy { IntTestResult(request[intHead]).ok } } then { GET("/headerspath").withHeaders(mapOf(qHead.name to "foo")).expectBodyJson(TestResult("foo")) GET("/headerspath").withHeaders(mapOf(qHead.name to "")).expectBody( TestErrorHttpResponse<TestResult, List<String>>( 400, listOf("Header parameter `q` is invalid, expecting non empty single-line string, got ``") ).serialized ) GET("/headerspath").withHeaders(mapOf()).expectBodyJson( TestErrorHttpResponse<TestResult, List<String>>( 400, listOf("Required Header parameter `q` is missing") ) ) GET("/headerspath2").withHeaders(mapOf(intHead.name to 3434)).expectBodyJson(IntTestResult(3434)) GET("/headerspath2").expectBodyJson( TestErrorHttpResponse<TestResult, List<String>>( 400, listOf("Required Header parameter `int` is missing") ) ) GET("/headerspath2").withHeaders(mapOf(intHead.name to "hello")).expectBodyJson( TestErrorHttpResponse<TestResult, List<String>>( 400, listOf("Header parameter `int` is invalid, expecting non negative integer, got `hello`") ) ) GET( "/headerspath2" ).withHeaders(mapOf(intHead.name to -34)).expectBodyJson( TestErrorHttpResponse<TestResult, List<String>>( 400, listOf("Header parameter `int` is invalid, expecting non negative integer, got `-34`") ) ) } } @Test fun `supports default values for header parameters`() { given { GET("headerspath3") with headers(offsetHead) isHandledBy { NullableIntTestResult(request[offsetHead]).ok } GET("headerspath4") with headers(limitHead) isHandledBy { NullableIntTestResult(request[limitHead]).ok } } then { GET("/headerspath3").withHeaders(mapOf(offsetHead.name to 42)) .expectBody(IntTestResult(42).serialized) GET("/headerspath3").expectBody(IntTestResult(666).serialized) GET("/headerspath3").expectBody(IntTestResult(666).serialized) GET("/headerspath4").withHeaders(mapOf(limitHead.name to 42)).expectBody( NullableIntTestResult( 42 ).serialized ) GET("/headerspath4").withHeaders(mapOf(limitHead.name to "")).expectBody("""{}""") GET("/headerspath4").expectBody("""{}""") } } @Test fun `supports custom parsing`() { val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); val date = "2018-06-30T02:59:51-00:00" given { GET("customParsing") with queries(time) isHandledBy { DateResult(request[time]).ok } } then { GET("/customParsing?time=$date").expectBody(DateResult(df.parse(date)).serialized) } } @Test fun `forbids using parameters which aren't registered`() { given { GET("sneakyqueryparams") isHandledBy { TestResult(request.get(queryParam)).ok } GET("sneakyheaderparams") isHandledBy { TestResult(request.get(headerParam)).ok } GET("sneakypathparams" / pathParam.copy(name = "sneaky")) isHandledBy { TestResult(request.get(pathParam)).ok } } then { GET("/sneakyqueryparams").expectBody( ErrorResponse( 500, "Attempting to use unregistered query parameter `param`" ).serialized ) GET("/sneakyheaderparams").expectBody( ErrorResponse( 500, "Attempting to use unregistered header parameter `param`" ).serialized ) GET("/sneakypathparams/343").expectBody( ErrorResponse( 500, "Attempting to use unregistered path parameter `param`" ).serialized ) } } @Test fun `supports body parameter`() { val bodyParam = BodyParam(42, "hello", SealedClass.One(33)) val function by parsing<BodyParam>() handling { val sealed = body.sealed BodyTestResult( body.int, when (sealed) { is SealedClass.One -> sealed.oneInt is SealedClass.Two -> 2 } ).ok } given { POST("bodyparam") with body<BodyParam>() isHandledBy function } then { POST("/bodyparam").withBody(bodyParam).expectBody(BodyTestResult(42, 33).serialized) } } @Test fun `returns error for failed parsing of body parameter`() { given { POST("bodyparam") with body<BodyParam>() isHandledBy { body.sealed.ok } } then { POST("/bodyparam").withBody("lolol").expectCode(400) .expectBody("""{"statusCode":400,"details":"Invalid body parameter"}""") } } @Test fun `supports a optional header parameters`() { val param by optionalHeader(ofNonNegativeInt) given { GET() withHeader param isHandledBy { (request[param] ?: 0).ok } } then { GET("/").withHeader("param" to "4").expectBody("4") GET("/").expectBody("0") } } @Test fun `supports a optional header parameter with default`() { val param by optionalHeader( ofNonNegativeInt, default = 5, emptyAsMissing = true, invalidAsMissing = true ) given { GET() withHeader param isHandledBy { (request[param]).ok } } then { GET("/") .withHeader("param" to "4") .expectBody("4") GET("/") .withHeader("param" to "foo") .expectBody("5") GET("/") .withHeader("param" to "") .expectBody("5") GET("/").expectBody("5") } } @Test fun `supports a optional header parameter without default`() { val param by optionalHeader( ofNonNegativeInt, emptyAsMissing = true, invalidAsMissing = true ) given { GET() withHeader param isHandledBy { ((request[param]) ?: 5).ok } } then { GET("/") .withHeader("param" to "4") .expectBody("4") GET("/") .withHeader("param" to "foo") .expectBody("5") GET("/") .withHeader("param" to "") .expectBody("5") GET("/").expectBody("5") } } @Test fun `supports a optional query parameter with default`() { val param by optionalQuery( ofNonNegativeInt, default = 5, emptyAsMissing = true, invalidAsMissing = true ) given { GET() withQuery param isHandledBy { (request[param]).ok } } then { GET("/?param=4") .expectBody("4") GET("/?param=foo") .expectBody("5") GET("/?param=") .expectBody("5") GET("/").expectBody("5") } } @Test fun `supports a optional query parameter without default`() { val param by optionalQuery( ofNonNegativeInt, emptyAsMissing = true, invalidAsMissing = true ) given { GET() withQuery param isHandledBy { (request[param] ?: 42).ok } } then { GET("/?param=4") .expectBody("4") GET("/?param=foo") .expectBody("42") GET("/?param=") .expectBody("42") GET("/").expectBody("42") } } @Test fun `supports a optional string header parameter with default`() { val param by optionalHeader( default = "5", emptyAsMissing = true, ) given { GET() withHeader param isHandledBy { (request[param]).ok } } then { GET("/") .withHeader("param" to "4") .expectBody(""""4"""") GET("/") .withHeader("param" to "") .expectBody(""""5"""") GET("/").expectBody(""""5"""") } } @Test fun `supports a optional string header parameter without default`() { val param by optionalHeader( emptyAsMissing = true, ) given { GET() withHeader param isHandledBy { ((request[param]) ?: "5").ok } } then { GET("/") .withHeader("param" to "4") .expectBody(""""4"""") GET("/") .withHeader("param" to "") .expectBody(""""5"""") GET("/").expectBody(""""5"""") } } @Test fun `supports a optional string query parameter with default`() { val param by optionalQuery( default = "5", emptyAsMissing = true, invalidAsMissing = true, ) given { GET() withQuery param isHandledBy { (request[param]).ok } } then { GET("/?param=4") .expectBody(""""4"""") GET("/?param=") .expectBody(""""5"""") GET("/").expectBody(""""5"""") } } @Test fun `supports a optional string query parameter without default`() { val param by optionalQuery( emptyAsMissing = true, ) given { GET() withQuery param isHandledBy { (request[param] ?: "42").ok } } then { GET("/?param=4") .expectBody(""""4"""") GET("/?param=") .expectBody(""""42"""") GET("/").expectBody(""""42"""") } } }
0
Kotlin
2
34
501b43074653207279fe3646a8f8519520967c3b
16,564
snitch
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/visitscheduler/service/MigrateVisitService.kt
ministryofjustice
409,259,375
false
null
package uk.gov.justice.digital.hmpps.visitscheduler.service import com.microsoft.applicationinsights.TelemetryClient import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import uk.gov.justice.digital.hmpps.visitscheduler.dto.CreateLegacyContactOnVisitRequestDto.Companion.UNKNOWN_TOKEN import uk.gov.justice.digital.hmpps.visitscheduler.dto.MigrateVisitRequestDto import uk.gov.justice.digital.hmpps.visitscheduler.model.OutcomeStatus import uk.gov.justice.digital.hmpps.visitscheduler.model.VisitNoteType import uk.gov.justice.digital.hmpps.visitscheduler.model.entity.LegacyData import uk.gov.justice.digital.hmpps.visitscheduler.model.entity.Visit import uk.gov.justice.digital.hmpps.visitscheduler.model.entity.VisitContact import uk.gov.justice.digital.hmpps.visitscheduler.model.entity.VisitNote import uk.gov.justice.digital.hmpps.visitscheduler.model.entity.VisitVisitor import uk.gov.justice.digital.hmpps.visitscheduler.repository.LegacyDataRepository import uk.gov.justice.digital.hmpps.visitscheduler.repository.VisitRepository import java.util.Locale @Service @Transactional class MigrateVisitService( private val legacyDataRepository: LegacyDataRepository, private val visitRepository: VisitRepository, private val prisonConfigService: PrisonConfigService, private val telemetryClient: TelemetryClient, ) { fun migrateVisit(migrateVisitRequest: MigrateVisitRequestDto): String { // Deserialization kotlin data class issue when OutcomeStatus = json type of null defaults do not get set hence below code val outcomeStatus = migrateVisitRequest.outcomeStatus ?: OutcomeStatus.NOT_RECORDED val prison = prisonConfigService.findPrisonByCode(migrateVisitRequest.prisonCode) val visitEntity = visitRepository.saveAndFlush( Visit( prisonerId = migrateVisitRequest.prisonerId, prison = prison, prisonId = prison.id, visitRoom = migrateVisitRequest.visitRoom, visitType = migrateVisitRequest.visitType, visitStatus = migrateVisitRequest.visitStatus, outcomeStatus = outcomeStatus, visitRestriction = migrateVisitRequest.visitRestriction, visitStart = migrateVisitRequest.startTimestamp, visitEnd = migrateVisitRequest.endTimestamp ) ) migrateVisitRequest.visitContact?.let { contact -> visitEntity.visitContact = createVisitContact( visitEntity, if (UNKNOWN_TOKEN == contact.name || contact.name.partition { it.isLowerCase() }.first.isNotEmpty()) contact.name else capitalise(contact.name), contact.telephone ) } migrateVisitRequest.visitors?.let { contactList -> contactList.forEach { visitEntity.visitors.add(createVisitVisitor(visitEntity, it.nomisPersonId)) } } migrateVisitRequest.visitNotes?.let { visitNotes -> visitNotes.forEach { visitEntity.visitNotes.add(createVisitNote(visitEntity, it.type, it.text)) } } migrateVisitRequest.legacyData?.let { saveLegacyData(visitEntity, it.leadVisitorId) } ?: run { saveLegacyData(visitEntity, null) } sendTelemetryData(visitEntity) visitRepository.saveAndFlush(visitEntity) migrateVisitRequest.createDateTime?.let { visitRepository.updateCreateTimestamp(it, visitEntity.id) } // Do this at end of this method, otherwise modify date would be overridden migrateVisitRequest.modifyDateTime?.let { visitRepository.updateModifyTimestamp(it, visitEntity.id) } return visitEntity.reference } private fun sendTelemetryData(visitEntity: Visit) { telemetryClient.trackEvent( TelemetryVisitEvents.VISIT_MIGRATED_EVENT.eventName, mapOf( "reference" to visitEntity.reference, "prisonerId" to visitEntity.prisonerId, "prisonId" to visitEntity.prison.code, "visitType" to visitEntity.visitType.name, "visitRoom" to visitEntity.visitRoom, "visitRestriction" to visitEntity.visitRestriction.name, "visitStart" to visitEntity.visitStart.toString(), "visitStatus" to visitEntity.visitStatus.name, "outcomeStatus" to visitEntity.outcomeStatus?.name ), null ) } private fun capitalise(sentence: String): String = sentence.lowercase(Locale.getDefault()).split(" ").joinToString(" ") { word -> var index = 0 for (ch in word) { if (ch in 'a'..'z') { break } index++ } if (index < word.length) word.replaceRange(index, index + 1, word[index].titlecase(Locale.getDefault())) else word } private fun createVisitNote(visit: Visit, type: VisitNoteType, text: String): VisitNote { return VisitNote( visitId = visit.id, type = type, text = text, visit = visit ) } private fun saveLegacyData(visit: Visit, leadPersonId: Long?) { val legacyData = LegacyData( visitId = visit.id, leadPersonId = leadPersonId ) legacyDataRepository.saveAndFlush(legacyData) } private fun createVisitContact(visit: Visit, name: String, telephone: String?): VisitContact { return VisitContact( visitId = visit.id, name = name, telephone = telephone ?: "", visit = visit ) } private fun createVisitVisitor(visit: Visit, personId: Long): VisitVisitor { return VisitVisitor( nomisPersonId = personId, visitId = visit.id, visit = visit, visitContact = null ) } }
3
Kotlin
2
6
01dcad3b0defb675a12da8d0f14cc130766410ff
5,590
visit-scheduler
MIT License
qa-kotest-articles/kotest-second/src/test/kotlin/ru/iopump/qa/sample/ordering/SecondSpec.kt
kochetkov-ma
284,747,386
false
null
package ru.iopump.qa.sample.ordering import io.kotest.core.spec.Order import io.kotest.core.spec.style.FreeSpec @Order(Int.MIN_VALUE + 1) class SecondSpec : FreeSpec() { init { "SecondSpec-Test" { } } }
0
Kotlin
2
7
cf6a49bc5d18ac0c690a508d048f7a246b41087d
220
pump-samples
Apache License 2.0
src/test/kotlin/de/roamingthings/jibworkbench/SmokeControllerComponentTest.kt
gAmUssA
172,143,234
false
null
package de.roamingthings.jibworkbench import org.junit.jupiter.api.Test import org.springframework.http.MediaType.TEXT_PLAIN import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status import org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup class SmokeControllerComponentTest { @Test internal fun `smoke endpoint should respond with content type text and status OK`() { // given val smokeController = SmokeController() val mockMvc = aMockMvcFor(smokeController) // when val requestResponse = mockMvc.perform(get("/smoke")) //then requestResponse .andExpect(status().isOk) .andExpect(content().contentTypeCompatibleWith(TEXT_PLAIN)) } @Test internal fun `burn endpoint should respond with content type text and status OK`() { // given val smokeController = SmokeController() val mockMvc = aMockMvcFor(smokeController) // when val requestResponse = mockMvc.perform(get("/burn")) //then requestResponse .andExpect(status().isOk) .andExpect(content().contentTypeCompatibleWith(TEXT_PLAIN)) } private fun aMockMvcFor(controller: Any): MockMvc = standaloneSetup(controller).build() }
0
Kotlin
0
0
69b42b5e1919ba0e1be9886094ab947c344726bf
1,560
spring-boot-jib-workbench
Apache License 2.0
features/home/src/main/java/app/zendoo/feature/home/di/home/HomeViewModelModule.kt
zendoo-app
202,864,140
false
null
package app.zendoo.feature.home.di.home import androidx.lifecycle.ViewModel import app.zendoo.di.viewmodel.ViewModelKey import app.zendoo.feature.home.ui.HomeViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class HomeViewModelModule { @Binds @IntoMap @ViewModelKey(HomeViewModel::class) internal abstract fun homeViewModel(viewModel: HomeViewModel): ViewModel }
29
Kotlin
1
0
56ebd79731a5a2e3241fabd085704a1bee71d15f
436
mobile-android-zendoo
Apache License 2.0
connectors/console/src/jvmMain/kotlin/com/river/connector/console/ConsoleExt.kt
River-Kt
539,201,163
false
null
@file:OptIn(ExperimentalCoroutinesApi::class) package com.river.connector.console import com.river.core.poll import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.invoke enum class Print { BREAK_LINE, NO_BREAK } enum class OutType { DEFAULT, ERROR } /** * Creates a flow of strings read from the console input (stdin) using the specified dispatcher. * * @param dispatcher The CoroutineDispatcher to use for reading from stdin. Defaults to a single-threaded dispatcher. * * @return A flow of strings read from the console input. * * Example usage: * * ``` * val consoleInputFlow = consoleIn() * consoleInputFlow.collect { input -> println("You entered: $input") } * ``` */ fun consoleIn( dispatcher: CoroutineDispatcher = Dispatchers.IO.limitedParallelism(1) ): Flow<String> = poll { dispatcher { listOf(String(System.`in`.readBytes())) } } /** * Outputs the flow of objects to the console (stdout or stderr) using the specified dispatcher, print, and mapper. * * @param dispatcher The CoroutineDispatcher to use for writing to the console. Defaults to a single-threaded dispatcher. * @param print The print mode (Print.BREAK_LINE or Print.NO_BREAK) to use for console output. * @param mapper A function that maps each object in the flow to a pair of (output item, output type). * Defaults to the original item and OutType.DEFAULT. * * @return The original flow of objects. * * Example usage: * * ``` * data class Person(val name: String, val age: Int) * val peopleFlow = flowOf(Person("Alice", 30), Person("Bob", 25)) * * peopleFlow.consoleOut().collect() * ``` */ fun <T : Any> Flow<T>.consoleOut( dispatcher: CoroutineDispatcher = Dispatchers.IO.limitedParallelism(1), print: Print = Print.BREAK_LINE, mapper: suspend (T) -> Pair<Any, OutType> = { it to OutType.DEFAULT }, ) = map(mapper) .onEach { (item, out) -> val outType = when (out) { OutType.DEFAULT -> System.out OutType.ERROR -> System.err } dispatcher { when (print) { Print.BREAK_LINE -> outType.println(item) Print.NO_BREAK -> outType.print(item) } } }
30
null
3
79
9841047b27268172a42e0e1ec74b095c0202a2cc
2,430
river
MIT License
src/main/java/net/crewco/AnglesAndDevils/commands/TemplateCommand.kt
XS-T
776,630,285
false
{"Kotlin": 75430}
package net.crewco.AnglesAndDevils.commands import cloud.commandframework.annotations.CommandDescription import cloud.commandframework.annotations.CommandMethod import cloud.commandframework.annotations.CommandPermission import com.google.inject.Inject import net.crewco.AnglesAndDevils.Startup import org.bukkit.entity.Player class TemplateCommand @Inject constructor(private val plugin: Startup) { @CommandMethod("templatecommand") @CommandDescription("Template Command") @CommandPermission("templateplugin.command.templatecommand") suspend fun template(player: Player) { } }
0
Kotlin
0
0
c1ae70d84e3e6385738e752b072772e54633a695
584
AngelsAndDevilsSMP
Apache License 2.0
src/main/kotlin/com/ymoch/study/server/service/debug/DebugRecorder.kt
ymoch
150,832,195
false
null
package com.ymoch.study.server.service.debug import com.ymoch.study.server.record.debug.DebugRecord import com.ymoch.study.server.record.debug.ExceptionRecord import java.util.Arrays import java.util.stream.Collectors import kotlin.reflect.jvm.jvmName class DebugRecorder { companion object { fun toStackTraceLine(element: StackTraceElement): String { val source = when { element.isNativeMethod -> "Native Method" element.fileName == null -> "Unknown Source" element.lineNumber < 0 -> element.fileName else -> "${element.fileName}:${element.lineNumber}" } return "${element.className}.${element.methodName}($source)" } } private var exception: Exception? = null fun registerException(exception: Exception) { this.exception = exception } fun toDebugRecord(): DebugRecord { val exceptionRecord = exception?.let { it -> val className = it::class.jvmName val stackTrace = Arrays.stream(it.stackTrace) .map { toStackTraceLine(it) } .collect(Collectors.toList()) ExceptionRecord(className, it.message, stackTrace) } return DebugRecord(exception = exceptionRecord) } }
0
Kotlin
0
0
1d82b182c6de9c88db26f0da1bbae0ba56fb4775
1,320
kotlin-server-study
MIT License
buildSrc/src/main/kotlin/org/partiql/pig/gradle/publish/PigPublishPlugin.kt
partiql
238,071,402
false
null
package org.partiql.pig.gradle.publish import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.JavaPlugin import org.gradle.api.plugins.JavaPluginExtension import org.gradle.api.publish.PublishingExtension import org.gradle.api.publish.maven.MavenPublication import org.gradle.api.publish.maven.plugins.MavenPublishPlugin import org.gradle.api.publish.maven.tasks.PublishToMavenRepository import org.gradle.jvm.tasks.Jar import org.gradle.kotlin.dsl.create import org.gradle.kotlin.dsl.get import org.gradle.kotlin.dsl.getByName import org.gradle.kotlin.dsl.provideDelegate import org.gradle.plugins.signing.SigningExtension import org.gradle.plugins.signing.SigningPlugin import org.jetbrains.dokka.gradle.DokkaPlugin import org.jetbrains.dokka.gradle.DokkaTask import java.io.File /** * Gradle plugin to consolidates the following publishing logic * - Maven Publishing * - Signing * - SourcesJar * - Dokka + JavadocJar */ abstract class PigPublishPlugin : Plugin<Project> { override fun apply(target: Project): Unit = with(target) { pluginManager.apply(JavaPlugin::class.java) pluginManager.apply(MavenPublishPlugin::class.java) pluginManager.apply(SigningPlugin::class.java) pluginManager.apply(DokkaPlugin::class.java) val ext = extensions.create("publish", PublishExtension::class.java) target.afterEvaluate { publish(ext) } } private fun Project.publish(ext: PublishExtension) { val releaseVersion = !version.toString().endsWith("-SNAPSHOT") // Run dokka unless the environment explicitly specifies false val runDokka = (System.getenv()["DOKKA"] != "false") || releaseVersion // Include "sources" and "javadoc" in the JAR extensions.getByType(JavaPluginExtension::class.java).run { withSourcesJar() withJavadocJar() } tasks.getByName<DokkaTask>("dokkaHtml") { onlyIf { runDokka } outputDirectory.set(File("${buildDir}/javadoc")) } // Add dokkaHtml output to the javadocJar tasks.getByName<Jar>("javadocJar") { onlyIf { runDokka } dependsOn(JavaPlugin.CLASSES_TASK_NAME) archiveClassifier.set("javadoc") from(tasks.named("dokkaHtml")) } // Setup Maven Central Publishing val publishing = extensions.getByType(PublishingExtension::class.java).apply { publications { create<MavenPublication>("maven") { artifactId = ext.artifactId from(components["java"]) pom { packaging = "jar" name.set(ext.name) description.set("The P.I.G. is a code generator for domain models such ASTs and execution plans.") url.set("<EMAIL>:partiql/partiql-ir-generator.git") scm { connection.set("scm:<EMAIL>:partiql/partiql-ir-generator.git") developerConnection.set("scm:<EMAIL>:partiql/partiql-ir-generator.git") url.set("<EMAIL>:partiql/partiql-ir-generator.git") } licenses { license { name.set("The Apache License, Version 2.0") url.set("http://www.apache.org/licenses/LICENSE-2.0.txt") } } developers { developer { name.set("<NAME>") email.set("<EMAIL>") organization.set("PartiQL") organizationUrl.set("https://github.com/partiql") } } } } } repositories { maven { url = uri("https://aws.oss.sonatype.org/service/local/staging/deploy/maven2") credentials { val ossrhUsername: String by rootProject val ossrhPassword: String by rootProject username = ossrhUsername password = <PASSWORD> } } } } // Sign only if publishing to Maven Central extensions.getByType(SigningExtension::class.java).run { setRequired { releaseVersion && gradle.taskGraph.allTasks.any { it is PublishToMavenRepository } } sign(publishing.publications["maven"]) } } } abstract class PublishExtension { var artifactId: String = "" var name: String = "" }
40
Kotlin
7
25
fa0f3dc5e672f77fad92fb802673f95979732be5
4,893
partiql-ir-generator
Apache License 2.0
app/src/main/java/vn/loitp/up/a/game/puzzle/ui/game/u/BitmapTile.kt
tplloi
126,578,283
false
null
package vn.loitp.up.a.game.puzzle.ui.game.u import android.graphics.Bitmap import android.util.Size data class BitmapTile( val image: Bitmap, val size: Size ) { private val tileSize = Size( /* width = */ image.width / size.width, /* height = */ image.height / size.height ) val tiles = Array(size.height) { y -> Array(size.width) { x -> Bitmap.createBitmap( /* source = */ image, /* x = */ x * tileSize.width, /* y = */ y * tileSize.height, /* width = */ tileSize.width, /* height = */ tileSize.height ) } } }
1
null
1
9
1bf1d6c0099ae80c5f223065a2bf606a7542c2b9
657
base
Apache License 2.0