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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gradle-conventions/conventions/src/main/kotlin/wottrich/github/io/smartchecklist/ConvetionsGradleDsl.kt | Wottrich | 295,605,540 | false | {"Kotlin": 351230} | import com.android.build.gradle.BaseExtension
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.plugins.ExtensionAware
import org.gradle.kotlin.dsl.get
import org.jetbrains.kotlin.gradle.dsl.KotlinJvmOptions
internal val Project.android: BaseExtension
get() = this.extensions["android"] as BaseExtension
internal fun Project.android(block: Action<BaseExtension>) {
block.execute(android)
}
internal fun BaseExtension.kotlinOptions(configure: KotlinJvmOptions.() -> Unit) {
(this as ExtensionAware).extensions.configure(KotlinJvmOptions::class.java, configure)
} | 12 | Kotlin | 0 | 8 | 1d8823ce64994bc8b44e3dc72711966265489edc | 607 | android-smart-checklist | MIT License |
app/src/main/java/com/wa2c/android/cifsdocumentsprovider/data/io/BackgroundBufferReader.kt | wa2c | 309,159,444 | false | null | /*
* MIT License
*
* Copyright (c) 2021 wa2c
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.wa2c.android.cifsdocumentsprovider.data.io
import com.wa2c.android.cifsdocumentsprovider.common.utils.logD
import com.wa2c.android.cifsdocumentsprovider.common.utils.logE
import com.wa2c.android.cifsdocumentsprovider.common.values.BUFFER_SIZE
import kotlinx.coroutines.*
import java.util.concurrent.ArrayBlockingQueue
import kotlin.coroutines.CoroutineContext
/**
* BackgroundBufferReader
*/
class BackgroundBufferReader (
/** Data Size */
private val dataSize: Long,
/** Buffer unit size */
private val bufferSize: Int = BUFFER_SIZE,
/** Buffer queue capacity */
private val queueCapacity: Int = 5,
/** Background reading */
private val readBackgroundAsync: (start: Long, array: ByteArray, off: Int, len: Int) -> Int
): CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.IO + job
/** Data buffer queue */
private val dataBufferQueue = ArrayBlockingQueue<Deferred<DataBuffer?>>(queueCapacity)
/** Current data buffer */
private var currentDataBuffer: DataBuffer? = null
/** Buffer loading job. */
private var bufferingJob: Job? = null
/**
* Read buffer.
*/
fun readBuffer(position: Long, size: Int, data: ByteArray): Int {
if (bufferingJob == null) {
startBackgroundCycle(position)
}
var dataOffset = 0
while (true) {
val c = currentDataBuffer ?: runBlocking {
dataBufferQueue.take().let {
try { it.await() } catch (e: Exception) { null }
}
}.also { currentDataBuffer = it } ?: continue
val bufferPosition = position + dataOffset
val bufferRemain = c.getRemainSize(bufferPosition)
val bufferOffset = c.getPositionOffset(bufferPosition)
if (bufferOffset < 0) {
startBackgroundCycle(bufferPosition)
continue
}
val remainDataSize = size - dataOffset
if (bufferRemain >= remainDataSize) {
// Middle current buffer
try {
c.data.copyInto(data, dataOffset, bufferOffset, bufferOffset + remainDataSize)
} catch (e: Exception) {
logE(e)
}
return size
} else {
// End of current buffer
val end = bufferOffset + bufferRemain
c.data.copyInto(data, dataOffset, bufferOffset, end)
currentDataBuffer = null
if (c.length == end) {
// End of data
return bufferRemain
} else {
dataOffset += bufferRemain
}
}
return 0
}
}
/**
* Start background reading.
*/
private fun startBackgroundCycle(startPosition: Long) {
logD("startBackgroundCycle=$startPosition")
reset()
bufferingJob = launch (Dispatchers.IO) {
try {
var currentPosition = startPosition
while (isActive) {
val remain = dataSize - currentPosition
if (dataSize > 0 && remain <= 0) break
if (remain > bufferSize) {
// Read buffer
val task = readAsync(currentPosition, bufferSize)
dataBufferQueue.put(task)
currentPosition += bufferSize
} else {
// End of data
val task = readAsync(currentPosition, remain.toInt())
dataBufferQueue.put(task)
currentPosition += remain
break
}
}
} finally {
bufferingJob = null
}
}
}
/**
* Read from Samba file.
*/
private fun readAsync(position: Long, buffSize: Int): Deferred<DataBuffer> {
return async (Dispatchers.IO) {
val data = ByteArray(buffSize)
val size = readBackgroundAsync(position, data, 0, buffSize)
val remain = buffSize - size
if (size > 0 && remain > 0) {
val subSize = readBackgroundAsync(position + size, data, size, remain)
DataBuffer(position, size + subSize, data)
} else {
DataBuffer(position, size, data)
}
}
}
/**
* Reset
*/
fun reset() {
logD("reset")
bufferingJob?.cancel()
bufferingJob = null
currentDataBuffer = null
dataBufferQueue.forEach { it.cancel() }
dataBufferQueue.clear()
}
/**
* Release
*/
fun release() {
reset()
}
/**
* Data buffer
*/
class DataBuffer(
/** Data absolute start position */
val position: Long = 0,
/** Data length */
val length: Int = 0,
/** Data buffer */
val data: ByteArray = ByteArray(BUFFER_SIZE),
) {
/** Data absolute end position */
val endPosition = position + length
/**
* Get offset with pointer and position. -1 if not in data.
* @param p Absolute position of stream
* @return Offset with start position and p
*/
fun getPositionOffset(p: Long): Int {
return when {
p < position -> -1
p > endPosition -> -1
else -> (p - position).toInt()
}
}
/**
* Get remain size from pointer. -1 if not in data.
* @param p Absolute position of stream
* @return Offset with p and end position
*/
fun getRemainSize(p: Long): Int {
return when {
p < position -> -1
p > endPosition -> -1
else -> (endPosition - p).toInt()
}
}
}
} | 5 | Kotlin | 2 | 19 | 9e4d8f13c9ec14f9f96f62a48601fba3067d0dc8 | 7,214 | cifs-documents-provider | MIT License |
fivefiveplayer/src/main/java/cn/onestravel/fivefiveplayer/interf/PlayerInterface.kt | onestravel | 248,478,489 | false | null | package cn.onestravel.fivefiveplayer.interf
import android.view.View
import cn.onestravel.fivefiveplayer.MediaDataSource
import cn.onestravel.fivefiveplayer.OnDoubleClickListener
import cn.onestravel.fivefiveplayer.impl.VideoDisplayTypeDef
import cn.onestravel.fivefiveplayer.kernel.MediaKernelApi
import cn.onestravel.fivefiveplayer.kernel.MediaKernelInterface
import java.lang.Exception
/**
* @author onestravel
* @createTime 2020-03-19
* @description 视频播放器开放API
*/
typealias OnPreparedListener = (PlayerInterface) -> Unit
typealias OnProgressListener = (position: Long, duration: Long) -> Unit
typealias OnCompleteListener = () -> Unit
typealias OnErrorListener = (Exception) -> Unit
typealias OnBackPressListener = () -> Unit
interface PlayerInterface {
companion object {
/**
* 播放异常
*/
const val STATE_ERROR: Int = -1
/**
* 未设置视频资源
*/
const val STATE_IDLE: Int = 0
/**
* 正在准备状态
*/
const val STATE_PREPARING: Int = 1
/**
* 视频资源准备完成
*/
const val STATE_PREPARED: Int = 2
/**
* 视频正在播放状态
*/
const val STATE_BUFFERING_PLAYING: Int = 3
/**
* 视频暂停播放状态
*/
const val STATE_BUFFERING_PAUSED: Int = 4
/**
* 视频正在播放状态
*/
const val STATE_PLAYING: Int = 5
/**
* 视频暂停播放状态
*/
const val STATE_PAUSED: Int = 6
/**
* 视频停止播放状态
*/
const val STATE_STOP: Int = 7
/**
* 视频播放完成状态
*/
const val STATE_COMPLETE: Int = 8
/**
* 视频自适应
*/
const val VIDEO_DISPLAY_TYPE_ADAPTER = 0
/**
* 原版视频
*/
const val VIDEO_DISPLAY_TYPE_ORIGINAL = 1
/**
* 视频某一个边达到最大宽/高度
*/
const val VIDEO_DISPLAY_TYPE_FIT_CENTER = 2
/**
* 填充满裁切视频
*/
const val VIDEO_DISPLAY_TYPE_CENTER_CROP = 3
const val PLAYER_STATE_NORMAL = 11
const val PLAYER_STATE_FULL_SCREEN = 12
const val PLAYER_STATE_TINY_WINDOW = 13
}
/**
* 设置预览图
*/
fun setPreviewImg(url: String)
/**
* 设置资源
*/
fun setDataSource(url: String)
/**
* 设置资源
*/
fun setDataSource(dataSource: MediaDataSource)
/**
* 开始播放视频
*/
fun start()
/**
* 从指定位置开始播放视频
*/
fun start(position: Long)
/**
* 暂停播放视频
*/
fun pause()
/**
* 停止播放视频
*/
fun stop()
/**
* 继续播放视频
*/
fun resume()
/**
* 视频定位到指定位置
*/
fun seekTo(position: Long)
/**
* 重置播放器
*/
fun reset()
/**
* 释放播放器
*/
fun release()
/**
* 获取视频总时长
*/
fun getDuration(): Long
/**
* 获取视频当前位置时长
*/
fun getCurrentPosition(): Long
/**
* 获取视频当前是否正在播放
*/
fun isPlaying(): Boolean
/**
* 获取视频当前是否正在暂停
*/
fun isPaused(): Boolean
/**
* 获取视频当前是否播放完成
*/
fun isCompletion(): Boolean
/**
* 设置音量
*/
fun setVolume(leftVolume: Float, rightVolume: Float)
/**
* 设置倍速
*/
fun setSpeed(speed: Float)
/**
* 设置旋转角度
*/
fun setVideoRotation(rotation: Float)
/**
* 设置视频显示类型
* @param type { #PlayerInterface#VIDEO_DISPLAY_TYPE_ADAPTER,
* PlayerInterface#VIDEO_DISPLAY_TYPE_ORIGINAL,
* PlayerInterface#VIDEO_DISPLAY_TYPE_FIT_CENTER,
* PlayerInterface#VIDEO_DISPLAY_TYPE_CENTER_CROP
* }
*/
fun setVideoDisplayType(@VideoDisplayTypeDef displayType: Int)
/**
* 设置准备完成监听事件
*/
fun setOnPreparedListener(onPreparedListener: OnPreparedListener)
/**
* 设置播放进度监听事件
*/
fun setOnProgressListener(onProgressListener: OnProgressListener)
/**
* 设置播放完成监听事件
*/
fun setOnCompleteListener(onCompleteListener: OnCompleteListener)
/**
* 设置播放异常监听事件
*/
fun setOnErrorListener(onErrorListener: OnErrorListener)
/**
* 设置播放器媒体内核class
*/
fun setMediaKernelClass(clazz:Class<out MediaKernelApi>)
} | 0 | null | 0 | 7 | b6fa85222973be5e28d6079d61372ca6335aee20 | 4,276 | FiveFiveVideoPlayer | Apache License 2.0 |
app/src/main/java/ir/sinadalvand/projects/bazaarproject/ui/fragment/DetailFragment.kt | sinadalvand | 334,198,446 | false | null | /*
* *
* * Created by <NAME> on 12/22/20 11:06 PM
* * Copyright (c) 2020 . All rights reserved.
* * Last modified 12/22/20 11:06 PM
*
*/
package ir.sinadalvand.projects.bazaarproject.ui.fragment
import android.os.Bundle
import android.view.View
import androidx.core.text.HtmlCompat
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import ir.sinadalvand.projects.bazaarproject.R
import ir.sinadalvand.projects.bazaarproject.contracts.ViewErrorHandler
import ir.sinadalvand.projects.bazaarproject.contracts.XfragmentVm
import ir.sinadalvand.projects.bazaarproject.contracts.XrequestStatus
import ir.sinadalvand.projects.bazaarproject.data.model.ResponseWrapper
import ir.sinadalvand.projects.bazaarproject.data.model.Venue
import ir.sinadalvand.projects.bazaarproject.util.Extensions.gone
import ir.sinadalvand.projects.bazaarproject.util.Extensions.invisible
import ir.sinadalvand.projects.bazaarproject.util.Extensions.visible
import ir.sinadalvand.projects.bazaarproject.util.Utils.getAddress
import ir.sinadalvand.projects.bazaarproject.util.Utils.getCategory
import ir.sinadalvand.projects.bazaarproject.viewmodel.FragmentDetailViewModel
import kotlinx.android.synthetic.main.fragment_details.*
import kotlinx.android.synthetic.main.layout_error_handler.*
class DetailFragment : XfragmentVm<FragmentDetailViewModel>(), ViewErrorHandler {
// use safe arg to prevent any error to pass parameters between fragments
private val navArgs: DetailFragmentArgs by navArgs()
override fun layoutView(): Any = R.layout.fragment_details
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
vm.venueDetail.observe(viewLifecycleOwner) {
setDetailsToViews(it.data)
errorHandler(it)
}
requestData()
}
private fun requestData() {
vm.requestVenue(navArgs.venueId)
}
// get what kind of error happend
private fun errorHandler(wrapper: ResponseWrapper<*>) {
when (wrapper.requestStatus) {
XrequestStatus.ERROR -> {
showErrorHandler(getString(R.string.unknown_error), getString(R.string.unknown_error_happened), null, getString(R.string.return_text)) {
findNavController().navigateUp()
}
}
XrequestStatus.NO_INTERNET -> {
showErrorHandler(getString(R.string.no_internet), getString(R.string.check_netwoek_desc), null, getString(R.string.retry)) {
requestData()
}
}
else -> {
hideErrorHandler()
}
}
}
// set values to views
private fun setDetailsToViews(venue: Venue?) {
if (venue == null) {
hideAllViews()
return
}
fragment_details_img_header.visible()
fragment_details_title?.text = HtmlCompat.fromHtml(venue.name ?: "", HtmlCompat.FROM_HTML_MODE_COMPACT)
fragment_details_txt_rate.text = getString(R.string.rate, venue.rate?.toString() ?: "1.0")
fragment_details_txt_like.text = (venue.like ?: 0).toString()
fragment_details_txt_category?.text = getCategory(venue.categories)
fragment_details_txt_address?.text = getAddress(venue.location)
}
private fun hideAllViews() {
fragment_details_layout_like.invisible()
fragment_details_layout_rate.invisible()
fragment_details_txt_category.invisible()
fragment_details_txt_address.invisible()
fragment_details_divider.invisible()
fragment_details_title.invisible()
fragment_details_recycler_photo.invisible()
fragment_details_img_header.invisible()
}
override fun showErrorHandler(title: String, msg: String, res: Int?, buttonText: String?, func: () -> Unit) {
layout_handler_layout_container.visible(true)
layout_handler_img_icon?.setImageResource(res ?: R.drawable.ic_warning)
layout_handler_txt_title?.text = title
layout_handler_txt_desc?.text = msg
if (buttonText == null) {
layout_handler_btn_action?.gone()
layout_handler_btn_action?.setOnClickListener(null)
} else {
layout_handler_btn_action?.visible()
layout_handler_btn_action?.text = buttonText
layout_handler_btn_action?.setOnClickListener { func.invoke() }
}
}
override fun hideErrorHandler() {
layout_handler_layout_container.invisible(true)
}
} | 0 | Kotlin | 1 | 3 | cde3057d765c536b0dc1997b3b204c38f5f1c925 | 4,600 | CompassSquare | Apache License 2.0 |
src/main/kotlin/fastify_decorators/plugin/inspections/ControllerClassDefaultExportInspection.kt | L2jLiga | 232,797,029 | false | null | // Copyright 2019-2021 Andrey Chalkin <L2jLiga> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package fastify_decorators.plugin.inspections
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.lang.javascript.psi.JSElementVisitor
import com.intellij.lang.javascript.psi.ecma6.TypeScriptClass
import com.intellij.lang.javascript.psi.ecmal4.JSAttributeList
import com.intellij.psi.PsiElementVisitor
import fastify_decorators.plugin.CONTROLLER_DECORATOR_NAME
import fastify_decorators.plugin.extensions.hasDecorator
import fastify_decorators.plugin.extensions.isFastifyDecoratorsContext
import fastify_decorators.plugin.inspections.quickfixes.ControllerDefaultExportQuickFix
class ControllerClassDefaultExportInspection : LocalInspectionTool() {
override fun getStaticDescription() =
"""
Applicable only when application using autoloader from fastify-decorators library.
Controller without default export can not be loaded and will throw Error in Runtime.
""".trimIndent()
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : JSElementVisitor() {
override fun visitTypeScriptClass(typeScriptClass: TypeScriptClass) {
if (!typeScriptClass.isFastifyDecoratorsContext) return
if (typeScriptClass.isExportedWithDefault || !typeScriptClass.hasDecorator()) return
val textRange = (typeScriptClass.attributeList as JSAttributeList).decorators
.find { it.text.startsWith("@$CONTROLLER_DECORATOR_NAME") }
?.textRangeInParent
?: throw IllegalStateException("@$CONTROLLER_DECORATOR_NAME decorator disappeared")
holder.registerProblem(
typeScriptClass,
textRange,
"@$CONTROLLER_DECORATOR_NAME must have default export",
ControllerDefaultExportQuickFix(
typeScriptClass
)
)
}
}
}
} | 3 | Kotlin | 0 | 1 | e59d02592188586ad1b7d49bc5672c60bd6e5720 | 2,208 | fastify-decorators-plugin | Apache License 2.0 |
app/src/main/java/com/jeremiahzucker/pandroid/player/Player.kt | sugarmanz | 95,634,669 | false | null | package com.jeremiahzucker.pandroid.player
import android.media.MediaPlayer
import android.util.Log
import com.jeremiahzucker.pandroid.request.Pandora
import com.jeremiahzucker.pandroid.request.json.v5.method.station.GetPlaylist
import com.jeremiahzucker.pandroid.request.json.v5.method.station.GetStation
import com.jeremiahzucker.pandroid.request.json.v5.model.ExpandedStationModel
import com.jeremiahzucker.pandroid.request.json.v5.model.FeedbackModel
import com.jeremiahzucker.pandroid.request.json.v5.model.TrackModel
import kotlin.reflect.KProperty
/**
* Created by sugarmanz on 9/10/17.
*/
internal object Player : PlayerInterface, MediaPlayer.OnCompletionListener {
private val TAG: String = Player::class.java.simpleName
// TODO: Consider faster alternatives to MediaPlayer
// At the moment, I am considering simply downloading the mp3 files
// and using the MediaPlayer to play them. This will hopefully solve
// the issues with prepareAsync being super slow and will allow for
// offline use.
private var mediaPlayer = MediaPlayer()
private val callbacks = ArrayList<PlayerInterface.Callback>()
private val tracks = ArrayList<TrackModel>()
private val feedbacks = mutableMapOf<String, FeedbackModel>()
private var index = 0
private val hasNext get() = index < tracks.size - 1
private val hasLast get() = tracks.isNotEmpty()
private val nextTrack get() = tracks[++index]
private val lastTrack get() = tracks[if (index - 1 < 0) index else --index]
private var isPaused = false
override var playMode: PlayMode = PlayMode.default
override var station: ExpandedStationModel? = null
set(value) {
// Only bother setting if changing stations
if (field?.stationToken != value?.stationToken) {
field = value
// Reset playlist
clearPlaylist()
// Load feedbacks first
loadFeedback()
// Load initial playlist
loadPlaylist()
}
}
override var currentTrack: TrackModel? = null
private set
override val isPlaying: Boolean by HandleIllegalStateDelegate(false) { mediaPlayer.isPlaying }
override val progress: Int by HandleIllegalStateDelegate(0) { mediaPlayer.currentPosition }
override val duration: Int by HandleIllegalStateDelegate(0) { mediaPlayer.duration }
internal class HandleIllegalStateDelegate<out T>(private val defaultValue: T, private val getter: () -> T) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return try {
getter()
} catch (e: IllegalStateException) {
mediaPlayer.release()
mediaPlayer = MediaPlayer()
defaultValue
}
}
}
init {
mediaPlayer.setOnCompletionListener(this)
}
// IMPORTANT: Assumes that currentTrack has been set already
override fun play(): Boolean {
if (isPaused) {
isPaused = false
mediaPlayer.start()
notifyPlayStatusChanged(true)
return true
} else if (currentTrack != null) {
mediaPlayer.reset()
mediaPlayer.setDataSource(currentTrack?.audioUrlMap?.highQuality?.audioUrl)
mediaPlayer.prepare() // TODO: PrepareAsync?????
mediaPlayer.start()
notifyPlayStatusChanged(true)
if (!hasNext)
loadPlaylist()
return true
}
return false
}
override fun play(station: ExpandedStationModel): Boolean {
isPaused = false
this.station = station
return true // Not really, lol
}
// Will add the track as the next track and then play it
override fun play(track: TrackModel): Boolean {
isPaused = false
return if (tracks.isNotEmpty()) {
tracks.add(index + 1, track)
playNext()
} else {
tracks.add(track)
play()
}
}
override fun playLast(): Boolean {
isPaused = false
if (hasLast) {
currentTrack = lastTrack
play()
notifyPlayLast(currentTrack as TrackModel)
return true
}
return false
}
override fun playNext(): Boolean {
isPaused = false
if (hasNext) {
currentTrack = nextTrack
play()
notifyPlayNext(currentTrack as TrackModel)
return true
}
return false
}
override fun pause(): Boolean {
if (isPlaying) {
mediaPlayer.pause()
isPaused = true
notifyPlayStatusChanged(false)
return true
}
return false
}
override fun seekTo(progress: Int): Boolean {
if (currentTrack != null) {
if (duration <= progress) {
onCompletion(mediaPlayer)
} else {
mediaPlayer.seekTo(progress)
}
return true
}
return false
}
override fun registerCallback(callback: PlayerInterface.Callback) {
callbacks.add(callback)
}
override fun unregisterCallback(callback: PlayerInterface.Callback) {
callbacks.remove(callback)
}
override fun removeCallbacks() {
callbacks.clear()
}
override fun releasePlayer() {
mediaPlayer.release()
}
private fun notifyPlayStatusChanged(isPlaying: Boolean) {
callbacks.forEach { it.onPlayStatusChanged(isPlaying) }
}
private fun notifyPlayLast(track: TrackModel) {
callbacks.forEach { it.onSwitchLast(track) }
}
private fun notifyPlayNext(track: TrackModel) {
callbacks.forEach { it.onSwitchNext(track) }
}
private fun notifyComplete(track: TrackModel?) {
callbacks.forEach { it.onComplete(track) }
}
override fun onCompletion(mediaPlayer: MediaPlayer?) {
var next: TrackModel? = null
// There is only one limited play mode which is list, player should be stopped when hitting the list end
if (playMode === PlayMode.LIST && index == tracks.size - 1) {
// In the end of the list
// Do nothing, just deliver the callback
} else if (playMode === PlayMode.SINGLE) {
currentTrack = currentTrack
play()
} else if (hasNext) {
currentTrack = nextTrack
play()
}
notifyComplete(currentTrack)
}
private fun clearPlaylist() {
mediaPlayer.reset()
index = 0
tracks.clear()
feedbacks.clear()
currentTrack = null
}
private fun loadPlaylist() = Pandora.HTTP
.RequestBuilder(GetPlaylist)
.body(GetPlaylist.RequestBody(station?.stationToken ?: ""))
.build<GetPlaylist.ResponseBody>()
.subscribe(this::loadPlaylistSuccess, this::loadPlaylistError)
private fun loadPlaylistSuccess(response: GetPlaylist.ResponseBody) {
// Add feedback id if it exists
response.items.forEach {
it.feedbackId = feedbacks[it.trackToken]?.feedbackId
}
// Add the tracks to the queue
tracks.addAll(response.items.filter { it.trackToken != null })
if (currentTrack == null) {
index = 0
currentTrack = tracks[0]
play()
notifyComplete(currentTrack)
}
}
private fun loadPlaylistError(throwable: Throwable) {
throwable.printStackTrace()
}
private fun loadFeedback() = Pandora.HTTPS
.RequestBuilder(GetStation)
.body(GetStation.RequestBody(station?.stationToken ?: "", true))
.build<GetStation.ResponseBody>()
.subscribe(this::loadFeedbackSuccess, this::loadFeedbackError)
private fun loadFeedbackSuccess(response: GetStation.ResponseBody) {
response.feedback.thumbsUp.associateBy { it.musicToken }
}
private fun loadFeedbackError(throwable: Throwable) {
throwable.printStackTrace()
}
} | 2 | Kotlin | 5 | 6 | a71f9ece2284e64a8666e4f8b61f7b6731efb288 | 8,182 | Pandroid | MIT License |
android/app/src/main/java/me/gentielezaj/wagwoord/models/proxyModels/RequestData.kt | gentielezaj | 211,967,241 | false | {"Text": 5, "Ignore List": 5, "Markdown": 1, "JSON": 10, "JavaScript": 58, "JSON with Comments": 2, "SCSS": 6, "Vue": 30, "HTML": 7, "SVG": 3, "CSS": 7, "Gradle": 5, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 2, "Kotlin": 123, "XML": 90, "Java": 1, "INI": 1, "Dotenv": 1, "Procfile": 1, "Microsoft Visual Studio Solution": 1} | package me.gentielezaj.wagwoord.models.proxyModels
import com.android.volley.Request
data class RequestData(
var action: String? = null,
var data: Any? = null,
var params: Map<String, String> = mapOf(),
var controller: String? = null,
var headers: MutableMap<String, String> = mutableMapOf(),
var domain: String? = null,
var method: Int = Request.Method.GET
) {
constructor(method: Int) : this(null, null, mapOf(), null, mutableMapOf(), null, method){}
constructor(method: Int, data: Any) : this(null, data, mapOf(), null, mutableMapOf(), null, method){}
constructor(method: Int, params: Map<String, String>) : this(null, null, params, null, mutableMapOf(), null, method){}
constructor(method: Int, action: String?) : this(action, null, mapOf(), null, mutableMapOf(), null, method){}
constructor(method: Int, action: String?, params: Map<String, String>) : this(action, null, params, null, mutableMapOf(), null, method){}
companion object {
fun Post(data: Any) = RequestData(Request.Method.POST, data);
fun Patch(params: Map<String, String>, action: String? = null) = RequestData(Request.Method.PATCH, action, params)
}
} | 36 | Kotlin | 0 | 0 | 3adf571dc6d4ce8a4e9410df18191c835ef101ce | 1,201 | wagwoord | MIT License |
src/main/kotlin/io/github/isning/gradle/plugins/cmake/targets/WindowsStoreTarget.kt | ISNing | 743,468,322 | false | {"Kotlin": 204825} | /*
* Copyright 2024 ISNing
*
* 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.github.isning.gradle.plugins.cmake.targets
import io.github.isning.gradle.plugins.cmake.CMakeTargetImpl
import io.github.isning.gradle.plugins.cmake.params.ModifiableCMakeBuildParams
import io.github.isning.gradle.plugins.cmake.params.ModifiableCMakeBuildParamsImpl
import io.github.isning.gradle.plugins.cmake.params.entries.platform.ModifiableWindowsStoreEntries
import io.github.isning.gradle.plugins.cmake.params.platform.ModifiableWindowsStoreParams
import io.github.isning.gradle.plugins.cmake.params.platform.ModifiableWindowsStoreParamsImpl
import org.gradle.api.Project
class WindowsStoreTarget(project: Project, name: String) :
CMakeTargetImpl<ModifiableWindowsStoreParams<ModifiableWindowsStoreEntries>,
ModifiableCMakeBuildParams>(project, name, {
ModifiableWindowsStoreParamsImpl()
}, {
ModifiableCMakeBuildParamsImpl()
})
| 0 | Kotlin | 0 | 1 | 219b3b3426ac7514d0ce16e6c6bb6b4bf5f62f0a | 1,480 | CMakePlugin | Apache License 1.1 |
plugins/groovy/src/org/jetbrains/plugins/groovy/bundled/BundledGroovyResolveScopeProvider.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.bundled
import com.intellij.openapi.module.impl.scopes.JdkScope
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.ResolveScopeEnlarger
import com.intellij.psi.search.SearchScope
class BundledGroovyResolveScopeProvider : ResolveScopeEnlarger() {
override fun getAdditionalResolveScope(file: VirtualFile, project: Project): SearchScope? {
val index = ProjectFileIndex.getInstance(project)
if (index.getModuleForFile(file) != null) {
return null
}
val rootFile = VfsUtil.getRootFile(file)
if (rootFile == bundledGroovyJarRoot) {
val scope = createBundledGroovyScope(project) ?: return null
val sdk = ProjectRootManager.getInstance(project).projectSdk ?: return null
val jdkScope = JdkScope(project, sdk.rootProvider.getFiles(OrderRootType.CLASSES), sdk.rootProvider.getFiles(OrderRootType.SOURCES), sdk.name)
return scope.uniteWith(jdkScope)
}
return null
}
} | 229 | null | 4931 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,334 | intellij-community | Apache License 2.0 |
app/src/main/java/com/mafqud/android/results/publishCase/PublishCaseIntent.kt | MafQud | 483,257,198 | false | null | package com.mafqud.android.results.publishCase
sealed class PublishCaseIntent {
data class Publish(val caseID: Int) : PublishCaseIntent()
} | 0 | Kotlin | 6 | 35 | 309e82d51d6c1c776365643ef48ecb78fd243c23 | 145 | MafQud-Android | MIT License |
app/src/main/java/com/rapidsos/era/authentication/password_reset/presenter/PasswordResetPresenter.kt | johndpope | 192,260,729 | false | {"Kotlin": 351294, "Shell": 212} | package com.rapidsos.era.authentication.password_reset.presenter
import com.hannesdorfmann.mosby3.mvp.MvpPresenter
import com.rapidsos.era.authentication.password_reset.view.PasswordResetView
/**
* @author <NAME>
*/
interface PasswordResetPresenter : MvpPresenter<PasswordResetView> {
/**
* Reset the user password for the email provided
* @param email the email to reset the password for
*/
fun resetPasswordForEmail(email: String)
/**
* Dispose all of the disposables in the presenter
*/
fun dispose()
} | 0 | Kotlin | 0 | 1 | 465a1dfbe3d3a9d99418e9b23fb0c6e8790c36c6 | 552 | era-android | Apache License 2.0 |
app/src/main/java/com/paylink/learncompose/MainActivity.kt | xKronos58 | 694,691,187 | false | {"Kotlin": 18458} | package com.paylink.learncompose
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
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.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.paylink.learncompose.ui.theme.LearnComposeTheme
import com.paylink.learncompose.ui.theme.surfaceColor
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
// Conversation(SampleData.conversationSample)
LoginMenuTest()
}
}
}
data class Message(val author: String, val body: String)
@Composable
fun MessageCard(msg: Message) {
LearnComposeTheme {
Row(modifier = Modifier.padding(all = 8.dp)) {
Image(
painter = painterResource(id = R.drawable.dog),
contentDescription = "Profile picture for ${msg.author}",
modifier = Modifier
// Set image size to 40 dp
.size(40.dp)
// Clip image to be shaped as a circle
.clip(CircleShape)
)
// Add a horizontal space between the image and the column
Spacer(modifier = Modifier.width(8.dp))
// We keep track if the message is expanded or not in this
// variable
var isExpanded by remember { mutableStateOf(false) }
// We toggle the isExpanded variable when we click on this Column
Column(modifier = Modifier.clickable { isExpanded = !isExpanded }) {
Text(
text = msg.author,
color = MaterialTheme.colorScheme.secondary,
style = MaterialTheme.typography.titleSmall
)
Spacer(modifier = Modifier.height(4.dp))
Surface(
shape = MaterialTheme.shapes.medium,
shadowElevation = 1.dp,
// surfaceColor color will be changing gradually from primary to surface
color = surfaceColor,
// animateContentSize will change the Surface size gradually
modifier = Modifier
.animateContentSize()
.padding(1.dp)
) {
Text(
text = msg.body,
modifier = Modifier.padding(all = 4.dp),
// If the message is expanded, we display all its content
// otherwise we only display the first line
maxLines = if (isExpanded) Int.MAX_VALUE else 1,
style = MaterialTheme.typography.bodyMedium
)
}
}
}
}
}
@Composable
fun Conversation(messages: List<Message>) {
LazyColumn {
items(messages) { messagee ->
MessageCard(msg = messagee)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginMenuTest(modifier: Modifier = Modifier) {
val gradientColorsList = listOf(
Color(0xFFC9FCFF),
Color(0xFF00ADF6)
)
Box (
modifier = Modifier
.fillMaxSize()
.background(bgGradient(gradientType = 0, colors = gradientColorsList))
// contentAlignment = Alignment.Center
) {
Box(
Modifier
.graphicsLayer {
translationX = -355.dp.toPx() / 2
translationY = 80.dp.toPx() / 2
}
.shadow(
elevation = 4.dp,
spotColor = Color(0x0),
ambientColor = Color(0xFF000000),
shape = RoundedCornerShape(size = 355.dp)
)
.width(355.dp)
.height(355.dp)
.background(
color = Color(0x4B00C2FF),
shape = RoundedCornerShape(
size = 355.dp
),
)
)
Box(
Modifier
.graphicsLayer {
translationX = 300.dp.toPx() / 2
translationY = 900.dp.toPx() / 2
}
.shadow(
elevation = 4.dp,
spotColor = Color(0x40000000),
ambientColor = Color(0xFF000000),
shape = RoundedCornerShape(size = 355.dp)
)
.width(355.dp)
.height(355.dp)
.background(
color = Color(0x7000C2FF),
shape = RoundedCornerShape(size = 355.dp)
)
)
Text(
text = "WELCOME!",
style = TextStyle(
fontSize = 32.sp,
fontWeight = FontWeight(750),
color = Color(0xFF000000),
textAlign = TextAlign.Center,
),
modifier = Modifier
.align(alignment = Alignment.Center)
.padding(bottom = 574.dp)
)
Box(modifier = Modifier
.shadow(
elevation = 4.dp,
spotColor = Color(0x40000000),
ambientColor = Color(0x40000000),
shape = RoundedCornerShape(size = 30.dp),
)
.width(318.dp)
.height(410.dp)
.clip(shape = RoundedCornerShape(size = 30.dp))
.background(
color = Color(0x7AFFFFFF),
shape = RoundedCornerShape(size = 30.dp)
)
.align(alignment = Alignment.Center)
) {
Text(
text = "LOGIN",
style = TextStyle(
fontSize = 32.sp,
fontWeight = FontWeight(500),
color = Color(0xFF000000),
textAlign = TextAlign.Center,
letterSpacing = 1.44.sp,
),
modifier = Modifier
.align(alignment = Alignment.Center)
.padding(bottom = 319.dp)
)
Text(
text = "USERNAME",
style = TextStyle(
fontSize = 16.sp,
fontWeight = FontWeight(500),
color = Color(0xFF000000),
letterSpacing = 0.8.sp,
),
modifier = Modifier
.align(alignment = Alignment.CenterStart)
.padding(bottom = 200.dp, start = 27.dp)
)
TextField(value = "Hello world!", onValueChange = {},
modifier = Modifier
.graphicsLayer {
translationY = -140.dp.toPx() / 2
}
.align(alignment = Alignment.Center)
.shadow(
elevation = 4.dp,
spotColor = Color(0xFF000000),
ambientColor = Color(0x40000000),
shape = RoundedCornerShape(10.dp)
)
.width(284.dp)
.height(30.dp)
.background(
color = Color(0xFFFFFFFF),
shape = RoundedCornerShape(size = 10.dp)
)
.clip(shape = RoundedCornerShape(size = 10.dp))
// .padding(bottom = 7 .dp)
)
Text(
text = "PASSWORD",
style = TextStyle(
fontSize = 16.sp,
fontWeight = FontWeight(500),
color = Color(0xFF000000),
letterSpacing = 0.8.sp,
),
modifier = Modifier
.align(alignment = Alignment.CenterStart)
.padding(bottom = 0.dp, start = 27.dp)
)
TextField(value = "Hello world!", onValueChange = {},
modifier = Modifier
.graphicsLayer {
translationY = 60.dp.toPx() / 2
}
.align(alignment = Alignment.Center)
.shadow(
elevation = 4.dp,
spotColor = Color(0xFF000000),
ambientColor = Color(0x40000000),
shape = RoundedCornerShape(10.dp)
)
.width(284.dp)
.height(30.dp)
.background(
color = Color(0xFFFFFFFF),
shape = RoundedCornerShape(size = 10.dp)
)
.clip(shape = RoundedCornerShape(size = 10.dp))
// .padding(bottom = 7 .dp)
)
var staySignedIn = true;
Checkbox(checked = staySignedIn, onCheckedChange = {
staySignedIn = !staySignedIn
})
}
}
}
@Composable
private fun bgGradient(
gradientType: Int,
colors: List<Color>
): Brush {
val endOffset = when (gradientType) {
0 -> Offset(0f, Float.POSITIVE_INFINITY)
1 -> Offset(Float.POSITIVE_INFINITY, 0f)
else -> Offset(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)
}
return Brush.linearGradient(
colors = colors,
start = Offset.Zero,
end = endOffset
)
}
@Preview
@Composable
fun PreviewLoginScreen() {
LearnComposeTheme {
LoginMenuTest()
}
}
/**
* SampleData for Jetpack Compose Tutorial
*/
object SampleData {
// Sample conversation data
val conversationSample = listOf(
Message(
"Lexi",
"Test...Test...Test..."
),
Message(
"Lexi",
"""List of Android versions:
|Android KitKat (API 19)
|Android Lollipop (API 21)
|Android Marshmallow (API 23)
|Android Nougat (API 24)
|Android Oreo (API 26)
|Android Pie (API 28)
|Android 10 (API 29)
|Android 11 (API 30)
|Android 12 (API 31)""".trim()
),
Message(
"Lexi",
"""I think Kotlin is my favorite programming language.
|It's so much fun!""".trim()
),
Message(
"Lexi",
"Searching for alternatives to XML layouts..."
),
Message(
"Lexi",
"""Hey, take a look at Jetpack Compose, it's great!
|It's the Android's modern toolkit for building native UI.
|It simplifies and accelerates UI development on Android.
|Less code, powerful tools, and intuitive Kotlin APIs :)""".trim()
),
Message(
"Lexi",
"It's available from API 21+ :)"
),
Message(
"Lexi",
"Writing Kotlin for UI seems so natural, Compose where have you been all my life?"
),
Message(
"Lexi",
"Android Studio next version's name is <NAME>"
),
Message(
"Lexi",
"Android Studio Arctic Fox tooling for Compose is top notch ^_^"
),
Message(
"Lexi",
"I didn't know you can now run the emulator directly from Android Studio"
),
Message(
"Lexi",
"Compose Previews are great to check quickly how a composable layout looks like"
),
Message(
"Lexi",
"Previews are also interactive after enabling the experimental setting"
),
Message(
"Lexi",
"Have you tried writing build.gradle with KTS?"
),
)
}
| 0 | Kotlin | 0 | 0 | e23ab0d0126e40d701d4f2aee369bf16354ff096 | 13,844 | PayLink_FrontEnd | MIT License |
secure-persist/src/androidTest/java/eu/anifantakis/lib/securepersist/CustomTypeDelegationDataStoreTest.kt | ioannisa | 804,068,487 | false | null | package eu.anifantakis.lib.securepersist
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class CustomTypeDelegationDataStoreTest {
private lateinit var persistManager: PersistManager
private lateinit var testClass: TestClass
data class AuthInfo(
val accessToken: String = "",
val refreshToken: String = "",
val expiresIn: Long = 0L
)
class TestClass(persistManager: PersistManager) {
var authInfo by persistManager.dataStoreDelegate(AuthInfo())
}
@Before
fun setup() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
persistManager = PersistManager(context)
testClass = TestClass(persistManager)
// Clear existing preference before each test
persistManager.dataStorePrefs.deleteDirect("authInfo")
// because the above is async leave some time to thread for deletion to happen
Thread.sleep(500L)
persistManager.dataStorePrefs.putDirect(
key = "authInfo",
value = AuthInfo(
accessToken = "token123",
refreshToken = "<PASSWORD>",
expiresIn = 3600L
)
)
Thread.sleep(500L)
}
@Test
fun testCustomTypeDataStoreDelegated() {
val storedAuthInfo by persistManager.dataStoreDelegate(AuthInfo(), "authInfo")
assertEquals("token123", storedAuthInfo.accessToken)
assertEquals("refresh123", storedAuthInfo.refreshToken)
assertEquals(3600L, storedAuthInfo.expiresIn)
}
@Test
fun testCustomTypeDataStoreDelegatedChangingValue() {
var storedAuthInfo by persistManager.dataStoreDelegate(AuthInfo(), "authInfo")
storedAuthInfo = storedAuthInfo.copy(accessToken = "accessToken999")
// Because the above is non-blocking lets wait before we assert
Thread.sleep(500L)
assertEquals("accessToken999", testClass.authInfo.accessToken)
assertEquals("refresh123", testClass.authInfo.refreshToken)
assertEquals(3600L, testClass.authInfo.expiresIn)
}
@Test
fun testCustomTypeDataStore() {
val storedAuthInfo = testClass.authInfo
assertEquals("token123", storedAuthInfo.accessToken)
assertEquals("refresh123", storedAuthInfo.refreshToken)
assertEquals(3600L, storedAuthInfo.expiresIn)
}
@Test
fun testCustomTypeDataStoreDelegation() {
// if no key provided, SharedPreferences uses the variable name as key
val authInfo by persistManager.dataStoreDelegate(AuthInfo())
assertEquals("token123", authInfo.accessToken)
assertEquals("refresh123", authInfo.refreshToken)
assertEquals(3600L, authInfo.expiresIn)
}
@Test
fun testCustomTypeDataStoreDelegationSetKey() {
// if a key is provided, it will be used by SharedPreference as a key
val storedAuthInfo by persistManager.dataStoreDelegate(AuthInfo(), "authInfo")
assertEquals("token123", storedAuthInfo.accessToken)
assertEquals("refresh123", storedAuthInfo.refreshToken)
assertEquals(3600L, storedAuthInfo.expiresIn)
}
} | 0 | null | 0 | 3 | f1043ab029eb387336101930516122a76b7e53c5 | 3,382 | SecuredAndroidPersistence | MIT License |
app/src/main/java/ke/co/tulivuapps/hobbyhorsetours/data/model/episode/PopularResponse.kt | brendenozie | 685,892,586 | false | {"Kotlin": 631866} | package ke.co.tulivuapps.hobbyhorsetours.data.model.episode
import android.os.Parcelable
import ke.co.tulivuapps.hobbyhorsetours.data.model.InfoResponse
import kotlinx.parcelize.Parcelize
@Parcelize
data class PopularResponse(
val info: InfoResponse,
val results: List<PopularResultResponse>
) : Parcelable
| 0 | Kotlin | 0 | 0 | 3f8f6a18adde1bb2c60b22585137dfa67568fff1 | 317 | HobbyHorseToursAndroidApp | Apache License 2.0 |
src/main/kotlin/com/thoughtworks/rldd/service/member/MemberRepository.kt | tw-rldd | 133,049,039 | false | {"Groovy": 9354, "Kotlin": 6547} | package com.thoughtworks.rldd.service.member
import com.thoughtworks.rldd.service.member.model.Member
import org.springframework.dao.EmptyResultDataAccessException
import org.springframework.jdbc.core.RowMapper
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.stereotype.Repository
@Repository
class MemberRepository(val namedParameterJdbcTemplate: NamedParameterJdbcTemplate) {
fun save(member: Member) {
if (exist(member)) {
namedParameterJdbcTemplate.update("UPDATE member SET username = :name, point = :point WHERE id = :id;",
mapOf(
"id" to member.id,
"name" to member.name,
"point" to member.point
))
} else {
namedParameterJdbcTemplate.update("INSERT INTO member (id, username, point) VALUES (:id, :name, :point);",
mapOf(
"id" to member.id,
"name" to member.name,
"point" to member.point
))
}
}
private fun exist(member: Member): Boolean {
return namedParameterJdbcTemplate.queryForObject("SELECT count(*) FROM member WHERE ID = :id;",
mapOf("id" to member.id), Int::class.java)!! > 0
}
fun retrieveAll(): List<Member> {
return namedParameterJdbcTemplate.query("SELECT * FROM member;",
RowMapper { rs, _ ->
val id = rs.getString("id")
val username = rs.getString("username")
val point = rs.getInt("point")
return@RowMapper Member(id, username, point)
})
}
fun findBy(userId: String): Member? {
try {
return namedParameterJdbcTemplate.queryForObject("SELECT * FROM member WHERE ID = :id;",
mapOf("id" to userId),
RowMapper { rs, _ ->
val username = rs.getString("username")
val point = rs.getInt("point")
return@RowMapper Member(userId, username, point)
})
} catch (error: EmptyResultDataAccessException) {
return null
}
}
fun removeBy(userId: String) {
namedParameterJdbcTemplate.update("DELETE FROM member WHERE ID = :id", mapOf("id" to userId))
}
} | 0 | Groovy | 0 | 0 | d3e6670252129b88066be7962def2b8e905ae022 | 2,153 | rldd-service | MIT License |
plugin/src/main/kotlin/ru/astrainteractive/slaughterhouse/command/di/CommandModule.kt | makeevrserg | 759,423,631 | false | {"Kotlin": 32620} | package ru.astrainteractive.slaughterhouse.command.di
import ru.astrainteractive.astralibs.lifecycle.Lifecycle
import ru.astrainteractive.slaughterhouse.command.common.CommonCommandsRegistry
import ru.astrainteractive.slaughterhouse.command.reload.ReloadCommandRegistry
import ru.astrainteractive.slaughterhouse.di.RootModule
interface CommandModule {
val lifecycle: Lifecycle
class Default(rootModule: RootModule) : CommandModule {
override val lifecycle: Lifecycle by lazy {
Lifecycle.Lambda(
onEnable = {
val dependencies = CommandManagerDependencies.Default(rootModule)
CommonCommandsRegistry(dependencies).register()
ReloadCommandRegistry(dependencies).register()
}
)
}
}
}
| 0 | Kotlin | 0 | 0 | 433468cfed9b9ca4e045ca7a5d4aa2386e04fbcc | 826 | Slaughterhouse | MIT License |
library/src/androidTest/java/com/github/lcdsmao/springx/InstrumentationUiTestScope.kt | lcdsmao | 187,489,244 | false | null | package com.github.lcdsmao.springx
import androidx.test.platform.app.InstrumentationRegistry
@Suppress("unused")
class InstrumentationUiTestScope : UiTestScope {
override fun runOnMainSync(block: () -> Unit) {
InstrumentationRegistry.getInstrumentation().runOnMainSync {
block.invoke()
}
}
override fun waitForIdleSync() {
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
}
class Runner : UiTestScope.Runner {
override fun runUiTest(block: () -> Unit) {
block.invoke()
}
}
}
| 12 | Kotlin | 1 | 104 | 2b8d9fee70981142967680cb038e04c2fca163a6 | 539 | SpringX | Apache License 2.0 |
src/main/java/lala/data/models/Candidate.kt | miguelslemos | 112,460,912 | false | null | package lala.data.models
/**
* Created by miguellemos on 03/10/17.
*/
class Candidate(val name: String, val code: Int, val party: String, val officeType: OfficeType) : AbsVote() {
override fun createVote(candidate: Candidate?): Candidate {
return candidate!!;
}
}
| 1 | null | 1 | 2 | 31db387ae4557eb55754c6afa986653c79b7c567 | 286 | brazilian-voting-system | Apache License 2.0 |
wash-bazel/kotlin/com/muandrew/stock/model/TransactionReport.kt | muandrew | 581,945,125 | false | {"Kotlin": 104075, "Rust": 12465, "Starlark": 11664, "Java": 457, "Shell": 127} | package com.muandrew.stock.model
import com.muandrew.money.Money
import com.squareup.moshi.Json
import java.time.LocalDate
sealed interface TransactionReport {
val ref: TransactionReference
data class ReceivedReport(
override val ref: TransactionReference,
val shares: Long,
val costBasis: Money,
) : TransactionReport
data class SaleReport(
override val ref: TransactionReference,
val shares: Long,
val saleValue: Money,
val basisBeforeAdjustment: Money,
val disallowedValue: Money,
val disallowedTransfer: List<WashRecord>,
val allowedTransfer: List<SaleRecord>,
) : TransactionReport {
data class WashRecord(
val soldLotId: String,
val soldLotDateForSalesCalculation: LocalDate,
val soldLotDate: LocalDate,
val transferredLotId: String,
val resultingId: String,
val shares: Long,
val basis: Money,
val gross: Money,
){
@Json(ignore = true)
val net get() = gross - basis
}
data class SaleRecord(
val soldLotId: String,
val soldLotDateForSalesCalculation: LocalDate,
val soldLotDate: LocalDate,
val shares: Long,
val basis: Money,
val gross: Money,
) {
@Json(ignore = true)
val net get() = gross - basis
}
}
} | 0 | Kotlin | 0 | 1 | 67137c11ce20c52fcf2560f3ce33a5b201ad6a46 | 1,485 | wash-sale | MIT License |
core/src/main/java/com/bruno13palhano/core/data/repository/delivery/DeliveryRepository.kt | bruno13palhano | 670,001,130 | false | {"Kotlin": 1037210} | package com.bruno13palhano.core.data.repository.delivery
import com.bruno13palhano.core.data.DeliveryData
import com.bruno13palhano.core.data.di.InternalDeliveryLight
import com.bruno13palhano.core.model.Delivery
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
internal class DeliveryRepository @Inject constructor(
@InternalDeliveryLight private val deliveryData: DeliveryData<Delivery>
) : DeliveryData<Delivery> {
override suspend fun insert(model: Delivery): Long {
return deliveryData.insert(model = model)
}
override suspend fun update(model: Delivery) {
deliveryData.update(model = model)
}
override suspend fun updateDeliveryPrice(id: Long, deliveryPrice: Float) {
deliveryData.updateDeliveryPrice(id = id, deliveryPrice = deliveryPrice)
}
override suspend fun updateShippingDate(id: Long, shippingDate: Long) {
deliveryData.updateShippingDate(id = id, shippingDate = shippingDate)
}
override suspend fun updateDeliveryDate(id: Long, deliveryDate: Long) {
deliveryData.updateDeliveryDate(id = id, deliveryDate = deliveryDate)
}
override suspend fun updateDelivered(id: Long, delivered: Boolean) {
deliveryData.updateDelivered(id = id, delivered = delivered)
}
override fun getDeliveries(delivered: Boolean): Flow<List<Delivery>> {
return deliveryData.getDeliveries(delivered = delivered)
}
override suspend fun deleteById(id: Long) {
deliveryData.deleteById(id = id)
}
override fun getAll(): Flow<List<Delivery>> {
return deliveryData.getAll()
}
override fun getById(id: Long): Flow<Delivery> {
return deliveryData.getById(id = id)
}
override fun getLast(): Flow<Delivery> {
return deliveryData.getLast()
}
override fun getCanceledDeliveries(): Flow<List<Delivery>> {
return deliveryData.getCanceledDeliveries()
}
} | 0 | Kotlin | 0 | 1 | 458547ab2a6c0d91e2489a9eab763243a00ca2cf | 1,947 | shop-dani-management | MIT License |
caiguicheng/week01/day04/day03作业修改版/demo03work/service/imp/PermissionServiceImp.kt | cgc186 | 229,741,189 | false | {"Text": 54, "Markdown": 3, "HTML": 29, "CSS": 24, "JavaScript": 24, "Java": 130, "Kotlin": 86, "Maven POM": 10, "Java Properties": 3, "XML": 41, "INI": 11, "YAML": 7, "SQL": 2, "JSON": 4, "Python": 1122, "PowerShell": 2, "Batchfile": 4, "reStructuredText": 3} | package com.example.demo03work.service.imp
import com.example.demo03work.dao.IPermission
import com.example.demo03work.entity.Permission
import com.example.demo03work.service.PermissionService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Lazy
import org.springframework.stereotype.Service
@Service
class PermissionServiceImp : PermissionService {
//使用时候创建
@Autowired
@Lazy
lateinit var iPermission: IPermission
/**
* 插入权限
* @return 是否成功
*/
override fun insertPermission(permission: Permission): Int{
return iPermission.insertPermission(permission)
}
/**
* 更新权限信息
* @return 是否成功
*/
override fun updatePermission(permission: Permission): Int{
return iPermission.updatePermission(permission)
}
/**
* 根据条件获得权限
* @return 权限列表
*/
override fun selectPermission(permission: Permission):List<Permission>{
return iPermission.selectPermission(permission)
}
/**
* 删除权限
* @return 是否成功
*/
override fun deletePermission(id:Int):Int{
return iPermission.deletePermission(id)
}
} | 3 | Python | 0 | 0 | b4da417e8eeb13d81d44467bd46dca73126625df | 1,186 | work | Academic Free License v3.0 |
analyzers/chronolens-decapsulations/src/test/kotlin/org/chronolens/decapsulations/java/JavaAnalyzerTest.kt | andreihh | 83,168,079 | false | null | /*
* Copyright 2018-2022 Andrei Heidelbacher <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chronolens.decapsulations.java
import kotlin.test.assertEquals
import org.chronolens.core.model.SourceTree
import org.chronolens.core.model.function
import org.chronolens.core.model.qualifiedSourcePathOf
import org.chronolens.core.model.type
import org.chronolens.decapsulations.AbstractDecapsulationAnalyzer
import org.chronolens.decapsulations.java.JavaAnalyzer.Companion.PACKAGE_LEVEL
import org.chronolens.decapsulations.java.JavaAnalyzer.Companion.PRIVATE_LEVEL
import org.chronolens.decapsulations.java.JavaAnalyzer.Companion.PRIVATE_MODIFIER
import org.chronolens.decapsulations.java.JavaAnalyzer.Companion.PROTECTED_LEVEL
import org.chronolens.decapsulations.java.JavaAnalyzer.Companion.PROTECTED_MODIFIER
import org.chronolens.decapsulations.java.JavaAnalyzer.Companion.PUBLIC_LEVEL
import org.chronolens.decapsulations.java.JavaAnalyzer.Companion.PUBLIC_MODIFIER
import org.chronolens.test.core.model.function
import org.chronolens.test.core.model.sourceFile
import org.chronolens.test.core.model.sourceTree
import org.chronolens.test.core.model.type
import org.junit.Ignore
import org.junit.Test
@Ignore
class JavaAnalyzerTest {
private fun getSourceTreeWithType(className: String, modifier: String? = null): SourceTree =
sourceTree {
+sourceFile("$className.java") {
+type(className) {
if (modifier != null) {
modifiers(modifier)
}
}
}
}
private fun getSourceTreeWithInterface(className: String): SourceTree = sourceTree {
+sourceFile("$className.java") {
+type(className) {
modifiers("interface")
+function("get()") {}
}
}
}
@Test
fun `test private visibility`() {
val name = "Main"
val sourceTree = getSourceTreeWithType(name, PRIVATE_MODIFIER)
val id = qualifiedSourcePathOf("$name.java").type(name)
val expectedLevel = PRIVATE_LEVEL
val actualLevel = AbstractDecapsulationAnalyzer.getVisibility(sourceTree, id)
assertEquals(expectedLevel, actualLevel)
}
@Test
fun `test package visibility`() {
val name = "Main"
val sourceTree = getSourceTreeWithType(name)
val id = qualifiedSourcePathOf("$name.java").type(name)
val expectedLevel = PACKAGE_LEVEL
val actualLevel = AbstractDecapsulationAnalyzer.getVisibility(sourceTree, id)
assertEquals(expectedLevel, actualLevel)
}
@Test
fun `test protected visibility`() {
val name = "Main"
val sourceTree = getSourceTreeWithType(name, PROTECTED_MODIFIER)
val id = qualifiedSourcePathOf("$name.java").type(name)
val expectedLevel = PROTECTED_LEVEL
val actualLevel = AbstractDecapsulationAnalyzer.getVisibility(sourceTree, id)
assertEquals(expectedLevel, actualLevel)
}
@Test
fun `test public visibility`() {
val name = "Main"
val sourceTree = getSourceTreeWithType(name, PUBLIC_MODIFIER)
val id = qualifiedSourcePathOf("$name.java").type(name)
val expectedLevel = PUBLIC_LEVEL
val actualLevel = AbstractDecapsulationAnalyzer.getVisibility(sourceTree, id)
assertEquals(expectedLevel, actualLevel)
}
@Test
fun `test interface method is public`() {
val name = "Main"
val sourceTree = getSourceTreeWithInterface(name)
val id = qualifiedSourcePathOf("$name.java").type(name).function("get()")
val expectedLevel = PUBLIC_LEVEL
val actualLevel = AbstractDecapsulationAnalyzer.getVisibility(sourceTree, id)
assertEquals(expectedLevel, actualLevel)
}
}
| 0 | Kotlin | 1 | 5 | 7531efb2207470346b0e8fad4181a4e1ad652f90 | 4,379 | chronolens | Apache License 2.0 |
Gelivery/app/src/main/java/com/tolganacar/gelivery/ui/viewmodel/FoodListViewModel.kt | tolganacar | 773,367,333 | false | {"Kotlin": 27678} | package com.tolganacar.gelivery.ui.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.tolganacar.gelivery.data.entity.Foods
import com.tolganacar.gelivery.data.repo.FoodsRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class FoodListViewModel @Inject constructor(var foodsRepository: FoodsRepository) : ViewModel() {
var foodList = MutableLiveData<List<Foods>>()
init {
loadFoods()
}
fun loadFoods() {
CoroutineScope(Dispatchers.Main).launch {
foodList.value = foodsRepository.loadFoods()
}
}
fun searchFoods(searchQuery: String) {
val filteredList = foodList.value?.filter { food ->
food.yemek_adi.contains(searchQuery, ignoreCase = true)
}
foodList.value = filteredList
}
} | 0 | Kotlin | 0 | 1 | 552de2090382e5d5ced5a5089eaa40339fbf5a4d | 995 | android-food-order-app-gelivery | Apache License 2.0 |
app/src/main/java/com/meronmks/chairs/Settings/AboutFragment.kt | meronmks | 115,629,807 | false | null | package com.meronmks.chairs.Settings
import android.os.Bundle
import android.preference.Preference
import androidx.preference.PreferenceFragment
import androidx.appcompat.app.AlertDialog
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.R.layout.preference
import com.meronmks.chairs.BuildConfig
import com.meronmks.chairs.R
import android.webkit.WebView
import android.view.LayoutInflater
class AboutFragment : PreferenceFragmentCompat(), androidx.preference.Preference.OnPreferenceClickListener {
override fun onPreferenceClick(p0: androidx.preference.Preference?): Boolean {
when (p0?.key) {
"OSSlist" -> {
val factory = LayoutInflater.from(activity)
val inputView = factory.inflate(R.layout.license_dialog, null)
val builder = AlertDialog.Builder(context!!)
builder.setTitle("オープンソースライセンス")
builder.setView(inputView)
if (inputView != null) {
val webView = inputView.findViewById(R.id.webView) as WebView
webView.loadUrl("file:///android_asset/licenses.html")
}
builder.setPositiveButton("OK") { _, _ -> }
val dialog = builder.create()
dialog.show()
}
}
return false
}
override fun onCreatePreferences(p0: Bundle?, p1: String?) {
addPreferencesFromResource(R.xml.about_fragment)
findPreference("appVersionText").title = "%s Ver%s".format(resources.getString(R.string.app_name), BuildConfig.VERSION_NAME)
findPreference("appVersionText").summary = "作者:meronmks\r\nPowered by mastodon4j"
findPreference("OSSlist").onPreferenceClickListener = this
}
} | 21 | Kotlin | 0 | 6 | 6703bbf4c3fd94ec5797b7fbdca6576b8924bffb | 1,780 | Chairs | MIT License |
app/src/main/java/com/arsylk/mammonsmite/presentation/dialog/pck/unpack/PckUnpackDialog.kt | Arsylk | 175,204,028 | false | null | package com.arsylk.mammonsmite.presentation.dialog.pck.unpack
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.*
import com.arsylk.mammonsmite.domain.common.IntentUtils
import com.arsylk.mammonsmite.domain.onEffect
import com.arsylk.mammonsmite.model.common.LogLine
import com.arsylk.mammonsmite.model.common.NavTab
import com.arsylk.mammonsmite.model.common.OperationProgress
import com.arsylk.mammonsmite.model.file.FileType
import com.arsylk.mammonsmite.model.file.FileTypeFile
import com.arsylk.mammonsmite.model.file.FileTypeFolder
import com.arsylk.mammonsmite.model.live2d.L2DFileLoaded
import com.arsylk.mammonsmite.presentation.Navigable.Companion.putArg
import com.arsylk.mammonsmite.presentation.Navigator
import com.arsylk.mammonsmite.presentation.composable.*
import com.arsylk.mammonsmite.presentation.dialog.NavigableDialog
import com.arsylk.mammonsmite.presentation.dialog.pck.unpack.PckUnpackDialog.Action
import com.arsylk.mammonsmite.presentation.dialog.pck.unpack.PckUnpackDialog.Tab
import com.arsylk.mammonsmite.presentation.nav
import com.arsylk.mammonsmite.presentation.screen.home.HomeScreen
import com.arsylk.mammonsmite.presentation.screen.pck.unpacked.PckUnpackedScreen
import com.arsylk.mammonsmite.presentation.view.live2d.Live2DSurfaceConfig
import kotlinx.serialization.ExperimentalSerializationApi
import org.koin.androidx.compose.viewModel
import org.koin.core.parameter.parametersOf
import java.io.File
@OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class, ExperimentalSerializationApi::class, ExperimentalMaterialApi::class)
object PckUnpackDialog : NavigableDialog {
override val route = "/pck/unpack/{path}"
override val label = "Unpack Pck"
override val args = listOf(
navArgument("path") { type = NavType.StringType }
)
fun navigate(nav: Navigator, path: String, builder: NavOptionsBuilder.() -> Unit = {}) {
val route = route.putArg("path", path)
nav.controller.navigate(route) {
launchSingleTop = true
apply(builder)
}
}
@Composable
override fun Compose(entry: NavBackStackEntry) {
val file = remember { File(entry.arguments?.getString("path")!!) }
val viewModel by viewModel<PckUnpackViewModel> { parametersOf(file) }
PckUnpackDialog(viewModel)
}
enum class Tab(override val label: String, override val icon: ImageVector) : NavTab {
FILES("Files", Icons.Default.Description),
PREVIEW("Preview", Icons.Default.Preview),
LOG("Log", Icons.Default.Article),
}
enum class Action(override val label: String, override val icon: ImageVector?) : ActionButtonItem {
CLEAN_UP("Clean up", Icons.Default.CleaningServices),
OPEN_PACKED("Open Packed", FileTypeFile.icon),
OPEN_UNPACKED("Open Unpacked", FileTypeFolder.icon),
SAVE_MODEL("Save", Icons.Default.Save),
}
}
@ExperimentalMaterialApi
@ExperimentalComposeUiApi
@ExperimentalSerializationApi
@ExperimentalFoundationApi
@Composable
fun PckUnpackDialog(viewModel: PckUnpackViewModel) {
val tab by viewModel.selectedTab.collectAsState()
var expanded by remember(tab) { mutableStateOf(false) }
Scaffold(
modifier = Modifier.fillMaxSize(0.9f),
topBar = {
val progress by viewModel.unpackProgress.collectAsState()
TopBar(progress)
},
bottomBar = {
BottomTabNavigation(
tabs = Tab.values(),
selected = tab,
onTabClick = viewModel::selectTab
)
},
floatingActionButton = {
if (tab == Tab.PREVIEW) return@Scaffold
val actionSet by viewModel.actionSet.collectAsState()
val list = remember(actionSet) { Action.values().filter { it in actionSet } }
ActionButton(
expanded = expanded,
actions = list,
onClick = { expanded = !expanded },
onActionClick = viewModel::onActionClick,
)
},
) { padding ->
Box(modifier = Modifier
.padding(padding)
.fillMaxSize()) {
when (tab) {
Tab.FILES -> {
val isLoading by viewModel.isLoading.collectAsState()
val itemList by viewModel.items.collectAsState(initial = emptyList())
if (isLoading && itemList.isEmpty()) CircularProgressIndicator(Modifier.align(Alignment.Center))
else FilesTabContent(itemList)
}
Tab.PREVIEW -> {
val loadedL2dFile by viewModel.loadedL2dFile.collectAsState()
PreviewTabContent(loadedL2dFile)
}
Tab.LOG -> {
val logList by viewModel.log.collectAsState()
LogTabContent(logList)
}
}
}
}
val context = LocalContext.current
val nav = nav
viewModel.onEffect(nav) { effect ->
when (effect) {
Effect.Dismiss -> nav.controller.popBackStack()
is Effect.OpenFile -> IntentUtils.openFile(context, effect.file)
is Effect.SaveUnpacked -> PckUnpackedScreen.navigate(nav, effect.folder) {
popUpTo(HomeScreen.route)
}
}
}
}
@Composable
fun TopBar(progress: OperationProgress) {
Column(modifier = Modifier.fillMaxWidth()) {
TopAppBar(
title = { Text(progress.toString()) },
backgroundColor = MaterialTheme.colors.primaryVariant,
)
LinearProgressIndicator(
progress = progress.percentage,
modifier = Modifier.fillMaxWidth(),
)
}
}
@Composable
fun FilesTabContent(items: List<PckHeaderItem>) {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(items) { item ->
PckHeaderItem(item)
}
}
}
@Composable
fun PreviewTabContent(loadedL2dFile: L2DFileLoaded?) {
var surfaceConfig by remember { mutableStateOf(Live2DSurfaceConfig.Default) }
Box(Modifier.fillMaxSize()) {
if (loadedL2dFile != null) {
Live2DSurface(
loadedL2dFile = loadedL2dFile,
surfaceConfig = surfaceConfig,
playMotion = false,
onMotionPlayed = {}
) { offset, scale ->
surfaceConfig = surfaceConfig.copy(
scale = surfaceConfig.scale * scale,
offsetX = surfaceConfig.offsetX + offset.x,
offsetY = surfaceConfig.offsetY + offset.y,
)
}
} else {
Text("Can't preview", modifier = Modifier.align(Alignment.Center))
}
}
}
@ExperimentalFoundationApi
@Composable
fun LogTabContent(logList: List<LogLine>) {
LogLines(logList)
}
@Composable
fun PckHeaderItem(item: PckHeaderItem) {
Column(modifier = Modifier.padding(8.dp)) {
when (item) {
is PckHeaderItem.Packed -> {
Text(item.entry.hashString)
}
is PckHeaderItem.Unpacked -> {
Text(item.entry.filename)
Text(
item.entry.hashString,
color = Color.LightGray,
fontSize = 12.sp
)
}
}
}
} | 3 | Java | 10 | 34 | 2ec0056ea61d3d170ac4ee22a96198d58f6214e2 | 8,269 | destiny-child-tools-kr-apk | MIT License |
data/src/main/java/com/qure/data/datasource/auth/AuthRemoteDataSource.kt | hegleB | 613,354,773 | false | {"Kotlin": 494598} | package com.qure.data.datasource.auth
import com.qure.data.entity.auth.SignUpUserEntity
interface AuthRemoteDataSource {
suspend fun postSignUp(
email: String,
userId: String,
): Result<SignUpUserEntity>
suspend fun getSignedUpUser(email: String): Result<SignUpUserEntity>
suspend fun deleteUserEmail(email: String): Result<Unit>
}
| 0 | Kotlin | 0 | 1 | cc3f629b8f4d4044da284aa89fd4b0998fee3549 | 368 | FishingMemory | The Unlicense |
src/main/kotlin/linkshell/Linkshell.kt | drakon64 | 622,012,311 | false | {"Kotlin": 174367} | package cloud.drakon.ktlodestone.linkshell
import cloud.drakon.ktlodestone.world.DataCenter
import cloud.drakon.ktlodestone.world.Region
/** A Linkshell. */
data class Linkshell(
/** The name of the Linkshell. */
val name: String,
/** When the Cross-world Linkshell was formed. Always `null` if this is not a Cross-world Linkshell, otherwise never `null`. */
val formed: Long?,
/** The data center of the Linkshell. Always `null` if this is not a Cross-world Linkshell, otherwise never `null`. */
val dataCenter: DataCenter?,
/** The Linkshell's region. Always `null` if this is not a Cross-world Linkshell, otherwise never `null`. */
val region: Region?,
/** How many active members the Linkshell has. */
val activeMembers: Short,
/** The Linkshells members. */
val members: List<LinkshellMember>,
)
| 3 | Kotlin | 0 | 1 | 495f5da50cadbdf7733179c70e1784319987ae5f | 851 | KtLodestone | MIT License |
app/src/main/java/com/babylon/wallet/android/presentation/settings/personas/createpersona/CreatePersonaConfirmationNav.kt | radixdlt | 513,047,280 | false | {"Kotlin": 4905038, "HTML": 215350, "Ruby": 2757, "Shell": 1963} | package com.babylon.wallet.android.presentation.settings.personas.createpersona
import androidx.annotation.VisibleForTesting
import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavType
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.babylon.wallet.android.presentation.navigation.markAsHighPriority
@VisibleForTesting
private const val ROUTE = "persona_completion_route/{$ARG_REQUEST_SOURCE}"
fun NavController.createPersonaConfirmationScreen(requestSource: CreatePersonaRequestSource) {
navigate("persona_completion_route/$requestSource")
}
fun NavGraphBuilder.createPersonaConfirmationScreen(
finishPersonaCreation: () -> Unit
) {
markAsHighPriority(ROUTE)
composable(
route = ROUTE,
arguments = listOf(
navArgument(ARG_REQUEST_SOURCE) {
type = NavType.EnumType(
CreatePersonaRequestSource::class.java
)
}
),
enterTransition = {
slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Up)
},
exitTransition = {
ExitTransition.None
},
popEnterTransition = {
EnterTransition.None
},
popExitTransition = {
slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Down)
}
) {
val requestSource = it.getCreatePersonaRequestSource()
CreatePersonaConfirmationScreen(
viewModel = hiltViewModel(),
finishPersonaCreation = finishPersonaCreation,
requestSource = requestSource
)
}
}
| 6 | Kotlin | 6 | 9 | a973af97556c2c3c5c800dac937d0007a13a3a1c | 1,917 | babylon-wallet-android | Apache License 2.0 |
app/src/main/java/com/apaluk/wsplayer/ui/common/composable/SingleEventHandler.kt | apaluk | 651,545,506 | false | null | package com.apaluk.wsplayer.ui.common.composable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import com.apaluk.wsplayer.core.util.SingleEvent
@Composable
fun <T> SingleEventHandler(
singleEvent: SingleEvent<T>,
handler: (T) -> Unit
) {
LaunchedEffect(singleEvent) {
singleEvent.flow.collect {
handler(it)
}
}
} | 0 | Kotlin | 0 | 0 | aa3fb1bf6f958af2f658e377f1941f7da783460f | 402 | ws-player-android | MIT License |
core/appinfo-api/src/main/java/com/grappim/hateitorrateit/core/appinfoapi/AppInfoProvider.kt | Grigoriym | 704,244,986 | false | {"Kotlin": 500015} | package com.grappim.hateitorrateit.core.appinfoapi
interface AppInfoProvider {
fun getAppInfo(): String
fun isDebug(): Boolean
}
| 9 | Kotlin | 0 | 1 | 9ba088698f4260b856915e1500fafc050f20f2cc | 138 | HateItOrRateIt | Apache License 2.0 |
app/src/main/java/com/kiwi/github_demo/utils/LinkHeaderParser.kt | hvsimon | 480,501,353 | false | null | package com.kiwi.github_demo.utils
import java.util.regex.Pattern
object LinkHeaderParser {
private val LINK_PATTERN = Pattern.compile("<([^>]*)>[\\s]*;[\\s]*rel=\"([a-zA-Z0-9]+)\"")
private val SINCE_PATTERN = Pattern.compile("\\bsince=(\\d+)")
private const val NEXT_LINK = "next"
fun String.extractLinks(): Map<String, String> {
val links = mutableMapOf<String, String>()
val matcher = LINK_PATTERN.matcher(this)
while (matcher.find()) {
val count = matcher.groupCount()
if (count == 2) {
links[matcher.group(2)!!] = matcher.group(1)!!
}
}
return links
}
fun Map<String, String>.nextSinceValue(): Int? {
return this[NEXT_LINK]?.let { next ->
val matcher = SINCE_PATTERN.matcher(next)
if (!matcher.find() || matcher.groupCount() != 1) {
null
} else {
try {
Integer.parseInt(matcher.group(1)!!)
} catch (ex: NumberFormatException) {
null
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | e384de10c14710e85ebd093da64c0e9cbd241fd7 | 1,143 | Github-Demo | Apache License 2.0 |
arrow-libs/core/arrow-core/src/main/kotlin/arrow/core/extensions/nonemptylist/functor/NonEmptyListFunctor.kt | clojj | 343,913,289 | true | {"Kotlin": 6274993, "SCSS": 78040, "JavaScript": 77812, "HTML": 21200, "Scala": 8073, "Shell": 2474, "Ruby": 83} | package arrow.core.extensions.nonemptylist.functor
import arrow.Kind
import arrow.core.ForNonEmptyList
import arrow.core.NonEmptyList
import arrow.core.NonEmptyList.Companion
import arrow.core.Tuple2
import arrow.core.extensions.NonEmptyListFunctor
/**
* cached extension
*/
@PublishedApi()
internal val functor_singleton: NonEmptyListFunctor = object :
arrow.core.extensions.NonEmptyListFunctor {}
/**
* Transform the [F] wrapped value [A] into [B] preserving the [F] structure
* Kind<F, A> -> Kind<F, B>
*
* ```kotlin:ank:playground
* import arrow.core.*
* import arrow.core.extensions.nonemptylist.functor.*
* import arrow.core.*
*
*
* import arrow.core.extensions.nonemptylist.applicative.just
*
* fun main(args: Array<String>) {
* val result =
* //sampleStart
* "Hello".just().map({ "$it World" })
* //sampleEnd
* println(result)
* }
* ```
*/
@JvmName("map")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(
"@extension kinded projected functions are deprecated",
ReplaceWith(
"fix().map<B>(arg1)",
"arrow.core.fix"
),
DeprecationLevel.WARNING
)
fun <A, B> Kind<ForNonEmptyList, A>.map(arg1: Function1<A, B>): NonEmptyList<B> =
arrow.core.NonEmptyList.functor().run {
[email protected]<A, B>(arg1) as arrow.core.NonEmptyList<B>
}
@JvmName("imap")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(
"@extension kinded projected functions are deprecated",
ReplaceWith(
"fix().map<B>(arg1)",
"arrow.core.fix"
),
DeprecationLevel.WARNING
)
fun <A, B> Kind<ForNonEmptyList, A>.imap(arg1: Function1<A, B>, arg2: Function1<B, A>):
NonEmptyList<B> = arrow.core.NonEmptyList.functor().run {
[email protected]<A, B>(arg1, arg2) as arrow.core.NonEmptyList<B>
}
/**
* Lifts a function `A -> B` to the [F] structure returning a polymorphic function
* that can be applied over all [F] values in the shape of Kind<F, A>
*
* `A -> B -> Kind<F, A> -> Kind<F, B>`
*
* ```kotlin:ank:playground
* import arrow.core.*
* import arrow.core.extensions.nonemptylist.functor.*
* import arrow.core.*
*
*
* import arrow.core.extensions.nonemptylist.applicative.just
*
* fun main(args: Array<String>) {
* val result =
* //sampleStart
* lift({ s: CharSequence -> "$s World" })("Hello".just())
* //sampleEnd
* println(result)
* }
* ```
*/
@JvmName("lift")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(
"@extension kinded projected functions are deprecated",
ReplaceWith(
"{ nel: NonEmptyList<Int> -> nel.map { arg0 }}",
"arrow.core.NonEmptyList"
),
DeprecationLevel.WARNING
)
fun <A, B> lift(arg0: Function1<A, B>): Function1<Kind<ForNonEmptyList, A>, Kind<ForNonEmptyList,
B>> = arrow.core.NonEmptyList
.functor()
.lift<A, B>(arg0) as kotlin.Function1<arrow.Kind<arrow.core.ForNonEmptyList, A>,
arrow.Kind<arrow.core.ForNonEmptyList, B>>
@JvmName("void")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(
"@extension kinded projected functions are deprecated",
ReplaceWith(
"fix().void<A>()",
"arrow.core.fix",
"arrow.core.void"
),
DeprecationLevel.WARNING
)
fun <A> Kind<ForNonEmptyList, A>.void(): NonEmptyList<Unit> =
arrow.core.NonEmptyList.functor().run {
[email protected]<A>() as arrow.core.NonEmptyList<kotlin.Unit>
}
@JvmName("fproduct")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(
"@extension kinded projected functions are deprecated",
ReplaceWith(
"fix().fproduct<A, B>(arg1)",
"arrow.core.fix",
"arrow.core.fproduct"
),
DeprecationLevel.WARNING
)
fun <A, B> Kind<ForNonEmptyList, A>.fproduct(arg1: Function1<A, B>): NonEmptyList<Tuple2<A, B>> =
arrow.core.NonEmptyList.functor().run {
[email protected]<A, B>(arg1) as arrow.core.NonEmptyList<arrow.core.Tuple2<A, B>>
}
@JvmName("mapConst")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(
"@extension kinded projected functions are deprecated",
ReplaceWith(
"fix().mapConst<A, B>(arg1)",
"arrow.core.fix",
"arrow.core.mapConst"
),
DeprecationLevel.WARNING
)
fun <A, B> Kind<ForNonEmptyList, A>.mapConst(arg1: B): NonEmptyList<B> =
arrow.core.NonEmptyList.functor().run {
[email protected]<A, B>(arg1) as arrow.core.NonEmptyList<B>
}
/**
* Replaces the [B] value inside [F] with [A] resulting in a Kind<F, A>
*/
@JvmName("mapConst")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(
"@extension kinded projected functions are deprecated",
ReplaceWith(
"arg1.fix().mapConst<B, A>(this)",
"arrow.core.fix",
"arrow.core.mapConst"
),
DeprecationLevel.WARNING
)
fun <A, B> A.mapConst(arg1: Kind<ForNonEmptyList, B>): NonEmptyList<A> =
arrow.core.NonEmptyList.functor().run {
[email protected]<A, B>(arg1) as arrow.core.NonEmptyList<A>
}
@JvmName("tupleLeft")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(
"@extension kinded projected functions are deprecated",
ReplaceWith(
"fix().tupleLeft<A, B>(arg1)",
"arrow.core.fix",
"arrow.core.tupleLeft"
),
DeprecationLevel.WARNING
)
fun <A, B> Kind<ForNonEmptyList, A>.tupleLeft(arg1: B): NonEmptyList<Tuple2<B, A>> =
arrow.core.NonEmptyList.functor().run {
[email protected]<A, B>(arg1) as arrow.core.NonEmptyList<arrow.core.Tuple2<B, A>>
}
@JvmName("tupleRight")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(
"@extension kinded projected functions are deprecated",
ReplaceWith(
"fix().tupleRight<A, B>(arg1)",
"arrow.core.fix",
"arrow.core.tupleRight"
),
DeprecationLevel.WARNING
)
fun <A, B> Kind<ForNonEmptyList, A>.tupleRight(arg1: B): NonEmptyList<Tuple2<A, B>> =
arrow.core.NonEmptyList.functor().run {
[email protected]<A, B>(arg1) as arrow.core.NonEmptyList<arrow.core.Tuple2<A, B>>
}
@JvmName("widen")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(
"@extension kinded projected functions are deprecated",
ReplaceWith(
"fix().widen<B, A>()",
"arrow.core.fix",
"arrow.core.widen"
),
DeprecationLevel.WARNING
)
fun <B, A : B> Kind<ForNonEmptyList, A>.widen(): NonEmptyList<B> =
arrow.core.NonEmptyList.functor().run {
[email protected]<B, A>() as arrow.core.NonEmptyList<B>
}
@Suppress(
"UNCHECKED_CAST",
"NOTHING_TO_INLINE"
)
@Deprecated("Functor typeclass is deprecated. Use concrete methods on NonEmptyList")
inline fun Companion.functor(): NonEmptyListFunctor = functor_singleton as arrow.core.extensions.NonEmptyListFunctor
| 0 | null | 0 | 0 | 5eae605bbaeb2b911f69a5bccf3fa45c42578416 | 7,115 | arrow | Apache License 2.0 |
app/src/main/java/ru/karasevm/privatednstoggle/DeleteServerDialogFragment.kt | karasevm | 397,230,660 | false | {"Kotlin": 23364} | package ru.karasevm.privatednstoggle
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
class DeleteServerDialogFragment(private val position: Int): DialogFragment() {
// Use this instance of the interface to deliver action events
private lateinit var listener: NoticeDialogListener
/* The activity that creates an instance of this dialog fragment must
* implement this interface in order to receive event callbacks.
* Each method passes the DialogFragment in case the host needs to query it. */
interface NoticeDialogListener {
fun onDialogPositiveClick(dialog: DialogFragment, position: Int)
}
// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
override fun onAttach(context: Context) {
super.onAttach(context)
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
listener = context as NoticeDialogListener
} catch (e: ClassCastException) {
// The activity doesn't implement the interface, throw exception
throw ClassCastException((context.toString() +
" must implement NoticeDialogListener"))
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val builder = AlertDialog.Builder(it)
builder.setMessage(R.string.delete_question)
.setPositiveButton(R.string.delete
) { _, _ ->
listener.onDialogPositiveClick(this, position)
}
.setNegativeButton(R.string.cancel
) { _, _ ->
dialog?.cancel()
}
// Create the AlertDialog object and return it
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
} | 0 | Kotlin | 2 | 28 | 2ab8354116cf42369bb122b5778c09b31e44b036 | 2,079 | PrivateDNSAndroid | MIT License |
src/main/kotlin/me/alvin0319/neisapi/request/EduSession.kt | alvin0319 | 395,893,385 | false | null | /*
* MIT License
*
* Copyright (c) 2021 alvin0319
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.alvin0319.neisapi.request
import me.alvin0319.neisapi.types.SchoolDistrictList
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClients
import java.util.Date
class EduSession(private val eduCode: SchoolDistrictList) {
var cookie: String = ""
get() {
if (time < Date().time || field == "") {
return refreshCookie()
}
return field
}
private var time: Long = -1
private fun refreshCookie(): String {
val client = HttpClients.createDefault()
val request = HttpGet("https://stu.${eduCode.url}/edusys.jsp?page=sts_m40000")
request.addHeader(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36"
)
val response = client.execute(request)
if (response.statusLine.statusCode != 200) {
throw IllegalStateException("Invalid HTTP status code returned: ${response.statusLine.statusCode}")
}
val cookie =
response.getHeaders("set-cookie")[1].toString().replace("Set-Cookie: ", "").replace("JSESSIONID=", "")
.replace("Path=/", "")
if (cookie == "") {
throw IllegalStateException("Server returned invalid cookie: $cookie")
}
this.cookie = cookie
time = Date().time + 1000 * 60 * 30
return this.cookie
}
companion object {
private val sessions: MutableMap<String, EduSession> = mutableMapOf()
fun getSession(eduCode: SchoolDistrictList): EduSession {
return sessions.getOrPut(eduCode.name) { EduSession(eduCode) }
}
}
}
| 0 | Kotlin | 1 | 2 | ccd7fd1645ca70c0814c8776205ac8dd0bafea68 | 2,877 | NeisAPI | MIT License |
src/main/kotlin/org/sendoh/exchange/CarRentalExchange.kt | HungUnicorn | 246,826,509 | false | null | package org.sendoh.exchange
import io.undertow.server.HttpServerExchange
import org.sendoh.web.exchange.Exchange
import org.sendoh.model.LocationWithDistance
import org.sendoh.request.RentCarCustomerRequest
class CarRentalExchange {
fun carLicenseNo(exchange: HttpServerExchange): String {
return Exchange.pathParams().pathParam(exchange, "carLicenseNo")!!
}
fun post(exchange: HttpServerExchange): RentCarCustomerRequest {
return Exchange.body().parseJson(exchange, RentCarCustomerRequest.typeRef())
}
fun delete(exchange: HttpServerExchange) : RentCarCustomerRequest {
return Exchange.body().parseJson(exchange, RentCarCustomerRequest.typeRef())
}
fun locationWithDistance(exchange: HttpServerExchange) : LocationWithDistance{
return Exchange.body().parseJson(exchange, LocationWithDistance.typeRef())
}
}
| 0 | Kotlin | 0 | 0 | 62214734f52157f2fa1828d055f5d4558da0ed11 | 878 | car-booking | MIT License |
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/HashtagLock.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.HashtagLock: ImageVector
get() {
if (_hashtagLock != null) {
return _hashtagLock!!
}
_hashtagLock = Builder(name = "HashtagLock", 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(22.0f, 14.0f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -2.206f, -1.794f, -4.0f, -4.0f, -4.0f)
reflectiveCurveToRelative(-4.0f, 1.794f, -4.0f, 4.0f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(7.0f)
curveToRelative(0.0f, 1.654f, 1.346f, 3.0f, 3.0f, 3.0f)
horizontalLineToRelative(6.0f)
curveToRelative(1.654f, 0.0f, 3.0f, -1.346f, 3.0f, -3.0f)
verticalLineToRelative(-7.0f)
horizontalLineToRelative(-2.0f)
close()
moveTo(19.0f, 20.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(2.0f)
close()
moveTo(20.0f, 14.0f)
horizontalLineToRelative(-4.0f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -1.103f, 0.897f, -2.0f, 2.0f, -2.0f)
reflectiveCurveToRelative(2.0f, 0.897f, 2.0f, 2.0f)
verticalLineToRelative(1.0f)
close()
moveTo(8.198f, 15.0f)
horizontalLineToRelative(1.802f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-2.042f)
lineToRelative(-0.841f, 7.0f)
horizontalLineToRelative(-2.012f)
lineToRelative(0.841f, -7.0f)
lineTo(0.0f, 17.0f)
lineToRelative(0.235f, -2.0f)
horizontalLineToRelative(5.951f)
lineToRelative(0.721f, -6.0f)
lineTo(0.706f, 9.0f)
lineToRelative(0.235f, -2.0f)
horizontalLineToRelative(6.206f)
lineToRelative(0.841f, -7.0f)
horizontalLineToRelative(2.012f)
lineToRelative(-0.841f, 7.0f)
horizontalLineToRelative(6.883f)
lineToRelative(0.841f, -7.0f)
horizontalLineToRelative(2.012f)
lineToRelative(-0.841f, 7.0f)
horizontalLineToRelative(5.946f)
lineToRelative(-0.235f, 2.0f)
horizontalLineToRelative(-1.305f)
curveToRelative(-1.099f, -1.224f, -2.688f, -2.0f, -4.46f, -2.0f)
reflectiveCurveToRelative(-3.36f, 0.776f, -4.46f, 2.0f)
horizontalLineToRelative(-4.622f)
lineToRelative(-0.721f, 6.0f)
close()
}
}
.build()
return _hashtagLock!!
}
private var _hashtagLock: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,888 | icons | MIT License |
src/main/kotlin/io/foxcapades/lib/cli/builder/util/values/ValueSource.kt | Foxcapades | 850,780,005 | false | {"Kotlin": 251181} | package io.foxcapades.lib.cli.builder.util.values
import kotlin.reflect.KClass
/**
* Represents or contains information about the origin of a value.
*
* @since 1.0.0
*/
interface ValueSource {
/**
* Short/simple name of the [ValueSource].
*
* If the source is a class member, this value will be the name of that class
* member.
*
* If the source is anonymous, this value is dependent on context and
* implementation.
*/
val name: String
val hasName: Boolean
/**
* Full reference to the [ValueSource].
*
* If the source is a class member, this value will contain the fully
* qualified name of the class as well as the name of the specific class
* member.
*
* If the source is anonymous, this value is dependent on context and
* implementation.
*/
val reference: String
/**
* Value source kind.
*/
val kind: Kind
/**
* If the containing class for a [ValueSource] is known, it will be available
* via this property.
*
* This property will always be `null` for [Kind.Anonymous], but may be
* present for other [kind] values.
*/
val containerType: KClass<*>?
/**
* If the containing instance for a [ValueSource] is known, it will be
* available via this property.
*
* This property will always be `null` for [Kind.Anonymous], but may be
* present for other [kind] values.
*/
val containerInstance: Any?
enum class Kind {
Property,
Getter,
Anonymous,
}
}
| 8 | Kotlin | 0 | 0 | 1b45c0e4ffa914ecc9c53356aa9d276a6d5aa6b7 | 1,492 | lib-kt-cli-builder | MIT License |
src/test/kotlin/no/nav/eessi/pensjon/eux/EuxServiceTest.kt | navikt | 178,813,650 | false | {"Kotlin": 965251, "Shell": 1714, "Dockerfile": 155} | package no.nav.eessi.pensjon.eux
import io.mockk.*
import no.nav.eessi.pensjon.eux.klient.EuxKlientLib
import no.nav.eessi.pensjon.eux.model.BucType
import no.nav.eessi.pensjon.eux.model.BucType.P_BUC_10
import no.nav.eessi.pensjon.eux.model.BucType.R_BUC_02
import no.nav.eessi.pensjon.eux.model.SedHendelse
import no.nav.eessi.pensjon.eux.model.SedType
import no.nav.eessi.pensjon.eux.model.SedType.*
import no.nav.eessi.pensjon.eux.model.buc.Buc
import no.nav.eessi.pensjon.eux.model.buc.DocumentsItem
import no.nav.eessi.pensjon.eux.model.buc.Organisation
import no.nav.eessi.pensjon.eux.model.buc.Participant
import no.nav.eessi.pensjon.eux.model.buc.SakType.ALDER
import no.nav.eessi.pensjon.eux.model.buc.SakType.UFOREP
import no.nav.eessi.pensjon.eux.model.document.ForenkletSED
import no.nav.eessi.pensjon.eux.model.document.SedStatus
import no.nav.eessi.pensjon.eux.model.sed.P15000
import no.nav.eessi.pensjon.eux.model.sed.R005
import no.nav.eessi.pensjon.eux.model.sed.SED
import no.nav.eessi.pensjon.listeners.fagmodul.FagmodulKlient
import no.nav.eessi.pensjon.utils.mapJsonToAny
import no.nav.eessi.pensjon.utils.toJson
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.util.*
private const val RINASAK_ID = "123456"
internal class EuxServiceTest {
private val euxKlientLib = mockk<EuxKlientLib>(relaxed = true)
private val euxCacheableKlient = EuxCacheableKlient(euxKlientLib)
private val fagmodulKlient: FagmodulKlient = mockk(relaxed = true)
private val helper = EuxService(euxCacheableKlient)
@AfterEach
fun after() {
confirmVerified(fagmodulKlient)
clearAllMocks()
}
@Test
fun `Sjekk at uthenting av gyldige dokumenter filtrerer korrekt`() {
val allSedTypes = SedType.entries
assertEquals(81, allSedTypes.size)
val bucDocs = allSedTypes.mapIndexed { index, sedType -> DocumentsItem(id = "$index", type = sedType, status = SedStatus.RECEIVED.name.lowercase(
Locale.getDefault()
)) }
val buc = buc(documents = bucDocs)
assertEquals(allSedTypes.size, buc.documents?.size)
val dokumenter = helper.hentAlleGyldigeDokumenter(buc)
assertEquals(61, dokumenter.size)
}
@Test
fun `Sjekk at uthenting av gyldige dokumenter filtrerer korrekt fra mock Buc`() {
val json = javaClass.getResource("/eux/buc/buc279020.json")!!.readText()
val buc = mapJsonToAny<Buc>(json)
assertEquals(8, helper.hentAlleGyldigeDokumenter(buc).size)
}
@Test
fun `Sjekk at uthenting av gyldige dokumenter fra BUC med gyldig og kansellerte`() {
val bucJson = javaClass.getResource("/buc/R_BUC_02.json")!!.readText()
val r005json = javaClass.getResource("/sed/R_BUC_02_R005_SE.json")!!.readText()
val buc = mapJsonToAny<Buc>(bucJson)
every { euxKlientLib.hentSedJson(eq(RINASAK_ID), any()) } returns r005json
every { euxKlientLib.hentSedJson(any(), any()) } returns SED(type = X008).toJson()
val alledocs = helper.hentAlleGyldigeDokumenter(buc)
assertEquals(2, alledocs.size)
val alleSediBuc = helper.hentSedMedGyldigStatus(RINASAK_ID, buc)
assertEquals(1, alleSediBuc.size)
val kansellertdocs = helper.hentAlleKansellerteSedIBuc(RINASAK_ID, buc)
assertEquals(1, kansellertdocs.size)
}
@Test
fun `Finn korrekt ytelsestype for AP fra sed R005`() {
val sedR005 = r005("/sed/R_BUC_02-R005-AP.json")
val sedHendelse = sedHendelse( "R")
val seds = listOf(sedR005)
val actual = helper.hentSaktypeType(sedHendelse, seds)
assertEquals(ALDER ,actual)
}
@Test
fun `Finn korrekt ytelsestype for UT fra sed R005`() {
val sedR005 = r005()
val sedHendelse = sedHendelse("R", sedType = P2100)
val seds = listOf(sedR005)
val actual = helper.hentSaktypeType(sedHendelse, seds)
assertEquals(UFOREP, actual)
}
@Test
fun `Finn korrekt ytelsestype for AP fra sed P15000`() {
val sedP15000 = mapJsonToAny<P15000>(javaClass.getResource("/buc/P15000-NAV.json")!!.readText())
val sedHendelse = sedHendelse("P", P_BUC_10, P15000)
val seds: List<SED> = listOf(r005(), sedP15000)
val actual = helper.hentSaktypeType(sedHendelse, seds)
assertEquals(ALDER, actual)
}
@Test
fun `Sjekker om Norge er caseOwner på buc`() {
val buc = buc("CaseOwner", "NO")
assertEquals(true, helper.isNavCaseOwner(buc))
}
@Test
fun `Sjekker om Norge ikke er caseOwner på buc`() {
val buc = buc("CaseOwner", "PL")
assertEquals(false, helper.isNavCaseOwner(buc))
}
@Test
fun `Sjekker om Norge ikk er caseOwner på buc del 2`() {
val buc = buc ("CounterParty", "NO")
assertEquals(false, helper.isNavCaseOwner(buc))
}
@Test
fun `henter en map av gyldige seds i buc`() {
val allDocsJson = javaClass.getResource("/fagmodul/alldocumentsids.json")!!.readText()
val alldocsid = mapJsonToAny<List<ForenkletSED>>(allDocsJson)
val bucDocs = alldocsid.mapIndexed { index, docs -> DocumentsItem(id = "$index", type = docs.type, status = docs.status?.name?.lowercase(
Locale.getDefault()
)) }
val buc = buc(documents = bucDocs)
val sedJson = javaClass.getResource("/buc/P2000-NAV.json")!!.readText()
val sedP2000 = mapJsonToAny<SED>(sedJson)
every { euxKlientLib.hentSedJson(any(), any()) } returns sedP2000.toJson()
val actual = helper.hentSedMedGyldigStatus(RINASAK_ID, buc)
assertEquals(1, actual.size)
val actualSed = actual.first()
assertEquals(P2000, actualSed.second.type)
verify(exactly = 1) { euxKlientLib.hentSedJson(any(), any()) }
}
private fun sedHendelse(sektorkode: String, bucType: BucType? = R_BUC_02, sedType: SedType? = R005) : SedHendelse {
return SedHendelse(rinaSakId = "123456", rinaDokumentId = "1234", sektorKode = sektorkode,
bucType = bucType, rinaDokumentVersjon = "1", sedType = sedType
)
}
private fun r005(sedfil: String? = "/sed/R_BUC_02-R005-UT.json"): R005 {
val sedR005 = mapJsonToAny<R005>(javaClass.getResource(sedfil)!!.readText())
return sedR005
}
private fun buc(
role: String? = "CaseOwner",
landkode: String? = "NO",
bucNavn: String? = BucType.P_BUC_01.name,
documents: List<DocumentsItem>? = emptyList()
) = Buc(RINASAK_ID, processDefinitionName = bucNavn, documents = documents, participants = listOf(Participant(role, Organisation(countryCode = landkode))))
}
| 2 | Kotlin | 3 | 5 | faacfce65e892dcbf08025bce87b35ab4e739987 | 6,784 | eessi-pensjon-journalforing | MIT License |
jtransc-core/src/com/jtransc/gen/common/CommonGenFolders.kt | jtransc | 51,313,992 | false | null | package com.jtransc.gen.common
import com.jtransc.vfs.MergeVfs
import com.jtransc.vfs.SyncVfsFile
class CommonGenFolders(
val assetFolders: List<SyncVfsFile>//,
//val target: SyncVfsFile
) {
val mergedAssets = MergeVfs(assetFolders)
//fun copyAssets() {
// copyAssetsTo(target)
//}
fun copyAssetsTo(target: SyncVfsFile) {
mergedAssets.copyTreeTo(target)
}
} | 59 | Java | 66 | 619 | 6f9a2166f128c2ce5fb66f9af46fdbdbcbbe4ba4 | 371 | jtransc | Apache License 2.0 |
app/src/main/java/com/wengelef/pixabaygallery/ui/list/adapter/PhotoViewHolder.kt | wengelef | 429,715,179 | false | null | package com.wengelef.pixabaygallery.ui.list.adapter
import androidx.recyclerview.widget.RecyclerView
import com.wengelef.pixabaygallery.databinding.ItemPhotoBinding
class PhotoViewHolder(val binding: ItemPhotoBinding) : RecyclerView.ViewHolder(binding.root) | 0 | Kotlin | 0 | 0 | 6c973f502463be888714a4749ddbfa98b4c98e5b | 259 | pixabay_gallery | Apache License 2.0 |
util/weixin/src/main/kotlin/top/bettercode/summer/util/wechat/controller/OffiaccountCallbackController.kt | top-bettercode | 387,652,015 | false | null | package top.bettercode.summer.util.wechat.controller
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import top.bettercode.logging.annotation.RequestLogging
import top.bettercode.simpleframework.web.BaseController
import top.bettercode.summer.util.wechat.support.IWechatService
import top.bettercode.summer.util.wechat.support.offiaccount.OffiaccountClient
import javax.validation.constraints.NotBlank
@ConditionalOnWebApplication
@Controller
@RequestMapping(value = ["/wechat"], name = "微信")
class OffiaccountCallbackController(
private val wechatService: IWechatService,
private val offiaccountClient: OffiaccountClient
) : BaseController() {
/*
* 公众号OAuth回调接口
*/
@RequestLogging(ignoredTimeout = true)
@GetMapping(value = ["/oauth"], name = "OAuth回调接口")
fun oauth(code: String?, state: String?): String {
plainTextError()
var openId: String? = null
var token: String? = null
try {
val accessToken =
if (code.isNullOrBlank()) null else offiaccountClient.getWebPageAccessToken(code)
openId = if (accessToken?.isOk == true) accessToken.openid else null
log.info("openId:{}", openId)
token = if (openId != null) wechatService.oauth(openId) else null
} catch (e: Exception) {
log.warn("token获取失败", e)
}
return offiaccountClient.properties.redirectUrl(token, openId, token != null)
}
/*
* js签名
*/
@ResponseBody
@GetMapping(value = ["/jsSign"], name = "js签名")
fun jsSignUrl(@NotBlank url: String): Any {
return ok(offiaccountClient.jsSignUrl(url))
}
@ResponseBody
@GetMapping(name = "验证回调")
fun access(signature: String?, echostr: String?, timestamp: String?, nonce: String?): Any? {
if (timestamp.isNullOrBlank() || nonce.isNullOrBlank() || offiaccountClient
.shaHex(offiaccountClient.properties.token, timestamp, nonce) != signature
) {
log.warn("非法请求.")
return false
}
return echostr
}
@ResponseBody
@PostMapping(name = "事件推送")
fun receive(
signature: String?, timestamp: String?,
nonce: String?, openid: String?, encrypt_type: String?, msg_signature: String?,
content: String?
): String? {
if (timestamp.isNullOrBlank() || nonce.isNullOrBlank() || openid.isNullOrBlank() || encrypt_type.isNullOrBlank() || msg_signature.isNullOrBlank() || content.isNullOrBlank()
|| offiaccountClient.shaHex(
offiaccountClient.properties.token,
timestamp,
nonce
) != signature
) {
log.warn("非法请求.")
} else {
wechatService.receive(
timestamp,
nonce,
openid,
encrypt_type,
msg_signature,
content
)
}
return null
}
} | 0 | Kotlin | 0 | 1 | 6fe2f1eb2e5db2c3b24eef3dd01a1cadbd2a3d17 | 3,302 | summer | Apache License 2.0 |
feature-staking-impl/src/main/java/io/novafoundation/nova/feature_staking_impl/presentation/validators/Common.kt | novasamatech | 415,834,480 | false | null | package io.novafoundation.nova.feature_staking_impl.presentation.validators
import io.novafoundation.nova.feature_staking_api.domain.model.Validator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
suspend fun List<Validator>.findSelectedValidator(accountIdHex: String) = withContext(Dispatchers.Default) {
firstOrNull { it.accountIdHex == accountIdHex }
}
| 13 | null | 6 | 9 | dea9f1144c1cbba1d876a9bb753f8541da38ebe0 | 390 | nova-wallet-android | Apache License 2.0 |
src/main/kotlin/de/itemis/mps/gradle/Common.kt | mbeddr | 84,947,979 | false | {"Kotlin": 109996, "JetBrains MPS": 47305, "Perl": 41096, "Groovy": 16119, "Shell": 8731} | package de.itemis.mps.gradle
import de.itemis.mps.gradle.generate.GeneratePluginExtensions
import org.apache.log4j.Logger
import org.gradle.api.GradleException
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.artifacts.Configuration
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.TaskContainer
import java.util.Collections.emptyList
import java.io.File
import javax.inject.Inject
private val logger = Logger.getLogger("de.itemis.mps.gradle.common")
const val MPS_SUPPORT_MSG =
"Version 1.5 doesn't only support MPS 2020.1+, please use versions 1.4 or below with older versions of MPS."
data class Plugin(
val id: String,
val path: String
)
data class Macro(
val name: String,
val value: String
)
open class BasePluginExtensions @Inject constructor(of: ObjectFactory, project: Project) {
val mpsConfig: Property<Configuration> = of.property(Configuration::class.java)
val mpsLocation: RegularFileProperty = of.fileProperty().convention { File(project.buildDir, "mps") }
val mpsVersion: Property<String> = of.property(String::class.java)
val plugins: ListProperty<Plugin> = of.listProperty(Plugin::class.java).convention(emptyList())
val pluginLocation: RegularFileProperty = of.fileProperty()
val macros: ListProperty<Macro> = of.listProperty(Macro::class.java).convention(emptyList())
val projectLocation: RegularFileProperty = of.fileProperty()
val debug: Property<Boolean> = of.property(Boolean::class.java).convention(false)
val javaExec: RegularFileProperty = of.fileProperty()
}
fun validateDefaultJvm() {
if (JavaVersion.current() != JavaVersion.VERSION_11) logger.error("MPS requires Java 11 but current JVM uses ${JavaVersion.current()}, starting MPS will most probably fail!")
}
fun argsFromBaseExtension(extensions: BasePluginExtensions): MutableList<String> {
val pluginLocation =
extensions.pluginLocation.map { sequenceOf("--plugin-location=${it.asFile.absolutePath}") }.getOrElse(
emptySequence()
)
val projectLocation = extensions.projectLocation.getOrElse { throw GradleException("No project path set") }.asFile
val prj = sequenceOf("--project=${projectLocation.absolutePath}")
return sequenceOf(
pluginLocation,
extensions.plugins.get().map { "--plugin=${it.id}::${it.path}" }.asSequence(),
extensions.macros.get().map { "--macro=${it.name}::${it.value}" }.asSequence(),
prj
).flatten().toMutableList()
}
fun BasePluginExtensions.getMPSVersion(): String {
/*
If the user supplies a MPS config we use this one to resolve MPS and get the version. For other scenarios the user
can supply mpsLocation and mpsVersion then we do not resolve anything and the users build script is responsible for
resolving a compatible MPS into th mpsLocation before the
*/
if (mpsConfig.isPresent) {
return mpsConfig
.get()
.resolvedConfiguration
.firstLevelModuleDependencies.find { it.moduleGroup == "com.jetbrains" && it.moduleName == "mps" }
?.moduleVersion ?: throw GradleException("MPS configuration doesn't contain MPS")
}
if (mpsVersion.isPresent) {
if (!mpsLocation.isPresent) {
throw GradleException("Setting an MPS version but no MPS location is not supported!")
}
return mpsVersion.get()
}
throw GradleException("Either mpsConfig or mpsVersion needs to specified!")
} | 22 | Kotlin | 16 | 14 | 08de38e4b18c1353af6b065593a9e348e8123947 | 3,793 | mps-gradle-plugin | Apache License 2.0 |
glados-client/glados-client-web/src/main/kotlin/jp/nephy/glados/clients/web/routing/pattern/WebPatternRoutingSubscription.kt | StarryBlueSky | 125,806,741 | false | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package jp.nephy.glados.clients.web.routing.pattern
import io.ktor.application.ApplicationCall
import io.ktor.application.call
import io.ktor.request.httpMethod
import io.ktor.request.path
import io.ktor.util.pipeline.PipelineContext
import jp.nephy.glados.GLaDOSSubscription
import jp.nephy.glados.api.Plugin
import jp.nephy.glados.api.Priority
import jp.nephy.glados.clients.web.HttpMethod
import jp.nephy.glados.clients.web.effectiveHost
import jp.nephy.glados.clients.web.glados
import jp.nephy.glados.clients.web.routing.RoutingHandler
import kotlin.reflect.KFunction
private val fragmentPattern = "^\\{(.+)}$".toRegex()
/**
* WebPatternRoutingSubscription.
*/
data class WebPatternRoutingSubscription(
override val plugin: Plugin,
override val function: KFunction<*>,
override val annotation: WebPatternRouting
): GLaDOSSubscription<WebPatternRouting, WebPatternRoutingEvent>(), RoutingHandler<WebPatternRoutingEvent> {
override val priority: Priority
get() = annotation.priority
private val domain = annotation.domain.ifBlank { null }
private val path = "/${annotation.path.removePrefix("/").removeSuffix("/").trim()}"
private val patterns = path.split("/").mapIndexedNotNull { i, it ->
(fragmentPattern.matchEntire(it)?.groupValues?.get(1) ?: return@mapIndexedNotNull null) to i
}.toMap()
override fun createEvent(context: PipelineContext<*, ApplicationCall>): WebPatternRoutingEvent? {
val method = context.call.request.httpMethod.glados
if (annotation.methods.isNotEmpty() && method !in annotation.methods && method != HttpMethod.OPTIONS) {
return null
}
if (domain != null && domain != context.call.request.effectiveHost) {
return null
}
val requestPath = context.call.request.path()
val (expectPaths, actualPaths) = path.split("/") to requestPath.split("/")
if (expectPaths.size != actualPaths.size) {
return null
}
for ((expected, actual) in expectPaths.zip(actualPaths)) {
if (!fragmentPattern.matches(expected) && expected != actual) {
return null
}
}
val currentFragments = context.call.request.path().split("/")
val fragments = patterns.map { (name, index) ->
name to currentFragments[index]
}.toMap()
return WebPatternRoutingEvent(this, context, fragments)
}
}
| 0 | Kotlin | 1 | 12 | 89c2ca214e728f454c386ebee4ee78c5a99d5130 | 3,643 | GLaDOS-bot | MIT License |
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensions/maven/MavenSyncSignalProvider.kt | AllenJLChen | 376,441,025 | true | null | package com.jetbrains.packagesearch.intellij.plugin.extensions.maven
import com.intellij.util.messages.SimpleMessageBusConnection
import com.jetbrains.packagesearch.intellij.plugin.extensibility.invoke
import com.jetbrains.packagesearch.intellij.plugin.extensions.AbstractMessageBusModuleChangesSignalProvider
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import org.jetbrains.idea.maven.project.MavenImportListener
import java.util.function.Supplier
internal class MavenSyncSignalProvider : AbstractMessageBusModuleChangesSignalProvider() {
override fun registerModuleChangesListener(bus: SimpleMessageBusConnection, listener: Supplier<Unit>) {
bus.subscribe(
MavenImportListener.TOPIC,
MavenImportListener { _, _ ->
logDebug("MavenModuleChangesSignalProvider#registerModuleChangesListener#ProjectDataImportListener")
listener()
}
)
}
}
| 0 | null | 0 | 0 | 6a513972ca5113b8854dfef1b8880ab5eaecac99 | 952 | intellij-community | Apache License 2.0 |
app/src/main/java/com/krygodev/appforartists/core/presentation/components/SetupBottomNavBar.kt | krygo-dev | 422,322,080 | false | {"Kotlin": 287182} | package com.krygodev.appforartists.core.presentation.components
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import com.krygodev.appforartists.core.presentation.util.BottomNavItem
@Composable
fun SetupBottomNavBar(
navController: NavController
) {
val items = listOf(
BottomNavItem.Home,
BottomNavItem.Search,
BottomNavItem.Chatrooms,
BottomNavItem.Profile
)
BottomNavBar(
items = items,
navController = navController,
onItemClick = {
navController.navigate(it.route) {
launchSingleTop = true
restoreState = true
}
}
)
} | 0 | Kotlin | 0 | 0 | 7840bddb76687010d5282d106920c236133677e9 | 702 | AppForArtists | MIT License |
inject-kotlin/src/test/kotlin/io/micronaut/kotlin/processing/elementapi/TestEntity.kt | micronaut-projects | 124,230,204 | false | null | package io.micronaut.kotlin.processing.elementapi
import jakarta.validation.constraints.*
import javax.persistence.*
@Entity
class TestEntity(
@Column(name="test_name") var name: String,
@Size(max=100) var age: Int,
primitiveArray: Array<Int>) {
@Id
@GeneratedValue
var id: Long? = null
@Version
var version: Long? = null
private var primitiveArray: Array<Int>? = null
private var v: Long? = null
@Version
fun getAnotherVersion(): Long? {
return v;
}
fun setAnotherVersion(v: Long) {
this.v = v
}
}
| 753 | null | 1061 | 6,059 | c9144646b31b23bd3c4150dec8ddd519947e55cf | 583 | micronaut-core | Apache License 2.0 |
app/src/main/java/com/bitwindow/aacpaginginfinitescrollingwithnetworksample/ui/list/MovieListAdapter.kt | asheshb | 150,709,173 | false | {"Gradle": 3, "Java Properties": 1, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Text": 1, "INI": 1, "Proguard": 1, "Kotlin": 20, "XML": 13, "Java": 1} | package com.bitwindow.aacpaginginfinitescrollingwithnetworksample.ui.list
import android.arch.paging.PagedListAdapter
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import com.bitwindow.aacpaginginfinitescrollingwithnetworksample.data.vo.Movie
class MovieListAdapter(private val listener: (Long) -> Unit) :
PagedListAdapter<Movie, RecyclerView.ViewHolder>(REPO_COMPARATOR) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return MovieListViewHolder.create(parent)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val movieItem = getItem(position)
if (movieItem != null) {
(holder as MovieListViewHolder).bind(movieItem, listener)
}
}
companion object {
private val REPO_COMPARATOR = object : DiffUtil.ItemCallback<Movie>() {
override fun areItemsTheSame(oldItem: Movie, newItem: Movie): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Movie, newItem: Movie): Boolean =
oldItem == newItem
}
}
} | 0 | Kotlin | 18 | 75 | 8f49aa7338bf5899d07a65dfeea1ad933a089bb9 | 1,219 | AACPagingInfiniteScrollingWithNetworkSample | Apache License 2.0 |
plugins/kotlin/j2k/shared/tests/testData/newJ2k/objectLiteral/AccessThisInsideAnonClass.k2.kt | JetBrains | 2,489,216 | false | {"Text": 9788, "INI": 517, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 633, "Markdown": 750, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7904, "SVG": 4537, "Kotlin": 60205, "Java": 84268, "HTML": 3803, "Java Properties": 217, "Gradle": 462, "Maven POM": 95, "JavaScript": 232, "CSS": 79, "JSON": 1436, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 735, "Groovy": 3102, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 73, "GraphQL": 127, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17095, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 85, "E-mail": 18, "Roff": 289, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1} | // ERROR: Function 'public' exposes its 'internal' parameter type 'Foo'.
internal interface Foo
class Bar {
fun test() {
object : Foo {
fun foo() {
bug(this)
}
}
}
fun bug(foo: Foo?) {
}
}
| 1 | null | 1 | 1 | 0d546ea6a419c7cb168bc3633937a826d4a91b7c | 263 | intellij-community | Apache License 2.0 |
CarLife-Android-Vehicle-V2.0/carlife-sdk/src/main/java/com/baidu/carlife/sdk/receiver/display/RemoteDisplayRenderer.kt | songzhixiang | 608,940,896 | true | {"Markdown": 7, "Text": 2, "Ignore List": 9, "Shell": 12, "Java Properties": 6, "Python": 1, "Ant Build System": 1, "XML": 232, "Batchfile": 4, "Gradle": 14, "INI": 9, "Java": 297, "AIDL": 5, "HTML": 14, "CSS": 18, "JavaScript": 8, "Proguard": 7, "Kotlin": 119, "Protocol Buffer": 126, "C++": 142, "Makefile": 8} | package com.baidu.carlife.sdk.receiver.display
import android.view.Surface
import com.baidu.carlife.protobuf.CarlifeVideoEncoderInfoProto.CarlifeVideoEncoderInfo
import com.baidu.carlife.sdk.CarLifeContext
import com.baidu.carlife.sdk.Constants
import com.baidu.carlife.sdk.Constants.MSG_CHANNEL_CMD
import com.baidu.carlife.sdk.internal.protocol.CarLifeMessage
import com.baidu.carlife.sdk.internal.protocol.CarLifeMessage.Companion.obtain
import com.baidu.carlife.sdk.internal.protocol.ServiceTypes
import com.baidu.carlife.sdk.internal.protocol.ServiceTypes.MSG_CMD_VIDEO_ENCODER_INIT_DONE
import com.baidu.carlife.sdk.internal.protocol.ServiceTypes.MSG_CMD_VIDEO_ENCODER_PAUSE
import com.baidu.carlife.sdk.internal.protocol.ServiceTypes.MSG_CMD_VIDEO_ENCODER_START
import com.baidu.carlife.sdk.internal.protocol.ServiceTypes.MSG_VIDEO_DATA
import com.baidu.carlife.sdk.receiver.OnVideoSizeChangedListener
import com.baidu.carlife.sdk.internal.DisplaySpec
import com.baidu.carlife.sdk.internal.transport.TransportListener
import com.baidu.carlife.sdk.receiver.SurfaceRequestCallback
import com.baidu.carlife.sdk.util.Logger
class RemoteDisplayRenderer(private val context: CarLifeContext,
private val listener: OnVideoSizeChangedListener
): TransportListener {
var encoderInfo: CarlifeVideoEncoderInfo? = null
private set
private var frameDecoder: FrameDecoder? = null
private var surface: Surface? = null
var displaySpec: DisplaySpec
var surfaceRequester: SurfaceRequestCallback? = null
init {
val screenWidth = context.applicationContext.resources.displayMetrics.widthPixels
val screenHeight = context.applicationContext.resources.displayMetrics.heightPixels
displaySpec = DisplaySpec(context.applicationContext, screenWidth, screenHeight, 30)
}
@Synchronized
fun setSurface(surface: Surface?) {
this.surface = surface
if (surface == null) {
Logger.d(Constants.TAG, "RemoteDisplayRenderer setSurface to null")
frameDecoder?.let {
it.release()
frameDecoder = null
context.postMessage(MSG_CHANNEL_CMD, MSG_CMD_VIDEO_ENCODER_PAUSE)
}
return
}
if (encoderInfo != null && frameDecoder == null) {
// 说明收到MSG_CMD_VIDEO_ENCODER_INIT_DONE的时候,还没有surface
// 此时需要创建decoder,并发送MSG_CMD_VIDEO_ENCODER_START
frameDecoder = FrameDecoder(context, surface, encoderInfo!!)
context.postMessage(MSG_CHANNEL_CMD, MSG_CMD_VIDEO_ENCODER_START)
Logger.d(Constants.TAG, "RemoteDisplayRenderer create decoder delayed")
}
else {
frameDecoder?.let {
Logger.d(Constants.TAG, "RemoteDisplayRenderer decoder set new surface")
it.setSurface(surface)
}
}
}
private fun stop() {
frameDecoder?.let {
it.release()
frameDecoder = null
}
encoderInfo = null
}
override fun onReceiveMessage(context: CarLifeContext, message: CarLifeMessage): Boolean {
when (message.serviceType) {
MSG_CMD_VIDEO_ENCODER_INIT_DONE -> {
synchronized(this) {
encoderInfo = message.protoPayload as CarlifeVideoEncoderInfo
listener.onVideoSizeChanged(encoderInfo!!.width, encoderInfo!!.height)
if (surface != null) {
frameDecoder = FrameDecoder(context, surface!!, encoderInfo!!)
var messgae = obtain(MSG_CHANNEL_CMD, MSG_CMD_VIDEO_ENCODER_START)
context.postMessage(messgae)
Logger.d(Constants.TAG, "RemoteDisplayRenderer postMessage MSG_CMD_VIDEO_ENCODER_START 1")
return true
}
}
encoderInfo?.let {
surfaceRequester?.requestSurface(it.width, it.height)
Logger.d(Constants.TAG, "RemoteDisplayRenderer decoder surface null")
}
return true
}
MSG_VIDEO_DATA -> {
if (message.payloadSize != 0) {
frameDecoder?.feedFrame(message)
}
return true
}
}
return false
}
fun onActivityStarted() {
if (frameDecoder != null) {
context.postMessage(MSG_CHANNEL_CMD, MSG_CMD_VIDEO_ENCODER_START)
}
}
fun onActivityStopped() {
if (frameDecoder != null) {
context.postMessage(MSG_CHANNEL_CMD, MSG_CMD_VIDEO_ENCODER_PAUSE)
}
}
override fun onConnectionDetached(context: CarLifeContext) {
stop()
}
override fun onConnectionReattached(context: CarLifeContext) {
stop()
}
override fun onConnectionEstablished(context: CarLifeContext) {
handleSendVideoInit()
}
private fun handleSendVideoInit() {
// 发送Encoder Init
val message = obtain(MSG_CHANNEL_CMD, ServiceTypes.MSG_CMD_VIDEO_ENCODER_INIT, 0)
message.payload(CarlifeVideoEncoderInfo.newBuilder()
.setWidth(displaySpec.width)
.setHeight(displaySpec.height)
.setFrameRate(displaySpec.frameRate)
.build())
context.postMessage(message)
}
} | 0 | null | 0 | 1 | fddb0be12a24b501bee435a56be3f564a158fd39 | 5,423 | apollo-DuerOS | Apache License 2.0 |
common/src/commonMain/kotlin/content/wiki/PageID.kt | xtexChooser | 513,449,471 | false | {"Kotlin": 67393, "HTML": 1083, "JavaScript": 445} | package argoner.common.content.wiki
typealias PageID = String | 0 | Kotlin | 0 | 0 | 97f9000db3ec6c04696b9c429d1fe00be53704e4 | 62 | argoner | Apache License 2.0 |
app/src/main/java/dev/patrickgold/florisboard/app/ui/settings/theme/EditPropertyDialog.kt | xiupos | 454,768,327 | true | {"Kotlin": 1533418, "C++": 239868, "CMake": 2100, "C": 528, "Python": 429, "Shell": 37} | /*
* Copyright (C) 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 dev.patrickgold.florisboard.app.ui.settings.theme
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.border
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.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.shape.CutCornerShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.isSpecified
import androidx.compose.ui.unit.isUnspecified
import androidx.compose.ui.unit.sp
import dev.patrickgold.florisboard.R
import dev.patrickgold.florisboard.app.res.stringRes
import dev.patrickgold.florisboard.app.ui.components.DpSizeSaver
import dev.patrickgold.florisboard.app.ui.components.FlorisChip
import dev.patrickgold.florisboard.app.ui.components.FlorisDropdownMenu
import dev.patrickgold.florisboard.app.ui.components.FlorisOutlinedTextField
import dev.patrickgold.florisboard.app.ui.components.FlorisTextButton
import dev.patrickgold.florisboard.common.ValidationResult
import dev.patrickgold.florisboard.common.kotlin.curlyFormat
import dev.patrickgold.florisboard.common.rememberValidationResult
import dev.patrickgold.florisboard.res.ext.ExtensionValidation
import dev.patrickgold.florisboard.snygg.SnyggLevel
import dev.patrickgold.florisboard.snygg.SnyggPropertySetSpec
import dev.patrickgold.florisboard.snygg.value.SnyggCutCornerDpShapeValue
import dev.patrickgold.florisboard.snygg.value.SnyggCutCornerPercentageShapeValue
import dev.patrickgold.florisboard.snygg.value.SnyggDefinedVarValue
import dev.patrickgold.florisboard.snygg.value.SnyggDpShapeValue
import dev.patrickgold.florisboard.snygg.value.SnyggImplicitInheritValue
import dev.patrickgold.florisboard.snygg.value.SnyggPercentageShapeValue
import dev.patrickgold.florisboard.snygg.value.SnyggRoundedCornerDpShapeValue
import dev.patrickgold.florisboard.snygg.value.SnyggRoundedCornerPercentageShapeValue
import dev.patrickgold.florisboard.snygg.value.SnyggShapeValue
import dev.patrickgold.florisboard.snygg.value.SnyggSolidColorValue
import dev.patrickgold.florisboard.snygg.value.SnyggSpSizeValue
import dev.patrickgold.florisboard.snygg.value.SnyggValue
import dev.patrickgold.florisboard.snygg.value.SnyggValueEncoder
import dev.patrickgold.florisboard.snygg.value.SnyggVarValueEncoders
import dev.patrickgold.jetpref.material.ui.ExperimentalJetPrefMaterialUi
import dev.patrickgold.jetpref.material.ui.JetPrefAlertDialog
import dev.patrickgold.jetpref.material.ui.JetPrefColorPicker
import dev.patrickgold.jetpref.material.ui.rememberJetPrefColorPickerState
internal val SnyggEmptyPropertyInfoForAdding = PropertyInfo(
name = "- select -",
value = SnyggImplicitInheritValue,
)
data class PropertyInfo(
val name: String,
val value: SnyggValue,
)
private enum class ShapeCorner {
TOP_START,
TOP_END,
BOTTOM_END,
BOTTOM_START;
@Composable
fun label(): String {
return stringRes(when (this) {
TOP_START -> R.string.enum__shape_corner__top_start
TOP_END -> R.string.enum__shape_corner__top_end
BOTTOM_END -> R.string.enum__shape_corner__bottom_end
BOTTOM_START -> R.string.enum__shape_corner__bottom_start
})
}
}
@Composable
internal fun EditPropertyDialog(
propertySetSpec: SnyggPropertySetSpec?,
initProperty: PropertyInfo,
level: SnyggLevel,
definedVariables: Map<String, SnyggValue>,
onConfirmNewValue: (String, SnyggValue) -> Boolean,
onDelete: () -> Unit,
onDismiss: () -> Unit,
) {
val isAddPropertyDialog = initProperty == SnyggEmptyPropertyInfoForAdding
var showSelectAsError by rememberSaveable { mutableStateOf(false) }
var showAlreadyExistsError by rememberSaveable { mutableStateOf(false) }
var propertyName by rememberSaveable {
mutableStateOf(if (isAddPropertyDialog && propertySetSpec == null) { "" } else { initProperty.name })
}
val propertyNameValidation = rememberValidationResult(ExtensionValidation.ThemeComponentVariableName, propertyName)
var propertyValueEncoder by remember {
mutableStateOf(if (isAddPropertyDialog && propertySetSpec == null) {
SnyggImplicitInheritValue
} else {
initProperty.value.encoder()
})
}
var propertyValue by remember {
mutableStateOf(if (isAddPropertyDialog && propertySetSpec == null) {
SnyggImplicitInheritValue
} else {
initProperty.value
})
}
fun isPropertyNameValid(): Boolean {
return propertyName.isNotBlank() && propertyName != SnyggEmptyPropertyInfoForAdding.name
}
fun isPropertyValueValid(): Boolean {
return when (val value = propertyValue) {
is SnyggImplicitInheritValue -> false
is SnyggDefinedVarValue -> value.key.isNotBlank()
is SnyggSpSizeValue -> value.sp.isSpecified && value.sp.value >= 1f
else -> true
}
}
JetPrefAlertDialog(
title = stringRes(if (isAddPropertyDialog) {
R.string.settings__theme_editor__add_property
} else {
R.string.settings__theme_editor__edit_property
}),
confirmLabel = stringRes(if (isAddPropertyDialog) {
R.string.action__add
} else {
R.string.action__apply
}),
onConfirm = {
if (!isPropertyNameValid() || !isPropertyValueValid()) {
showSelectAsError = true
} else {
if (!onConfirmNewValue(propertyName, propertyValue)) {
showAlreadyExistsError = true
}
}
},
dismissLabel = stringRes(R.string.action__cancel),
onDismiss = onDismiss,
neutralLabel = if (!isAddPropertyDialog) { stringRes(R.string.action__delete) } else { null },
onNeutral = onDelete,
neutralColors = ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colors.error,
),
) {
Column {
AnimatedVisibility(visible = showAlreadyExistsError) {
Text(
modifier = Modifier.padding(bottom = 16.dp),
text = stringRes(R.string.settings__theme_editor__property_already_exists),
color = MaterialTheme.colors.error,
)
}
DialogProperty(text = stringRes(R.string.settings__theme_editor__property_name)) {
PropertyNameInput(
propertySetSpec = propertySetSpec,
name = propertyName,
nameValidation = propertyNameValidation,
onNameChange = { name ->
if (propertySetSpec != null) {
propertyValueEncoder = SnyggImplicitInheritValue
}
propertyName = name
},
level = level,
isAddPropertyDialog = isAddPropertyDialog,
showSelectAsError = showSelectAsError,
)
}
DialogProperty(text = stringRes(R.string.settings__theme_editor__property_value)) {
PropertyValueEncoderDropdown(
supportedEncoders = remember(propertyName) {
propertySetSpec?.propertySpec(propertyName)?.encoders ?: SnyggVarValueEncoders
},
encoder = propertyValueEncoder,
onEncoderChange = { encoder ->
propertyValueEncoder = encoder
propertyValue = encoder.defaultValue()
},
enabled = isPropertyNameValid(),
isError = showSelectAsError && propertyValueEncoder == SnyggImplicitInheritValue,
)
PropertyValueEditor(
value = propertyValue,
onValueChange = { propertyValue = it },
level = level,
definedVariables = definedVariables,
isError = showSelectAsError && !isPropertyValueValid(),
)
}
}
}
}
@Composable
private fun PropertyNameInput(
propertySetSpec: SnyggPropertySetSpec?,
name: String,
nameValidation: ValidationResult,
onNameChange: (String) -> Unit,
level: SnyggLevel,
isAddPropertyDialog: Boolean,
showSelectAsError: Boolean,
) {
if (propertySetSpec != null) {
val possiblePropertyNames = remember(propertySetSpec) {
listOf(SnyggEmptyPropertyInfoForAdding.name) + propertySetSpec.supportedProperties.map { it.name }
}
val possiblePropertyLabels = possiblePropertyNames.map { translatePropertyName(it, level) }
var propertiesExpanded by remember { mutableStateOf(false) }
val propertiesSelectedIndex = remember(name) {
possiblePropertyNames.indexOf(name).coerceIn(possiblePropertyNames.indices)
}
FlorisDropdownMenu(
items = possiblePropertyLabels,
expanded = propertiesExpanded,
enabled = isAddPropertyDialog,
selectedIndex = propertiesSelectedIndex,
isError = showSelectAsError && propertiesSelectedIndex == 0,
onSelectItem = { index ->
onNameChange(possiblePropertyNames[index])
},
onExpandRequest = { propertiesExpanded = true },
onDismissRequest = { propertiesExpanded = false },
)
} else {
FlorisOutlinedTextField(
value = name,
onValueChange = onNameChange,
enabled = isAddPropertyDialog,
showValidationHint = isAddPropertyDialog,
showValidationError = showSelectAsError,
validationResult = nameValidation,
)
}
}
@Composable
private fun PropertyValueEncoderDropdown(
supportedEncoders: List<SnyggValueEncoder>,
encoder: SnyggValueEncoder,
onEncoderChange: (SnyggValueEncoder) -> Unit,
enabled: Boolean = true,
isError: Boolean = false,
) {
val encoders = remember(supportedEncoders) {
listOf(SnyggImplicitInheritValue) + supportedEncoders
}
var expanded by remember { mutableStateOf(false) }
val selectedIndex = remember(encoder) {
encoders.indexOf(encoder).coerceIn(encoders.indices)
}
FlorisDropdownMenu(
items = encoders,
labelProvider = { translatePropertyValueEncoderName(it) },
expanded = expanded,
enabled = enabled,
selectedIndex = selectedIndex,
isError = isError,
onSelectItem = { index ->
onEncoderChange(encoders[index])
},
onExpandRequest = { expanded = true },
onDismissRequest = { expanded = false },
)
}
@OptIn(ExperimentalJetPrefMaterialUi::class)
@Composable
private fun PropertyValueEditor(
value: SnyggValue,
onValueChange: (SnyggValue) -> Unit,
level: SnyggLevel,
definedVariables: Map<String, SnyggValue>,
isError: Boolean = false,
) {
when (value) {
is SnyggDefinedVarValue -> {
val variableKeys = remember(definedVariables) {
listOf("") + definedVariables.keys.toList()
}
val selectedIndex by remember(variableKeys, value.key) {
mutableStateOf(variableKeys.indexOf(value.key).coerceIn(variableKeys.indices))
}
var expanded by remember { mutableStateOf(false) }
Row(
modifier = Modifier.padding(top = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
FlorisDropdownMenu(
modifier = Modifier
.padding(end = 12.dp)
.weight(1f),
items = variableKeys,
labelProvider = { translatePropertyName(it, level) },
expanded = expanded,
selectedIndex = selectedIndex,
isError = isError,
onSelectItem = { index ->
onValueChange(SnyggDefinedVarValue(variableKeys[index]))
},
onExpandRequest = { expanded = true },
onDismissRequest = { expanded = false },
)
SnyggValueIcon(
value = value,
definedVariables = definedVariables,
)
}
}
is SnyggSolidColorValue -> {
Column(modifier = Modifier.padding(top = 8.dp)) {
Row(
modifier = Modifier.padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
modifier = Modifier
.padding(end = 12.dp)
.weight(1f),
text = value.encoder().serialize(value).getOrDefault("?"),
)
SnyggValueIcon(
value = value,
definedVariables = definedVariables,
)
}
val state = rememberJetPrefColorPickerState(initColor = value.color)
JetPrefColorPicker(
onColorChange = { onValueChange(SnyggSolidColorValue(it)) },
state = state,
)
}
}
is SnyggSpSizeValue -> {
var sizeStr by remember {
val sp = value.sp.takeUnless { it.isUnspecified } ?: SnyggSpSizeValue.defaultValue().sp
mutableStateOf(sp.value.toString())
}
Row(
modifier = Modifier.padding(top = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
FlorisOutlinedTextField(
modifier = Modifier.weight(1f),
value = sizeStr,
onValueChange = { value ->
sizeStr = value
val size = sizeStr.toFloatOrNull()?.let { SnyggSpSizeValue(it.sp) }
onValueChange(size ?: SnyggSpSizeValue(TextUnit.Unspecified))
},
isError = value.sp.isUnspecified || value.sp.value < 1f,
)
Text(
modifier = Modifier.padding(start = 8.dp),
text = "sp",
fontFamily = FontFamily.Monospace,
)
}
}
is SnyggShapeValue -> when (value) {
is SnyggDpShapeValue -> {
var showDialogInitDp by rememberSaveable(stateSaver = DpSizeSaver) {
mutableStateOf(0.dp)
}
var showDialogForCorner by rememberSaveable {
mutableStateOf<ShapeCorner?>(null)
}
var topStart by rememberSaveable(stateSaver = DpSizeSaver) {
mutableStateOf(when (value) {
is SnyggCutCornerDpShapeValue -> value.topStart
is SnyggRoundedCornerDpShapeValue -> value.topStart
})
}
var topEnd by rememberSaveable(stateSaver = DpSizeSaver) {
mutableStateOf(when (value) {
is SnyggCutCornerDpShapeValue -> value.topEnd
is SnyggRoundedCornerDpShapeValue -> value.topEnd
})
}
var bottomEnd by rememberSaveable(stateSaver = DpSizeSaver) {
mutableStateOf(when (value) {
is SnyggCutCornerDpShapeValue -> value.bottomEnd
is SnyggRoundedCornerDpShapeValue -> value.bottomEnd
})
}
var bottomStart by rememberSaveable(stateSaver = DpSizeSaver) {
mutableStateOf(when (value) {
is SnyggCutCornerDpShapeValue -> value.bottomStart
is SnyggRoundedCornerDpShapeValue -> value.bottomStart
})
}
val shape = remember(topStart, topEnd, bottomEnd, bottomStart) {
when (value) {
is SnyggCutCornerDpShapeValue -> {
CutCornerShape(topStart, topEnd, bottomEnd, bottomStart)
}
is SnyggRoundedCornerDpShapeValue -> {
RoundedCornerShape(topStart, topEnd, bottomEnd, bottomStart)
}
}
}
LaunchedEffect(shape) {
onValueChange(when (value) {
is SnyggCutCornerDpShapeValue -> {
SnyggCutCornerDpShapeValue(shape as CutCornerShape, topStart, topEnd, bottomEnd, bottomStart)
}
is SnyggRoundedCornerDpShapeValue -> {
SnyggRoundedCornerDpShapeValue(shape as RoundedCornerShape, topStart, topEnd, bottomEnd, bottomStart)
}
})
}
Row(
modifier = Modifier
.padding(vertical = 8.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround,
) {
Column {
FlorisChip(
onClick = {
showDialogInitDp = topStart
showDialogForCorner = ShapeCorner.TOP_START
},
text = stringRes(R.string.unit__display_pixel__symbol).curlyFormat("v" to topStart.value),
shape = MaterialTheme.shapes.medium,
)
FlorisChip(
onClick = {
showDialogInitDp = bottomStart
showDialogForCorner = ShapeCorner.BOTTOM_START
},
text = stringRes(R.string.unit__display_pixel__symbol).curlyFormat("v" to bottomStart.value),
shape = MaterialTheme.shapes.medium,
)
}
Box(
modifier = Modifier
.requiredSize(40.dp)
.border(1.dp, MaterialTheme.colors.onBackground, shape),
)
Column {
FlorisChip(
onClick = {
showDialogInitDp = topEnd
showDialogForCorner = ShapeCorner.TOP_END
},
text = stringRes(R.string.unit__display_pixel__symbol).curlyFormat("v" to topEnd.value),
shape = MaterialTheme.shapes.medium,
)
FlorisChip(
onClick = {
showDialogInitDp = bottomEnd
showDialogForCorner = ShapeCorner.BOTTOM_END
},
text = stringRes(R.string.unit__display_pixel__symbol).curlyFormat("v" to bottomEnd.value),
shape = MaterialTheme.shapes.medium,
)
}
}
val dialogForCorner = showDialogForCorner
if (dialogForCorner != null) {
var showValidationErrors by rememberSaveable { mutableStateOf(false) }
var size by rememberSaveable {
mutableStateOf(showDialogInitDp.value.toString())
}
val sizeValidation = rememberValidationResult(ExtensionValidation.SnyggDpShapeValue, size)
JetPrefAlertDialog(
title = dialogForCorner.label(),
confirmLabel = stringRes(R.string.action__apply),
onConfirm = {
if (sizeValidation.isInvalid()) {
showValidationErrors = true
} else {
val sizeDp = size.toFloat().dp
when (dialogForCorner) {
ShapeCorner.TOP_START -> topStart = sizeDp
ShapeCorner.TOP_END -> topEnd = sizeDp
ShapeCorner.BOTTOM_END -> bottomEnd = sizeDp
ShapeCorner.BOTTOM_START -> bottomStart = sizeDp
}
showDialogForCorner = null
}
},
dismissLabel = stringRes(R.string.action__cancel),
onDismiss = {
showDialogForCorner = null
},
) {
Column {
FlorisOutlinedTextField(
value = size,
onValueChange = { size = it },
showValidationError = showValidationErrors,
validationResult = sizeValidation,
)
FlorisTextButton(
onClick = {
if (sizeValidation.isInvalid()) {
showValidationErrors = true
} else {
val sizeDp = size.toFloat().dp
topStart = sizeDp
topEnd = sizeDp
bottomEnd = sizeDp
bottomStart = sizeDp
showDialogForCorner = null
}
},
modifier = Modifier.align(Alignment.End),
text = stringRes(R.string.settings__theme_editor__property_value_shape_apply_for_all_corners),
)
}
}
}
}
is SnyggPercentageShapeValue -> {
var showDialogInitPercentage by rememberSaveable {
mutableStateOf(0)
}
var showDialogForCorner by rememberSaveable {
mutableStateOf<ShapeCorner?>(null)
}
var topStart by rememberSaveable {
mutableStateOf(when (value) {
is SnyggCutCornerPercentageShapeValue -> value.topStart
is SnyggRoundedCornerPercentageShapeValue -> value.topStart
})
}
var topEnd by rememberSaveable {
mutableStateOf(when (value) {
is SnyggCutCornerPercentageShapeValue -> value.topEnd
is SnyggRoundedCornerPercentageShapeValue -> value.topEnd
})
}
var bottomEnd by rememberSaveable {
mutableStateOf(when (value) {
is SnyggCutCornerPercentageShapeValue -> value.bottomEnd
is SnyggRoundedCornerPercentageShapeValue -> value.bottomEnd
})
}
var bottomStart by rememberSaveable {
mutableStateOf(when (value) {
is SnyggCutCornerPercentageShapeValue -> value.bottomStart
is SnyggRoundedCornerPercentageShapeValue -> value.bottomStart
})
}
val shape = remember(topStart, topEnd, bottomEnd, bottomStart) {
when (value) {
is SnyggCutCornerPercentageShapeValue -> {
CutCornerShape(topStart, topEnd, bottomEnd, bottomStart)
}
is SnyggRoundedCornerPercentageShapeValue -> {
RoundedCornerShape(topStart, topEnd, bottomEnd, bottomStart)
}
}
}
LaunchedEffect(shape) {
onValueChange(when (value) {
is SnyggCutCornerPercentageShapeValue -> {
SnyggCutCornerPercentageShapeValue(shape as CutCornerShape, topStart, topEnd, bottomEnd, bottomStart)
}
is SnyggRoundedCornerPercentageShapeValue -> {
SnyggRoundedCornerPercentageShapeValue(shape as RoundedCornerShape, topStart, topEnd, bottomEnd, bottomStart)
}
})
}
Row(
modifier = Modifier
.padding(vertical = 8.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround,
) {
Column {
FlorisChip(
onClick = {
showDialogInitPercentage = topStart
showDialogForCorner = ShapeCorner.TOP_START
},
text = stringRes(R.string.unit__percent__symbol).curlyFormat("v" to topStart),
shape = MaterialTheme.shapes.medium,
)
FlorisChip(
onClick = {
showDialogInitPercentage = bottomStart
showDialogForCorner = ShapeCorner.BOTTOM_START
},
text = stringRes(R.string.unit__percent__symbol).curlyFormat("v" to bottomStart),
shape = MaterialTheme.shapes.medium,
)
}
Box(
modifier = Modifier
.requiredSize(40.dp)
.border(1.dp, MaterialTheme.colors.onBackground, shape),
)
Column {
FlorisChip(
onClick = {
showDialogInitPercentage = topEnd
showDialogForCorner = ShapeCorner.TOP_END
},
text = stringRes(R.string.unit__percent__symbol).curlyFormat("v" to topEnd),
shape = MaterialTheme.shapes.medium,
)
FlorisChip(
onClick = {
showDialogInitPercentage = bottomEnd
showDialogForCorner = ShapeCorner.BOTTOM_END
},
text = stringRes(R.string.unit__percent__symbol).curlyFormat("v" to bottomEnd),
shape = MaterialTheme.shapes.medium,
)
}
}
val dialogForCorner = showDialogForCorner
if (dialogForCorner != null) {
var showValidationErrors by rememberSaveable { mutableStateOf(false) }
var size by rememberSaveable {
mutableStateOf(showDialogInitPercentage.toString())
}
val sizeValidation = rememberValidationResult(ExtensionValidation.SnyggPercentageShapeValue, size)
JetPrefAlertDialog(
title = dialogForCorner.label(),
confirmLabel = stringRes(R.string.action__apply),
onConfirm = {
if (sizeValidation.isInvalid()) {
showValidationErrors = true
} else {
val sizePercentage = size.toInt()
when (showDialogForCorner) {
ShapeCorner.TOP_START -> topStart = sizePercentage
ShapeCorner.TOP_END -> topEnd = sizePercentage
ShapeCorner.BOTTOM_END -> bottomEnd = sizePercentage
ShapeCorner.BOTTOM_START -> bottomStart = sizePercentage
else -> { }
}
showDialogForCorner = null
}
},
dismissLabel = stringRes(R.string.action__cancel),
onDismiss = {
showDialogForCorner = null
},
) {
Column {
FlorisOutlinedTextField(
value = size,
onValueChange = { size = it },
showValidationError = showValidationErrors,
validationResult = sizeValidation,
)
FlorisTextButton(
onClick = {
if (sizeValidation.isInvalid()) {
showValidationErrors = true
} else {
val sizePercentage = size.toInt()
topStart = sizePercentage
topEnd = sizePercentage
bottomEnd = sizePercentage
bottomStart = sizePercentage
showDialogForCorner = null
}
},
modifier = Modifier.align(Alignment.End),
text = stringRes(R.string.settings__theme_editor__property_value_shape_apply_for_all_corners),
)
}
}
}
}
else -> {
Row(
modifier = Modifier
.padding(vertical = 8.dp)
.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
) {
Box(
modifier = Modifier
.requiredSize(40.dp)
.border(1.dp, MaterialTheme.colors.onBackground, value.shape),
)
}
}
}
else -> {
// Render nothing
}
}
}
| 0 | Kotlin | 0 | 0 | a8b0a6d555be3a84f8ffa327378535b7976d1959 | 33,214 | florisboard | Apache License 2.0 |
kmqtt-common/src/jvmMain/kotlin/IgnoreJs.kt | davidepianca98 | 235,132,697 | false | {"Kotlin": 524141, "Dockerfile": 3673} | @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
public actual annotation class IgnoreJs | 2 | Kotlin | 19 | 92 | eff347bc03c4093a974731d0974e5592bde5bb49 | 98 | KMQTT | MIT License |
helm-values-intellij-plugin/src/main/kotlin/io/github/fstaudt/helm/idea/tasks/actions/UpdateDependencyAllNotificationAction.kt | fstaudt | 496,545,363 | false | {"Kotlin": 487830} | package io.github.fstaudt.helm.idea.tasks.actions
import com.intellij.notification.Notification
import com.intellij.openapi.actionSystem.AnActionEvent
import io.github.fstaudt.helm.idea.tasks.UpdateDependencyAllTask
class UpdateDependencyAllNotificationAction(key: String = "tasks.updateDependencyAll") :
ProjectNotificationAction(key) {
override fun actionPerformed(event: AnActionEvent, notification: Notification) {
progressManager.run(UpdateDependencyAllTask(event.project!!))
notification.expire()
}
}
| 7 | Kotlin | 0 | 9 | c09efaef0df8a1cb56d03de45adfd661371c14d0 | 537 | helm-values | Apache License 2.0 |
lambda-news/android-compose/src/main/java/news/lambda/android/Routes.kt | pardom | 257,625,684 | false | null | package news.lambda.android
import max.Uri
import news.lambda.model.ItemId
import news.lambda.model.UserId
object Routes {
private const val URI_BASE = "https://lambda.news"
fun itemList(): Uri = Uri.parse("$URI_BASE/items")
fun itemDetail(itemId: ItemId): Uri = Uri.parse("$URI_BASE/items/${itemId.value}")
fun userDetail(userId: UserId): Uri = Uri.parse("$URI_BASE/users/${userId.value}")
}
| 0 | Kotlin | 0 | 3 | 64b0c000c4a78d5730190b2bbe52c5728197e47d | 415 | lambda-news | Apache License 2.0 |
lib/src/main/java/com/sn/lib/NestedProgress.kt | emreesen27 | 461,118,305 | false | {"Kotlin": 15082} | package com.sn.lib
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import android.view.animation.*
import androidx.annotation.ColorInt
import androidx.annotation.Dimension
import com.sn.lib.Constants.ANIM_DURATION
import com.sn.lib.Constants.CIRCLE_RADIUS
import com.sn.lib.Constants.COLOR_BLUE
import com.sn.lib.Constants.COLOR_LIGHT_BLUE
import com.sn.lib.Constants.DESIRED_WH
import com.sn.lib.Constants.INNER_ANIM_INTERPOLATOR
import com.sn.lib.Constants.INNER_LOADER_LENGTH
import com.sn.lib.Constants.INNER_STROKE_WIDTH
import com.sn.lib.Constants.MAX_B_CIRCLES
import com.sn.lib.Constants.MAX_STROKE
import com.sn.lib.Constants.MAX_TOTAL_STROKE
import com.sn.lib.Constants.MID_POINT
import com.sn.lib.Constants.MIN_B_CIRCLES
import com.sn.lib.Constants.MIN_STOKE
import com.sn.lib.Constants.OUTER_ANIM_INTERPOLATOR
import com.sn.lib.Constants.OUTER_LOADER_LENGTH
import com.sn.lib.Constants.OUTER_STROKE_WIDTH
import com.sn.lib.Constants.SPACE_BETWEEN_CIRCLES
import com.sn.lib.Constants.START_POINT
import com.sn.lib.ext.dp
import kotlin.math.min
import kotlin.math.roundToInt
/**
* @author Aydin Emre E.
* @version 1.0.2
* @since 19-02-2022
*/
@Suppress("unused", "MemberVisibilityCanBePrivate")
class NestedProgress @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
/**
* Default values are defined here. If a new one is not assigned, these values are used.
* @see [Constants]
*/
// Animation value of progressions. These values are assigned to the "sweep angle" value in drawArc
private var innerLoaderAnimValue: Int = 0
private var outerLoaderAnimValue: Int = 0
// Animation always starts at 1 and goes full round until 360
private val innerLoaderAnimator = ValueAnimator.ofInt(1, CIRCLE_RADIUS)
private val outerLoaderAnimator = ValueAnimator.ofInt(1, CIRCLE_RADIUS)
private val innerLoadingRect: RectF = RectF()
private val outerLoadingRect: RectF = RectF()
private val paint = Paint().apply {
this.style = Paint.Style.STROKE
this.isAntiAlias = true
}
// Animation times for both progresses
var innerLoaderAnimDuration: Int = ANIM_DURATION
var outerLoaderAnimDuration: Int = ANIM_DURATION
// Animation types for both progresses
var innerAnimInterpolator = INNER_ANIM_INTERPOLATOR
var outerAnimInterpolator = OUTER_ANIM_INTERPOLATOR
@ColorInt
var innerLoaderColor: Int = COLOR_LIGHT_BLUE
@ColorInt
var outerLoaderColor: Int = COLOR_BLUE
/** You must value between the drawing angles of the circle (1-359), with value of 0 and 360, the animation is not visible.
* - innerLoaderLength
* - outerLoaderLength
*/
var innerLoaderLength: Float = INNER_LOADER_LENGTH
var outerLoaderLength: Float = OUTER_LOADER_LENGTH
/** Strokes can be in the range 1 to 10, otherwise the illegal argument exception error is thrown.
* @throws IllegalArgumentException
* - innerLoaderStrokeWidth
* - outerLoaderStrokeWidth
* @see [dp] An extensions written for float. It is used to convert the default value to dp.
*/
@Dimension
var innerLoaderStrokeWidth: Float = INNER_STROKE_WIDTH.dp
set(value) {
field =
if (value > MAX_STROKE.dp || value < MIN_STOKE.dp) throw IllegalArgumentException(
resources.getString(
R.string.stroke_range_error
)
) else value
}
@Dimension
var outerLoaderStrokeWidth: Float = OUTER_STROKE_WIDTH.dp
set(value) {
field =
if (value > MAX_STROKE.dp || value < MIN_STOKE.dp) throw IllegalArgumentException(
resources.getString(
R.string.stroke_range_error
)
) else value
}
/** Set the distance between the two loaders. The higher this value, the smaller the "internal loader".
* Space between circles can be in the range 1 to 10, otherwise the illegal argument exception error is thrown.
* @throws IllegalArgumentException
* - spaceBetweenCircles
*/
@Dimension
var spaceBetweenCircles = SPACE_BETWEEN_CIRCLES.dp
set(value) {
field =
if (value > MAX_B_CIRCLES.dp || value < MIN_B_CIRCLES.dp) throw IllegalArgumentException(
resources.getString(
R.string.space_between_range_error
)
) else value
}
/**
* You can find the attributes from the attrs.xml file.
*/
init {
val attributes = context.obtainStyledAttributes(attrs, R.styleable.NestedProgress)
innerLoaderColor =
attributes.getColor(R.styleable.NestedProgress_innerLoaderColor, this.innerLoaderColor)
outerLoaderColor =
attributes.getColor(R.styleable.NestedProgress_outerLoaderColor, this.outerLoaderColor)
innerLoaderLength =
attributes.getFloat(
R.styleable.NestedProgress_innerLoaderLength,
this.innerLoaderLength
)
outerLoaderLength =
attributes.getFloat(
R.styleable.NestedProgress_outerLoaderLength,
this.outerLoaderLength
)
innerLoaderAnimDuration =
attributes.getInt(
R.styleable.NestedProgress_innerLoaderAnimDuration,
this.innerLoaderAnimDuration
)
outerLoaderAnimDuration =
attributes.getInt(
R.styleable.NestedProgress_outerLoaderAnimDuration,
this.outerLoaderAnimDuration
)
innerLoaderStrokeWidth =
attributes.getDimension(
R.styleable.NestedProgress_innerLoaderStrokeWidth,
this.innerLoaderStrokeWidth
)
outerLoaderStrokeWidth =
attributes.getDimension(
R.styleable.NestedProgress_outerLoaderStrokeWidth,
this.outerLoaderStrokeWidth
)
innerAnimInterpolator =
attributes.getInt(
R.styleable.NestedProgress_innerAnimInterpolator,
this.innerAnimInterpolator
)
outerAnimInterpolator =
attributes.getInt(
R.styleable.NestedProgress_outerAnimInterpolator,
this.outerAnimInterpolator
)
spaceBetweenCircles =
attributes.getDimension(
R.styleable.NestedProgress_spaceBetweenCircles,
this.spaceBetweenCircles
)
attributes.recycle()
innerLoaderAnimation()
outerLoaderAnimation()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val widthMode = MeasureSpec.getMode(widthMeasureSpec)
val widthSize = MeasureSpec.getSize(widthMeasureSpec)
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
val heightSize = MeasureSpec.getSize(heightMeasureSpec)
val desired = DESIRED_WH.dp.roundToInt()
val width = when (widthMode) {
MeasureSpec.EXACTLY -> {
widthSize
}
MeasureSpec.AT_MOST -> {
min(desired, widthSize)
}
else -> {
desired
}
}
val height = when (heightMode) {
MeasureSpec.EXACTLY -> {
heightSize
}
MeasureSpec.AT_MOST -> {
min(desired, heightSize)
}
else -> {
desired
}
}
setMeasuredDimension(width, height)
val highStroke = outerLoaderStrokeWidth + innerLoaderStrokeWidth
val expansion = MAX_TOTAL_STROKE.dp - highStroke
outerLoadingRect.set(
START_POINT + expansion + (highStroke / MID_POINT),
START_POINT + expansion + (highStroke / MID_POINT),
width - (expansion + (highStroke / MID_POINT)),
width - (expansion + (highStroke / MID_POINT))
)
innerLoadingRect.set(
START_POINT + (expansion + highStroke + spaceBetweenCircles),
START_POINT + (expansion + highStroke + spaceBetweenCircles),
width - (expansion + highStroke + spaceBetweenCircles),
width - (expansion + highStroke + spaceBetweenCircles)
)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
updatePaint(outerLoaderColor, outerLoaderStrokeWidth)
canvas.drawArc(
outerLoadingRect,
outerLoaderAnimValue.toFloat(),
outerLoaderLength,
false,
paint
)
updatePaint(innerLoaderColor, innerLoaderStrokeWidth)
canvas.drawArc(
innerLoadingRect,
innerLoaderAnimValue.toFloat(),
innerLoaderLength,
false,
paint
)
}
// Starts the animation when the screen is attached
override fun onAttachedToWindow() {
super.onAttachedToWindow()
startAnimation()
}
// Stops the animation when the screen is detached
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
stopAnimation()
}
private fun startAnimation() {
innerLoaderAnimator.start()
outerLoaderAnimator.start()
}
private fun stopAnimation() {
innerLoaderAnimator.end()
outerLoaderAnimator.end()
}
/**
* Both progresses use the same paint object, which is updated with this function before being drawn.
* @param color [Int]
* @param strokeWidth [Float]
*/
private fun updatePaint(color: Int, strokeWidth: Float) {
paint.color = color
paint.strokeWidth = strokeWidth
}
/**
* Returns an interpolator back based on the integer value
* sorting is the same as enum in attrs.xml.
* @param interpolator [Int]
*/
private fun getAnimation(interpolator: Int): Interpolator {
return when (interpolator) {
0 -> AccelerateInterpolator()
1 -> DecelerateInterpolator()
2 -> AccelerateDecelerateInterpolator()
3 -> AnticipateInterpolator()
4 -> AnticipateOvershootInterpolator()
5 -> LinearInterpolator()
6 -> OvershootInterpolator()
else -> AccelerateDecelerateInterpolator()
}
}
/**
* Animation continues until progress is removed. Inherits its properties from defined variables.
* - innerLoaderAnimation
* - outerLoaderAnimation
*/
private fun innerLoaderAnimation() {
innerLoaderAnimator.interpolator = getAnimation(innerAnimInterpolator)
innerLoaderAnimator.duration = innerLoaderAnimDuration.toLong()
innerLoaderAnimator.repeatCount = ValueAnimator.INFINITE
innerLoaderAnimator.addUpdateListener { animation ->
innerLoaderAnimValue = animation.animatedValue as Int
invalidate()
}
}
private fun outerLoaderAnimation() {
outerLoaderAnimator.interpolator = getAnimation(outerAnimInterpolator)
outerLoaderAnimator.duration = outerLoaderAnimDuration.toLong()
outerLoaderAnimator.repeatCount = ValueAnimator.INFINITE
outerLoaderAnimator.addUpdateListener { animation ->
outerLoaderAnimValue = animation.animatedValue as Int
invalidate()
}
}
}
| 0 | Kotlin | 3 | 19 | cf2e70342228b708e2fd6fca3a185ebcecf925a4 | 11,839 | Android-Nested-Progress | MIT License |
data/src/main/kotlin/data/di/DataModule.kt | kryntor57 | 776,260,246 | false | {"Kotlin": 38499} | package data.di
import android.content.Context
import androidx.room.Room
import com.cat.flights.viewer.BuildConfig
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import data.local.AppDB
import data.local.LocationDao
import data.network.FlightService
import data.network.LocationService
import data.network.priceline.DefaultRetrofitJsonFormat
import data.network.priceline.PriceLineRetrofitFactory
import data.repository.LocationRepository
import data.repository.LocationRepositoryImpl
import data.repository.FlightRepository
import data.repository.FlightRepositoryImpl
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.serialization.json.Json
import retrofit2.Retrofit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
public abstract class ExternalModule {
@Binds
@Singleton
internal abstract fun bindCitiesRepository(impl: LocationRepositoryImpl) : LocationRepository
@Binds
@Singleton
internal abstract fun bindFlightsRepository(impl: FlightRepositoryImpl) : FlightRepository
}
@Module
@InstallIn(SingletonComponent::class)
internal class DataModule {
@Singleton
@Provides
fun provideAppDB(@ApplicationContext context: Context) : AppDB {
return Room.databaseBuilder(context, AppDB::class.java, "flights")
.build()
}
@Provides
fun provideLocationDao(db: AppDB) : LocationDao = db.locationDao()
@Provides
fun provideComputationScheduler() : Scheduler = Schedulers.computation()
@Provides
fun provideLocationService(retrofit: Retrofit) : LocationService {
return retrofit.create(LocationService::class.java)
}
@Provides
@Singleton
fun provideFlightService(retrofit: Retrofit) : FlightService {
return retrofit.create(FlightService::class.java)
}
@Provides
@Singleton
fun provideJson() : Json = DefaultRetrofitJsonFormat
@Provides
@Singleton
fun provideRetrofit(json: Json) : Retrofit = PriceLineRetrofitFactory(
baseUrl = BuildConfig.PricelineBaseurl,
apiKey = BuildConfig.PricelineRapidapiApikey,
host = BuildConfig.RapidapiPriceLineHost,
json = json
).create()
}
| 1 | Kotlin | 0 | 0 | e2ed947513924e1246640a677326022de319d23f | 2,392 | flightsviewer | Apache License 2.0 |
src/org/jetbrains/r/diagnostic/RExceptionAnalyzerReporter.kt | JetBrains | 214,212,060 | false | {"Kotlin": 2849970, "Java": 814635, "R": 36890, "CSS": 23692, "Lex": 14307, "HTML": 10063, "Rez": 245, "Rebol": 64} | /*
* 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.diagnostic
import com.intellij.diagnostic.ITNReporter
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import org.jetbrains.r.RPluginUtil
import java.text.SimpleDateFormat
import java.time.Duration
import java.time.Instant
class RExceptionAnalyzerReporter : ITNReporter() {
private val pluginDescriptor = RPluginUtil.getPlugin()
private val expired =
Duration.between(Instant.now(), SimpleDateFormat("yyyy-MM-dd").parse(EXPIRING_DATE).toInstant()).toDays() <= 0
override fun showErrorInRelease(event: IdeaLoggingEvent): Boolean = !expired
override fun getPluginDescriptor() = pluginDescriptor
}
private const val EXPIRING_DATE = "2020-12-15" | 2 | Kotlin | 12 | 62 | d4d5cf9c09804454f811df7de0c02506d6ef12d3 | 839 | Rplugin | Apache License 2.0 |
app/src/main/java/me/demo/yandexsimulator/di/module/builder/ConnectivityBuilder.kt | devazimjon | 602,052,895 | false | null | package me.demo.yandexsimulator.di.module.builder
import me.demo.yandexsimulator.common.util.Connectivity
import me.demo.yandexsimulator.common.util.ConnectivityImpl
import dagger.Binds
import dagger.Module
@Module
abstract class ConnectivityBuilder {
@Binds
abstract fun bindConnectivity(connectivityImpl: ConnectivityImpl): Connectivity
} | 0 | Kotlin | 0 | 0 | 83a6a68f1b13c18c3cb0166100c76feeebe2d26e | 352 | appliedlabs-task | Apache License 2.0 |
src/main/kotlin/model/Person.kt | joseluisgs | 433,598,374 | false | {"Kotlin": 76586} | package model
import javax.persistence.*
@Entity
@NamedQueries(
NamedQuery(name = "Person.findAll", query = "SELECT p FROM Person p"),
NamedQuery(name = "Person.findByName", query = "SELECT p FROM Person p WHERE p.name = :name"),
)
data class Person(
// Mis constructor primario
@Column(nullable = false)
var name: String,
@Column(nullable = true)
var email: String?,
@Column(nullable = true)
@OneToMany(
cascade = [CascadeType.ALL],
orphanRemoval = true
)
var myPhoneNumbers: MutableSet<PhoneNumber>?,
@Column(nullable = false)
@OneToMany(
cascade = [CascadeType.ALL],
fetch = FetchType.LAZY,
orphanRemoval = true,
mappedBy = "person"
)
var myAddress: MutableSet<Address>?
) {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = 0
constructor(id: Long, name: String, email: String?, telephone: Set<PhoneNumber>?, address: Set<Address>?) :
this(
name,
email,
telephone?.toMutableSet(),
address?.toMutableSet(),
) {
this.id = id
}
} | 0 | Kotlin | 3 | 3 | 4e41214bb590334e41038c770aa18026619356db | 1,181 | Contactos-Kotlin-JPA | MIT License |
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createFunction/call/member/funOnJavaInterface.before.Main.kt | JetBrains | 2,489,216 | false | null | // "/(Create member function 'A.foo')|(Create method 'foo' in 'A')/" "true"
// ERROR: Unresolved reference: foo
internal fun test(a: A): Int? {
return a.<caret>foo<String, Int>(1, "2")
} | 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 191 | intellij-community | Apache License 2.0 |
ui/src/main/java/ru/tinkoff/acquiring/sdk/utils/MoneyUtils.kt | TinkoffCreditSystems | 268,528,392 | false | null | /*
* Copyright © 2020 Tinkoff Bank
*
* 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 ru.tinkoff.acquiring.sdk.utils
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import java.math.BigDecimal
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*
import java.util.regex.Pattern
/**
* @author <NAME>
*/
internal object MoneyUtils {
private val RUS_LOCALE = Locale("ru", "RU")
private const val DEFAULT_MONEY_DECIMAL_SEPARATOR = ','
private const val DEFAULT_MONEY_GROUPING_SEPARATOR = '\u00a0'
private val MONEY_FORMAT: DecimalFormat
private val MONEY_FORMAT_PRECISE: DecimalFormat
private const val POINT_SEPARATOR = '.'
private const val MONEY_FRACTIONAL_PART = ".00"
private const val DEFAULT_NORMALIZED = "0.00"
init {
val decimalFormatSymbols = DecimalFormatSymbols(RUS_LOCALE)
decimalFormatSymbols.decimalSeparator = DEFAULT_MONEY_DECIMAL_SEPARATOR
decimalFormatSymbols.groupingSeparator = DEFAULT_MONEY_GROUPING_SEPARATOR
MONEY_FORMAT = DecimalFormat("#,##0.##", decimalFormatSymbols)
MONEY_FORMAT_PRECISE = DecimalFormat("#,##0.####", decimalFormatSymbols)
}
fun replaceArtifacts(string: String): String {
return string.replace(DEFAULT_MONEY_DECIMAL_SEPARATOR.toString(), ".").replace(DEFAULT_MONEY_GROUPING_SEPARATOR.toString(), "")
}
fun format(s: String): String {
val integral: String
var fraction = ""
val commaIndex = s.indexOf(DEFAULT_MONEY_DECIMAL_SEPARATOR)
if (commaIndex != -1) {
integral = s.substring(0, commaIndex)
fraction = s.substring(commaIndex, s.length)
} else {
integral = s
}
return if (integral.isEmpty()) {
fraction
} else {
val formatString = formatMoney(BigDecimal(replaceArtifacts(integral)))
"$formatString$fraction"
}
}
fun normalize(rawMoney: String): String {
var normalized: String
if (TextUtils.isEmpty(rawMoney)) {
normalized = DEFAULT_NORMALIZED
} else {
normalized = replaceArtifacts(rawMoney)
if (!normalized.contains(POINT_SEPARATOR.toString())) {
normalized += MONEY_FRACTIONAL_PART
} else {
if (normalized[0] == POINT_SEPARATOR) {
normalized = "0$normalized"
}
}
}
return normalized
}
private fun formatMoney(amount: BigDecimal): String {
return MONEY_FORMAT.format(amount)
}
class MoneyWatcher : TextWatcher {
private var pattern: Pattern? = null
private var beforeEditing = ""
private var selfEdit: Boolean = false
init {
setLengthLimit(DEFAULT_LIMIT)
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
if (selfEdit) {
return
}
beforeEditing = s.toString()
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(editable: Editable) {
if (selfEdit) {
return
}
var resultString = replaceArtifacts(editable.toString())
resultString = resultString.replace('.', DEFAULT_MONEY_DECIMAL_SEPARATOR)
if (!TextUtils.isEmpty(resultString)) {
val isValidCharacters = pattern!!.matcher(resultString).matches()
resultString = if (!isValidCharacters) {
beforeEditing
} else {
format(resultString)
}
}
selfEdit = true
editable.replace(0, editable.length, resultString, 0, resultString.length)
selfEdit = false
}
/**
* Sets length limit and updates regex pattern for validation.
* 9 is suggested for RUB, 7 is suggested for other currencies.
*
* @param lengthLimit the length limit.
*/
fun setLengthLimit(lengthLimit: Int) {
val patternValue = String.format(Locale.getDefault(), FORMAT_PATTERN, DEFAULT_MONEY_GROUPING_SEPARATOR, lengthLimit, DEFAULT_MONEY_DECIMAL_SEPARATOR)
pattern = Pattern.compile(patternValue)
}
companion object {
private const val DEFAULT_LIMIT = 7
private const val FORMAT_PATTERN = "^((\\d%s?){1,%d})?(%s\\d{0,2})?$"
}
}
}
| 26 | Kotlin | 16 | 23 | 6deb46fa37a41292e8065a3d7b944acb2e3eac26 | 5,160 | AcquiringSdkAndroid | Apache License 2.0 |
app/src/main/java/com/marknkamau/justjava/ui/previousOrders/PreviousOrdersPresenter.kt | letya999 | 210,450,705 | true | {"Kotlin": 167548} | package com.marknkamau.justjava.ui.previousOrders
import com.marknjunge.core.auth.AuthService
import com.marknjunge.core.data.firebase.OrderService
import com.marknkamau.justjava.ui.BasePresenter
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.launch
class PreviousOrdersPresenter(private val view: PreviousOrdersView,
private val authenticationService: AuthService,
private val orderService: OrderService,
mainDispatcher: CoroutineDispatcher
): BasePresenter(mainDispatcher){
fun getPreviousOrders() {
uiScope.launch {
try {
val previousOrders = orderService.getPreviousOrders(authenticationService.getCurrentUser().userId)
if (previousOrders.isEmpty()) {
view.displayNoOrders()
} else {
val sorted = previousOrders.sortedBy { it.date }.reversed().toMutableList()
view.displayOrders(sorted)
}
} catch (e: Exception) {
view.displayMessage(e.message ?: "Error getting previous orders")
}
}
}
} | 0 | Kotlin | 0 | 0 | 5539f6a0de94745db190e212d6b8a31a19c6de7b | 1,210 | Just-Coffee | Apache License 2.0 |
app/src/main/java/com/ikuzMirel/flick/data/repositories/UserRepository.kt | IkuzItsuki | 564,666,943 | false | null | package com.ikuzMirel.flick.data.repositories
import com.ikuzMirel.flick.data.model.UserData
import com.ikuzMirel.flick.data.response.BasicResponse
import com.ikuzMirel.flick.data.response.FriendListResponse
import com.ikuzMirel.flick.data.response.FriendResponse
import com.ikuzMirel.flick.data.response.UserListResponse
import kotlinx.coroutines.flow.Flow
interface UserRepository {
suspend fun getUserInfo(userId: String): Flow<BasicResponse<UserData>>
suspend fun getUserFriends(): Flow<BasicResponse<FriendListResponse>>
suspend fun getUserFriend(friendUserId: String): Flow<BasicResponse<FriendResponse>>
suspend fun searchUsers(searchQuery: String): Flow<BasicResponse<UserListResponse>>
} | 0 | Kotlin | 1 | 2 | 7e2e2e172879532d958c7e73e577088eefb18510 | 714 | FLICK | Apache License 2.0 |
AndroidSdk/src/main/java/com/recurly/androidsdk/data/network/RecurlyApiClient.kt | recurly | 26,036,448 | false | {"Kotlin": 106151, "Shell": 1278} | package com.recurly.androidsdk.data.network
import com.recurly.androidsdk.data.model.tokenization.TokenizationRequest
import com.recurly.androidsdk.data.model.tokenization.TokenizationResponse
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
/**
* Here should be all the calls to the api with retrofit
*/
interface RecurlyApiClient {
@FormUrlEncoded
@POST("js/v1/tokens")
suspend fun recurlyTokenization(
@Field(value = "first_name", encoded = true) first_name: String,
@Field(value = "last_name", encoded = true) last_name: String,
@Field(value = "company", encoded = true) company: String,
@Field(value = "address1", encoded = true) address1: String,
@Field(value = "address2", encoded = true) address2: String,
@Field(value = "city", encoded = true) city: String,
@Field(value = "state", encoded = true) state: String,
@Field(value = "postal_code", encoded = true) postal_code: String,
@Field(value = "country", encoded = true) country: String,
@Field(value = "phone", encoded = true) phone: String,
@Field(value = "vat_number", encoded = true) vat_number: String,
@Field(value = "tax_identifier", encoded = true) tax_identifier: String,
@Field(value = "tax_identifier_type", encoded = true) tax_identifier_type: String,
@Field(value = "number", encoded = true) number: Long,
@Field(value = "month", encoded = true) month: Int,
@Field(value = "year", encoded = true) year: Int,
@Field(value = "cvv", encoded = true) cvv: Int,
@Field(value = "version", encoded = true) version: String,
@Field(value = "key", encoded = true) key: String,
@Field(value = "deviceId", encoded = true) deviceId: String,
@Field(value = "sessionId", encoded = true) sessionId: String
): Response<TokenizationResponse>
} | 2 | Kotlin | 5 | 8 | eb4c71ea983df9c0a36573c067f90ff6db6c3caa | 1,983 | recurly-client-android | MIT License |
AndroidSdk/src/main/java/com/recurly/androidsdk/data/network/RecurlyApiClient.kt | recurly | 26,036,448 | false | {"Kotlin": 106151, "Shell": 1278} | package com.recurly.androidsdk.data.network
import com.recurly.androidsdk.data.model.tokenization.TokenizationRequest
import com.recurly.androidsdk.data.model.tokenization.TokenizationResponse
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
/**
* Here should be all the calls to the api with retrofit
*/
interface RecurlyApiClient {
@FormUrlEncoded
@POST("js/v1/tokens")
suspend fun recurlyTokenization(
@Field(value = "first_name", encoded = true) first_name: String,
@Field(value = "last_name", encoded = true) last_name: String,
@Field(value = "company", encoded = true) company: String,
@Field(value = "address1", encoded = true) address1: String,
@Field(value = "address2", encoded = true) address2: String,
@Field(value = "city", encoded = true) city: String,
@Field(value = "state", encoded = true) state: String,
@Field(value = "postal_code", encoded = true) postal_code: String,
@Field(value = "country", encoded = true) country: String,
@Field(value = "phone", encoded = true) phone: String,
@Field(value = "vat_number", encoded = true) vat_number: String,
@Field(value = "tax_identifier", encoded = true) tax_identifier: String,
@Field(value = "tax_identifier_type", encoded = true) tax_identifier_type: String,
@Field(value = "number", encoded = true) number: Long,
@Field(value = "month", encoded = true) month: Int,
@Field(value = "year", encoded = true) year: Int,
@Field(value = "cvv", encoded = true) cvv: Int,
@Field(value = "version", encoded = true) version: String,
@Field(value = "key", encoded = true) key: String,
@Field(value = "deviceId", encoded = true) deviceId: String,
@Field(value = "sessionId", encoded = true) sessionId: String
): Response<TokenizationResponse>
} | 2 | Kotlin | 5 | 8 | eb4c71ea983df9c0a36573c067f90ff6db6c3caa | 1,983 | recurly-client-android | MIT License |
src/main/kotlin/no/nav/helse/flex/service/LesVedtakService.kt | navikt | 259,604,826 | false | null | package no.nav.helse.flex.service
import no.nav.helse.flex.api.AbstractApiError
import no.nav.helse.flex.api.LogLevel
import no.nav.helse.flex.brukernotifkasjon.BrukernotifikasjonKafkaProdusent
import no.nav.helse.flex.db.*
import no.nav.helse.flex.domene.VedtakStatus
import no.nav.helse.flex.domene.VedtakStatusDTO
import no.nav.helse.flex.kafka.VedtakStatusKafkaProducer
import no.nav.helse.flex.metrikk.Metrikk
import no.nav.helse.flex.service.LesVedtakService.LesResultat.*
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.Instant
@Service
@Transactional
class LesVedtakService(
private val vedtakDAO: VedtakDAO,
private val brukernotifikasjonKafkaProdusent: BrukernotifikasjonKafkaProdusent,
private val metrikk: Metrikk,
private val utbetalingRepository: UtbetalingRepository,
private val vedtakStatusProducer: VedtakStatusKafkaProducer,
@Value("\${on-prem-kafka.username}") private val serviceuserUsername: String,
) {
fun lesVedtak(fnr: String, vedtaksId: String): String {
val (lesUtbetaling, _) = lesUtbetaling(fnr = fnr, utbetalingsId = vedtaksId)
val lestGammeltVedtak = lesGammeltVedtak(fnr = fnr, vedtaksId = vedtaksId)
if (lestGammeltVedtak == IKKE_FUNNET && lesUtbetaling == IKKE_FUNNET) {
throw VedtakIkkeFunnetException(vedtaksId)
}
if (lestGammeltVedtak == ALLEREDE_LEST || lesUtbetaling == ALLEREDE_LEST) {
return "Vedtak $vedtaksId er allerede lest"
}
if (lestGammeltVedtak == LEST) {
return "Leste vedtak $vedtaksId"
}
vedtakStatusProducer.produserMelding(
VedtakStatusDTO(fnr = fnr, id = vedtaksId, vedtakStatus = VedtakStatus.LEST)
)
utbetalingRepository.updateLestByFnrAndId(
lest = Instant.now(),
fnr = fnr,
id = vedtaksId
)
return "Leste vedtak $vedtaksId"
}
private fun lesUtbetaling(fnr: String, utbetalingsId: String): Pair<LesResultat, String?> {
val utbetalingDbRecord = utbetalingRepository
.findUtbetalingDbRecordsByFnr(fnr)
.find { it.id == utbetalingsId }
?: return IKKE_FUNNET to null
if (utbetalingDbRecord.lest != null) {
return ALLEREDE_LEST to null
}
if (utbetalingDbRecord.brukernotifikasjonSendt == null) {
return ALDRI_SENDT_BRUKERNOTIFIKASJON to null
}
return LEST to utbetalingDbRecord.varsletMed
}
private fun lesGammeltVedtak(fnr: String, vedtaksId: String): LesResultat {
if (vedtakDAO.finnVedtak(fnr).none { it.id == vedtaksId }) {
return IKKE_FUNNET
}
if (vedtakDAO.lesVedtak(fnr, vedtaksId)) {
return LEST
}
return ALLEREDE_LEST
}
enum class LesResultat {
IKKE_FUNNET,
LEST,
ALLEREDE_LEST,
ALDRI_SENDT_BRUKERNOTIFIKASJON,
}
class VedtakIkkeFunnetException(vedtaksId: String) : AbstractApiError(
message = "Fant ikke vedtak $vedtaksId",
httpStatus = HttpStatus.NOT_FOUND,
reason = "VEDTAK_IKKE_FUNNET",
loglevel = LogLevel.WARN
)
}
| 1 | Kotlin | 0 | 1 | 6922b6ef2a754a01ad7b6bcee141f1a3f76cc754 | 3,369 | spinnsyn-backend | MIT License |
michiganelections_api/src/main/java/io/michiganelections/api/model/Election.kt | MI-Vote | 298,102,135 | false | null | package io.michiganelections.api.model
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Election(
val id: Long,
val name: String,
val url: String,
val date: String,
val description: String,
val active: Boolean,
val referenceUrl: String?
)
| 6 | Kotlin | 2 | 3 | 9c4c28a38ccc59f381bbb289f64493fe7ba2ea03 | 288 | mivote-android | MIT License |
app/src/main/java/xyz/teamgravity/notepad/viewmodel/NoteViewModel.kt | raheemadamboev | 312,077,625 | false | null | package xyz.teamgravity.notepad.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import xyz.teamgravity.notepad.model.NoteModel
class NoteViewModel(application: Application) : AndroidViewModel(application) {
private val repository = NoteRepository(application)
fun insert(note: NoteModel) = repository.insert(note)
fun update(note: NoteModel) = repository.update(note)
fun delete(note: NoteModel) = repository.delete(note)
fun deleteSelected(notes: List<NoteModel>) = repository.deleteSelected(notes)
fun deleteAll() = repository.deleteAll()
fun getAllNotes() = repository.getAllNotes()
} | 0 | Kotlin | 0 | 0 | 51bc6bb874fbc3d1e690f8458648689ee6f31298 | 660 | notepad-app | Apache License 2.0 |
composeApp/src/desktopMain/kotlin/io/haskins/staffmanagement/dao/models/EmployeeNotes.kt | haskins-io | 777,847,073 | false | {"Kotlin": 107617} | package io.haskins.staffmanagement.dao.models
import org.jetbrains.exposed.sql.Column
import org.jetbrains.exposed.sql.Table
object EmployeeNotes: Table() {
val id: Column<Int> = integer("en_id").autoIncrement()
val employeeId: Column<Int> = (integer("employee_id") references Employees.id)
val noteId = reference("note_id", Notes)
override val primaryKey = PrimaryKey(Employees.id, name="employeenotes_pk")
} | 0 | Kotlin | 0 | 0 | a01c66e731daa71d55366c2c2e98345ab158b86a | 430 | StaffManagement | MIT License |
vk-sdk-api/src/main/java/com/vk/sdk/api/database/methods/DatabaseGetChairs.kt | wesshi-tiktok | 358,352,248 | true | {"Kotlin": 4764291, "Java": 37555} | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.database.methods
import com.vk.sdk.api.ApiRequestBase
import com.vk.sdk.api.GsonHolder
import com.vk.sdk.api.database.dto.DatabaseGetChairsResponseDto
import com.vk.sdk.api.database.responses.DatabaseGetChairsResponse
import kotlin.Int
import org.json.JSONObject
/**
* Returns list of chairs on a specified faculty.
* @param facultyId id of the faculty to get chairs from minimum 0
* @param offset offset required to get a certain subset of chairs minimum 0
* @param count amount of chairs to get default 100 minimum 0 maximum 10000
*/
class DatabaseGetChairs(
private val facultyId: Int,
private val offset: Int? = null,
private val count: Int? = null
) : ApiRequestBase<DatabaseGetChairsResponseDto>(methodName = "database.getChairs") {
init {
addParam("faculty_id", facultyId)
offset?.let { value ->
addParam("offset", value)
}
count?.let { value ->
addParam("count", value)
}
}
override fun parse(r: JSONObject): DatabaseGetChairsResponseDto =
GsonHolder.gson.fromJson(r.toString(), DatabaseGetChairsResponse::class.java).response
}
| 0 | null | 0 | 0 | 32898fa706e4064118ae18327649e89a22fc6070 | 2,554 | vk-android-sdk | MIT License |
agent/src/main/kotlin/ru/art/platform/agent/extension/PathExtensions.kt | art-community | 284,500,366 | false | null | package ru.art.platform.agent.extension
import ru.art.core.constants.StringConstants.*
import ru.art.platform.agent.constants.IgnoringDirectories.IGNORING_DIRECTORIES
import java.nio.file.*
import java.util.stream.Collectors
import java.util.stream.Collectors.*
import kotlin.streams.asStream
import kotlin.streams.toList
fun Path.extractName() = toAbsolutePath().toString().substringAfterLast(SLASH)
fun Path.findParentDirectoriesOfFilesStartsWith(name: String, filter: (Path) -> Boolean = { true }) = toFile()
.walkTopDown()
.onEnter { directory -> !IGNORING_DIRECTORIES.contains(directory.name)}
.filter { file ->
try {
file.isFile && file.name.startsWith(name) && filter(file.toPath())
} catch (ignored: Throwable) {
false
}
}
.map { file -> file.parentFile.toPath() }
fun Path.firstFileStartsWith(name: String, filter: (Path) -> Boolean = { true }): Path? = toFile()
.walkTopDown()
.firstOrNull { file ->
try {
file.isFile && file.name.startsWith(name) && filter(file.toPath())
} catch (ignored: Throwable) {
false
}
}
?.toPath()
fun Path.listFiles() = toFile()
.walkTopDown()
.filter { file ->
try {
file.isFile
} catch (e: Throwable) {
false
}
}
| 1 | TypeScript | 0 | 1 | 80051409f70eec2abb66afb7d72359a975198a2b | 1,458 | art-platform | Apache License 2.0 |
app/src/main/java/com/aquispe/wonkainc/data/local/database/EmployeeRemoteKeysDao.kt | arman-visual | 674,817,363 | false | null | package com.aquispe.wonkainc.data.local.database
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.aquispe.wonkainc.data.local.database.entities.EmployeeRemoteKeys
@Dao
interface EmployeeRemoteKeysDao {
@Query("SELECT * FROM employee_remote_keys WHERE id = :id")
suspend fun getRemoteKeyById(id: Int): EmployeeRemoteKeys?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun addAllRemoteKeys(remoteKeys: List<EmployeeRemoteKeys>)
@Query("DELETE FROM employee_remote_keys")
suspend fun clearRemoteKeys()
@Query("SELECT created_at FROM employee_remote_keys ORDER BY created_at DESC LIMIT 1")
suspend fun getCreationTime(): Long?
}
| 0 | Kotlin | 0 | 0 | 748ecfcea8999d5f05a8784e114fd60f7c07f06e | 756 | WonkaInc | Apache License 2.0 |
kotlin/src/com/soup/memo/kotlin/AbstractTest.kt | yiguotang | 215,424,006 | false | {"Java": 319276, "Kotlin": 12457, "HTML": 1790, "Thrift": 768} | package com.soup.memo.kotlin
/**
* <p>
* 抽象类示例
* </p>
*
* @author zhaoyi
* @date 2020-03-13 21:57
* @since 1.0
*/
open class BaseClass {
open fun method() {
}
}
abstract class ChildClass : BaseClass() {
override fun method() {
}
} | 4 | null | 1 | 1 | 6738760544b7d06803dcab500ca44e30c9a07822 | 266 | soup-memo | Apache License 2.0 |
engine/src/main/kotlin/io/kotless/gen/factory/azure/utils/FilesCreationTf.kt | JetBrains | 192,359,205 | false | null | package io.kotless.gen.factory.azure.utils
import io.terraformkt.terraform.TFResource
object FilesCreationTf {
fun localFile(id: String, content: String, fileName: String) = ResourceFromString(
id, "local_file", """
resource "local_file" "$id" {
content = "$content"
filename = "$fileName"
}
""".trimIndent()
)
fun zipFile(id: String, sourceDir: String, outputPath: String, depends: List<String>) = ResourceFromString(
id, "archive_file", """
resource "archive_file" "$id" {
type = "zip"
output_path = "$outputPath"
source_dir = "$sourceDir"
depends_on = [${
depends.joinToString(
"\",\"",
prefix = "\"",
postfix = "\""
)
}]
}
""".trimIndent()
)
class ResourceFromString(
id: String,
val type: String,
val value: String
) : TFResource(id, type) {
override fun render(): String {
return value
}
}
}
| 51 | null | 56 | 975 | 596c77f41410409207647dfd195e34f4562728ed | 1,152 | kotless | Apache License 2.0 |
app/src/main/java/com/macs/revitalize/presentation/calendar/service/AlaramReceiver.kt | Raghu0203 | 634,680,689 | false | null | package com.example.calenderappdemo.service
import android.content.BroadcastReceiver
import android.content.Intent
import com.example.calenderappdemo.MainActivity
import android.app.PendingIntent
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import androidx.core.app.NotificationCompat
import android.media.RingtoneManager
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationManagerCompat
import com.macs.revitalize.R
class AlaramReceiver : BroadcastReceiver() {
@RequiresApi(Build.VERSION_CODES.O)
override fun onReceive(context: Context, intent: Intent) {
val event = intent.getStringExtra("event")
val time = intent.getStringExtra("time")
val notid = intent.getIntExtra("id", 0)
val activityintent = Intent(context, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
context,
0,
activityintent,
PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
)
val channelId = "channel_id"
val name: CharSequence = "channel_name"
val description = "description"
val channel = NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_HIGH)
channel.description = description
val notificationManager = context.getSystemService(
NotificationManager::class.java
)
notificationManager.createNotificationChannel(channel)
val notification = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_launcher_background)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentTitle(event).setContentText(time).setDeleteIntent(pendingIntent)
.setGroup("Group_calender_view").build()
val notificationManagerCompat = NotificationManagerCompat.from(context)
notificationManagerCompat.notify(notid, notification)
}
} | 0 | Kotlin | 0 | 0 | b777a9092bf754fbcb3900036b3908733fc95e42 | 2,052 | Revitalize | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/example/fragments/Fragment1.kt | esd1361e | 848,817,710 | false | {"Kotlin": 5060} | package com.example.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.fragments.databinding.Fragment1Binding
class Fragment1 :Fragment() {
lateinit var binding :Fragment1Binding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = Fragment1Binding.inflate(layoutInflater , container,false)
return binding.root
}
} | 0 | Kotlin | 0 | 0 | 481343a880eca97ff1405f5a5087b6aa3d562912 | 548 | Fragment-Project-Dunijet | MIT License |
PayPalWebPayments/src/main/java/com/paypal/android/paypalwebpayments/errors/PayPalWebCheckoutError.kt | paypal | 390,097,712 | false | null | package com.paypal.android.paypalwebpayments.errors
import com.braintreepayments.api.BrowserSwitchException
import com.paypal.android.corepayments.PayPalSDKError
internal object PayPalWebCheckoutError {
// 0. An unknown error occurred.
val unknownError = PayPalSDKError(
code = PayPalWebCheckoutErrorCode.UNKNOWN.ordinal,
errorDescription = "An unknown error occurred. Contact developer.paypal.com/support."
)
// 1. Result did not contain the expected data.
val malformedResultError = PayPalSDKError(
code = PayPalWebCheckoutErrorCode.MALFORMED_RESULT.ordinal,
errorDescription = "Result did not contain the expected data. Payer ID or Order ID is null."
)
fun browserSwitchError(cause: BrowserSwitchException) = PayPalSDKError(
code = PayPalWebCheckoutErrorCode.BROWSER_SWITCH.ordinal,
errorDescription = cause.message ?: "Unable to Browser Switch"
)
}
| 22 | null | 45 | 74 | dcc46f92771196e979f7863b9b8d3fa3d6dc1a7d | 938 | paypal-android | Apache License 2.0 |
build-logic/convention/src/main/kotlin/com/vk/id/AndroidCompose.kt | VKCOM | 696,297,549 | false | {"Kotlin": 929849, "Shell": 17068, "AIDL": 3429, "JavaScript": 1182} | /*
* Copyright 2022 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.vk.id
import com.vk.id.util.android
import org.gradle.api.Project
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.getByType
import org.jetbrains.kotlin.gradle.dsl.KotlinAndroidProjectExtension
/**
* Configure Compose-specific options
*/
internal fun Project.configureAndroidCompose() {
with(pluginManager) {
apply(libs.findPlugin("compose-compiler").get().get().pluginId)
}
extensions.android {
buildFeatures {
compose = true
}
dependencies {
val bom = libs.findLibrary("androidx-compose-bom").get()
add("implementation", platform(bom))
add("androidTestImplementation", platform(bom))
}
}
with(extensions.getByType<KotlinAndroidProjectExtension>()) {
compilerOptions {
// Force implicit visibility modifiers to avoid mistakes like exposing internal api
freeCompilerArgs.addAll(buildComposeMetricsParameters())
}
}
}
private fun Project.buildComposeMetricsParameters(): List<String> {
val metricParameters = mutableListOf<String>()
val enableMetricsProvider = project.providers.gradleProperty("enableComposeCompilerMetrics")
val enableMetrics = (enableMetricsProvider.orNull == "true")
if (enableMetrics) {
val metricsFolder = project.layout.buildDirectory.file("compose-metrics").get().asFile
metricParameters.add("-P")
metricParameters.add(
"plugin:androidx.compose.compiler.plugins.kotlin:metricsDestination=" + metricsFolder.absolutePath
)
}
val enableReportsProvider = project.providers.gradleProperty("enableComposeCompilerReports")
val enableReports = (enableReportsProvider.orNull == "true")
if (enableReports) {
val reportsFolder = project.layout.buildDirectory.file("compose-reports").get().asFile
metricParameters.add("-P")
metricParameters.add(
"plugin:androidx.compose.compiler.plugins.kotlin:reportsDestination=" + reportsFolder.absolutePath
)
}
return metricParameters.toList()
}
| 2 | Kotlin | 3 | 28 | b5fae72f77a8edd0211c873346c6f8a4579b99c2 | 2,734 | vkid-android-sdk | MIT License |
src/main/kotlin/grd/kotlin/authapi/interfaces/IPostgresRepository.kt | gardehal | 708,548,046 | false | {"Kotlin": 468271, "Shell": 612, "HTML": 331} | package grd.kotlin.authapi.interfaces
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
import org.springframework.stereotype.Repository
@Repository
@EnableJpaRepositories
interface IPostgresRepository<TEntity: Any> : JpaRepository<TEntity, String>
| 0 | Kotlin | 0 | 0 | 14ed0a4f310f90c32880bfd1d0eacbe4c8780bd0 | 339 | kotlin-auth-api | MIT License |
app/src/main/java/com/breezepowell/features/newcollection/model/NewCollectionListResponseModel.kt | DebashisINT | 558,285,083 | false | {"Kotlin": 28543924, "Java": 1666150} | package com.breezepowell.features.newcollection.model
import com.breezepowell.app.domain.CollectionDetailsEntity
import com.breezepowell.base.BaseResponse
import com.breezepowell.features.shopdetail.presentation.model.collectionlist.CollectionListDataModel
/**
* Created by Saikat on 15-02-2019.
*/
class NewCollectionListResponseModel : BaseResponse() {
//var collection_list: ArrayList<CollectionListDataModel>? = null
var collection_list: ArrayList<CollectionDetailsEntity>? = null
} | 0 | Kotlin | 0 | 0 | f2764306c066accfdacd74ccb38f006546fe1ecc | 498 | PowellLaboratories | Apache License 2.0 |
app/src/main/java/com/transcendensoft/hedbanz/presentation/game/list/delegates/GameOverAdapterDelegate.kt | itcherry | 106,057,820 | false | {"Java": 1108999, "Kotlin": 277763} | package com.transcendensoft.hedbanz.presentation.game.list.delegates
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hannesdorfmann.adapterdelegates3.AdapterDelegate
import com.transcendensoft.hedbanz.R
import com.transcendensoft.hedbanz.domain.entity.Message
import com.transcendensoft.hedbanz.domain.entity.MessageType
import com.transcendensoft.hedbanz.presentation.game.list.holder.GameOverViewHolder
import io.reactivex.subjects.PublishSubject
import javax.inject.Inject
/**
* Copyright 2018. <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* This delegate is responsible for creating {@link GameOverViewHolder}
* and binding ViewHolder widgets according to model.
*
* An AdapterDelegate get added to an AdapterDelegatesManager.
* This manager is the man in the middle between RecyclerView.
* Adapter and each AdapterDelegate.
*
* @author <NAME>. E-mail: <EMAIL>
* Developed by <u>Transcendensoft</u>
*/
class GameOverAdapterDelegate @Inject constructor() :
AdapterDelegate<List<@JvmSuppressWildcards Message>>() {
val restartSubject: PublishSubject<View> = PublishSubject.create()
val cancelSubject: PublishSubject<View> = PublishSubject.create()
override fun onCreateViewHolder(parent: ViewGroup?): RecyclerView.ViewHolder {
val context = parent?.context
val itemView = LayoutInflater.from(context)
.inflate(R.layout.item_game_over, parent, false)
return GameOverViewHolder(context!!, itemView)
}
override fun isForViewType(items: List<Message>, position: Int): Boolean {
val message = items[position]
return message.messageType == MessageType.GAME_OVER
}
override fun onBindViewHolder(items: List<Message>, position: Int,
holder: RecyclerView.ViewHolder, payloads: MutableList<Any>) {
if(holder is GameOverViewHolder) {
holder.restartClickObservable().subscribe(restartSubject)
holder.cancelClickObservable().subscribe(cancelSubject)
val message = items[position]
holder.bindEnabledButtons(!(message.isFinished && !message.isLoading))
}
}
} | 1 | null | 1 | 1 | 0d426d5f98b5f788c2adfedddd5474e20d9f99bf | 2,794 | Hedbanz | Apache License 2.0 |
identity/src/test/java/com/stripe/android/identity/utils/PairMediatorLiveDataTest.kt | stripe | 6,926,049 | false | null | package com.stripe.android.identity.utils
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.MutableLiveData
import com.google.common.truth.Truth.assertThat
import com.stripe.android.identity.networking.Resource
import com.stripe.android.identity.networking.Status
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestRule
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
internal class PairMediatorLiveDataTest {
@get:Rule
var rule: TestRule = InstantTaskExecutorRule()
private val firstLiveData = MutableLiveData<Resource<String>>()
private val secondLiveData = MutableLiveData<Resource<String>>()
@Test
fun `when initialized then emits loading`() {
val pairMediatorLiveData = PairMediatorLiveData(firstLiveData, secondLiveData)
// need a observer to trigger latest value.
pairMediatorLiveData.observeForever {}
assertThat(pairMediatorLiveData.value?.status).isEqualTo(Status.LOADING)
}
@Test
fun `when one live data posts value then emits loading`() {
val pairMediatorLiveData = PairMediatorLiveData(firstLiveData, secondLiveData)
pairMediatorLiveData.observeForever {}
firstLiveData.postValue(Resource.success("data"))
assertThat(pairMediatorLiveData.value?.status).isEqualTo(Status.LOADING)
}
@Test
fun `when one live data posts error then emits error`() {
val pairMediatorLiveData = PairMediatorLiveData(firstLiveData, secondLiveData)
pairMediatorLiveData.observeForever {}
firstLiveData.postValue(Resource.error())
assertThat(pairMediatorLiveData.value?.status).isEqualTo(Status.ERROR)
}
@Test
fun `when both livedatas post value then emits success`() {
val pairMediatorLiveData = PairMediatorLiveData(firstLiveData, secondLiveData)
pairMediatorLiveData.observeForever {}
val value1 = "value1"
val value2 = "value2"
firstLiveData.postValue(Resource.success(value1))
secondLiveData.postValue(Resource.success(value2))
assertThat(pairMediatorLiveData.value?.status).isEqualTo(Status.SUCCESS)
assertThat(pairMediatorLiveData.value?.data).isEqualTo(Pair(value1, value2))
}
}
| 64 | Kotlin | 522 | 935 | bec4fc5f45b5401a98a310f7ebe5d383693936ea | 2,336 | stripe-android | MIT License |
app/src/main/java/dev/leonlatsch/photok/cgallery/ui/GalleryViewModel.kt | leonlatsch | 287,088,448 | false | {"Kotlin": 355341, "HTML": 1049} | /*
* Copyright 2020-2023 <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 dev.leonlatsch.photok.cgallery.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import coil.ImageLoader
import dagger.hilt.android.lifecycle.HiltViewModel
import dev.leonlatsch.photok.cgallery.ui.navigation.GalleryNavigationEvent
import dev.leonlatsch.photok.imageloading.di.EncryptedImageLoader
import dev.leonlatsch.photok.model.repositories.PhotoRepository
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import javax.inject.Inject
@HiltViewModel
class GalleryViewModel @Inject constructor(
photoRepository: PhotoRepository,
@EncryptedImageLoader val encryptedImageLoader: ImageLoader,
private val galleryUiStateFactory: GalleryUiStateFactory,
) : ViewModel() {
private val photosFlow = photoRepository.observeAll()
.stateIn(viewModelScope, SharingStarted.Eagerly, listOf())
private val multiSelectionState =
MutableStateFlow(MultiSelectionState(isActive = false, listOf()))
val uiState: StateFlow<GalleryUiState> = combine(
photosFlow,
multiSelectionState
) { photos, multiSelectionState ->
galleryUiStateFactory.create(photos, multiSelectionState)
}.stateIn(viewModelScope, SharingStarted.Lazily, GalleryUiState.Empty)
private val eventsChannel = Channel<GalleryNavigationEvent>()
val eventsFlow = eventsChannel.receiveAsFlow()
fun handleUiEvent(event: GalleryUiEvent) {
when (event) {
is GalleryUiEvent.OpenImportMenu -> eventsChannel.trySend(GalleryNavigationEvent.OpenImportMenu)
is GalleryUiEvent.PhotoClicked -> onPhotoClicked(event.item)
is GalleryUiEvent.PhotoLongPressed -> onPhotoLongPressed(event.item)
is GalleryUiEvent.CancelMultiSelect -> onCancelMultiSelect()
is GalleryUiEvent.OnDelete -> onDeleteSelectedItems()
is GalleryUiEvent.OnExport -> onExportSelectedItems()
is GalleryUiEvent.SelectAll -> onSelectAll()
}
}
private fun onSelectAll() {
multiSelectionState.update {
it.copy(
isActive = true,
selectedItemUUIDs = photosFlow.value.map { photo -> photo.uuid })
}
}
private fun onExportSelectedItems() {
val uuidsToExport = multiSelectionState.value.selectedItemUUIDs
eventsChannel.trySend(
GalleryNavigationEvent.StartExportDialog(
photosFlow.value.filter { uuidsToExport.contains(it.uuid) })
)
onCancelMultiSelect()
}
private fun onDeleteSelectedItems() {
val uuidsToDelete = multiSelectionState.value.selectedItemUUIDs
eventsChannel.trySend(GalleryNavigationEvent.StartDeleteDialog(
photosFlow.value.filter { uuidsToDelete.contains(it.uuid) }
))
onCancelMultiSelect()
}
private fun onCancelMultiSelect() {
multiSelectionState.update { it.copy(isActive = false, selectedItemUUIDs = emptyList()) }
}
private fun onPhotoLongPressed(item: PhotoTile) {
if (multiSelectionState.value.isActive.not()) {
multiSelectionState.update {
it.copy(
isActive = true,
selectedItemUUIDs = listOf(item.uuid)
)
}
}
}
private fun onPhotoClicked(item: PhotoTile) {
if (multiSelectionState.value.isActive.not()) {
eventsChannel.trySend(GalleryNavigationEvent.OpenPhoto(item.uuid))
} else {
if (multiSelectionState.value.selectedItemUUIDs.contains(item.uuid)) {
// Remove
multiSelectionState.update {
it.copy(
isActive = it.selectedItemUUIDs.size != 1,
selectedItemUUIDs = it.selectedItemUUIDs.filterNot { selectedUUid ->
selectedUUid == item.uuid
},
)
}
} else {
// Add
multiSelectionState.update {
it.copy(
selectedItemUUIDs = it.selectedItemUUIDs + listOf(item.uuid)
)
}
}
}
}
}
| 29 | Kotlin | 40 | 372 | 2d4a3fe0e976c26c672f62fcd1030f1dbb45cd58 | 5,137 | Photok | Apache License 2.0 |
data_structure/src/main/java/guideme/volunteers/helpers/dataservices/databases/DatabaseUser.kt | mniami | 79,149,480 | false | {"Shell": 2, "Gradle": 4, "YAML": 2, "Java Properties": 2, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "XML": 37, "Kotlin": 136, "Java": 2} | package guideme.volunteers.helpers.dataservices.databases
class DatabaseUser (
val uid : String,
val providerId : String,
val displayName : String?,
val email : String?,
val token : String?) | 0 | Kotlin | 0 | 1 | ec79ba258d26206d8cd2ee7eb8ebcdc94696be5f | 231 | volunteers | Apache License 2.0 |
android/quest/src/main/java/org/smartregister/fhircore/quest/ui/patient/register/components/RegisterList.kt | opensrp | 339,242,809 | false | null | /*
* Copyright 2021 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartregister.fhircore.quest.ui.patient.register.components
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Divider
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.items
import org.smartregister.fhircore.engine.ui.components.CircularProgressBar
import org.smartregister.fhircore.engine.ui.components.ErrorMessage
import org.smartregister.fhircore.engine.ui.theme.DividerColor
import org.smartregister.fhircore.quest.ui.shared.models.RegisterViewData
import timber.log.Timber
@Composable
fun RegisterList(
pagingItems: LazyPagingItems<RegisterViewData>,
onRowClick: (String) -> Unit,
modifier: Modifier = Modifier
) {
LazyColumn {
items(pagingItems, key = { it.logicalId }) {
RegisterListRow(registerViewData = it!!, onRowClick = onRowClick)
Divider(color = DividerColor, thickness = 1.dp)
}
pagingItems.apply {
when {
loadState.refresh is LoadState.Loading ->
item {
CircularProgressBar(modifier = modifier.wrapContentWidth(Alignment.CenterHorizontally))
}
loadState.append is LoadState.Loading ->
item {
CircularProgressBar(modifier = modifier.wrapContentWidth(Alignment.CenterHorizontally))
}
loadState.refresh is LoadState.Error -> {
val loadStateError = pagingItems.loadState.refresh as LoadState.Error
item {
ErrorMessage(
message = loadStateError.error.also { Timber.e(it) }.localizedMessage!!,
onClickRetry = { retry() }
)
}
}
loadState.append is LoadState.Error -> {
val error = pagingItems.loadState.append as LoadState.Error
item {
ErrorMessage(message = error.error.localizedMessage!!, onClickRetry = { retry() })
}
}
}
}
}
}
| 158 | Kotlin | 10 | 18 | 9d7044a12ef2726705a3019cb26ab03bc48bc28c | 2,749 | fhircore | Apache License 2.0 |
app/src/main/java/br/com/dnassuncao/movieapp/features/search_movie/presentantion/MovieSearchState.kt | dnassuncao | 765,808,513 | false | {"Kotlin": 60631} | package br.com.dnassuncao.movieapp.features.search_movie.presentantion
import androidx.paging.PagingData
import br.com.dnassuncao.movieapp.features.search_movie.domain.MovieSearch
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
data class MovieSearchState(
val query: String = "",
val estado: String = "",
val movies: Flow<PagingData<MovieSearch>> = emptyFlow()
)
| 0 | Kotlin | 0 | 0 | c1728e432704fdd32d410a7ee89c898538138f52 | 407 | movies-compose | MIT License |
app/src/main/java/com/example/pixabaygalleryapp/base/FragmentBase.kt | AliAzaz | 360,302,381 | false | {"Kotlin": 65074, "CMake": 1688, "C++": 254} | package com.example.pixabaygalleryapp.base
import androidx.fragment.app.Fragment
abstract class FragmentBase : Fragment() | 0 | Kotlin | 3 | 13 | 3c17348512636bdb82da816a9c600998255808f4 | 123 | PixabayGalleryApp | MIT License |
src/en/comikey/src/eu/kanade/tachiyomi/extension/en/comikey/dto/MangaDetailsDto.kt | AntsyLich | 361,748,620 | true | {"Kotlin": 4347255, "Shell": 3677} | package eu.kanade.tachiyomi.extension.en.comikey.dto
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class MangaDetailsDto(
@SerialName("id")
val id: Int? = null,
@SerialName("link")
val link: String? = null,
@SerialName("name")
val name: String? = null,
@SerialName("e4pid")
val e4pid: String? = null,
@SerialName("uslug")
val uslug: String? = null,
@SerialName("alt")
val alt: String? = null,
@SerialName("author")
val author: List<Author?>? = null,
@SerialName("artist")
val artist: List<Artist?>? = null,
@SerialName("adult")
val adult: Boolean? = null,
@SerialName("tags")
val tags: List<Tag?>? = null,
@SerialName("keywords")
val keywords: String? = null,
@SerialName("description")
val description: String? = null,
@SerialName("excerpt")
val excerpt: String? = null,
@SerialName("created_at")
val createdAt: String? = null,
@SerialName("modified_at")
val modifiedAt: String? = null,
@SerialName("publisher")
val publisher: Publisher? = null,
@SerialName("color")
val color: String? = null,
@SerialName("in_exclusive")
val inExclusive: Boolean? = null,
@SerialName("in_hype")
val inHype: Boolean? = null,
@SerialName("all_free")
val allFree: Boolean? = null,
@SerialName("availability_strategy")
val availabilityStrategy: AvailabilityStrategy? = null,
@SerialName("campaigns")
val campaigns: List<String?>? = null, // unknown list element type, was null
@SerialName("last_updated")
val lastUpdated: String? = null,
@SerialName("chapter_count")
val chapterCount: Int? = null,
@SerialName("update_status")
val updateStatus: Int? = null,
@SerialName("update_text")
val updateText: String? = null,
@SerialName("format")
val format: Int? = null,
@SerialName("cover")
val cover: String? = null,
@SerialName("logo")
val logo: String? = null,
@SerialName("banner")
val banner: String? = null,
@SerialName("showcase")
val showcase: String? = null, // unknown type, was null
@SerialName("preview")
val preview: String? = null, // unknown type, was null
@SerialName("chapter_title")
val chapterTitle: String? = null,
@SerialName("geoblocks")
val geoblocks: String? = null
) {
@Serializable
data class Author(
@SerialName("id")
val id: Int? = null,
@SerialName("name")
val name: String? = null,
@SerialName("alt")
val alt: String? = null
)
@Serializable
data class Artist(
@SerialName("id")
val id: Int? = null,
@SerialName("name")
val name: String? = null,
@SerialName("alt")
val alt: String? = null
)
@Serializable
data class Tag(
@SerialName("name")
val name: String? = null,
@SerialName("description")
val description: String? = null,
@SerialName("slug")
val slug: String? = null,
@SerialName("color")
val color: String? = null,
@SerialName("is_primary")
val isPrimary: Boolean? = null
)
@Serializable
data class Publisher(
@SerialName("id")
val id: Int? = null,
@SerialName("name")
val name: String? = null,
@SerialName("language")
val language: String? = null,
@SerialName("homepage")
val homepage: String? = null,
@SerialName("logo")
val logo: String? = null,
@SerialName("geoblocks")
val geoblocks: String? = null
)
@Serializable
data class AvailabilityStrategy(
@SerialName("starting_count")
val startingCount: Int? = null,
@SerialName("latest_only_free")
val latestOnlyFree: Boolean? = null,
@SerialName("catchup_count")
val catchupCount: Int? = null,
@SerialName("simulpub")
val simulpub: Boolean? = null,
@SerialName("fpf_becomes_paid")
val fpfBecomesPaid: String? = null,
@SerialName("fpf_becomes_free")
val fpfBecomesFree: String? = null,
@SerialName("fpf_becomes_backlog")
val fpfBecomesBacklog: String? = null,
@SerialName("backlog_becomes_backlog")
val backlogBecomesBacklog: String? = null
)
}
| 0 | Kotlin | 1 | 2 | b7739ce48737111cd094c1f1964cf3361da46080 | 4,397 | tachiyomi-extensions | Apache License 2.0 |
src/en/comikey/src/eu/kanade/tachiyomi/extension/en/comikey/dto/MangaDetailsDto.kt | AntsyLich | 361,748,620 | true | {"Kotlin": 4347255, "Shell": 3677} | package eu.kanade.tachiyomi.extension.en.comikey.dto
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class MangaDetailsDto(
@SerialName("id")
val id: Int? = null,
@SerialName("link")
val link: String? = null,
@SerialName("name")
val name: String? = null,
@SerialName("e4pid")
val e4pid: String? = null,
@SerialName("uslug")
val uslug: String? = null,
@SerialName("alt")
val alt: String? = null,
@SerialName("author")
val author: List<Author?>? = null,
@SerialName("artist")
val artist: List<Artist?>? = null,
@SerialName("adult")
val adult: Boolean? = null,
@SerialName("tags")
val tags: List<Tag?>? = null,
@SerialName("keywords")
val keywords: String? = null,
@SerialName("description")
val description: String? = null,
@SerialName("excerpt")
val excerpt: String? = null,
@SerialName("created_at")
val createdAt: String? = null,
@SerialName("modified_at")
val modifiedAt: String? = null,
@SerialName("publisher")
val publisher: Publisher? = null,
@SerialName("color")
val color: String? = null,
@SerialName("in_exclusive")
val inExclusive: Boolean? = null,
@SerialName("in_hype")
val inHype: Boolean? = null,
@SerialName("all_free")
val allFree: Boolean? = null,
@SerialName("availability_strategy")
val availabilityStrategy: AvailabilityStrategy? = null,
@SerialName("campaigns")
val campaigns: List<String?>? = null, // unknown list element type, was null
@SerialName("last_updated")
val lastUpdated: String? = null,
@SerialName("chapter_count")
val chapterCount: Int? = null,
@SerialName("update_status")
val updateStatus: Int? = null,
@SerialName("update_text")
val updateText: String? = null,
@SerialName("format")
val format: Int? = null,
@SerialName("cover")
val cover: String? = null,
@SerialName("logo")
val logo: String? = null,
@SerialName("banner")
val banner: String? = null,
@SerialName("showcase")
val showcase: String? = null, // unknown type, was null
@SerialName("preview")
val preview: String? = null, // unknown type, was null
@SerialName("chapter_title")
val chapterTitle: String? = null,
@SerialName("geoblocks")
val geoblocks: String? = null
) {
@Serializable
data class Author(
@SerialName("id")
val id: Int? = null,
@SerialName("name")
val name: String? = null,
@SerialName("alt")
val alt: String? = null
)
@Serializable
data class Artist(
@SerialName("id")
val id: Int? = null,
@SerialName("name")
val name: String? = null,
@SerialName("alt")
val alt: String? = null
)
@Serializable
data class Tag(
@SerialName("name")
val name: String? = null,
@SerialName("description")
val description: String? = null,
@SerialName("slug")
val slug: String? = null,
@SerialName("color")
val color: String? = null,
@SerialName("is_primary")
val isPrimary: Boolean? = null
)
@Serializable
data class Publisher(
@SerialName("id")
val id: Int? = null,
@SerialName("name")
val name: String? = null,
@SerialName("language")
val language: String? = null,
@SerialName("homepage")
val homepage: String? = null,
@SerialName("logo")
val logo: String? = null,
@SerialName("geoblocks")
val geoblocks: String? = null
)
@Serializable
data class AvailabilityStrategy(
@SerialName("starting_count")
val startingCount: Int? = null,
@SerialName("latest_only_free")
val latestOnlyFree: Boolean? = null,
@SerialName("catchup_count")
val catchupCount: Int? = null,
@SerialName("simulpub")
val simulpub: Boolean? = null,
@SerialName("fpf_becomes_paid")
val fpfBecomesPaid: String? = null,
@SerialName("fpf_becomes_free")
val fpfBecomesFree: String? = null,
@SerialName("fpf_becomes_backlog")
val fpfBecomesBacklog: String? = null,
@SerialName("backlog_becomes_backlog")
val backlogBecomesBacklog: String? = null
)
}
| 0 | Kotlin | 1 | 2 | b7739ce48737111cd094c1f1964cf3361da46080 | 4,397 | tachiyomi-extensions | Apache License 2.0 |
app/src/main/java/com/duangs/sample/MainActivity.kt | duyangs | 220,271,935 | false | null | package com.duangs.sample
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.Exception
class MainActivity : AppCompatActivity() {
private var level = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
signal.apply {
setConnected(false)
setSignalLevel(level)
}
connectSwitch.setOnClickListener {
signal.setConnected(connectSwitch.isChecked)
}
resetBtn.setOnClickListener {
try {
signal.setSignalLevel(level)
} catch (e: Exception) {
e.printStackTrace()
Toast.makeText(this@MainActivity, e.message, Toast.LENGTH_LONG).show()
}
}
levelEdit.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
level = try {
s.toString().toInt()
} catch (e: Exception) {
e.printStackTrace()
level
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
}
}
| 0 | Kotlin | 3 | 2 | 5265e54f090725cca9fe285babfdc9c7069416ba | 1,567 | SignalV | Apache License 2.0 |
src/main/kotlin/com/kneelawk/modpackeditor/data/curseapi/ModLoaderListElementData.kt | Kneelawk | 254,924,756 | false | {"Gradle": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "INI": 1, "Java": 1, "CSS": 4, "Kotlin": 79} | package com.kneelawk.modpackeditor.data.curseapi
import java.time.LocalDateTime
import javax.json.JsonObject
/**
* Immutable interface describing a mod loader in Curse's database.
*/
interface ModLoaderListElementData {
val name: String
val gameVersion: String
val latest: Boolean
val recommended: Boolean
val dateModified: LocalDateTime
fun toJSON(): JsonObject
} | 13 | null | 1 | 1 | 380d51abc06da93759778a390718571035d066de | 393 | CurseModpackEditor | MIT License |
app/src/main/java/com/rerere/iwara4a/ui/theme/Theme.kt | AikQ002 | 421,345,581 | true | {"Kotlin": 510692, "Java": 6107} | package com.rerere.iwara4a.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.Colors
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val DarkColorPalette = darkColors(
primary = CustomColor,
secondary = Color(0xffaa0529),
onSecondary = Color.White
)
private val LightColorPalette = lightColors(
primary = CustomColor,
secondary = Color(0xffaa0529),
onSecondary = Color.White
)
val Colors.uiBackGroundColor
get() = if (isLight) {
Color.White
} else {
Color.Black
}
@Composable
fun Iwara4aTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette.copy(
primary = CustomColor
)
} else {
LightColorPalette.copy(
primary = CustomColor
)
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
} | 0 | null | 0 | 0 | 3092b99faa429013c16ce2e03418db41c143e821 | 1,196 | iwara4a | Apache License 2.0 |
retroauth/src/main/java/com/andretietz/retroauth/Retroauth.kt | andretietz | 37,072,673 | false | null | /*
* Copyright (c) 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.andretietz.retroauth
import okhttp3.OkHttpClient
import retrofit2.Retrofit
/**
* This is the wrapper builder to create the [Retrofit] object.
*/
object Retroauth {
fun <OWNER : Any> setup(
retrofit: Retrofit,
authenticator: Authenticator<OWNER>,
ownerStorage: OwnerStorage<OWNER>,
credentialStorage: CredentialStorage<OWNER>
): Retrofit {
val okHttpClient = retrofit.callFactory().let { callFactory ->
check(callFactory is OkHttpClient) { "Retroauth only works with OkHttp as Http Client!" }
callFactory.newBuilder()
.addInterceptor(CredentialInterceptor(authenticator, ownerStorage, credentialStorage))
.build()
}
return retrofit.newBuilder()
.client(okHttpClient)
.build()
}
}
fun <OWNER : Any> Retrofit.authentication(
authenticator: Authenticator<OWNER>,
ownerStorage: OwnerStorage<OWNER>,
credentialStorage: CredentialStorage<OWNER>
): Retrofit = Retroauth.setup(this, authenticator, ownerStorage, credentialStorage)
| 0 | Kotlin | 39 | 408 | 43a88b18e65f56fefa015613d75a50e704804924 | 1,610 | retroauth | Apache License 2.0 |
app/src/main/java/dev/zezula/books/ui/screen/list/SortBooksDialog.kt | zezulaon | 589,699,261 | false | {"Kotlin": 433845} | package dev.zezula.books.ui.screen.list
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.AlertDialogDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import dev.zezula.books.R
import dev.zezula.books.data.SortBooksBy
@Composable
@OptIn(ExperimentalMaterial3Api::class)
fun SortBooksDialog(
uiState: BookListUiState,
onSortSelected: (SortBooksBy) -> Unit,
onDismissRequested: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismissRequested,
) {
Surface(
modifier = Modifier
.wrapContentWidth()
.wrapContentHeight(),
shape = MaterialTheme.shapes.large,
tonalElevation = AlertDialogDefaults.TonalElevation,
) {
Column(modifier = Modifier.padding(16.dp)) {
Text(
text = stringResource(R.string.sort_books_by_dialog_title),
style = MaterialTheme.typography.titleMedium,
)
Spacer(modifier = Modifier.height(8.dp))
Column(modifier = Modifier.selectableGroup()) {
val selectedSortBooksBy = uiState.sortBooksBy
SortBooksBy.entries.forEach { sortBooksBy ->
SortItem(
currentSort = sortBooksBy,
isSelected = sortBooksBy == selectedSortBooksBy,
onOptionsSelected = { onSortSelected(sortBooksBy) },
)
}
}
}
}
}
}
@Composable
private fun SortItem(currentSort: SortBooksBy, isSelected: Boolean, onOptionsSelected: () -> Unit) {
val title = stringResource(currentSort.dialogTitleRes())
Row(
Modifier
.fillMaxWidth()
.height(56.dp)
.selectable(
selected = isSelected,
onClick = { onOptionsSelected() },
role = Role.RadioButton,
)
.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(
selected = isSelected,
onClick = null, // null recommended for accessibility with screen readers
)
Text(
text = title,
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(start = 16.dp),
)
}
}
private fun SortBooksBy.dialogTitleRes(): Int {
return when (this) {
SortBooksBy.TITLE -> R.string.sort_books_by_label_title
SortBooksBy.AUTHOR -> R.string.sort_books_by_label_author
SortBooksBy.DATE_ADDED -> R.string.sort_books_by_label_date
SortBooksBy.USER_RATING -> R.string.sort_books_by_label_rating
}
}
| 1 | Kotlin | 0 | 6 | be59271d664d3839107f6143794826e759a6d9c1 | 3,767 | my-library | Apache License 2.0 |
app/src/main/java/com/yuchen/howyo/signin/SignInViewModel.kt | ione0213 | 418,168,888 | false | null | package com.yuchen.howyo.signin
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.yuchen.howyo.data.Result
import com.yuchen.howyo.data.User
import com.yuchen.howyo.data.source.HowYoRepository
import kotlinx.coroutines.*
class SignInViewModel(private val howYoRepository: HowYoRepository) : ViewModel() {
private val _createUserResult = MutableLiveData<String?>()
val createUserResult: LiveData<String?>
get() = _createUserResult
private val _currentUser = MutableLiveData<User>()
private val currentUser: LiveData<User>
get() = _currentUser
private var viewModelJob = Job()
// the Coroutine runs using the Main (UI) dispatcher
private val coroutineScope = CoroutineScope(viewModelJob + Dispatchers.Main)
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
fun createUser(user: User) {
coroutineScope.launch {
withContext(Dispatchers.IO) {
when (val result = howYoRepository.createUser(user)) {
is Result.Success -> {
user.id = result.data
_currentUser.postValue(user)
_createUserResult.postValue(result.data)
}
else -> {
_createUserResult.value = null
}
}
}
}
}
fun setUser() {
UserManager.apply {
userId = currentUser.value?.id
currentUserEmail = currentUser.value?.email
}
}
}
| 0 | Kotlin | 0 | 0 | 481104d1a79bd7c9e761ce6c5c7d28aa94b6aaa6 | 1,653 | HowYo | MIT License |
app/src/main/java/com/example/advancedclipboardandroid/ContentTypes.kt | ultradr3mer | 324,060,770 | false | {"Java": 58811, "Kotlin": 26422, "Shell": 1664, "Scala": 1133} | package com.example.advancedclipboardandroid
import java.util.*
object ContentTypes {
val Image: UUID = UUID.fromString("179A4F4D-0534-414E-8F0C-821D49521E32")
val PlainText: UUID = UUID.fromString("A0F2881D-304B-4BF9-B072-BF0173C60B70")
val File: UUID = UUID.fromString("34056D41-44DA-4C6C-A91B-142F5D78D12D")
} | 1 | null | 1 | 1 | ed724f69f12514bbe7af5bdd2834172b0a5da414 | 326 | AdvancedClipboard.Android | MIT License |
app/src/main/java/com/yenaly/han1meviewer/ui/fragment/home/download/DownloadedFragment.kt | YenalyLiew | 524,046,895 | false | {"Kotlin": 784135, "Java": 88900} | package com.yenaly.han1meviewer.ui.fragment.home.download
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.core.view.MenuProvider
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.yenaly.han1meviewer.R
import com.yenaly.han1meviewer.databinding.FragmentListOnlyBinding
import com.yenaly.han1meviewer.logic.entity.HanimeDownloadEntity
import com.yenaly.han1meviewer.ui.StateLayoutMixin
import com.yenaly.han1meviewer.ui.activity.MainActivity
import com.yenaly.han1meviewer.ui.adapter.HanimeDownloadedRvAdapter
import com.yenaly.han1meviewer.ui.fragment.IToolbarFragment
import com.yenaly.han1meviewer.ui.viewmodel.DownloadViewModel
import com.yenaly.han1meviewer.util.setStateViewLayout
import com.yenaly.yenaly_libs.base.YenalyFragment
import com.yenaly.yenaly_libs.utils.unsafeLazy
import kotlinx.coroutines.launch
/**
* 已下载影片
*
* @project Han1meViewer
* @author <NAME>
* @time 2022/08/01 001 17:45
*/
class DownloadedFragment : YenalyFragment<FragmentListOnlyBinding, DownloadViewModel>(),
IToolbarFragment<MainActivity>, StateLayoutMixin {
private val adapter by unsafeLazy { HanimeDownloadedRvAdapter(this) }
override fun initData(savedInstanceState: Bundle?) {
(activity as MainActivity).setupToolbar()
binding.rvList.layoutManager = LinearLayoutManager(context)
binding.rvList.adapter = adapter
ViewCompat.setOnApplyWindowInsetsListener(binding.rvList) { v, insets ->
val navBar = insets.getInsets(WindowInsetsCompat.Type.navigationBars())
v.updatePadding(bottom = navBar.bottom)
WindowInsetsCompat.CONSUMED
}
adapter.setStateViewLayout(R.layout.layout_empty_view)
loadAllSortedDownloadedHanime()
}
override fun bindDataObservers() {
viewLifecycleOwner.lifecycleScope.launch {
viewModel.downloaded.flowWithLifecycle(viewLifecycleOwner.lifecycle)
.collect {
adapter.submitList(it)
}
}
}
override fun MainActivity.setupToolbar() {
val fv = [email protected]
addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menu.clear()
menuInflater.inflate(R.menu.menu_downloaded_toolbar, menu)
menu.findItem(fv.currentSortOptionId).isChecked = true
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
fv.currentSortOptionId = menuItem.itemId
menuItem.isChecked = true
return loadAllSortedDownloadedHanime()
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
}
// #issue-18: 添加下载区排序
private fun loadAllSortedDownloadedHanime(): Boolean = when (viewModel.currentSortOptionId) {
R.id.sm_sort_by_alphabet_ascending -> {
viewModel.loadAllDownloadedHanime(
sortedBy = HanimeDownloadEntity.SortedBy.TITLE,
ascending = true
)
true
}
R.id.sm_sort_by_alphabet_descending -> {
viewModel.loadAllDownloadedHanime(
sortedBy = HanimeDownloadEntity.SortedBy.TITLE,
ascending = false
)
true
}
R.id.sm_sort_by_date_ascending -> {
viewModel.loadAllDownloadedHanime(
sortedBy = HanimeDownloadEntity.SortedBy.ID,
ascending = true
)
true
}
R.id.sm_sort_by_date_descending -> {
viewModel.loadAllDownloadedHanime(
sortedBy = HanimeDownloadEntity.SortedBy.ID,
ascending = false
)
true
}
else -> false
}
} | 37 | Kotlin | 112 | 1,547 | 2d46bb034ee804194748b1cb444332054b8d7544 | 4,141 | Han1meViewer | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/nomisprisonerapi/helper/builders/VisitVisitor.kt | ministryofjustice | 444,895,409 | false | {"Kotlin": 3369064, "PLSQL": 337743, "Dockerfile": 1112} | package uk.gov.justice.digital.hmpps.nomisprisonerapi.helper.builders
import org.springframework.stereotype.Component
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.Person
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.Visit
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.VisitVisitor
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.repository.VisitVisitorRepository
@DslMarker
annotation class VisitVisitorDslMarker
@NomisDataDslMarker
interface VisitVisitorDsl
@Component
class VisitVisitorBuilderRepository(
private val visitVisitorRepository: VisitVisitorRepository,
) {
fun save(visitor: VisitVisitor): VisitVisitor = visitVisitorRepository.save(visitor)
}
@Component
class VisitVisitorBuilderFactory(
private val repository: VisitVisitorBuilderRepository,
) {
fun builder() = VisitVisitorBuilderRepositoryBuilder(repository)
}
class VisitVisitorBuilderRepositoryBuilder(private val repository: VisitVisitorBuilderRepository) : VisitVisitorDsl {
fun build(
visit: Visit,
person: Person,
groupLeader: Boolean,
): VisitVisitor =
VisitVisitor(
visit = visit,
person = person,
groupLeader = groupLeader,
)
.let { repository.save(it) }
}
| 1 | Kotlin | 2 | 0 | fe77e261ba81c5f80db066c3ea0cc4e4d860e89a | 1,239 | hmpps-nomis-prisoner-api | MIT License |
src/test/kotlin/uk/gov/justice/digital/hmpps/nomisprisonerapi/helper/builders/VisitVisitor.kt | ministryofjustice | 444,895,409 | false | {"Kotlin": 3369064, "PLSQL": 337743, "Dockerfile": 1112} | package uk.gov.justice.digital.hmpps.nomisprisonerapi.helper.builders
import org.springframework.stereotype.Component
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.Person
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.Visit
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.VisitVisitor
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.repository.VisitVisitorRepository
@DslMarker
annotation class VisitVisitorDslMarker
@NomisDataDslMarker
interface VisitVisitorDsl
@Component
class VisitVisitorBuilderRepository(
private val visitVisitorRepository: VisitVisitorRepository,
) {
fun save(visitor: VisitVisitor): VisitVisitor = visitVisitorRepository.save(visitor)
}
@Component
class VisitVisitorBuilderFactory(
private val repository: VisitVisitorBuilderRepository,
) {
fun builder() = VisitVisitorBuilderRepositoryBuilder(repository)
}
class VisitVisitorBuilderRepositoryBuilder(private val repository: VisitVisitorBuilderRepository) : VisitVisitorDsl {
fun build(
visit: Visit,
person: Person,
groupLeader: Boolean,
): VisitVisitor =
VisitVisitor(
visit = visit,
person = person,
groupLeader = groupLeader,
)
.let { repository.save(it) }
}
| 1 | Kotlin | 2 | 0 | fe77e261ba81c5f80db066c3ea0cc4e4d860e89a | 1,239 | hmpps-nomis-prisoner-api | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.