path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
756M
| is_fork
bool 2
classes | languages_distribution
stringlengths 12
2.44k
⌀ | content
stringlengths 6
6.29M
| issues
float64 0
10k
⌀ | main_language
stringclasses 128
values | forks
int64 0
54.2k
| stars
int64 0
157k
| commit_sha
stringlengths 40
40
| size
int64 6
6.29M
| name
stringlengths 1
100
| license
stringclasses 104
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
shi-microservice-uaa/src/main/kotlin/io/github/kaisery/shi/microservice/uaa/config/OAuth2AuthorizationServerConfig.kt | KaiserY | 143,286,010 | false | null | package io.github.kaisery.shi.microservice.uaa.config
import io.github.kaisery.shi.microservice.common.constant.OAuth2Scope
import io.github.kaisery.shi.microservice.uaa.oauth.CustomTokenGranter
import io.github.kaisery.shi.microservice.uaa.service.UserService
import org.springframework.context.annotation.Configuration
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer
import org.springframework.security.oauth2.provider.CompositeTokenGranter
import org.springframework.security.oauth2.provider.TokenGranter
import org.springframework.security.oauth2.provider.token.TokenStore
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter
@Configuration
@EnableAuthorizationServer
class OAuth2AuthorizationServerConfig(
val authenticationManager: AuthenticationManager,
val userService: UserService,
val passwordEncoder: PasswordEncoder,
val tokenStore: TokenStore,
val jwtAccessTokenConverter: JwtAccessTokenConverter
) : AuthorizationServerConfigurerAdapter() {
override fun configure(endpoints: AuthorizationServerEndpointsConfigurer?) {
endpoints!!.authenticationManager(authenticationManager)
.tokenStore(tokenStore)
.accessTokenConverter(jwtAccessTokenConverter)
.tokenGranter(tokenGranter(endpoints))
}
override fun configure(clients: ClientDetailsServiceConfigurer?) {
clients!!.inMemory()
.withClient("server")
.secret(passwordEncoder.encode("server"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes(OAuth2Scope.STANDARD)
.and()
.withClient("custom")
.secret(passwordEncoder.encode("custom"))
.authorizedGrantTypes("custom", "refresh_token")
.scopes(OAuth2Scope.CUSTOM)
}
override fun configure(security: AuthorizationServerSecurityConfigurer?) {
security!!.allowFormAuthenticationForClients()
}
fun tokenGranter(endpoints: AuthorizationServerEndpointsConfigurer): TokenGranter {
val tokenGranters = arrayListOf(endpoints.tokenGranter)
tokenGranters.add(CustomTokenGranter(
userService,
endpoints.tokenServices,
endpoints.clientDetailsService,
endpoints.oAuth2RequestFactory,
"custom"))
return CompositeTokenGranter(tokenGranters)
}
}
| 0 | Kotlin | 0 | 0 | 5d79153488566d6a12e98c6574a77c4cb1e4f27f | 2,901 | shi-microservice | MIT License |
winterhold/src/main/java/winterhold/util/MonsterExtensions.kt | TijmenvanderKemp | 325,634,389 | false | null | package winterhold.util
import com.megacrit.cardcrawl.monsters.AbstractMonster
import com.megacrit.cardcrawl.monsters.MonsterGroup
val MonsterGroup.stillFightingMonsters: List<AbstractMonster>
get() = monsters.filter { it.isStillFighting }
val AbstractMonster.isStillFighting: Boolean
get() = !isDeadOrEscaped | 1 | Kotlin | 1 | 0 | b17bded16770cd170d092f66c26efb6b44fcf76e | 319 | StS-Winterhold | MIT License |
app/src/main/java/com/softwarehut/mvpplayground/domain/home/HomeView.kt | softwarehutpl | 139,710,457 | false | {"Kotlin": 49242} | package com.softwarehut.mvpplayground.domain.home
import com.softwarehut.mvp.domain.paramless.View
interface HomeView : View | 0 | Kotlin | 0 | 0 | fe91f41fad6413a8dabd3b3e9e1e0826e8cd7553 | 126 | MvpPlayground | Apache License 2.0 |
src/main/kotlin/br/com/zupacademy/marcosOT6/pix/remover/RemoveChaveController.kt | MarcosMarchado | 400,509,718 | true | {"Kotlin": 38293, "Dockerfile": 166} | package br.com.zupacademy.marcosOT6.pix.remover
import br.com.zupacademy.marcosOT6.pix.PixServiceRemoverGrpc
import br.com.zupacademy.marcosOT6.pix.RemoverChavePixRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Delete
@Controller("/api/v1/clientes/{codigoInterno}/pix/{idChave}")
class RemoveChaveController(val removeChaveEndpointGrpc: PixServiceRemoverGrpc.PixServiceRemoverBlockingStub) {
@Delete
fun remover(codigoInterno: String, idChave: String): HttpResponse<Any> {
val requestGrpc = RemoverChavePixRequest
.newBuilder()
.setCodigoInterno(codigoInterno)
.setPixId(idChave)
.build()
removeChaveEndpointGrpc.removerChave(requestGrpc)
return HttpResponse.ok()
}
} | 0 | Kotlin | 0 | 0 | dc6346dbef1e98ec3fa1feda2e16ae54aaccc1ff | 838 | orange-talents-06-template-pix-keymanager-rest | Apache License 2.0 |
base/src/main/kotlin/org/jaram/jubaky/util/TimestampDateFormat.kt | jubaky | 195,964,455 | false | null | package org.jaram.jubaky.util
import java.text.DateFormat
import java.text.FieldPosition
import java.text.NumberFormat
import java.text.ParsePosition
import java.util.*
class TimestampDateFormat : DateFormat() {
init {
if (calendar == null) {
calendar = Calendar.getInstance(TimeZone.getDefault(), Locale.KOREA)
}
if (numberFormat == null) {
numberFormat = NumberFormat.getIntegerInstance(Locale.KOREA)
numberFormat.isGroupingUsed = false
}
}
override fun parse(source: String, pos: ParsePosition): Date? {
return source.toLongOrNull()?.let { Date(it) }
}
override fun format(date: Date, toAppendTo: StringBuffer, fieldPosition: FieldPosition): StringBuffer {
return toAppendTo.append(date.time)
}
} | 1 | Kotlin | 1 | 0 | 834790726cc2d9be82eded60fc2449cf7e22591a | 813 | api_server | Apache License 2.0 |
packages/expo-modules-core/android/src/main/java/expo/modules/kotlin/types/TypeConverterProvider.kt | Randall71 | 683,272,022 | true | {"TypeScript": 8397135, "Kotlin": 3465183, "Objective-C": 2658390, "Swift": 1805030, "Java": 1578205, "JavaScript": 851655, "C++": 312502, "C": 236338, "Objective-C++": 174849, "Ruby": 169843, "Shell": 59462, "HTML": 31106, "CMake": 25733, "CSS": 107, "Batchfile": 89} | @file:OptIn(ExperimentalStdlibApi::class)
package abi49_0_0.expo.modules.kotlin.types
import android.graphics.Color
import android.net.Uri
import android.view.View
import abi49_0_0.com.facebook.react.bridge.Dynamic
import abi49_0_0.com.facebook.react.bridge.ReadableArray
import abi49_0_0.com.facebook.react.bridge.ReadableMap
import expo.modules.annotation.Config
import abi49_0_0.expo.modules.kotlin.apifeatures.EitherType
import abi49_0_0.expo.modules.kotlin.exception.MissingTypeConverter
import abi49_0_0.expo.modules.kotlin.jni.CppType
import abi49_0_0.expo.modules.kotlin.jni.ExpectedType
import abi49_0_0.expo.modules.kotlin.jni.JavaScriptFunction
import abi49_0_0.expo.modules.kotlin.jni.JavaScriptObject
import abi49_0_0.expo.modules.kotlin.jni.JavaScriptValue
import abi49_0_0.expo.modules.kotlin.records.Record
import abi49_0_0.expo.modules.kotlin.records.RecordTypeConverter
import abi49_0_0.expo.modules.kotlin.sharedobjects.SharedObject
import abi49_0_0.expo.modules.kotlin.sharedobjects.SharedObjectTypeConverter
import abi49_0_0.expo.modules.kotlin.typedarray.BigInt64Array
import abi49_0_0.expo.modules.kotlin.typedarray.BigUint64Array
import abi49_0_0.expo.modules.kotlin.typedarray.Float32Array
import abi49_0_0.expo.modules.kotlin.typedarray.Float64Array
import abi49_0_0.expo.modules.kotlin.typedarray.Int16Array
import abi49_0_0.expo.modules.kotlin.typedarray.Int32Array
import abi49_0_0.expo.modules.kotlin.typedarray.Int8Array
import abi49_0_0.expo.modules.kotlin.typedarray.TypedArray
import abi49_0_0.expo.modules.kotlin.typedarray.Uint16Array
import abi49_0_0.expo.modules.kotlin.typedarray.Uint32Array
import abi49_0_0.expo.modules.kotlin.typedarray.Uint8Array
import abi49_0_0.expo.modules.kotlin.typedarray.Uint8ClampedArray
import abi49_0_0.expo.modules.kotlin.types.io.FileTypeConverter
import abi49_0_0.expo.modules.kotlin.types.io.PathTypeConverter
import abi49_0_0.expo.modules.kotlin.types.net.JavaURITypeConverter
import abi49_0_0.expo.modules.kotlin.types.net.URLTypConverter
import abi49_0_0.expo.modules.kotlin.types.net.UriTypeConverter
import abi49_0_0.expo.modules.kotlin.views.ViewTypeConverter
import java.io.File
import java.net.URI
import java.net.URL
import java.nio.file.Path
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.full.isSubclassOf
import kotlin.reflect.typeOf
interface TypeConverterProvider {
fun obtainTypeConverter(type: KType): TypeConverter<*>
}
inline fun <reified T : Any> obtainTypeConverter(): TypeConverter<T> {
@Suppress("UNCHECKED_CAST")
return TypeConverterProviderImpl.obtainTypeConverter(typeOf<T>()) as TypeConverter<T>
}
inline fun <reified T> convert(value: Dynamic): T {
val converter = TypeConverterProviderImpl.obtainTypeConverter(typeOf<T>())
return converter.convert(value) as T
}
inline fun <reified T> convert(value: Any?): T {
val converter = TypeConverterProviderImpl.obtainTypeConverter(typeOf<T>())
return converter.convert(value) as T
}
fun convert(value: Dynamic, type: KType): Any? {
val converter = TypeConverterProviderImpl.obtainTypeConverter(type)
return converter.convert(value)
}
object TypeConverterProviderImpl : TypeConverterProvider {
private val cachedConverters = createCachedConverters(false)
private val nullableCachedConverters = createCachedConverters(true)
private val cachedRecordConverters = mutableMapOf<KClass<*>, TypeConverter<*>>()
private val cachedCustomConverters = mutableMapOf<KType, TypeConverter<*>>()
private fun getCachedConverter(inputType: KType): TypeConverter<*>? {
return if (inputType.isMarkedNullable) {
nullableCachedConverters[inputType.classifier]
} else {
cachedConverters[inputType.classifier]
}
}
override fun obtainTypeConverter(type: KType): TypeConverter<*> {
getCachedConverter(type)?.let {
return it
}
val kClass = type.classifier as? KClass<*> ?: throw MissingTypeConverter(type)
if (kClass.java.isArray) {
return ArrayTypeConverter(this, type)
}
if (kClass.isSubclassOf(List::class)) {
return ListTypeConverter(this, type)
}
if (kClass.isSubclassOf(Map::class)) {
return MapTypeConverter(this, type)
}
if (kClass.isSubclassOf(Pair::class)) {
return PairTypeConverter(this, type)
}
if (kClass.isSubclassOf(Array::class)) {
return ArrayTypeConverter(this, type)
}
if (kClass.java.isEnum) {
@Suppress("UNCHECKED_CAST")
return EnumTypeConverter(kClass as KClass<Enum<*>>, type.isMarkedNullable)
}
val cachedConverter = cachedRecordConverters[kClass]
if (cachedConverter != null) {
return cachedConverter
}
if (kClass.isSubclassOf(Record::class)) {
val converter = RecordTypeConverter<Record>(this, type)
cachedRecordConverters[kClass] = converter
return converter
}
if (kClass.isSubclassOf(View::class)) {
return ViewTypeConverter<View>(type)
}
if (kClass.isSubclassOf(SharedObject::class)) {
return SharedObjectTypeConverter<SharedObject>(type)
}
if (kClass.isSubclassOf(JavaScriptFunction::class)) {
return JavaScriptFunctionTypeConverter<Any>(type)
}
return handelEither(type, kClass)
?: handelCustomConverter(type, kClass)
?: throw MissingTypeConverter(type)
}
@OptIn(EitherType::class)
private fun handelEither(type: KType, kClass: KClass<*>): TypeConverter<*>? {
if (kClass.isSubclassOf(Either::class)) {
if (kClass.isSubclassOf(EitherOfFour::class)) {
return EitherOfFourTypeConverter<Any, Any, Any, Any>(this, type)
}
if (kClass.isSubclassOf(EitherOfThree::class)) {
return EitherOfThreeTypeConverter<Any, Any, Any>(this, type)
}
return EitherTypeConverter<Any, Any>(this, type)
}
return null
}
private fun handelCustomConverter(type: KType, kClass: KClass<*>): TypeConverter<*>? {
val cachedConverter = cachedCustomConverters[type]
if (cachedConverter != null) {
return cachedConverter
}
val typeName = kClass.java.canonicalName ?: return null
val converterProviderName = "${Config.packageNamePrefix}$typeName${Config.classNameSuffix}"
return try {
val converterClazz = Class.forName(converterProviderName)
val converterProvider = converterClazz.newInstance()
val method = converterProvider.javaClass.getMethod(Config.converterProviderFunctionName, KType::class.java)
(method.invoke(converterProvider, type) as TypeConverter<*>)
.also {
cachedCustomConverters[type] = it
}
} catch (e: Throwable) {
null
}
}
private fun createCachedConverters(isOptional: Boolean): Map<KClass<*>, TypeConverter<*>> {
val intTypeConverter = createTrivialTypeConverter(
isOptional, ExpectedType(CppType.INT)
) { it.asDouble().toInt() }
val longTypeConverter = createTrivialTypeConverter(
isOptional, ExpectedType(CppType.LONG)
) { it.asDouble().toLong() }
val doubleTypeConverter = createTrivialTypeConverter(
isOptional, ExpectedType(CppType.DOUBLE)
) { it.asDouble() }
val floatTypeConverter = createTrivialTypeConverter(
isOptional, ExpectedType(CppType.FLOAT)
) { it.asDouble().toFloat() }
val boolTypeConverter = createTrivialTypeConverter(
isOptional, ExpectedType(CppType.BOOLEAN)
) { it.asBoolean() }
val converters = mapOf(
Int::class to intTypeConverter,
java.lang.Integer::class to intTypeConverter,
Long::class to longTypeConverter,
java.lang.Long::class to longTypeConverter,
Double::class to doubleTypeConverter,
java.lang.Double::class to doubleTypeConverter,
Float::class to floatTypeConverter,
java.lang.Float::class to floatTypeConverter,
Boolean::class to boolTypeConverter,
java.lang.Boolean::class to boolTypeConverter,
String::class to createTrivialTypeConverter(
isOptional, ExpectedType(CppType.STRING)
) { it.asString() },
ReadableArray::class to createTrivialTypeConverter(
isOptional, ExpectedType(CppType.READABLE_ARRAY)
) { it.asArray() },
ReadableMap::class to createTrivialTypeConverter(
isOptional, ExpectedType(CppType.READABLE_MAP)
) { it.asMap() },
IntArray::class to createTrivialTypeConverter(
isOptional, ExpectedType.forPrimitiveArray(CppType.INT)
) {
val jsArray = it.asArray()
IntArray(jsArray.size()) { index ->
jsArray.getInt(index)
}
},
DoubleArray::class to createTrivialTypeConverter(
isOptional, ExpectedType.forPrimitiveArray(CppType.DOUBLE)
) {
val jsArray = it.asArray()
DoubleArray(jsArray.size()) { index ->
jsArray.getDouble(index)
}
},
FloatArray::class to createTrivialTypeConverter(
isOptional, ExpectedType.forPrimitiveArray(CppType.FLOAT)
) {
val jsArray = it.asArray()
FloatArray(jsArray.size()) { index ->
jsArray.getDouble(index).toFloat()
}
},
BooleanArray::class to createTrivialTypeConverter(
isOptional, ExpectedType.forPrimitiveArray(CppType.BOOLEAN)
) {
val jsArray = it.asArray()
BooleanArray(jsArray.size()) { index ->
jsArray.getBoolean(index)
}
},
JavaScriptValue::class to createTrivialTypeConverter(
isOptional, ExpectedType(CppType.JS_VALUE)
),
JavaScriptObject::class to createTrivialTypeConverter(
isOptional, ExpectedType(CppType.JS_OBJECT)
),
Int8Array::class to Int8ArrayTypeConverter(isOptional),
Int16Array::class to Int16ArrayTypeConverter(isOptional),
Int32Array::class to Int32ArrayTypeConverter(isOptional),
Uint8Array::class to Uint8ArrayTypeConverter(isOptional),
Uint8ClampedArray::class to Uint8ClampedArrayTypeConverter(isOptional),
Uint16Array::class to Uint16ArrayTypeConverter(isOptional),
Uint32Array::class to Uint32ArrayTypeConverter(isOptional),
Float32Array::class to Float32ArrayTypeConverter(isOptional),
Float64Array::class to Float64ArrayTypeConverter(isOptional),
BigInt64Array::class to BigInt64ArrayTypeConverter(isOptional),
BigUint64Array::class to BigUint64ArrayTypeConverter(isOptional),
TypedArray::class to TypedArrayTypeConverter(isOptional),
URL::class to URLTypConverter(isOptional),
Uri::class to UriTypeConverter(isOptional),
URI::class to JavaURITypeConverter(isOptional),
File::class to FileTypeConverter(isOptional),
Any::class to AnyTypeConverter(isOptional),
)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
return converters + mapOf(
Path::class to PathTypeConverter(isOptional),
Color::class to ColorTypeConverter(isOptional),
)
}
return converters
}
}
| 0 | null | 0 | 0 | 429dc7fc191474ab1d5b54b836c0ab60ed2be88b | 10,966 | expo | MIT License |
app/src/main/java/com/example/ktomoya/rusuapp/view/extension.kt | tnyo43 | 191,516,461 | false | null | package com.example.ktomoya.rusuapp.view
import android.support.annotation.IdRes
import android.view.View
fun <T: View> View.bindView(@IdRes id: Int): Lazy<T> = lazy {
findViewById(id) as T
} | 0 | Kotlin | 0 | 1 | c2898c1bb9bf2ab9c688f33e1b5728e0db303d95 | 197 | RusubanApp | MIT License |
solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonRules.kt | w4bo | 707,148,116 | true | {"Kotlin": 3269104, "Java": 14292, "ANTLR": 10366, "CSS": 1535, "Prolog": 818} | package it.unibo.tuprolog.solve.stdlib
import it.unibo.tuprolog.solve.ExecutionContext
import it.unibo.tuprolog.solve.rule.RuleWrapper
import it.unibo.tuprolog.solve.stdlib.rule.Append
import it.unibo.tuprolog.solve.stdlib.rule.Arrow
import it.unibo.tuprolog.solve.stdlib.rule.CurrentPrologFlag
import it.unibo.tuprolog.solve.stdlib.rule.Member
import it.unibo.tuprolog.solve.stdlib.rule.Not
import it.unibo.tuprolog.solve.stdlib.rule.Once
import it.unibo.tuprolog.solve.stdlib.rule.Semicolon
import it.unibo.tuprolog.solve.stdlib.rule.SetPrologFlag
import it.unibo.tuprolog.theory.Theory
object CommonRules {
val wrappers: Sequence<RuleWrapper<ExecutionContext>> = sequenceOf(
Not,
Arrow,
Semicolon.If.Then,
Semicolon.If.Else,
Semicolon.Or.Left,
Semicolon.Or.Right,
Member.Base,
Member.Recursive,
Append.Base,
Append.Recursive,
Once,
SetPrologFlag,
CurrentPrologFlag
)
val theory: Theory
get() = Theory.indexedOf(wrappers.map { it.implementation })
}
| 0 | Kotlin | 0 | 0 | fec568d1af94bd30193eee724881655c75b3cd41 | 1,079 | FineshiftSoft0 | Apache License 2.0 |
app/src/main/java/com/thread0/weather/adapter/RvAdapterAirQuaH.kt | wuzelong | 384,625,570 | false | null | package com.thread0.weather.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.thread0.weather.R
import com.thread0.weather.data.model.AirQualityHourlyBean
import kotlinx.android.synthetic.main.rv_item_air_quality_h.view.*
class RvAdapterAirQuaH : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var list = mutableListOf<AirQualityHourlyBean>()
private lateinit var mContext: Context
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
holder.itemView.tv_item_air_quality_time.text = list[position].time
holder.itemView.tv_item_air_quality.text = list[position].quality
holder.itemView.tv_item_air_quality_aqi.text = list[position].aqi
holder.itemView.tv_item_air_quality.setTextColor(ContextCompat.getColor(mContext,list[position].color))
holder.itemView.tv_item_air_quality_aqi.setTextColor(ContextCompat.getColor(mContext,list[position].color))
}
fun setData(airList: List<AirQualityHourlyBean>) {
list.clear()
list.addAll(airList)
notifyDataSetChanged()
}
override fun getItemCount(): Int = list.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
mContext = parent.context
val view = LayoutInflater.from(mContext).inflate(R.layout.rv_item_air_quality_h, parent, false)
return ViewHolder(view)
}
class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!)
} | 0 | Kotlin | 0 | 1 | 00f93f0c656d3734c4d3bb10c66ec94f6e030d7e | 1,660 | weather | Apache License 2.0 |
data/remote/src/main/java/com/brunotiba/remote/model/Uv.kt | BrunoTiba | 225,494,572 | false | null | package com.brunotiba.remote.model
import com.squareup.moshi.Json
/**
* Entity representation of a Uv index.
*
* @param lat latitude for returned data
* @param lon longitude for returned data
* @param dateIso date and time corresponding to returned date
* @param date ISO 8601 timestamp
* @param value ultraviolet index
*/
data class Uv(
@field:Json(name = "lat") val lat: Double,
@field:Json(name = "lon") val lon: Double,
@field:Json(name = "date_iso") val dateIso: String,
@field:Json(name = "date") val date: Long,
@field:Json(name = "value") val value: Double
)
| 0 | Kotlin | 0 | 3 | dcc8aabb44e4f078a8149b0af6d06f36ab8d8f77 | 597 | Sunny-Side-App | Apache License 2.0 |
app/src/main/java/com/paricottfsm/features/stockAddCurrentStock/api/ShopAddStockRepository.kt | DebashisINT | 699,836,260 | false | {"Kotlin": 13981342, "Java": 1002311} | package com.paricottfsm.features.stockAddCurrentStock.api
import com.paricottfsm.base.BaseResponse
import com.paricottfsm.features.location.model.ShopRevisitStatusRequest
import com.paricottfsm.features.location.shopRevisitStatus.ShopRevisitStatusApi
import com.paricottfsm.features.stockAddCurrentStock.ShopAddCurrentStockRequest
import com.paricottfsm.features.stockAddCurrentStock.model.CurrentStockGetData
import com.paricottfsm.features.stockCompetetorStock.model.CompetetorStockGetData
import io.reactivex.Observable
class ShopAddStockRepository (val apiService : ShopAddStockApi){
fun shopAddStock(shopAddCurrentStockRequest: ShopAddCurrentStockRequest?): Observable<BaseResponse> {
return apiService.submShopAddStock(shopAddCurrentStockRequest)
}
fun getCurrStockList(sessiontoken: String, user_id: String, date: String): Observable<CurrentStockGetData> {
return apiService.getCurrStockListApi(sessiontoken, user_id, date)
}
} | 0 | Kotlin | 0 | 0 | 3b0c6ce555939d3ed8bf74ba006fe97899e0e53c | 970 | ParicottIndiaPapercup | Apache License 2.0 |
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D22.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2020
import io.github.pshegger.aoc.common.BaseSolver
class Y2020D22 : BaseSolver() {
override val year = 2020
override val day = 22
override fun part1(): Long {
val input = parseInput()
val p1 = input.first.toMutableList()
val p2 = input.second.toMutableList()
while (p1.isNotEmpty() && p2.isNotEmpty()) {
val c1 = p1.removeAt(0)
val c2 = p2.removeAt(0)
if (c1 > c2) {
p1.add(c1)
p1.add(c2)
}
if (c2 > c1) {
p2.add(c2)
p2.add(c1)
}
}
val winnerDeck = if (p1.isNotEmpty()) p1 else p2
return winnerDeck.foldIndexed(0L) { index, acc, card ->
val weight = winnerDeck.size - index
acc + weight * card
}
}
override fun part2(): Long {
val (p1, p2) = parseInput()
val (_, winnerDeck) = recursiveCombat(p1, p2)
return winnerDeck.foldIndexed(0L) { index, acc, card ->
val weight = winnerDeck.size - index
acc + weight * card
}
}
private fun recursiveCombat(p1Start: List<Int>, p2Start: List<Int>): Pair<Boolean, List<Int>> {
val rounds = mutableMapOf<Pair<List<Int>, List<Int>>, Boolean>()
val p1 = p1Start.toMutableList()
val p2 = p2Start.toMutableList()
while (p1.isNotEmpty() && p2.isNotEmpty()) {
val state = Pair(p1, p2)
if (rounds[state] == true) {
return Pair(true, p1)
} else {
rounds[state] = true
}
val c1 = p1.removeAt(0)
val c2 = p2.removeAt(0)
val (p1Wins, _) = when {
p1.size >= c1 && p2.size >= c2 -> recursiveCombat(p1.take(c1), p2.take(c2))
c1 > c2 -> Pair(true, p1)
else -> Pair(false, p2)
}
if (p1Wins) {
p1.add(c1)
p1.add(c2)
} else {
p2.add(c2)
p2.add(c1)
}
}
return if (p1.isNotEmpty()) Pair(true, p1) else Pair(false, p2)
}
private fun parseInput() = readInput {
val lines = readLines()
val player1Cards = lines.takeWhile { it.isNotBlank() }.drop(1).map { it.toInt() }
val player2Cards = lines.dropWhile { it.isNotBlank() }.drop(2).map { it.toInt() }
Pair(player1Cards, player2Cards)
}
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 2,521 | advent-of-code | MIT License |
app/src/test/java/com/coinninja/coinkeeper/cn/wallet/WalletFlagsTest.kt | coinninjadev | 175,276,289 | false | null | package com.coinninja.coinkeeper.cn.wallet
import com.google.common.truth.Truth.assertThat
import org.junit.Test
class WalletFlagsTest {
@Test
fun purpose49_version0_active() {
val flags = WalletFlags.compose(WalletFlags.purpose49, WalletFlags.v0)
assertThat(flags.flag).isEqualTo(0)
assertThat(flags.versionBit).isEqualTo(0)
assertThat(flags.purposeBit).isEqualTo(0)
assertThat(flags.hasPurpose(WalletFlags.purpose49)).isTrue()
assertThat(flags.hasVersion(WalletFlags.v0)).isTrue()
assertThat(flags.hasVersion(WalletFlags.v1)).isFalse()
assertThat(flags.hasVersion(WalletFlags.v2)).isFalse()
assertThat(flags.isActive()).isTrue()
}
@Test
fun purpose49_version1_active() {
val flags = WalletFlags.compose(WalletFlags.purpose49, WalletFlags.v1)
assertThat(flags.flag).isEqualTo(1)
assertThat(flags.versionBit).isEqualTo(1)
assertThat(flags.purposeBit).isEqualTo(0)
assertThat(flags.hasPurpose(WalletFlags.purpose49)).isTrue()
assertThat(flags.hasVersion(WalletFlags.v0)).isFalse()
assertThat(flags.hasVersion(WalletFlags.v1)).isTrue()
assertThat(flags.hasVersion(WalletFlags.v2)).isFalse()
assertThat(flags.isActive()).isTrue()
}
@Test
fun purpose49_version2_active() {
val flags = WalletFlags.compose(WalletFlags.purpose49, WalletFlags.v2)
assertThat(flags.flag).isEqualTo(2)
assertThat(flags.versionBit).isEqualTo(2)
assertThat(flags.purposeBit).isEqualTo(0)
assertThat(flags.hasPurpose(WalletFlags.purpose49)).isTrue()
assertThat(flags.hasVersion(WalletFlags.v0)).isFalse()
assertThat(flags.hasVersion(WalletFlags.v1)).isFalse()
assertThat(flags.hasVersion(WalletFlags.v2)).isTrue()
assertThat(flags.isActive()).isTrue()
}
@Test
fun purpose84_version0_active() {
val flags = WalletFlags.compose(WalletFlags.purpose84, WalletFlags.v0)
assertThat(flags.flag).isEqualTo(16)
assertThat(flags.versionBit).isEqualTo(0)
assertThat(flags.purposeBit).isEqualTo(1)
assertThat(flags.hasVersion(WalletFlags.v0)).isTrue()
assertThat(flags.hasVersion(WalletFlags.v1)).isFalse()
assertThat(flags.hasVersion(WalletFlags.v2)).isFalse()
assertThat(flags.hasPurpose(WalletFlags.purpose84)).isTrue()
assertThat(flags.isActive()).isTrue()
}
@Test
fun purpose84_version1_active() {
val flags = WalletFlags.compose(WalletFlags.purpose84, WalletFlags.v1)
assertThat(flags.flag).isEqualTo(17)
assertThat(flags.versionBit).isEqualTo(1)
assertThat(flags.purposeBit).isEqualTo(1)
assertThat(flags.hasVersion(WalletFlags.v0)).isFalse()
assertThat(flags.hasVersion(WalletFlags.v1)).isTrue()
assertThat(flags.hasVersion(WalletFlags.v2)).isFalse()
assertThat(flags.hasPurpose(WalletFlags.purpose84)).isTrue()
assertThat(flags.isActive()).isTrue()
}
@Test
fun purpose84_version2_active() {
val flags = WalletFlags.compose(WalletFlags.purpose84, WalletFlags.v2)
assertThat(flags.flag).isEqualTo(18)
assertThat(flags.versionBit).isEqualTo(2)
assertThat(flags.purposeBit).isEqualTo(1)
assertThat(flags.hasVersion(WalletFlags.v0)).isFalse()
assertThat(flags.hasVersion(WalletFlags.v1)).isFalse()
assertThat(flags.hasVersion(WalletFlags.v2)).isTrue()
assertThat(flags.hasPurpose(WalletFlags.purpose84)).isTrue()
assertThat(flags.isActive()).isTrue()
}
@Test
fun not_active_version_0_purpose_49() {
val flags = WalletFlags.compose(WalletFlags.purpose84, WalletFlags.v2, false)
assertThat(flags.flag).isEqualTo(274)
assertThat(flags.versionBit).isEqualTo(2)
assertThat(flags.purposeBit).isEqualTo(1)
assertThat(flags.isActive()).isFalse()
assertThat(flags.hasVersion(WalletFlags.v0)).isFalse()
assertThat(flags.hasVersion(WalletFlags.v1)).isFalse()
assertThat(flags.hasVersion(WalletFlags.v2)).isTrue()
assertThat(flags.hasPurpose(WalletFlags.purpose84)).isTrue()
}
@Test
fun getter_for_purpose49_version1() {
assertThat(WalletFlags.purpose49v1).isEqualTo(1)
}
@Test
fun getter_for_purpose49_version1_disabled() {
assertThat(WalletFlags.purpose49v1Disabled).isEqualTo(257)
}
@Test
fun getter_for_purpose84_version2() {
assertThat(WalletFlags.purpose84v2).isEqualTo(18)
}
}
| 2 | Kotlin | 0 | 5 | d67d7c0b9cad27db94470231073c5d6cdda83cd0 | 4,601 | dropbit-android | MIT License |
core/src/main/java/com/kingsland/core/database/dao/ProjectDao.kt | data-programmer | 599,861,493 | false | null | package com.kingsland.core.database.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.kingsland.core.database.dto.ProjectDto
@Dao
interface ProjectDao {
@Query("select * from Project")
fun getAllProjects(): List<ProjectDto>
@Query("select * from Project where id = :id")
fun getProjectById(id: Int): ProjectDto
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertProject(projectDto: ProjectDto)
@Update
fun updateProject(projectDto: ProjectDto)
@Delete
fun deleteProject(projectDto: ProjectDto)
} | 0 | Kotlin | 0 | 0 | bcd53b9784689e5b60d893248ccc2910b17391e0 | 690 | ProjectTrakAndroid | MIT License |
modules/ext/android/src/main/kotlin/kekmech/ru/ext_android/ClipboardExt.kt | tonykolomeytsev | 203,239,594 | false | {"Kotlin": 972736, "JavaScript": 8360, "Python": 2365, "Shell": 46} | package kekmech.ru.ext_android
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Context.CLIPBOARD_SERVICE
fun Context.copyToClipboard(text: String, label: String = ""): Boolean =
runCatching {
val clipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
clipboard.setPrimaryClip(ClipData.newPlainText(label, text))
}.isSuccess
| 18 | Kotlin | 4 | 30 | de1929aa80141629b56a8dbc11096c6135a90c10 | 441 | mpeiapp | MIT License |
src/main/kotlin/org/koil/public/PublicController.kt | HappyValleyIO | 261,192,535 | false | {"Kotlin": 176341, "JavaScript": 37475, "CSS": 5287} | package org.koil.public
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.servlet.ModelAndView
@Controller
class PublicController {
@GetMapping("/")
fun index(): ModelAndView {
return ModelAndView("pages/index")
}
}
| 11 | Kotlin | 1 | 13 | 2ab66c2afcb25d113e4c2c4f9c89d18c6a807951 | 326 | koil | MIT License |
src/Day09.kt | petoS6 | 573,018,212 | false | {"Kotlin": 14258} | import java.lang.Math.abs
import kotlin.math.sign
data class P(val x: Int, val y: Int)
private fun P.isCloseTo(other: P) =
(x == other.x && y == other.y) ||
(x == other.x + 1 && y == other.y) ||
(x == other.x - 1 && y == other.y) ||
(x == other.x && y == other.y + 1) ||
(x == other.x && y == other.y - 1) ||
(x == other.x - 1 && y == other.y - 1) ||
(x == other.x + 1 && y == other.y + 1) ||
(x == other.x - 1 && y == other.y + 1) ||
(x == other.x + 1 && y == other.y - 1)
fun main() {
fun part1(lines: List<String>): Int {
val points = mutableListOf<P>()
points.add(P(0, 4))
var h = P(0, 4)
var t = P(0, 4)
lines.forEach { line ->
val splitted = line.split(" ")
val direction = splitted[0]
val count = splitted[1].toInt()
repeat(count) {
when(direction) {
"R" -> {
h = h.copy(x = h.x + 1)
if (t.isCloseTo(h).not()) t = h.copy(x = h.x - 1)
}
"L" -> {
h = h.copy(x = h.x - 1)
if (t.isCloseTo(h).not()) t = h.copy(x = h.x + 1)
}
"U" -> {
h = h.copy(y = h.y - 1)
if (t.isCloseTo(h).not()) t = h.copy(y = h.y + 1)
}
"D" -> {
h = h.copy(y = h.y + 1)
if (t.isCloseTo(h).not()) t = h.copy(y = h.y - 1)
}
}
points.add(t)
}
}
return points.distinct().size
}
fun part2(lines: List<String>) = rope(lines, 10)
val testInput = readInput("Day09.txt")
println(part1(testInput))
println(part2(testInput))
}
fun move(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> =
if(abs(head.first - tail.first) > 1 || abs(head.second - tail.second) > 1) {
val tailX = if (head.first == tail.first) 0 else (head.first - tail.first).sign
val tailY = if (head.second == tail.second) 0 else (head.second - tail.second).sign
tail.first + tailX to tail.second + tailY
} else tail
fun rope(lines: List<String>, length: Int) : Int {
val rope = Array(length) { 0 to 0}
val tailVisited = mutableSetOf<Pair<Int, Int>>()
tailVisited.add(rope.last())
for (instr in lines) {
val (dir: String, dist: String) = instr.split(" ")
val step = when (dir) {
"R" -> 1 to 0
"L" -> -1 to 0
"U" -> 0 to 1
"D" -> 0 to -1
else -> error("Unknown")
}
repeat(dist.toInt()) {
rope[0] = rope[0].first + step.first to rope[0].second + step.second
for (i in 0 until rope.lastIndex) {
rope[i + 1] = move(rope[i], rope[i+1])
}
tailVisited += rope.last()
}
}
return tailVisited.size
} | 0 | Kotlin | 0 | 0 | 40bd094155e664a89892400aaf8ba8505fdd1986 | 2,686 | kotlin-aoc-2022 | Apache License 2.0 |
app/src/main/java/com/mohandass/botforge/chat/ui/components/dialogs/SaveChatDialog.kt | L4TTiCe | 611,975,837 | false | {"Kotlin": 675333} | // SPDX-FileCopyrightText: 2023 <NAME> (L4TTiCe)
//
// SPDX-License-Identifier: MIT
package com.mohandass.botforge.chat.ui.components.dialogs
import androidx.compose.foundation.clickable
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.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.google.accompanist.placeholder.PlaceholderHighlight
import com.google.accompanist.placeholder.material.placeholder
import com.google.accompanist.placeholder.material.shimmer
import com.mohandass.botforge.R
import kotlin.reflect.KFunction1
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SaveChatDialog(
initialChatName: String = "",
generatedChatName: String = "",
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
isAutoGenerateChatNameEnabled: Boolean = true,
generateChatName: KFunction1<(String) -> Unit, Unit>
) {
val chatName = remember { mutableStateOf(initialChatName) }
val generatedName = remember { mutableStateOf(generatedChatName) }
LaunchedEffect(Unit) {
if (isAutoGenerateChatNameEnabled) {
generateChatName {
generatedName.value = it
if (chatName.value.isEmpty() || chatName.value.isBlank()) {
chatName.value = it
}
}
}
}
AlertDialog(
modifier = Modifier
.fillMaxWidth()
.height(320.dp),
onDismissRequest = onDismiss,
title = {
Text(text = stringResource(id = R.string.save_chat_dialog_title))
},
text = {
Column(
modifier = Modifier
.padding(10.dp)
) {
if (isAutoGenerateChatNameEnabled) {
Text(
text = stringResource(id = R.string.save_chat_dialog_chat_title_hint),
style = MaterialTheme.typography.labelLarge
)
Text(
text = generatedName.value,
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier
.fillMaxWidth()
.clickable {
chatName.value = generatedName.value
}
.placeholder(
visible = generatedName.value.isEmpty() ||
generatedName.value.isBlank(),
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.2f),
highlight = PlaceholderHighlight.shimmer(),
)
)
Spacer(modifier = Modifier.height(10.dp))
}
OutlinedTextField(
value = chatName.value,
singleLine = true,
onValueChange = { chatName.value = it },
label = {
Text(text = stringResource(id = R.string.save_chat_dialog_chat_title))
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Done
),
)
}
},
confirmButton = {
TextButton(onClick = { onConfirm(chatName.value) }) {
Text(text = stringResource(id = R.string.save))
}
},
dismissButton = {
Row {
TextButton(onClick = onDismiss) {
Text(text = stringResource(id = R.string.cancel))
}
TextButton(onClick = { chatName.value = "" }) {
Text(text = stringResource(id = R.string.clear))
}
}
}
)
}
@Preview
@Composable
fun SavePersonaDialogPreview() {
SaveChatDialog(
initialChatName = "",
onDismiss = {},
onConfirm = {},
generateChatName = ::println
)
}
| 2 | Kotlin | 1 | 27 | a08591acec7433d9e443e8c0a33c5b01b6aa6071 | 4,851 | BotForge | MIT License |
opendc-stdlib/src/main/kotlin/com/atlarge/opendc/model/topology/TopologyListener.kt | atlarge-research | 79,902,611 | false | null | /*
* MIT License
*
* Copyright (c) 2017 atlarge-research
*
* 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.atlarge.opendc.model.topology;
import com.atlarge.opendc.simulator.Entity
/**
* A listener interface for [Topology] instances. The methods of this interface are invoked on
* mutation of the topology the listener is listening to.
*
* @author <NAME> (<EMAIL>)
*/
interface TopologyListener {
/**
* This method is invoked when an [Entity] is added to the [Topology].
*
* @param node The entity that has been added to the [Topology].
*/
fun Topology.onNodeAdded(node: Entity<*>) {}
/**
* This method is invoked when an [Entity] is removed from the [Topology].
*
* @param node The entity that has been removed from the [Topology].
*/
fun Topology.onNodeRemoved(node: Entity<*>) {}
/**
* This method is invoked when an [Edge] is added to the [Topology].
*
* @param edge The edge that has been added to the [Topology].
*/
fun Topology.onEdgeAdded(edge: Edge<*>) {}
/**
* This method is invoked when an [Edge] is removed from the [Topology].
*
* @param edge The entity that has been removed from the [Topology].
*/
fun Topology.onEdgeRemoved(edge: Edge<*>) {}
}
| 2 | Kotlin | 7 | 9 | f399e3d598d156926d0a74aa512f777ff0d9ad10 | 2,367 | opendc-simulator | MIT License |
src/main/java/uk/gov/justice/hmpps/casenotes/dto/BookingIdentifier.kt | ministryofjustice | 195,988,411 | false | {"Kotlin": 153118, "Java": 132329, "Mustache": 1803, "Dockerfile": 1342, "Shell": 580} | package uk.gov.justice.hmpps.casenotes.dto
class BookingIdentifier(val type: String, val value: String)
| 0 | Kotlin | 1 | 0 | 89d669573ab93e01ec9114000e649f2e61071b98 | 105 | offender-case-notes | MIT License |
android-arch-base-lite/src/main/kotlin/moe/feng/common/arch/BaseFragment.kt | fython | 115,638,922 | false | null | package moe.feng.common.arch
import android.app.Fragment
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
abstract class BaseFragment : Fragment() {
abstract @LayoutRes fun getDefaultLayoutId(): Int
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = inflater.inflate(getDefaultLayoutId(), container, false)
} | 0 | Kotlin | 1 | 10 | a7c78c1a5ceea35aab3637ec042eced5a05803e1 | 534 | NyanAndroidArch | MIT License |
client/app/src/main/java/xyz/tcreopargh/amttd/ui/todoedit/TodoEditFragment.kt | TCreopargh | 346,990,489 | false | {"Kotlin": 330427, "Batchfile": 20} | package xyz.tcreopargh.amttd.ui.todoedit
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.graphics.PorterDuff
import android.os.Bundle
import android.text.InputType
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.view.*
import android.widget.*
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.todo_view_fragment.*
import xyz.tcreopargh.amttd.R
import xyz.tcreopargh.amttd.api.data.*
import xyz.tcreopargh.amttd.api.data.action.ActionDeadlineChanged
import xyz.tcreopargh.amttd.api.data.action.ActionGeneric
import xyz.tcreopargh.amttd.api.data.action.ActionType
import xyz.tcreopargh.amttd.api.exception.AmttdException
import xyz.tcreopargh.amttd.api.json.request.ActionCrudRequest
import xyz.tcreopargh.amttd.api.json.request.TodoEntryCrudRequest
import xyz.tcreopargh.amttd.api.json.response.ActionCrudResponse
import xyz.tcreopargh.amttd.api.json.response.TodoEntryCrudResponse
import xyz.tcreopargh.amttd.ui.FragmentOnMainActivityBase
import xyz.tcreopargh.amttd.util.CrudTask
import xyz.tcreopargh.amttd.util.format
import xyz.tcreopargh.amttd.util.setColor
import java.util.*
/**
* This fragment allows the user to view or edit an to-do entry.
*
* An action list is displayed to show the history of action performed on this entry.
*/
class TodoEditFragment : FragmentOnMainActivityBase(R.string.todo_edit_title) {
companion object {
fun newInstance() = TodoEditFragment()
}
lateinit var viewModel: TodoEditViewModel
private lateinit var todoEditSwipeContainer: SwipeRefreshLayout
private var expandActions = true
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.todo_edit_fragment, container, false)
viewModel.entry.observe(viewLifecycleOwner) {
if (it != null) {
initView(view, it)
todoEditSwipeContainer.isRefreshing = false
}
}
todoEditSwipeContainer = view.findViewById(R.id.todoEditSwipeContainer)
todoEditSwipeContainer.setOnRefreshListener {
initializeItems()
}
viewModel.exception.observe(viewLifecycleOwner) {
it?.run {
Toast.makeText(
context,
getString(R.string.error_occurred) + it.getLocalizedString(context),
Toast.LENGTH_SHORT
).show()
todoSwipeContainer.isRefreshing = false
viewModel.exception.value = null
}
}
viewModel.dirty.observe(viewLifecycleOwner) {
if (it) {
initializeItems()
viewModel.dirty.value = false
}
}
viewModel.entryDeleted.observe(viewLifecycleOwner) {
if (it) {
activity?.onBackPressed()
viewModel.entryDeleted.value = false
}
}
initializeItems()
return view
}
private fun deleteEntry() {
AlertDialog.Builder(context).apply {
setTitle(R.string.delete_todo_entry)
setMessage(getString(R.string.delete_entry_confirm))
setPositiveButton(R.string.confirm) { dialog, _ ->
object :
CrudTask<TodoEntryImpl, TodoEntryCrudRequest, TodoEntryCrudResponse>(
request = TodoEntryCrudRequest(
operation = CrudType.DELETE,
entity = TodoEntryImpl(
viewModel.entry.value ?: throw AmttdException(
AmttdException.ErrorCode.REQUESTED_ENTITY_INVALID
)
),
userId = loggedInUser?.uuid
),
path = "/todo-entry",
responseType = object :
TypeToken<TodoEntryCrudResponse>() {}.type
) {
override fun onSuccess(entity: TodoEntryImpl?) {
viewModel.entryDeleted.postValue(true)
}
override fun onFailure(e: Exception) {
viewModel.exception.postValue(
AmttdException.getFromException(
e
)
)
}
}.start()
dialog.dismiss()
}
setNegativeButton(R.string.cancel) { dialog, _ -> dialog.cancel() }
}.create().show()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this).get(TodoEditViewModel::class.java)
val args = arguments?.deepCopy()
viewModel.entryId.value = UUID.fromString(args?.get("entryId").toString())
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.options_todo_edit, menu)
}
@SuppressLint("InflateParams")
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.actionDeleteEntry -> {
deleteEntry()
return true
}
}
return false
}
private fun initializeItems() {
todoEditSwipeContainer.isRefreshing = true
val uuid = viewModel.entryId.value ?: return
object : CrudTask<TodoEntryImpl, TodoEntryCrudRequest, TodoEntryCrudResponse>(
request = TodoEntryCrudRequest(
CrudType.READ,
TodoEntryImpl(entryId = uuid),
userId = loggedInUser?.uuid
),
path = "/todo-entry",
responseType = object : TypeToken<TodoEntryCrudResponse>() {}.type
) {
override fun onSuccess(entity: TodoEntryImpl?) {
viewModel.entry.postValue(entity)
}
override fun onFailure(e: Exception) {
viewModel.exception.postValue(AmttdException.getFromException(e))
}
}.start()
}
@SuppressLint("InflateParams")
private fun initView(viewRoot: View, entry: ITodoEntry) {
viewRoot.apply {
findViewById<EditText>(R.id.todoEditTitleText)?.apply {
setText(
entry.title,
TextView.BufferType.NORMAL
)
inputType = InputType.TYPE_NULL
setOnClickListener {
AlertDialog.Builder(context).apply {
@SuppressLint("InflateParams")
val dialogView =
layoutInflater.inflate(R.layout.todo_title_edit_layout, null)
val titleText =
dialogView.findViewById<EditText>(R.id.todoTitleEditTitleText)
entry.title.let {
titleText.setText(it)
}
setView(dialogView)
setPositiveButton(R.string.confirm) { dialog, _ ->
object :
CrudTask<ActionGeneric, ActionCrudRequest, ActionCrudResponse>(
request = ActionCrudRequest(
operation = CrudType.CREATE,
entity = ActionGeneric(
actionType = ActionType.TITLE_CHANGED,
oldValue = entry.title,
newValue = titleText.text.toString()
),
userId = loggedInUser?.uuid,
entryId = viewModel.entryId.value
),
path = "/action",
responseType = object :
TypeToken<ActionCrudResponse>() {}.type
) {
override fun onSuccess(entity: ActionGeneric?) {
viewModel.dirty.postValue(true)
}
override fun onFailure(e: Exception) {
viewModel.exception.postValue(
AmttdException.getFromException(
e
)
)
}
}.start()
dialog.dismiss()
}
setNegativeButton(R.string.cancel) { dialog, _ -> dialog.cancel() }
}.create().show()
}
}
findViewById<EditText>(R.id.todoEditDescriptionText)?.apply {
setText(
entry.description,
TextView.BufferType.NORMAL
)
inputType = InputType.TYPE_NULL
isSingleLine = false
setOnClickListener {
AlertDialog.Builder(context).apply {
@SuppressLint("InflateParams")
val dialogView =
layoutInflater.inflate(R.layout.todo_description_edit_layout, null)
val titleText =
dialogView.findViewById<EditText>(R.id.todoDescriptionEditTitleText)
entry.description.let {
titleText.setText(it)
}
setView(dialogView)
setPositiveButton(R.string.confirm) { dialog, _ ->
object :
CrudTask<ActionGeneric, ActionCrudRequest, ActionCrudResponse>(
request = ActionCrudRequest(
operation = CrudType.CREATE,
entity = ActionGeneric(
actionType = ActionType.DESCRIPTION_CHANGED,
oldValue = entry.title,
newValue = titleText.text.toString()
),
userId = loggedInUser?.uuid,
entryId = viewModel.entryId.value
),
path = "/action",
responseType = object :
TypeToken<ActionCrudResponse>() {}.type
) {
override fun onSuccess(entity: ActionGeneric?) {
viewModel.dirty.postValue(true)
}
override fun onFailure(e: Exception) {
viewModel.exception.postValue(
AmttdException.getFromException(
e
)
)
}
}.start()
dialog.dismiss()
}
setNegativeButton(R.string.cancel) { dialog, _ -> dialog.cancel() }
}.create().show()
}
}
findViewById<Button>(R.id.addTaskButton)?.apply {
setOnClickListener {
showEditTaskDialog(true)
}
}
findViewById<ImageButton>(R.id.todoEditStatusEditButton)?.apply {
setOnClickListener {
setOnClickListener {
AlertDialog.Builder(context).apply {
setTitle(R.string.todo_status)
val items =
TodoStatus.values().map { it.getDisplayString() }.toTypedArray()
setItems(items) { dialog, which ->
object :
CrudTask<ActionGeneric, ActionCrudRequest, ActionCrudResponse>(
request = ActionCrudRequest(
operation = CrudType.CREATE,
entity = ActionGeneric(
actionType = ActionType.STATUS_CHANGED,
fromStatus = entry.status,
toStatus = TodoStatus.values()[which]
),
userId = loggedInUser?.uuid,
entryId = viewModel.entryId.value
),
path = "/action",
responseType = object :
TypeToken<ActionCrudResponse>() {}.type
) {
override fun onSuccess(entity: ActionGeneric?) {
viewModel.dirty.postValue(true)
}
override fun onFailure(e: Exception) {
viewModel.exception.postValue(
AmttdException.getFromException(
e
)
)
}
}.start()
dialog.dismiss()
}
setNegativeButton(R.string.cancel) { dialog, _ -> dialog.cancel() }
}.create().show()
}
}
}
findViewById<TextView>(R.id.todoEditStatusText)?.text = entry.status.getDisplayString()
findViewById<TextView>(R.id.todoEditDeadlineText)?.text =
entry.deadline?.run { format() + " " + format(true) }
?: getString(R.string.deadline_not_set)
findViewById<ImageView>(R.id.todoEditIconColor)?.setColorFilter(
entry.status.color,
PorterDuff.Mode.SRC
)
findViewById<ImageButton>(R.id.todoEditDeadlineEditButton)?.setOnClickListener {
setDeadline()
}
val tasks = findViewById<LinearLayout>(R.id.todoTaskItemView)
val actions = findViewById<LinearLayout>(R.id.actionHistoryLayout)
findViewById<Button>(R.id.actionExpandButton)?.apply {
text =
if (expandActions) context.getString(R.string.collapse) else context.getString(R.string.expand)
setOnClickListener {
if (expandActions) {
expandActions = false
text = context.getString(R.string.expand)
actions.visibility = View.GONE
} else {
expandActions = true
text = context.getString(R.string.collapse)
actions.visibility = View.VISIBLE
}
}
}
tasks.removeAllViewsInLayout()
actions.removeAllViewsInLayout()
for (task in entry.tasks) {
val itemView = layoutInflater.inflate(R.layout.task_view_item, null)
itemView.apply {
val checkbox = findViewById<CheckBox>(R.id.taskCheckbox).apply {
text = task.name
isChecked = task.completed
setOnCheckedChangeListener { _, isChecked ->
object : CrudTask<ActionGeneric, ActionCrudRequest, ActionCrudResponse>(
request = ActionCrudRequest(
operation = CrudType.CREATE,
entity = ActionGeneric(
actionType = if (isChecked) {
ActionType.TASK_COMPLETED
} else {
ActionType.TASK_UNCOMPLETED
},
task = TaskImpl(
task
)
),
userId = loggedInUser?.uuid,
entryId = viewModel.entryId.value
),
path = "/action",
responseType = object : TypeToken<ActionCrudResponse>() {}.type
) {
override fun onSuccess(entity: ActionGeneric?) {
viewModel.dirty.postValue(true)
}
override fun onFailure(e: Exception) {
viewModel.exception.postValue(AmttdException.getFromException(e))
}
}.start()
}
}
findViewById<View>(R.id.taskPlaceholderView).apply {
setOnClickListener {
checkbox.toggle()
}
}
findViewById<ImageButton>(R.id.taskEditButton).apply {
setOnClickListener {
showEditTaskDialog(false, task)
}
}
}
tasks.addView(itemView)
}
for (actionGeneric in entry.actionHistory) {
val action = ActionGeneric(actionGeneric).action
val itemView = layoutInflater.inflate(R.layout.action_view_item, null)
itemView.apply {
findViewById<TextView>(R.id.actionText).apply {
setCompoundDrawablesRelativeWithIntrinsicBounds(
ContextCompat.getDrawable(
context,
action.getImageRes()
)?.apply {
setTint(context.getColor(R.color.grey))
}, null, null, null
)
text = TextUtils.concat(
action.getDisplayText(), " ",
SpannableString("@").setColor(context.getColor(R.color.primary)),
" ",
SpannableString(action.timeCreated.format(false)).setColor(
context.getColor(
R.color.secondary
)
),
" ",
SpannableString(action.timeCreated.format(true)).setColor(
context.getColor(
R.color.purple_200
)
)
) as Spanned
}
}
actions.addView(itemView)
}
}
}
private fun showEditTaskDialog(isAdd: Boolean, task: ITask? = null) {
AlertDialog.Builder(context).apply {
@SuppressLint("InflateParams")
val viewRoot = layoutInflater.inflate(R.layout.task_edit_layout, null)
val titleText = viewRoot.findViewById<EditText>(R.id.taskEditTitleText)
val oldName = task?.name
if (isAdd) {
viewRoot.findViewById<TextView>(R.id.taskEditDialogTitle).setText(R.string.add_task)
}
task?.name?.let {
titleText.setText(it)
}
setView(viewRoot)
setPositiveButton(R.string.confirm) { dialog, _ ->
val name = titleText.text.toString()
if (isAdd) {
object : CrudTask<ActionGeneric, ActionCrudRequest, ActionCrudResponse>(
request = ActionCrudRequest(
operation = CrudType.CREATE,
entity = ActionGeneric(
actionType = ActionType.TASK_ADDED,
task = TaskImpl(
name = name
)
),
userId = loggedInUser?.uuid,
entryId = viewModel.entryId.value
),
path = "/action",
responseType = object : TypeToken<ActionCrudResponse>() {}.type
) {
override fun onSuccess(entity: ActionGeneric?) {
viewModel.dirty.postValue(true)
}
override fun onFailure(e: Exception) {
viewModel.exception.postValue(AmttdException.getFromException(e))
}
}.start()
} else {
object : CrudTask<ActionGeneric, ActionCrudRequest, ActionCrudResponse>(
request = ActionCrudRequest(
operation = CrudType.CREATE,
entity = ActionGeneric(
actionType = ActionType.TASK_EDITED,
oldValue = oldName,
newValue = task?.name,
task = TaskImpl(
task
?: throw AmttdException(AmttdException.ErrorCode.JSON_NON_NULLABLE_VALUE_IS_NULL)
).apply {
this.name = name
}
),
userId = loggedInUser?.uuid,
entryId = viewModel.entryId.value
),
path = "/action",
responseType = object : TypeToken<ActionCrudResponse>() {}.type
) {
override fun onSuccess(entity: ActionGeneric?) {
viewModel.dirty.postValue(true)
}
override fun onFailure(e: Exception) {
viewModel.exception.postValue(AmttdException.getFromException(e))
}
}.start()
}
dialog.dismiss()
}
if (!isAdd) {
setNeutralButton(R.string.remove) { dialog, _ ->
AlertDialog.Builder(context).apply {
setTitle(R.string.remove_task)
setMessage(R.string.remove_task_confirm)
setPositiveButton(R.string.confirm) { dialogInner, _ ->
object : CrudTask<ActionGeneric, ActionCrudRequest, ActionCrudResponse>(
request = ActionCrudRequest(
operation = CrudType.CREATE,
entity = ActionGeneric(
actionType = ActionType.TASK_REMOVED,
task = TaskImpl(
task
?: throw AmttdException(AmttdException.ErrorCode.JSON_NON_NULLABLE_VALUE_IS_NULL)
)
),
userId = loggedInUser?.uuid,
entryId = viewModel.entryId.value
),
path = "/action",
responseType = object : TypeToken<ActionCrudResponse>() {}.type
) {
override fun onSuccess(entity: ActionGeneric?) {
viewModel.dirty.postValue(true)
}
override fun onFailure(e: Exception) {
viewModel.exception.postValue(AmttdException.getFromException(e))
}
}.start()
dialog.dismiss()
dialogInner.dismiss()
}
setNegativeButton(R.string.cancel) { dialogInner, _ -> dialogInner.cancel() }
}.create().show()
}
}
setNegativeButton(R.string.cancel) { dialog, _ -> dialog.cancel() }
}.create().show()
}
private fun setDeadline() {
val currentDate = Calendar.getInstance()
val date: Calendar = Calendar.getInstance()
DatePickerDialog(
context ?: return, { _, year, monthOfYear, dayOfMonth ->
date.set(year, monthOfYear, dayOfMonth)
TimePickerDialog(
context, { _, hourOfDay, minute ->
date.set(Calendar.HOUR_OF_DAY, hourOfDay)
date.set(Calendar.MINUTE, minute)
object : CrudTask<ActionGeneric, ActionCrudRequest, ActionCrudResponse>(
request = ActionCrudRequest(
operation = CrudType.CREATE,
entity = ActionGeneric(ActionDeadlineChanged(
actionId = UUID.randomUUID(),
user = UserImpl(
loggedInUser
?: throw AmttdException(AmttdException.ErrorCode.LOGIN_REQUIRED)
),
timeCreated = Calendar.getInstance(),
oldValue = null,
newValue = null
).apply {
oldDeadline = viewModel.entry.value?.deadline
newDeadline = date
}),
userId = loggedInUser?.uuid,
entryId = viewModel.entryId.value
),
path = "/action",
responseType = object : TypeToken<ActionCrudResponse>() {}.type
) {
override fun onSuccess(entity: ActionGeneric?) {
viewModel.dirty.postValue(true)
}
override fun onFailure(e: Exception) {
viewModel.exception.postValue(AmttdException.getFromException(e))
}
}.start()
},
currentDate[Calendar.HOUR_OF_DAY],
currentDate[Calendar.MINUTE],
true
).show()
},
currentDate[Calendar.YEAR],
currentDate[Calendar.MONTH],
currentDate[Calendar.DATE]
).apply {
datePicker.minDate = currentDate.timeInMillis
}.show()
}
} | 0 | Kotlin | 1 | 2 | ce50443464e0ba0eef2a998f7d227ba5a38af68f | 29,037 | A-Million-Things-To-Do | MIT License |
app/src/main/java/app/isfaaghyth/uicomponent/ui/person/adapter/CharacterAdapter.kt | isfaaghyth | 263,394,849 | false | null | package app.isfaaghyth.uicomponent.ui.person.adapter
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import app.isfaaghyth.uicomponent.ui.person.CharUIView
import app.isfaaghyth.uicomponent.ui.person.viewholder.CharViewHolder
import app.isfaaghyth.uicomponent.view.uimodel.CharacterUIModel
class CharacterAdapter(
private val characters: List<CharacterUIModel>,
private val listener: CharUIView.Listener
): RecyclerView.Adapter<CharViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CharViewHolder {
return CharViewHolder.create(parent, listener)
}
override fun onBindViewHolder(holder: CharViewHolder, position: Int) {
holder.bind(characters[position])
}
override fun getItemCount(): Int = characters.size
} | 0 | Kotlin | 4 | 55 | 0a35882c9a26f27b3a455fdde647865d8effe455 | 820 | floppy | Apache License 2.0 |
app/src/main/java/com/dombikpanda/doktarasor/data/model/QuestionCharts.kt | omeryavuzyigit61 | 507,668,259 | false | {"Kotlin": 106259} | package com.dombikpanda.doktarasor.data.model
data class QuestionCharts(
var answerQuestion: Int = -1,
var questionAsked: Int = -1
)
| 0 | Kotlin | 0 | 0 | 8b68b97a359630fb4f333f2d5f6d034e4e172cd6 | 142 | DoktaraSor | MIT License |
src/main/kotlin/com/patronusstudio/BottleFlip/Model/UserModel.kt | Patronus-Studio | 506,114,514 | false | {"Kotlin": 112407, "Procfile": 85} | package com.patronusstudio.BottleFlip.Model
import com.google.gson.annotations.SerializedName
import com.patronusstudio.BottleFlip.Base.BaseModel
import com.patronusstudio.BottleFlip.enums.GenderEnum
data class UserModel(
@SerializedName("username") val username: String,
@SerializedName("email") val email: String? = null,
@SerializedName("gender") val gender: GenderEnum? = null,
@SerializedName("password") val password: String? = null,
@SerializedName("userType") val userType: String = "0",
@SerializedName("createdTime") val createdTime: Long? = null,
@SerializedName("authToken") val authToken: String? = null,
@SerializedName("pushToken") val pushToken: String? = null,
):BaseModel()
| 0 | Kotlin | 0 | 0 | 66330a2aa108cdd432bd2782485b5dc2d00572e5 | 726 | Sise-Backend | Apache License 2.0 |
android/build.gradle.kts | Quillraven | 204,287,647 | false | null | plugins {
id("com.android.application")
kotlin("android")
}
android {
compileSdkVersion(29)
sourceSets {
named("main") {
java.srcDirs("src/main/kotlin")
assets.srcDirs(project.file("../assets"))
jniLibs.srcDirs("libs")
}
}
defaultConfig {
applicationId = "${project.property("packageName")}"
minSdkVersion(24)
targetSdkVersion(29)
versionCode = 2
versionName = "1.1"
}
buildTypes {
named("release") {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
}
}
compileOptions {
sourceCompatibility = JavaVersion.valueOf("${project.property("java")}")
targetCompatibility = JavaVersion.valueOf("${project.property("java")}")
}
kotlinOptions {
jvmTarget = "${project.property("jvmTarget")}"
}
}
val natives: Configuration by configurations.creating
dependencies {
implementation(project(":core"))
api("com.badlogicgames.gdx:gdx-backend-android:${project.property("gdx")}")
natives("com.badlogicgames.gdx:gdx-platform:${project.property("gdx")}:natives-armeabi")
natives("com.badlogicgames.gdx:gdx-platform:${project.property("gdx")}:natives-armeabi-v7a")
natives("com.badlogicgames.gdx:gdx-platform:${project.property("gdx")}:natives-arm64-v8a")
natives("com.badlogicgames.gdx:gdx-platform:${project.property("gdx")}:natives-x86")
natives("com.badlogicgames.gdx:gdx-platform:${project.property("gdx")}:natives-x86_64")
api("com.badlogicgames.gdx:gdx-box2d:${project.property("gdx")}")
natives("com.badlogicgames.gdx:gdx-box2d-platform:${project.property("gdx")}:natives-armeabi")
natives("com.badlogicgames.gdx:gdx-box2d-platform:${project.property("gdx")}:natives-armeabi-v7a")
natives("com.badlogicgames.gdx:gdx-box2d-platform:${project.property("gdx")}:natives-arm64-v8a")
natives("com.badlogicgames.gdx:gdx-box2d-platform:${project.property("gdx")}:natives-x86")
natives("com.badlogicgames.gdx:gdx-box2d-platform:${project.property("gdx")}:natives-x86_64")
api("com.badlogicgames.gdx:gdx-freetype:${project.property("gdx")}")
natives("com.badlogicgames.gdx:gdx-freetype-platform:${project.property("gdx")}:natives-armeabi")
natives("com.badlogicgames.gdx:gdx-freetype-platform:${project.property("gdx")}:natives-armeabi-v7a")
natives("com.badlogicgames.gdx:gdx-freetype-platform:${project.property("gdx")}:natives-arm64-v8a")
natives("com.badlogicgames.gdx:gdx-freetype-platform:${project.property("gdx")}:natives-x86")
natives("com.badlogicgames.gdx:gdx-freetype-platform:${project.property("gdx")}:natives-x86_64")
api("com.badlogicgames.box2dlights:box2dlights:${project.property("box2DLight")}")
api("com.badlogicgames.ashley:ashley:${project.property("ashley")}")
api("com.badlogicgames.gdx:gdx-ai:${project.property("gdxAI")}")
api("org.jetbrains.kotlin:kotlin-stdlib")
}
// Called every time gradle gets executed, takes the native dependencies of
// the natives configuration, and extracts them to the proper libs/ folders
// so they get packed with the APK.
tasks.register("copyAndroidNatives") {
doFirst {
natives.files.forEach { jar ->
val outputDir = file("libs/" + jar.nameWithoutExtension.substringAfterLast("natives-"))
outputDir.mkdirs()
copy {
from(zipTree(jar))
into(outputDir)
include("*.so")
}
}
}
}
tasks.whenTaskAdded {
if ("package" in name) {
dependsOn("copyAndroidNatives")
}
}
| 0 | Kotlin | 19 | 81 | 0454372392de55e9790c950238a0c509c527e8c4 | 3,701 | Quilly-s-Adventure | MIT License |
src/test/kotlin/dev/blog/IntegrationTests.kt | roalcantara | 667,451,525 | false | null | package dev.blog
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class IntegrationTests(@Autowired val restTemplate: TestRestTemplate) {
@BeforeAll
fun setup() {
println(">> Setup")
}
@Test
fun `Assert blog page title, content and status code`() {
println(">> Assert blog page title, content and status code")
val entity = restTemplate.getForEntity<String>("/")
assertThat(entity.statusCode).isEqualTo(HttpStatus.OK)
assertThat(entity.body).contains("<h1>Blog</h1>", "Lorem")
}
@Test
fun `Assert article page title, content and status code`() {
println(">> Assert article page title, content and status code")
val title = "Lorem"
val entity = restTemplate.getForEntity<String>("/article/${title.toSlug()}")
assertThat(entity.statusCode).isEqualTo(HttpStatus.OK)
assertThat(entity.body).contains(title, "Lorem", "dolor sit amet")
}
@AfterAll
fun teardown() {
println(">> Tear down")
}
}
| 1 | Kotlin | 0 | 0 | 160f170ebdc8b46981bad67a1a0b401d90077d0b | 1,083 | blog | MIT License |
src/main/kotlin/org/cascadebot/bot/Main.kt | CascadeBot | 540,879,487 | false | {"Kotlin": 79746, "Dockerfile": 289, "Shell": 77} | package org.cascadebot.bot
import ch.qos.logback.classic.Level
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import dev.minn.jda.ktx.util.SLF4J
import kotlinx.cli.ArgParser
import kotlinx.cli.ArgType
import net.dv8tion.jda.api.JDABuilder
import net.dv8tion.jda.api.entities.Activity
import net.dv8tion.jda.api.requests.GatewayIntent
import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder
import net.dv8tion.jda.api.sharding.ShardManager
import org.cascadebot.bot.cmd.meta.CommandManager
import org.cascadebot.bot.components.ComponentCache
import org.cascadebot.bot.db.PostgresManager
import org.cascadebot.bot.events.InteractionListener
import org.cascadebot.bot.events.ReadyListener
import org.cascadebot.bot.rabbitmq.RabbitMQManager
import org.cascadebot.bot.utils.LogbackUtil
import org.hibernate.HibernateException
import kotlin.system.exitProcess
object Main {
val logger by SLF4J("Main")
lateinit var componentCache: ComponentCache
private set
lateinit var shardManager: ShardManager
private set
lateinit var commandManager: CommandManager
private set
lateinit var postgresManager: PostgresManager
private set
var rabbitMQManager: RabbitMQManager? = null
private set
lateinit var config: Config
private set
val json: ObjectMapper = ObjectMapper().apply {
registerModule(KotlinModule.Builder().build())
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
}
private fun runBot() {
logger.info("Starting CascadeBot")
config = loadConfig()
if (config.development?.debugLogs == true) {
LogbackUtil.setAppenderLevel("STDOUT", Level.DEBUG)
}
componentCache = ComponentCache(config.values.maxComponentsCachedPerChannel)
try {
postgresManager = PostgresManager(config.database)
} catch (e: HibernateException) {
// Get the root Hibernate exception
var exception = e
while (exception.cause != null && exception.cause is HibernateException) {
exception = e.cause as HibernateException
}
logger.error("Could not initialise database: {}", exception.message)
exitProcess(1)
}
if (config.rabbitMQ != null) {
rabbitMQManager = RabbitMQManager(config.rabbitMQ!!)
} else {
logger.warn("RabbitMQ config not detected, won't be able to communicate with any other components")
}
commandManager = CommandManager()
shardManager = buildShardManager()
}
private fun loadConfig(): Config {
val configResult = Config.load()
if (configResult.isInvalid()) {
// Print out the invalid config message. Replace all double new lines with single for compactness
logger.error(
"Could not load config: \n" + configResult.getInvalidUnsafe().description().replace("\n\n", "\n")
)
exitProcess(1)
}
return configResult.getUnsafe()
}
private fun buildShardManager(): ShardManager {
val defaultShardManagerBuilder =
DefaultShardManagerBuilder.create(GatewayIntent.getIntents(GatewayIntent.ALL_INTENTS)) // TODO do we want to have all here? I imagine eventually, but don't know about mvp
.setToken(config.discord.token)
.setActivityProvider { Activity.playing("Cascade Bot") }
.addEventListeners(ReadyListener())
.addEventListeners(InteractionListener())
config.discord.shards?.let {
when (it) {
is Sharding.Total -> {
defaultShardManagerBuilder.setShardsTotal(it.total)
}
is Sharding.MinMax -> {
defaultShardManagerBuilder.setShardsTotal(it.total)
defaultShardManagerBuilder.setShards(it.min, it.max)
}
}
}
return defaultShardManagerBuilder.build()
}
private fun updateDiscordCommands(token: String) {
LogbackUtil.setAppenderLevel("STDOUT", Level.DEBUG)
logger.info("Uploading commands to Discord and then exiting.")
val cmdManager = CommandManager()
val jda = JDABuilder.createLight(token)
.setEnabledIntents(listOf())
.build()
cmdManager.registerCommandsOnce(jda)
exitProcess(0)
}
private fun processCmdArgs(args: Array<String>) {
if (args.isNotEmpty()) {
val parser = ArgParser("example")
val updateCommands by parser.option(
ArgType.String,
fullName = "update-commands",
shortName = "u",
description = "Attempts to update slash commands with Discord then exits",
)
parser.parse(args)
updateCommands?.let { token -> updateDiscordCommands(token) }
}
}
@JvmStatic
fun main(args: Array<String>) {
processCmdArgs(args)
try {
runBot()
} catch (e: Exception) {
logger.error("Error in bot execution", e)
}
}
} | 0 | Kotlin | 0 | 0 | b01e0f53de1b512487c10f52012d1203426d7dd5 | 5,356 | Bot | MIT License |
extensions/transfer/transfer-provision-azure/build.gradle.kts | daniil-pankratov | 377,485,099 | true | {"Java": 1027157, "Kotlin": 32583, "Python": 22015, "HCL": 18303, "Mustache": 16725, "Dockerfile": 2228, "XSLT": 1535, "Shell": 334} | /*
* Copyright (c) Microsoft Corporation.
* All rights reserved.
*/
plugins {
`java-library`
}
val storageBlobVersion: String by project
dependencies {
api(project(":spi"))
api(project(":extensions:schema"))
implementation("com.azure:azure-storage-blob:${storageBlobVersion}")
testImplementation(testFixtures(project(":common")))
}
| 0 | null | 0 | 0 | aab814eb874e3cf4cf4ad897d28a99d15561a85a | 362 | Data-Appliance-GX | MIT License |
cc-jacoco/cc-android/dev_dq_#411671_coverage2/21acf985/src/site/duqian/android_ui/view/CircleGapProgressView.kt | duqian291902259 | 404,950,295 | false | {"Kotlin": 99089, "Java": 81765, "Vue": 19323, "JavaScript": 3983, "Dockerfile": 1471, "HTML": 1439, "Shell": 510, "Makefile": 94} | package site.duqian.android_ui.view
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.core.util.Pair
import site.duqian.android_ui.R
import site.duqian.android_ui.utils.UIUtils
import kotlin.math.min
/**
* Description:圆环进度条,中间有间隔,画扇形,画进度文本
*
* @author 杜小菜 on 2021/3/23 - 11:11 .
* E-mail: <EMAIL>
*/
class CircleGapProgressView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private var centerPadding = 0
private var mTextSize = 15f
private var mTextColor = -1
private var progressWidth = 0f
private var progressNum = 0
private var gapSize = 0f
private var bgColor = 0
private var progressColor = 0
private val bgPaint: Paint
private var mTextPaint: Paint? = null
private val progressPaint: Paint
//进度扇形所在的圆范围
private val rectF = RectF()
//进度条划过的角度
private var progressDegree = 0f
//扇形 + 之间的空隙的角度
private val gapProgressDegree: Float
private var center: Pair<Float?, Float?>? = null
private var maxProgress = 100
private var currentProgress = 0
//中间的text文本要真实,但是进度条不一定
private var currentProgressText = 0
private var isShowProgressText = false
private val mTextBound = Rect()
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val measuredWidth = MeasureSpec.getSize(widthMeasureSpec)
val measuredHeight = MeasureSpec.getSize(heightMeasureSpec)
Log.i("dq-ui", "measuredWidth=$measuredWidth,measuredHeight=$measuredHeight")
val min = min(measuredWidth, measuredHeight)
setMeasuredDimension(min, min)
rectF[centerPadding.toFloat(), centerPadding.toFloat(), measuredWidth.toFloat() - centerPadding] =
measuredHeight.toFloat() - centerPadding
//每个一个扇形进度 / 周长 * 360
progressDegree =
(3.14f * measuredWidth / progressNum - gapSize) / (3.14f * measuredWidth) * 360f
center = Pair.create(measuredWidth / 2f, measuredHeight / 2f)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
try {
if (center!!.first == null || center!!.second == null) {
return
}
//绘制背景圆环,相当于每次都是绘制了一次进度100的扇形
if (bgPaint.color != 0) {
var startDegree = 0f
while (startDegree < 360) {
canvas.drawArc(
rectF,
startDegree + ORIGIN_DEGREE,
progressDegree,
false,
bgPaint
)
startDegree += gapProgressDegree
}
}
//绘制进度
var startDegree = calculateStartDegree()
while (startDegree < 360) {
canvas.drawArc(
rectF,
startDegree + ORIGIN_DEGREE,
progressDegree,
false,
progressPaint
)
startDegree += gapProgressDegree
}
setProgressText(canvas)
} catch (e: Exception) {
}
}
private fun setProgressText(canvas: Canvas) {
if (isShowProgressText) {
val text = "$currentProgressText%"
mTextPaint!!.getTextBounds(text, 0, text.length, mTextBound)
canvas.drawText(
text, width / 2.0f - mTextBound.width() / 2.0f,
height / 2.0f + mTextBound.height() / 2.0f, mTextPaint!!
)
}
}
fun setProgressColor(color: Int) {
progressColor = color
progressPaint.color = progressColor
invalidate()
}
fun setMaxProgress(maxProgress: Int) {
this.maxProgress = maxProgress
invalidate()
}
fun setCurrentProgress(currentProgress: Int) {
var currentProgress = currentProgress
if (currentProgress > maxProgress) {
currentProgress = maxProgress
}
this.currentProgress = currentProgress
currentProgressText = currentProgress
if (currentProgress in 1..10) {
//防止看不到进度?
this.currentProgress = 10
}
invalidate()
}
private fun calculateStartDegree(): Float {
//计算当前的进度位置,第几个扇形
val startProgress =
Math.ceil(progressNum.toDouble() * (maxProgress - currentProgress) / maxProgress)
.toInt()
//计算这个扇形的开始角度 = 每个进度的角度 * 已过去的进度数
return gapProgressDegree * (progressNum - startProgress)
}
companion object {
private const val ORIGIN_DEGREE = -90f
}
init {
val a = context.theme.obtainStyledAttributes(attrs, R.styleable.CircleGapProgressView, 0, 0)
try {
progressWidth = a.getDimension(
R.styleable.CircleGapProgressView_progress_width,
UIUtils.dp2px(context, 3f).toFloat()
)
progressNum = a.getInt(R.styleable.CircleGapProgressView_progress_num, 10)
gapSize = a.getDimension(
R.styleable.CircleGapProgressView_gap_size,
UIUtils.dp2px(context, 1f).toFloat()
)
bgColor = a.getColor(R.styleable.CircleGapProgressView_bg_color, Color.WHITE)
progressColor = a.getColor(R.styleable.CircleGapProgressView_progress_color, 0xffffff)
currentProgress = a.getInt(R.styleable.CircleGapProgressView_current_progress, 0)
maxProgress = a.getColor(R.styleable.CircleGapProgressView_max_progress, 100)
isShowProgressText =
a.getBoolean(R.styleable.CircleGapProgressView_showProgressText, false)
mTextColor = a.getColor(R.styleable.CircleGapProgressView_text_color, 0xffffff)
mTextSize = a.getDimension(R.styleable.CircleGapProgressView_text_size, 15f)
centerPadding = progressWidth.toInt()
} finally {
a.recycle()
}
//底色
bgPaint = Paint()
bgPaint.style = Paint.Style.STROKE
bgPaint.isAntiAlias = true
bgPaint.color = bgColor
bgPaint.strokeWidth = progressWidth
//进度画笔
progressPaint = Paint()
progressPaint.style = Paint.Style.STROKE
progressPaint.isAntiAlias = true
progressPaint.color = progressColor
progressPaint.strokeWidth = progressWidth
gapProgressDegree = 360f / progressNum
if (isShowProgressText) {
mTextPaint = Paint()
mTextPaint?.apply {
this.strokeWidth = 4f
this.textSize = mTextSize
this.isAntiAlias = true
this.color = mTextColor
this.textAlign = Paint.Align.LEFT
}
}
setCurrentProgress(currentProgress)
}
} | 2 | Kotlin | 2 | 4 | afd9cd99821f848d1249bacb47490a7e12d3cd59 | 7,344 | Coverage_JacocoWebServer | Apache License 2.0 |
alerting/src/main/kotlin/org/opensearch/alerting/util/DocLevelMonitorQueries.kt | downsrob | 445,308,211 | true | {"Kotlin": 1391895, "Java": 61866, "Shell": 1903, "Python": 1379} | /*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.alerting.util
import org.apache.logging.log4j.LogManager
import org.opensearch.ResourceAlreadyExistsException
import org.opensearch.action.admin.indices.create.CreateIndexRequest
import org.opensearch.action.admin.indices.create.CreateIndexResponse
import org.opensearch.action.admin.indices.get.GetIndexRequest
import org.opensearch.action.admin.indices.get.GetIndexResponse
import org.opensearch.action.admin.indices.mapping.put.PutMappingRequest
import org.opensearch.action.bulk.BulkRequest
import org.opensearch.action.bulk.BulkResponse
import org.opensearch.action.index.IndexRequest
import org.opensearch.action.support.WriteRequest.RefreshPolicy
import org.opensearch.action.support.master.AcknowledgedResponse
import org.opensearch.alerting.core.model.DocLevelMonitorInput
import org.opensearch.alerting.core.model.DocLevelQuery
import org.opensearch.alerting.core.model.ScheduledJob
import org.opensearch.alerting.model.Monitor
import org.opensearch.alerting.opensearchapi.suspendUntil
import org.opensearch.client.Client
import org.opensearch.cluster.service.ClusterService
import org.opensearch.common.settings.Settings
import org.opensearch.common.unit.TimeValue
private val log = LogManager.getLogger(DocLevelMonitorQueries::class.java)
class DocLevelMonitorQueries(private val client: Client, private val clusterService: ClusterService) {
companion object {
@JvmStatic
fun docLevelQueriesMappings(): String {
return DocLevelMonitorQueries::class.java.classLoader.getResource("mappings/doc-level-queries.json").readText()
}
}
suspend fun initDocLevelQueryIndex(): Boolean {
if (!docLevelQueryIndexExists()) {
val indexRequest = CreateIndexRequest(ScheduledJob.DOC_LEVEL_QUERIES_INDEX)
.mapping(docLevelQueriesMappings())
.settings(
Settings.builder().put("index.hidden", true)
.build()
)
return try {
val createIndexResponse: CreateIndexResponse = client.suspendUntil { client.admin().indices().create(indexRequest, it) }
createIndexResponse.isAcknowledged
} catch (t: ResourceAlreadyExistsException) {
if (t.message?.contains("already exists") == true) {
true
} else {
throw t
}
}
}
return true
}
fun docLevelQueryIndexExists(): Boolean {
val clusterState = clusterService.state()
return clusterState.routingTable.hasIndex(ScheduledJob.DOC_LEVEL_QUERIES_INDEX)
}
suspend fun indexDocLevelQueries(
monitor: Monitor,
monitorId: String,
refreshPolicy: RefreshPolicy = RefreshPolicy.IMMEDIATE,
indexTimeout: TimeValue
) {
val docLevelMonitorInput = monitor.inputs[0] as DocLevelMonitorInput
val index = docLevelMonitorInput.indices[0]
val queries: List<DocLevelQuery> = docLevelMonitorInput.queries
val clusterState = clusterService.state()
val getIndexRequest = GetIndexRequest().indices(index)
val getIndexResponse: GetIndexResponse = client.suspendUntil {
client.admin().indices().getIndex(getIndexRequest, it)
}
val indices = getIndexResponse.indices()
indices?.forEach { indexName ->
if (clusterState.routingTable.hasIndex(indexName)) {
val indexMetadata = clusterState.metadata.index(indexName)
if (indexMetadata.mapping()?.sourceAsMap?.get("properties") != null) {
val properties = (
(indexMetadata.mapping()?.sourceAsMap?.get("properties"))
as Map<String, Map<String, Any>>
)
val updatedProperties = properties.entries.associate {
if (it.value.containsKey("path")) {
val newVal = it.value.toMutableMap()
newVal["path"] = "${it.value["path"]}_${indexName}_$monitorId"
"${it.key}_${indexName}_$monitorId" to newVal
} else {
"${it.key}_${indexName}_$monitorId" to it.value
}
}
val updateMappingRequest = PutMappingRequest(ScheduledJob.DOC_LEVEL_QUERIES_INDEX)
updateMappingRequest.source(mapOf<String, Any>("properties" to updatedProperties))
val updateMappingResponse: AcknowledgedResponse = client.suspendUntil {
client.admin().indices().putMapping(updateMappingRequest, it)
}
if (updateMappingResponse.isAcknowledged) {
val indexRequests = mutableListOf<IndexRequest>()
queries.forEach {
var query = it.query
properties.forEach { prop ->
query = query.replace("${prop.key}:", "${prop.key}_${indexName}_$monitorId:")
}
val indexRequest = IndexRequest(ScheduledJob.DOC_LEVEL_QUERIES_INDEX)
.id(it.id + "_${indexName}_$monitorId")
.source(
mapOf(
"query" to mapOf("query_string" to mapOf("query" to query)),
"monitor_id" to monitorId,
"index" to indexName
)
)
indexRequests.add(indexRequest)
}
if (indexRequests.isNotEmpty()) {
val bulkResponse: BulkResponse = client.suspendUntil {
client.bulk(
BulkRequest().setRefreshPolicy(refreshPolicy).timeout(indexTimeout).add(indexRequests), it
)
}
}
}
}
}
}
}
}
| 0 | Kotlin | 1 | 0 | b9b1cfa343feabe7e107f2e8d6c061ef9a160db2 | 6,408 | alerting | Apache License 2.0 |
app/src/main/java/com/example/week2/data/Multimedia.kt | hnt281098 | 172,295,700 | false | null | package com.example.week2.data
import com.google.gson.annotations.SerializedName
data class Multimedia(
val rank: Int,
val subtype: String,
val caption: Any,
val credit: Any,
val type: String,
val url: String,
val height: Int,
val width: Int,
val legacy: Legacy,
val subType: String,
@SerializedName("crop_name")
val cropName: String
) | 0 | Kotlin | 0 | 0 | 8b1e1a81fae3999b5cb1df748b5ff536346fac47 | 385 | Week2 | Apache License 2.0 |
metronome-android/app/src/main/java/com/jedparsons/metronome/storage/SharedPrefsRhythmStore.kt | jedp | 496,303,738 | false | {"Kotlin": 38641, "Swift": 17862, "C++": 3314, "CMake": 1613} | package com.jedparsons.metronome.storage
import android.content.SharedPreferences
import com.jedparsons.metronome.model.RhythmModel
import com.jedparsons.metronome.model.RhythmModel.Companion.DEFAULT_BPM
import com.jedparsons.metronome.model.RhythmModel.Companion.DEFAULT_DIVISIONS
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
/**
* [RhythmStore] backed by shared prefs.
*/
class SharedPrefsRhythmStore(
private val sharedPrefs: SharedPreferences,
private val context: CoroutineContext = Dispatchers.IO
) : RhythmStore {
companion object {
const val BPM_KEY = "bpm"
const val DIV_KEY = "div"
}
override suspend fun save(rhythmModel: RhythmModel) {
withContext(context) {
check(rhythmModel.divisions.isNotEmpty()) { "Divisions cannot be empty" }
check(rhythmModel.bpm > 0) { "BPM cannot be negative" }
with(sharedPrefs.edit()) {
putInt(BPM_KEY, rhythmModel.bpm)
putString(DIV_KEY, rhythmModel.divisions.joinToString(","))
commit()
}
}
}
override suspend fun load(): RhythmModel {
return withContext(context) {
RhythmModel(
bpm = sharedPrefs.getInt(
BPM_KEY, DEFAULT_BPM
),
divisions = deserializeDivisions(
sharedPrefs.getString(
DIV_KEY, serializeDivisions(DEFAULT_DIVISIONS)
)
)
)
}
}
private fun serializeDivisions(divisions: List<Int>): String {
return divisions.joinToString(",")
}
private fun deserializeDivisions(serialized: String?): List<Int> {
return serialized
?.split(",")
?.map { s -> s.toInt() }
?.toList()
?: DEFAULT_DIVISIONS
}
}
| 0 | Kotlin | 0 | 0 | 7def45961f3597bb55584f67043b69ea8bc798e6 | 1,742 | asymmetronome | MIT License |
build.gradle.kts | 770grappenmaker | 705,037,045 | false | {"Kotlin": 58766} | import org.jetbrains.dokka.gradle.DokkaTask
plugins {
kotlin("jvm")
id("org.jetbrains.dokka")
`maven-publish`
`java-library`
signing
}
repositories {
mavenCentral()
}
group = "com.grappenmaker"
version = "0.1.2"
kotlin {
jvmToolchain(8)
explicitApi()
}
val dokkaHtml by tasks.getting(DokkaTask::class)
val dokkaAsJavadoc by tasks.registering(Jar::class) {
dependsOn(dokkaHtml)
from(dokkaHtml.outputDirectory)
archiveClassifier.set("javadoc")
}
java {
withSourcesJar()
}
dependencies {
api("org.ow2.asm:asm:9.6")
api("org.ow2.asm:asm-commons:9.6")
}
publishing {
publications {
fun MavenPublication.setup() {
artifact(dokkaAsJavadoc)
from(components["java"])
pom {
name = project.name
description = "A library for handling and using JVM name mappings (SRG, Tiny, Proguard)"
url = "https://github.com/770grappenmaker/mappings-util"
packaging = "jar"
licenses {
license {
name = "The MIT License"
url = "https://opensource.org/license/mit/"
distribution = "repo"
}
}
developers {
developer {
id = "770grappenmaker"
name = "NotEvenJoking"
email = "<EMAIL>"
url = "https://github.com/770grappenmaker/"
}
}
scm {
connection = "scm:git:git://github.com/770grappenmaker/mappings-util.git"
developerConnection = "scm:git:ssh://github.com:770grappenmaker/mappings-util.git"
url = "https://github.com/770grappenmaker/mappings-util/tree/main"
}
}
}
create<MavenPublication>("central") {
groupId = "io.github.770grappenmaker"
setup()
}
create<MavenPublication>("packages", MavenPublication::setup)
}
repositories {
maven {
name = "Packages"
url = uri("https://maven.pkg.github.com/770grappenmaker/mappings-util")
credentials {
username = System.getenv("GITHUB_ACTOR")
password = System.getenv("GITHUB_TOKEN")
}
}
maven {
name = "Central"
url = uri("https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/")
credentials(PasswordCredentials::class)
}
}
}
signing {
sign(publishing.publications)
} | 0 | Kotlin | 2 | 5 | 641842ce6dce1f20253cac710482464d015f779f | 2,730 | mappings-util | MIT License |
commonLib/src/main/java/com/itskylin/common/lib/view/PointoutLineView.kt | BlueSky15171 | 148,615,849 | false | {"Java": 206860, "Kotlin": 46757} | package com.itskylin.common.lib.view
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.itskylin.common.lib.R
/**
* @author <NAME>
* @version V1.0
* @Package CommonLib/com.konying.commonlib.view
* @Description:
* @email <EMAIL>
* @date 2018/7/5 11:06
*/
class PointoutLineView : View {
private var mWidth: Int = 0
private var mHeight: Int = 0
private var lineColor: Int = 0
private var lineWidth: Float = 0f
private lateinit var linePaint: Paint
//padding
private var leftPadding: Int = 0
private var topPadding: Int = 0
private var rightPadding: Int = 0
private var bottomPadding: Int = 0
//set style
private var styleInt: Int = 0
var isShowleft: Boolean = false
var isShowTop: Boolean = false
var isShowRight: Boolean = false
var isShowBottom: Boolean = false
enum class Style {
TOP, MIDDLE, BOTTOM
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
if (attrs != null) {
@SuppressLint("Recycle") val typedArray = context.obtainStyledAttributes(attrs, R.styleable.PointoutLineView)
lineColor = typedArray.getColor(R.styleable.PointoutLineView_lineColor, DEFAULT_COLOR)
lineWidth = typedArray.getDimension(R.styleable.PointoutLineView_lineWidth, DEFAULT_LINE_WIDTH)
styleInt = typedArray.getInt(R.styleable.PointoutLineView_showStyle, 2)
style
}
linePaint = Paint()
linePaint.color = lineColor
linePaint.strokeWidth = lineWidth
linePaint.isAntiAlias = true
linePaint.strokeCap = Paint.Cap.BUTT
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
mWidth = w
mHeight = h
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
this.leftPadding = left
this.topPadding = top
this.rightPadding = right
this.bottomPadding = bottom
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
//top
if (isShowTop) canvas.drawLine((mWidth / 2).toFloat(), top.toFloat(), (mWidth / 2).toFloat(), (mHeight / 2).toFloat(), linePaint)//red
// canvas.drawLine(mWidth / 2, getTop(), mWidth / 2, mHeight / 2, linePaintTop);//red
//bottom
if (isShowBottom) canvas.drawLine((mWidth / 2).toFloat(), (mHeight / 2).toFloat(), (mWidth / 2).toFloat(), mHeight.toFloat(), linePaint)//
// canvas.drawLine(mWidth / 2, mHeight / 2, mWidth / 2, mHeight, linePaintBottom);//
//leftPadding
if (isShowleft) canvas.drawLine(leftPadding.toFloat(), (mHeight / 2).toFloat(), (mWidth / 2).toFloat(), (mHeight / 2).toFloat(), linePaint)
// canvas.drawLine(leftPadding, mHeight / 2, mWidth / 2, mHeight / 2, linePaintLeft);
//right
if (isShowRight) canvas.drawLine((mWidth / 2).toFloat(), (mHeight / 2).toFloat(), mWidth.toFloat(), (mHeight / 2).toFloat(), linePaint)
// canvas.drawLine(mWidth / 2, mHeight / 2, mWidth, mHeight / 2, linePaintRight);
}
var style: Style? = null
get() = field
set(value) = when (value) {
PointoutLineView.Style.TOP -> {
field = value
isShowleft = false
isShowTop = false
isShowRight = true
isShowBottom = true
}
PointoutLineView.Style.BOTTOM -> {
field = value
isShowleft = false
isShowTop = true
isShowRight = true
isShowBottom = false
}
PointoutLineView.Style.MIDDLE -> {
field = value
isShowleft = false
isShowTop = true
isShowRight = true
isShowBottom = true
}
else -> {
field = value
isShowleft = false
isShowTop = true
isShowRight = true
isShowBottom = true
}
}
companion object {
private val DEFAULT_SHOW = true
private val DEFAULT_COLOR = Color.BLACK
private val DEFAULT_LINE_WIDTH = 2f
}
}
| 0 | Java | 0 | 0 | 62267a64cb64c0382b975cabc761a8b44db2eda9 | 4,631 | KotlinDemo | MIT License |
library/src/main/java/com/ola/chat/picker/album/model/reposity/MediaDataManager.kt | olaola-chat | 581,383,264 | false | null | package com.ola.chat.picker.album.model.reposity
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.MediaStore
import android.text.TextUtils
import androidx.core.content.ContentResolverCompat
import androidx.core.os.CancellationSignal
import com.ola.chat.picker.album.model.MediaData
import com.ola.chat.picker.album.model.MediaType
class MediaDataManager {
fun loadAllData(context: Context): List<MediaData> {
val resultList = mutableListOf<MediaData>()
loadImage(context)?.apply {
val imageList = loadCursor(this, MediaType.TYPE_IMAGE)
resultList.addAll(imageList)
}
loadVideo(context)?.apply {
val videoList = loadCursor(this, MediaType.TYPE_VIDEO)
resultList.addAll(videoList)
}
return resultList
}
private fun loadCursor(cursor: Cursor, mediaType: MediaType): List<MediaData> = cursor.run {
val resultList = mutableListOf<MediaData>()
val idIndex = getColumnIndex(MediaStore.MediaColumns._ID)
val pathIndex = getColumnIndex(MediaStore.MediaColumns.DATA)
val mimeTypeIndex = getColumnIndex(MediaStore.MediaColumns.MIME_TYPE)
val sizeIndex = getColumnIndex(MediaStore.MediaColumns.SIZE)
val dateAddIndex = getColumnIndex(MediaStore.MediaColumns.DATE_ADDED)
val dateModifiedIndex = getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED)
val widthIndex = getColumnIndex(MediaStore.MediaColumns.WIDTH)
val heightIndex = getColumnIndex(MediaStore.MediaColumns.HEIGHT)
val durationIndex = getColumnIndex(MediaStore.Video.Media.DURATION)
if (idIndex == -1 || mimeTypeIndex == -1) {
// 必要字段
emptyList()
} else {
while (cursor.moveToNext()) {
val id = getInt(idIndex)
val path = getString(pathIndex)
val mimeType = getMiMeType(getString(mimeTypeIndex), mediaType)
val size = getLong(sizeIndex)
val displayName = id.toString()
val dateAdd = getLong(dateAddIndex)
val dateModify = getLong(dateModifiedIndex)
val width = getInt(widthIndex)
val height = getInt(heightIndex)
val duration = if (durationIndex == -1) 0 else getLong(durationIndex)
// val orientation = getInt(orientationIndex)
val uri = ContentUris.withAppendedId(
when (mediaType) {
MediaType.TYPE_IMAGE -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
MediaType.TYPE_VIDEO -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
},
id.toLong()
)
resultList.add(
MediaData(
mimeType = mimeType,
path = path,
uri = uri,
dateAdd = dateAdd,
dateModify = dateModify,
displayName = displayName,
width = width,
height = height,
duration = duration,
orientation = 0,
size = size
)
)
}
cursor.close()
resultList
}
}
private fun getMiMeType(mimeType: String?, mediaType: MediaType): String {
return when {
!TextUtils.isEmpty(mimeType) -> mimeType!!
mediaType == MediaType.TYPE_IMAGE -> "image/*"
mediaType == MediaType.TYPE_VIDEO -> "video/*"
else -> "*/*"
}
}
private fun loadImage(context: Context): Cursor? {
var mimeTypeSelection = ""
val mimeTypeSelectionArgs = arrayOf(
"image/jpeg",
"image/jpg",
"image/png",
"image/gif",
"image/webp"
)
for (i in 0 until mimeTypeSelectionArgs.size - 1) {
mimeTypeSelection += MediaStore.Images.Media.MIME_TYPE + "=? or "
}
mimeTypeSelection += MediaStore.Images.Media.MIME_TYPE + "=?"
return query(
context,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection = arrayOf(
MediaStore.MediaColumns._ID,
MediaStore.MediaColumns.DATA,
MediaStore.MediaColumns.MIME_TYPE,
MediaStore.MediaColumns.SIZE,
MediaStore.MediaColumns.DATE_ADDED,
MediaStore.MediaColumns.DATE_MODIFIED,
MediaStore.MediaColumns.WIDTH,
MediaStore.MediaColumns.HEIGHT
// MediaStore.MediaColumns.ORIENTATION
),
selection = mimeTypeSelection,
selectionArgs = mimeTypeSelectionArgs
)
}
private fun loadVideo(context: Context): Cursor? {
return query(
context,
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
arrayOf(
MediaStore.MediaColumns._ID,
MediaStore.MediaColumns.DATA,
MediaStore.MediaColumns.MIME_TYPE,
MediaStore.MediaColumns.SIZE,
MediaStore.MediaColumns.DATE_ADDED,
MediaStore.MediaColumns.DATE_MODIFIED,
MediaStore.MediaColumns.WIDTH,
MediaStore.MediaColumns.HEIGHT,
MediaStore.Video.Media.DURATION
// MediaStore.MediaColumns.ORIENTATION
)
)
}
private fun query(
context: Context,
uri: Uri,
projection: Array<String> = arrayOf(
MediaStore.MediaColumns._ID,
MediaStore.MediaColumns.DATA,
MediaStore.MediaColumns.MIME_TYPE,
MediaStore.MediaColumns.SIZE,
MediaStore.MediaColumns.DATE_ADDED,
MediaStore.MediaColumns.DATE_MODIFIED,
MediaStore.MediaColumns.WIDTH,
MediaStore.MediaColumns.HEIGHT
// MediaStore.MediaColumns.ORIENTATION
),
selection: String? = null,
selectionArgs: Array<String>? = null,
sortOrder: String? = "${MediaStore.MediaColumns.DATE_MODIFIED} DESC",
cancelSignal: CancellationSignal? = null
): Cursor? {
return ContentResolverCompat.query(
context.contentResolver,
uri,
projection,
selection,
selectionArgs,
sortOrder,
cancelSignal
)
}
} | 1 | Kotlin | 0 | 0 | f22dc84cfca4d594f5cbb0482d0a0b2b3cfad9ee | 6,705 | image_picker_adr | Apache License 2.0 |
flowbinding-viewpager2/src/main/java/reactivecircus/flowbinding/viewpager2/ViewPager2PageScrolledFlow.kt | ReactiveCircus | 201,777,295 | false | null | @file:Suppress("MatchingDeclarationName")
package reactivecircus.flowbinding.viewpager2
import androidx.annotation.CheckResult
import androidx.viewpager2.widget.ViewPager2
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import reactivecircus.flowbinding.common.checkMainThread
/**
* Create a [Flow] of page scroll events on the [ViewPager2] instance.
*
* Note: Created flow keeps a strong reference to the [ViewPager2] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* viewPager2.pageScrollEvents()
* .onEach { event ->
* // handle page scroll event
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun ViewPager2.pageScrollEvents(): Flow<ViewPager2PageScrollEvent> = callbackFlow {
checkMainThread()
val callback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
trySend(
ViewPager2PageScrollEvent(
view = this@pageScrollEvents,
position = position,
positionOffset = positionOffset,
positionOffsetPixel = positionOffsetPixels
)
)
}
}
registerOnPageChangeCallback(callback)
awaitClose { unregisterOnPageChangeCallback(callback) }
}.conflate()
public data class ViewPager2PageScrollEvent(
public val view: ViewPager2,
public val position: Int,
public val positionOffset: Float,
public val positionOffsetPixel: Int
)
| 6 | Kotlin | 43 | 894 | 25e5b9723211d37c3cb36daae8649cc1d603691a | 1,857 | FlowBinding | Apache License 2.0 |
ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/catalog/SCMCatalogACL.kt | nemerosa | 19,351,480 | false | {"Kotlin": 8298680, "JavaScript": 2587834, "Java": 1129286, "HTML": 505573, "Groovy": 377453, "CSS": 137378, "Less": 35164, "Dockerfile": 6298, "Shell": 5086} | package net.nemerosa.ontrack.extension.scm.catalog
import net.nemerosa.ontrack.model.security.GlobalFunction
import net.nemerosa.ontrack.model.security.RoleContributor
import net.nemerosa.ontrack.model.security.Roles
import org.springframework.stereotype.Component
/**
* Function needed to access the SCM catalog
*/
interface SCMCatalogAccessFunction : GlobalFunction
/**
* Grants the [SCMCatalogAccessFunction] to all global roles
*/
@Component
class SCMCatalogACL : RoleContributor {
override fun getGlobalFunctionContributionsForGlobalRoles(): Map<String, List<Class<out GlobalFunction>>> =
Roles.GLOBAL_ROLES.associateWith {
listOf(SCMCatalogAccessFunction::class.java)
}
} | 39 | Kotlin | 26 | 94 | c3cd484b681647bf68e43fa76a0bd4fccacf2972 | 730 | ontrack | MIT License |
feature_castdetail/src/main/java/com/andtv/flicknplay/castdetail/data/remote/api/CastFlicknplayApi.kt | procoder1128 | 553,094,605 | false | null |
package com.andtv.flicknplay.castdetail.data.remote.api
import com.andtv.flicknplay.model.data.remote.*
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Path
/**
*
*/
interface CastFlicknplayApi {
@GET("people/{id}")
fun getCastDetails(
@Path("id") id: Int
): Single<CastResponseWrapper>
fun getMovieCredits(castId: Int): Single<CastResponseWrapper>
fun getTvShowCredits(castId: Int): Any
}
| 0 | Kotlin | 1 | 4 | 45d661d6b872c13b6a1235bbb9a44c91740d3f9d | 457 | blockchain | Apache License 2.0 |
codegen-server/src/main/kotlin/software/amazon/smithy/rust/codegen/server/smithy/protocols/ServerRustXml.kt | mchoicpe-amazon | 452,059,744 | true | {"Rust": 1858816, "Kotlin": 1202855, "Python": 26959, "TypeScript": 18127, "Shell": 9467, "JavaScript": 1244} | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
package software.amazon.smithy.rust.codegen.server.smithy.protocols
import software.amazon.smithy.aws.traits.protocols.RestXmlTrait
import software.amazon.smithy.model.Model
import software.amazon.smithy.model.shapes.OperationShape
import software.amazon.smithy.model.traits.TimestampFormatTrait
import software.amazon.smithy.rust.codegen.rustlang.CargoDependency
import software.amazon.smithy.rust.codegen.rustlang.RustModule
import software.amazon.smithy.rust.codegen.rustlang.asType
import software.amazon.smithy.rust.codegen.rustlang.rust
import software.amazon.smithy.rust.codegen.rustlang.rustBlockTemplate
import software.amazon.smithy.rust.codegen.smithy.CodegenContext
import software.amazon.smithy.rust.codegen.smithy.RuntimeType
import software.amazon.smithy.rust.codegen.smithy.generators.protocol.ProtocolSupport
import software.amazon.smithy.rust.codegen.smithy.protocols.HttpBindingResolver
import software.amazon.smithy.rust.codegen.smithy.protocols.HttpTraitHttpBindingResolver
import software.amazon.smithy.rust.codegen.smithy.protocols.Protocol
import software.amazon.smithy.rust.codegen.smithy.protocols.ProtocolContentTypes
import software.amazon.smithy.rust.codegen.smithy.protocols.ProtocolGeneratorFactory
import software.amazon.smithy.rust.codegen.smithy.protocols.parse.RestXmlParserGenerator
import software.amazon.smithy.rust.codegen.smithy.protocols.parse.StructuredDataParserGenerator
import software.amazon.smithy.rust.codegen.smithy.protocols.serialize.StructuredDataSerializerGenerator
import software.amazon.smithy.rust.codegen.smithy.protocols.serialize.XmlBindingTraitSerializerGenerator
import software.amazon.smithy.rust.codegen.util.expectTrait
class ServerRestXmlFactory(private val generator: (CodegenContext) -> Protocol = { ServerRestXml(it) }) :
ProtocolGeneratorFactory<ServerHttpProtocolGenerator> {
override fun protocol(codegenContext: CodegenContext): Protocol = generator(codegenContext)
override fun buildProtocolGenerator(codegenContext: CodegenContext): ServerHttpProtocolGenerator =
ServerHttpProtocolGenerator(codegenContext, ServerRestXml(codegenContext))
override fun transformModel(model: Model): Model = model
override fun support(): ProtocolSupport {
return ProtocolSupport(
/* Client support */
requestSerialization = false,
requestBodySerialization = false,
responseDeserialization = false,
errorDeserialization = false,
/* Server support */
requestDeserialization = true,
requestBodyDeserialization = true,
responseSerialization = true,
errorSerialization = true
)
}
}
open class ServerRestXml(private val codegenContext: CodegenContext) : Protocol {
private val restXml = codegenContext.serviceShape.expectTrait<RestXmlTrait>()
private val runtimeConfig = codegenContext.runtimeConfig
private val errorScope = arrayOf(
"Bytes" to RuntimeType.Bytes,
"Error" to RuntimeType.GenericError(runtimeConfig),
"HeaderMap" to RuntimeType.http.member("HeaderMap"),
"Response" to RuntimeType.http.member("Response"),
"XmlError" to CargoDependency.smithyXml(runtimeConfig).asType().member("decode::XmlError")
)
private val xmlDeserModule = RustModule.private("xml_deser")
protected val restXmlErrors: RuntimeType = when (restXml.isNoErrorWrapping) {
true -> RuntimeType.unwrappedXmlErrors(runtimeConfig)
false -> RuntimeType.wrappedXmlErrors(runtimeConfig)
}
override val httpBindingResolver: HttpBindingResolver =
HttpTraitHttpBindingResolver(codegenContext.model, ProtocolContentTypes.consistent("application/xml"))
override val defaultTimestampFormat: TimestampFormatTrait.Format =
TimestampFormatTrait.Format.DATE_TIME
override fun structuredDataParser(operationShape: OperationShape): StructuredDataParserGenerator {
return RestXmlParserGenerator(codegenContext, restXmlErrors)
}
override fun structuredDataSerializer(operationShape: OperationShape): StructuredDataSerializerGenerator {
return XmlBindingTraitSerializerGenerator(codegenContext, httpBindingResolver)
}
override fun parseHttpGenericError(operationShape: OperationShape): RuntimeType =
RuntimeType.forInlineFun("parse_http_generic_error", xmlDeserModule) { writer ->
writer.rustBlockTemplate(
"pub fn parse_http_generic_error(response: &#{Response}<#{Bytes}>) -> Result<#{Error}, #{XmlError}>",
*errorScope
) {
rust("#T::parse_generic_error(response.body().as_ref())", restXmlErrors)
}
}
override fun parseEventStreamGenericError(operationShape: OperationShape): RuntimeType =
RuntimeType.forInlineFun("parse_event_stream_generic_error", xmlDeserModule) { writer ->
writer.rustBlockTemplate(
"pub fn parse_event_stream_generic_error(payload: &#{Bytes}) -> Result<#{Error}, #{XmlError}>",
*errorScope
) {
rust("#T::parse_generic_error(payload.as_ref())", restXmlErrors)
}
}
}
| 0 | Rust | 0 | 0 | bee5b1134fa146d1f0f20b94942ba2f74139a5cf | 5,342 | smithy-rs | Apache License 2.0 |
app/src/main/java/com/example/getpethelp/ui/tasks/TaskInfoFragment.kt | Mike-Like11 | 387,766,743 | false | null | package com.example.getpethelp.ui.tasks
import android.app.AlertDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageButton
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.findFragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.getpethelp.R
import com.example.getpethelp.models.CommentInfo
import com.example.getpethelp.models.TaskInfo
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.button.MaterialButton
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ValueEventListener
import com.google.firebase.database.ktx.database
import com.google.firebase.database.ktx.getValue
import com.google.firebase.ktx.Firebase
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [TaskInfoFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class TaskInfoFragment : Fragment() {
// TODO: Rename and change types of parameters
private lateinit var task:TaskInfo
private lateinit var quitButton: MaterialButton
private lateinit var executeButton: MaterialButton
private lateinit var name_task_info: TextView
private lateinit var desc_task_info:TextView
private lateinit var time_task_info:TextView
private lateinit var user_task_info:TextView
private lateinit var edit_comment_task:EditText
private lateinit var send_comment:ImageButton
private lateinit var destination_task_info:TextView
private var columnCount = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
task = it.getSerializable("task") as TaskInfo
columnCount = it.getInt(TaskFragment.ARG_COLUMN_COUNT)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_task_info, container, false)
quitButton = view.findViewById(R.id.quit_button_task)
executeButton = view.findViewById(R.id.perform_button_task)
name_task_info = view.findViewById(R.id.name_task_info)
name_task_info.text = task.name
desc_task_info = view.findViewById(R.id.desc_task_info)
desc_task_info.text = task.desc
time_task_info = view.findViewById(R.id.time_task_info)
time_task_info.text = task.date.toLocaleString()
user_task_info = view.findViewById(R.id.user_task_info)
user_task_info.text = task.user_name
edit_comment_task = view.findViewById(R.id.edit_comment_task)
send_comment = view.findViewById(R.id.send_comment)
destination_task_info = view.findViewById(R.id.destination_task_info)
if (task.address == null)
destination_task_info.text = ""
else
destination_task_info.text = task.address
destination_task_info.setOnClickListener {
//
val taskinfo = MapDialogFragment()
val bundle = Bundle()
bundle.putSerializable("address",task.address)
taskinfo.arguments = bundle
taskinfo.show(activity?.supportFragmentManager!!, null);
}
val listik = view.findViewById(R.id.list2) as RecyclerView
if (true) {
with(listik ) {
layoutManager = when {
columnCount <= 1 -> LinearLayoutManager(context)
else -> GridLayoutManager(context, columnCount)
}
val my_items = ArrayList<CommentInfo>()
Firebase.database.reference.child("tasks").child(task.id.toString()).child("comments").addValueEventListener(object:
ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
my_items.clear()
for (ds: DataSnapshot in snapshot.children){
my_items.add(ds.getValue<CommentInfo>() as CommentInfo)
}
adapter = CommentsRecyclerViewAdapter(my_items)
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
send_comment.setOnClickListener {
task.comments.add(CommentInfo(edit_comment_task.text.toString(),
FirebaseAuth.getInstance().currentUser?.displayName!!
))
Firebase.database.reference.child("tasks").child(task.id.toString()).child("comments").setValue(task.comments)
}
executeButton.setOnClickListener {
Firebase.database.reference.child("users").addValueEventListener(object:
ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for (ds: DataSnapshot in snapshot.children){
if(FirebaseAuth.getInstance().currentUser?.uid.equals(ds.key)){
task.user_name_executor = ds.child("name").getValue(String::class.java)
Firebase.database.reference.child("tasks").child(task.id.toString()).child("user_name_executor").setValue(task.user_name_executor);
val bnv: BottomNavigationView = requireActivity().findViewById(R.id.bottom_navigation_my_tasks)
bnv.visibility = View.VISIBLE
requireActivity().supportFragmentManager
.beginTransaction()
.replace(R.id.const_list,
TaskFragment()
)
.commit()
}
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
quitButton.setOnClickListener {
val bnv: BottomNavigationView = requireActivity().findViewById(R.id.bottom_navigation_my_tasks)
bnv.visibility = View.VISIBLE
requireActivity().supportFragmentManager
.beginTransaction()
.replace(R.id.fragment_container, TasksFragment())
.commit()
}
return view
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment TaskInfoFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(task:TaskInfo) =
TaskInfoFragment().apply {
arguments = Bundle().apply {
putSerializable("task",task)
}
}
}
} | 0 | Kotlin | 0 | 0 | 3372f036df001b97b6e83ea37c3ede7b03504f92 | 7,952 | Get-Pet-Help-Android-version | MIT License |
app/src/main/java/com/example/jobsity/main_screen/delegates/ShowDelegate.kt | ispam | 531,694,937 | false | {"Kotlin": 51150} | package com.example.jobsity.main_screen.delegates
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.text.HtmlCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.example.jobsity.common.delegate.DelegateAdapter
import com.example.jobsity.data.local.entities.ShowItem
import com.example.jobsity.databinding.DelegateShowBinding
import com.squareup.picasso.Picasso
class ShowDelegate(
private val onClick: ((ShowItem) -> Unit)?
) : DelegateAdapter<ShowDelegate.ViewHolder, ShowItem> {
override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder {
return ViewHolder(
DelegateShowBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(viewHolder: ViewHolder, item: ShowItem) {
viewHolder.bind(item)
}
inner class ViewHolder(
private val binding: DelegateShowBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(item: ShowItem) {
with(binding) {
root.setOnClickListener {
onClick?.invoke(item)
}
Picasso.get().load(item.image.medium).into(showImg)
showName.text = item.name
showGenres.text = item.genres.toString()
showPremiered.text = "Premiered ${item.premiered}"
showSummary.isVisible = item.showSummary
showSummary.text = HtmlCompat.fromHtml(item.summary, HtmlCompat.FROM_HTML_MODE_LEGACY)
}
}
}
} | 0 | Kotlin | 0 | 0 | df072255f1e62b37258117edae7388df60d9a2e0 | 1,683 | jobsity | Apache License 2.0 |
src/main/kotlin/xyz/ludoviko/vido/protokolo/FileSignature.kt | Lucxjo | 369,267,096 | false | null | package xyz.ludoviko.vido.protokolo
import kotlinx.serialization.Serializable
@Serializable
data class FileSignature(val signature: String, val filename: String) | 0 | Kotlin | 0 | 0 | 38a0593a5d45b36bea4938fd4253c9ed6d376127 | 163 | vido-protokolo | MIT License |
home/src/main/java/com/pabloangeles/hackernewsapp/home/data/models/ListNewHitsModel.kt | PabloJair | 551,790,924 | false | {"Kotlin": 68936} | package com.pabloangeles.hackernewsapp.home.data.models
import com.google.gson.annotations.SerializedName
data class ListNewHitsModel(
@SerializedName("exhaustiveNbHits") val exhaustiveNbHits: Boolean,
@SerializedName("exhaustiveTypo") val exhaustiveTypo: Boolean,
@SerializedName("hits") val hits: java.util.ArrayList<Hit>,
@SerializedName("hitsPerPage") val hitsPerPage: Int,
@SerializedName("nbHits") val nbHits: Int,
@SerializedName("nbPages") val nbPages: Int,
@SerializedName("page") val page: Int,
@SerializedName("params") val params: String,
@SerializedName("processingTimeMS") val processingTimeMS: Int,
@SerializedName("query") val query: String
)
data class Hit(
@SerializedName("author") val author: String,
@SerializedName("comment_text") val commentText: String? = "",
@SerializedName("created_at") val createdAt: String? = "",
@SerializedName("created_at_i") val createdAtI: Int,
@SerializedName("num_comments") val numComments: Int?,
@SerializedName("objectID") val objectID: Long,
@SerializedName("parent_id") val parentId: Int,
@SerializedName("points") val points: Int?,
@SerializedName("story_id") val storyId: Long?,
@SerializedName("story_text") val storyText: String?,
@SerializedName("story_title") val storyTitle: String?,
@SerializedName("story_url") val storyUrl: String?,
@SerializedName("_tags") val tags: List<String>,
@SerializedName("title") val title: String?,
@SerializedName("url") val url: String?
)
| 0 | Kotlin | 0 | 0 | a88fc09a8d5c8cbea13e598c2c75513a95533678 | 1,540 | hacks_news-demo | MIT License |
preview/src/main/kotlin/com/timemates/app/preview/feature/common/TestPreview.kt | timemates | 575,537,317 | false | {"Kotlin": 345380} | package com.timemates.app.preview.feature.common
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
@Composable
fun Something() {
Text("Hello World")
}
@Preview(showBackground = true)
@Composable
fun PreviewSomething() {
Something()
} | 20 | Kotlin | 0 | 22 | 9ac818cd982773efc399fe8149a1b4a0f631c554 | 327 | app | MIT License |
logging/src/commonMain/kotlin/org/lighthousegames/logging/LogFactory.kt | LighthouseGames | 332,284,926 | false | {"Kotlin": 34392} | package org.lighthousegames.logging
interface LogFactory {
fun createKmLog(tag: String, className: String): KmLog
} | 7 | Kotlin | 9 | 43 | 14fb6e483bbf8ba8b6675cdf15bd1d2ffd9bcd3c | 120 | KmLogging | Apache License 2.0 |
src/com/theah64/mock_api/servlets/GenReduxDuckServlet.kt | theapache64 | 91,213,451 | false | {"Java": 246193, "Kotlin": 171960, "JavaScript": 14154, "CSS": 3391} | package com.theah64.mock_api.servlets
import com.theah64.mock_api.database.Routes
import com.theah64.mock_api.utils.CodeGenJava
import com.theah64.webengine.utils.PathInfo
import com.theah64.webengine.utils.Request
import org.json.JSONException
import javax.servlet.annotation.WebServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.io.IOException
import java.sql.SQLException
/**
* Created by theapache64 on 28/11/17.
*/
@WebServlet(urlPatterns = ["/v1/gen_redux_duck"])
class GenReduxDuckServlet : AdvancedBaseServlet() {
override val isSecureServlet: Boolean
get() = false
@Throws(javax.servlet.ServletException::class, IOException::class)
override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
doPost(req, resp)
}
override val requiredParameters: Array<String>?
get() = arrayOf(KEY_PROJECT_NAME, Routes.COLUMN_NAME)
@Throws(IOException::class, JSONException::class, SQLException::class, Request.RequestException::class, PathInfo.PathInfoException::class)
override fun doAdvancedPost() {
val projectName = getStringParameter(KEY_PROJECT_NAME)!!
val routeName = getStringParameter(Routes.COLUMN_NAME)!!
val responseClass = CodeGenJava.getFirstCharUppercase(CodeGenJava.toCamelCase(routeName)) + "Response"
val route = Routes.instance.get(projectName, routeName)
if (route != null) {
httpServletResponse!!.contentType = "text/plain"
val codeBuilder = StringBuilder()
//Adding main constant
val ROUTE_NAME = getFormattedRouteNameWithCaps(routeName)
codeBuilder.append("\n// Keyword")
codeBuilder.append(String.format("\nconst %s = '%s';\n", ROUTE_NAME, ROUTE_NAME))
// Response class name
val responseClassName = getResponseClassNameFromRoute(routeName)
//Reducer
val reducerName = getReducerNameRouteName(routeName)
codeBuilder.append(String.format("\nexport const %s = \n (state : NetworkResponse<%s>, action : BaseAction) => \n ResponseManager.manage(%s, state, action);\n\n", reducerName, responseClassName, ROUTE_NAME))
// Params
codeBuilder.append("// Params\nexport class Params {\n constructor(\n")
for (param in route.params!!) {
codeBuilder.append(" public readonly ").append(param.name)
.append(String.format("%s: ", if (param.isRequired) "" else "?")).append(getPrimitive(param.dataType))
.append(",\n")
}
codeBuilder.append(" ) { }\n}")
codeBuilder.append("\n\n")
//Action
val actionName = getActionNameFromRouteName(routeName)
codeBuilder.append(String.format("// Action \nexport const %s = (", actionName))
//Looping through params
if (route.isSecure) {
codeBuilder.append("\n@Header(KEY_AUTHORIZATION) String apiKey,")
}
val hasFileParam = false
if (!route.params.isEmpty()) {
codeBuilder.append("\n\tparams : Params")
}
codeBuilder.append(String.format("%s): AxiosRequest => new AxiosRequest(", if (route.params.isEmpty()) "" else "\n"))
.append(String.format("\n\t%s,", ROUTE_NAME))
.append(String.format("\n\t'%s',", route.method))
.append(String.format("\n\t'/%s',\n", route.name))
if (!route.params.isEmpty()) {
codeBuilder.append("\tparams\n")
}
if (hasFileParam) {
val index = codeBuilder.indexOf("@" + route.method)
codeBuilder.insert(index, "@Multipart\n")
}
codeBuilder.append(");\n")
writer!!.write(codeBuilder.toString())
} else {
throw Request.RequestException("Invalid route")
}
}
private fun getFormattedRouteNameWithCaps(routeName: String): String {
return routeName
.replace("([a-zA-Z][a-z]*)([A-Z])".toRegex(), "$1_$2")
.toUpperCase()
.replace("[\\W+]".toRegex(), "_")
}
private fun getPrimitive(dataType: String): String {
if (dataType == "Integer") {
return "number"
}
return if (dataType != "string") {
dataType.toLowerCase()
} else dataType
}
companion object {
private val KEY_PROJECT_NAME = "project_name"
private const val MULTIPART_KEY = "@Part MultipartBody.Part"
private fun getActionNameFromRouteName(routeName: String): String {
var routeName = routeName
routeName = routeName.replace("[^\\w]+".toRegex(), "_")
return CodeGenJava.toCamelCase(routeName)
}
private fun getResponseClassNameFromRoute(routeName: String): String {
var routeName = routeName
routeName = routeName.replace("[^\\w]+".toRegex(), "_")
return CodeGenJava.getFirstCharUppercase(CodeGenJava.toCamelCase(routeName)) + "Response"
}
private fun getReducerNameRouteName(routeName: String): String {
var routeName = routeName
routeName = routeName.replace("[^\\w]+".toRegex(), "_")
return CodeGenJava.toCamelCase(routeName) + "Reducer"
}
}
}
| 5 | Java | 0 | 1 | f19a9e650a6641ccd59192c176fbbc8eb51cf473 | 5,518 | Mock-API | Apache License 2.0 |
domain-android-overlay/src/main/java/com/kotlinbyte/domain_android_overlay/usecase/SignInViaGoogle.kt | AliAzizi | 430,624,753 | false | {"Kotlin": 65698} | package com.kotlinbyte.domain_android_overlay.usecase
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.tasks.Task
import com.kotlinbyte.domain.interactor.UseCase
import com.kotlinbyte.domain.vobject.AuthResult
import com.kotlinbyte.domain_android_overlay.repository.SignInRepositoryFramework
import dagger.hilt.android.scopes.FragmentScoped
import javax.inject.Inject
@FragmentScoped
class SignInViaGoogle @Inject constructor(private val repository: SignInRepositoryFramework) :
UseCase<AuthResult, Task<GoogleSignInAccount>?>() {
override suspend fun run(params: Task<GoogleSignInAccount>?) = repository.signIn(params)
} | 0 | Kotlin | 0 | 0 | 482ac65e2e55b36deba201d2657440d39ad3d1c9 | 679 | MovieHall | MIT License |
eth-testing-endpoints/src/main/kotlin/jp/co/soramitsu/soranet/eth/endpoints/routing/DepostiRouting.kt | soramitsu | 244,327,657 | true | {"Kotlin": 354839, "Java": 294223, "Solidity": 39532, "Shell": 2504, "Groovy": 607, "Dockerfile": 329} | /*
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package jp.co.soramitsu.soranet.eth.endpoints.routing
import com.github.kittinunf.result.Result
import de.nielsfalk.ktor.swagger.created
import de.nielsfalk.ktor.swagger.description
import de.nielsfalk.ktor.swagger.post
import de.nielsfalk.ktor.swagger.responds
import de.nielsfalk.ktor.swagger.version.shared.Group
import io.ktor.application.call
import io.ktor.http.HttpStatusCode
import io.ktor.locations.Location
import io.ktor.response.respond
import io.ktor.routing.Routing
import jp.co.soramitsu.soranet.eth.endpoints.dto.EthDepositRequest
import jp.co.soramitsu.soranet.eth.endpoints.dto.PlainResponse
import jp.co.soramitsu.soranet.eth.sidechain.util.DeployHelper
import mu.KLogging
import java.math.BigInteger
private val logger = KLogging().logger
@Group("eth")
@Location("/eth/deposit")
class DepositLocation
fun Routing.deposit(deployHelper: DeployHelper) {
post<DepositLocation, EthDepositRequest>(
"execute"
.description("Sends ETH to a specified address")
.responds(created<PlainResponse>())
) { _, ethDepositRequest ->
logger.info("Eth deposit invoked with parameters:${ethDepositRequest.address}, ${ethDepositRequest.amount}")
sendEth(deployHelper, ethDepositRequest).fold(
{ call.respond(message = PlainResponse.ok(), status = HttpStatusCode.OK) },
{ ex ->
call.respond(
message = PlainResponse.error(ex),
status = HttpStatusCode.InternalServerError
)
}
)
}
}
private fun sendEth(
deployHelper: DeployHelper,
ethDepositRequest: EthDepositRequest
): Result<String, Exception> {
return Result.of {
deployHelper.sendEthereum(
BigInteger(ethDepositRequest.amount).multiply(BigInteger.valueOf(1000000000000000000)),
ethDepositRequest.address
)
}
}
| 0 | Kotlin | 0 | 2 | 7e595d327ef9061efe8c2459a7bd000310cde082 | 2,000 | soranet-eth | Apache License 2.0 |
PluginsAndFeatures/azure-toolkit-for-intellij/rider/src/org/jetbrains/plugins/azure/functions/buildTasks/BuildFunctionsProjectBeforeRunTaskProvider.kt | JetBrains | 137,064,201 | true | {"Java": 6822615, "Kotlin": 2384238, "C#": 198892, "Scala": 151332, "Gherkin": 108427, "JavaScript": 98350, "HTML": 23518, "CSS": 21770, "Groovy": 21447, "Shell": 21354, "XSLT": 7141, "Dockerfile": 3518, "Batchfile": 2155} | /**
* Copyright (c) 2019-2022 JetBrains s.r.o.
*
* All rights reserved.
*
* MIT License
*
* 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 org.jetbrains.plugins.azure.functions.buildTasks
import com.intellij.execution.BeforeRunTask
import com.intellij.execution.BeforeRunTaskProvider
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.util.Key
import com.jetbrains.rider.build.BuildHost
import com.jetbrains.rider.build.BuildParameters
import com.jetbrains.rider.build.tasks.BuildTaskThrottler
import com.jetbrains.rider.model.BuildTarget
import org.jetbrains.plugins.azure.RiderAzureBundle.message
import org.jetbrains.plugins.azure.functions.run.AzureFunctionsHostConfiguration
import javax.swing.Icon
class BuildFunctionsProjectBeforeRunTask : BeforeRunTask<BuildFunctionsProjectBeforeRunTask>(BuildFunctionsProjectBeforeRunTaskProvider.providerId)
class BuildFunctionsProjectBeforeRunTaskProvider : BeforeRunTaskProvider<BuildFunctionsProjectBeforeRunTask>(){
companion object {
val providerId = Key.create<BuildFunctionsProjectBeforeRunTask>("BuildFunctionsProject")
}
override fun getId(): Key<BuildFunctionsProjectBeforeRunTask>? = providerId
override fun getName(): String? = message("run_config.run_function_app.form.function_app.before_run_tasks.build_function_project_name")
override fun getDescription(task: BuildFunctionsProjectBeforeRunTask): String = message("run_config.run_function_app.form.function_app.before_run_tasks.build_function_project_description")
override fun isConfigurable() = false
override fun getIcon(): Icon = AllIcons.Actions.Compile
private fun shouldCreateBuildBeforeRunTaskByDefault(runConfiguration: RunConfiguration): Boolean {
return runConfiguration is AzureFunctionsHostConfiguration
}
override fun createTask(runConfiguration: RunConfiguration): BuildFunctionsProjectBeforeRunTask? {
if (!shouldCreateBuildBeforeRunTaskByDefault(runConfiguration)) return null
val task = BuildFunctionsProjectBeforeRunTask()
task.isEnabled = true
return task
}
override fun canExecuteTask(configuration: RunConfiguration, task: BuildFunctionsProjectBeforeRunTask): Boolean {
return BuildHost.getInstance(configuration.project).ready.value
}
override fun executeTask(context: DataContext, configuration: RunConfiguration, env: ExecutionEnvironment,
task: BuildFunctionsProjectBeforeRunTask): Boolean {
val project = configuration.project
val buildHost = BuildHost.getInstance(project)
val selectedProjectsForBuild = when (configuration) {
is AzureFunctionsHostConfiguration -> listOf(configuration.parameters.projectFilePath)
else -> emptyList()
}
if (!buildHost.ready.value)
return false
val throttler = BuildTaskThrottler.getInstance(project)
return throttler.buildSequentiallySync(BuildParameters(BuildTarget(), selectedProjectsForBuild)).msBuildStatus
}
}
| 70 | Java | 10 | 41 | 5ffb7e600c2bdac8762461921c6255106b376a5d | 4,252 | azure-tools-for-intellij | MIT License |
feature-account-impl/src/main/java/jp/co/soramitsu/account/impl/presentation/importing/source/view/SeedImportView.kt | soramitsu | 278,060,397 | false | {"Kotlin": 4749089, "Java": 18796} | package jp.co.soramitsu.account.impl.presentation.importing.source.view
import android.content.Context
import android.util.AttributeSet
import androidx.core.view.isVisible
import androidx.lifecycle.LifecycleOwner
import jp.co.soramitsu.account.api.presentation.importing.ImportAccountType
import jp.co.soramitsu.account.impl.presentation.importing.source.model.ImportSource
import jp.co.soramitsu.account.impl.presentation.importing.source.model.RawSeedImportSource
import jp.co.soramitsu.common.utils.bindTo
import jp.co.soramitsu.common.utils.nameInputFilters
import jp.co.soramitsu.common.view.InputField
import jp.co.soramitsu.common.view.shape.getIdleDrawable
import jp.co.soramitsu.feature_account_impl.R
import jp.co.soramitsu.feature_account_impl.databinding.ImportSourceSeedBinding
class SeedImportView @JvmOverloads constructor(
context: Context,
private val isChainAccount: Boolean,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ImportSourceView(R.layout.import_source_seed, context, attrs, defStyleAttr) {
private val binding: ImportSourceSeedBinding = ImportSourceSeedBinding.bind(this)
override val nameInputView: InputField
get() = binding.importSeedUsernameInput
init {
init()
}
constructor(context: Context, type: ImportAccountType, isChainAccount: Boolean) : this(context, isChainAccount) {
init(type)
}
fun init(type: ImportAccountType = ImportAccountType.Substrate) {
binding.importSeedContentContainer.background = context.getIdleDrawable()
binding.importSeedUsernameInput.content.filters = nameInputFilters()
setImportAccountType(type)
binding.importSeedUsernameInput.isVisible = !isChainAccount
binding.usernameHintTv.isVisible = !isChainAccount
}
private fun setImportAccountType(type: ImportAccountType) {
when (type) {
ImportAccountType.Substrate -> binding.importSeedTitle.setText(R.string.account_import_substrate_raw_seed_placeholder)
ImportAccountType.Ethereum -> binding.importSeedTitle.setText(R.string.account_import_ethereum_raw_seed_placeholder)
}
}
override fun observeSource(source: ImportSource, blockchainType: ImportAccountType, lifecycleOwner: LifecycleOwner) {
require(source is RawSeedImportSource)
binding.importSeedContent.bindTo(source.rawSeedLiveData, lifecycleOwner)
}
}
| 16 | Kotlin | 22 | 75 | c8074122fa171223eea6f6d6e434aa1041d1c71f | 2,425 | fearless-Android | Apache License 2.0 |
org.librarysimplified.audiobook.api/src/main/java/org/librarysimplified/audiobook/api/PlayerPositionParserType.kt | NYPL-Simplified | 139,462,999 | false | {"Kotlin": 544969, "Java": 2451} | package org.librarysimplified.audiobook.api
import com.fasterxml.jackson.databind.node.ObjectNode
/**
* A parser of player positions.
*/
interface PlayerPositionParserType {
/**
* Parse a player position from the given JSON object node.
*
* @param node An object node
* @return A parsed player position, or a reason why it couldn't be parsed
*/
fun parseFromObjectNode(node: ObjectNode): PlayerResult<PlayerPosition, Exception>
}
| 1 | Kotlin | 2 | 2 | 6633bcd1006ead70bc2ffd945cacb6b38af8e8e5 | 456 | audiobook-android | Apache License 2.0 |
app/src/main/java/com/azhar/rsbedcovid/view/activities/KotaActivity.kt | AzharRivaldi | 401,559,823 | false | null | package com.azhar.rsbedcovid.view.activities
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.NewInstanceFactory
import androidx.recyclerview.widget.LinearLayoutManager
import com.azhar.rsbedcovid.R
import com.azhar.rsbedcovid.model.kota.ModelKotaResult.ModelKota
import com.azhar.rsbedcovid.utils.Constant
import com.azhar.rsbedcovid.view.adapter.KotaAdapter
import com.azhar.rsbedcovid.viewmodel.PrimaryViewModel
import kotlinx.android.synthetic.main.activity_kota.*
import java.util.*
class KotaActivity : AppCompatActivity() {
lateinit var primaryViewModel: PrimaryViewModel
lateinit var kotaAdapter: KotaAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kota)
setSupportActionBar(toolbar)
assert(supportActionBar != null)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowTitleEnabled(false)
tvTitle.setText(Constant.provinsiName)
linearNoData.setVisibility(View.GONE)
kotaAdapter = KotaAdapter(this)
rvDaftarKota.setLayoutManager(LinearLayoutManager(this))
rvDaftarKota.setAdapter(kotaAdapter)
rvDaftarKota.setHasFixedSize(true)
//viewmodel
primaryViewModel = ViewModelProvider(this, NewInstanceFactory()).get(PrimaryViewModel::class.java)
primaryViewModel.setKota(Constant.provinsiId)
progressBar.setVisibility(View.VISIBLE)
primaryViewModel.getKota().observe(this, Observer<ArrayList<ModelKota?>> { modelKota: ArrayList<ModelKota?> ->
if (modelKota.size != 0) {
kotaAdapter.setKotaAdapter(modelKota)
} else {
progressBar.setVisibility(View.GONE)
linearNoData.setVisibility(View.VISIBLE)
rvDaftarKota.setVisibility(View.GONE)
}
progressBar.setVisibility(View.GONE)
})
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
} | 0 | Kotlin | 0 | 8 | b30c08b56ab12b2fee66497abfadef5f5f2c291a | 2,426 | Hospital-Covid-19 | Apache License 2.0 |
app/src/main/java/com/system/moneycontrol/ui/utils/ProgressBarAnimation.kt | enirsilvaferraz | 138,302,967 | false | {"Kotlin": 71910} | package com.system.moneycontrol.ui.utils
import android.view.View
import android.view.animation.Animation
import android.view.animation.Transformation
import android.widget.ProgressBar
import androidx.appcompat.widget.LinearLayoutCompat
class ProgressBarAnimation(
private val mProgressContainer: LinearLayoutCompat,
private val mProgressBar: ProgressBar,
fullDuration: Long) : Animation() {
private var mTo: Int = 0
private var mFrom: Int = 0
private val mStepDuration: Long
init {
mStepDuration = fullDuration / mProgressBar.max
}
fun setProgress(progressParam: Int) {
mProgressContainer.visibility = View.VISIBLE
var progress = progressParam
if (progress < 0) {
progress = 0
}
if (progress > mProgressBar.max) {
progress = mProgressBar.max
}
mTo = progress
mFrom = mProgressBar.progress
duration = Math.abs(mTo - mFrom) * mStepDuration
mProgressBar.startAnimation(this)
}
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
val value = mFrom + (mTo - mFrom) * interpolatedTime
mProgressBar.progress = value.toInt()
if (mProgressBar.progress == mProgressBar.max) {
mProgressContainer.visibility = View.GONE
}
}
} | 0 | Kotlin | 0 | 0 | 7087fde3fbd7433d294cb43e874939df4f10b7e1 | 1,370 | Money-Control | Apache License 2.0 |
src/main/kotlin/ru/coding4fun/intellij/database/model/property/security/login/MsLoginModel.kt | scrappyCoco | 201,919,288 | false | null | package ru.coding4fun.intellij.database.model.property.security.login
import ru.coding4fun.intellij.database.model.common.BasicIdentity
import ru.coding4fun.intellij.database.model.common.BuiltinPermission
import ru.coding4fun.intellij.database.model.common.Named
import ru.coding4fun.intellij.database.model.property.security.role.RoleMember
import ru.coding4fun.intellij.database.ui.form.common.ModelModification
import ru.coding4fun.intellij.database.ui.form.common.Modifications
import ru.coding4fun.intellij.database.ui.form.common.toModificationList
class MsLoginModel : Named {
//region Login
lateinit var login: ModelModification<MsLogin>
lateinit var certificates: List<BasicIdentity>
lateinit var asymmetricKeys: List<BasicIdentity>
lateinit var credentials: List<BasicIdentity>
lateinit var databases: List<BasicIdentity>
lateinit var languages: List<BasicIdentity>
//endregion
//region Securables
lateinit var builtInPermission: List<BuiltinPermission>
lateinit var securables: List<MsSecurable>
lateinit var serverPermissions: List<MsServerPermission>
//endregion
lateinit var serverRoles: List<RoleMember>
//region Databases
lateinit var loginDatabases: List<MsDatabaseOfLogin>
lateinit var dbRoles: List<MsDatabaseRoleMembership>
//endregion
//region Modifications
var memberModifications: Modifications<RoleMember> = emptyList<RoleMember>().toModificationList()
var serverPermissionModifications: Modifications<MsServerPermission> = emptyList<MsServerPermission>().toModificationList()
var dbModifications: Modifications<MsDatabaseOfLogin> = emptyList<MsDatabaseOfLogin>().toModificationList()
var dbRoleModifications: Modifications<MsDatabaseRoleMembership> = emptyList<MsDatabaseRoleMembership>().toModificationList()
//endregion
override var name: String
get() = (login.new ?: login.old)!!.name
set(_) {}
} | 0 | Kotlin | 2 | 1 | 1408f2a9229dbdf9ad99966faa5e7a5b74786270 | 1,856 | SQL-Server-Administration-Tool | Apache License 2.0 |
model/src/commonMain/kotlin/io/github/droidkaigi/confsched2020/model/SessionList.kt | DroidKaigi | 202,978,106 | false | null | package io.github.droidkaigi.confsched2020.model
data class SessionList(private val sessions: List<Session>) : List<Session> by sessions {
val dayToSessionMap: Map<SessionPage.Day, SessionList> by lazy {
minus(events)
.groupBy { it.dayNumber }
.mapKeys {
SessionPage.dayOfNumber(
it.key
)
}
.mapValues { (_, value) -> SessionList(value) }
}
val events: SessionList by lazy {
SessionList(filter { it.room.roomType == Room.RoomType.EXHIBITION })
}
val favorited: SessionList by lazy {
SessionList(filter { it.isFavorited })
}
val currentSessionIndex by lazy {
when (val lastFinished = indexOfLast { it.isFinished }) {
-1 -> {
// if sessions dose not started we don't use it
-1
}
size - 1 -> {
// if it is last we don't use it
-1
}
else -> {
lastFinished + 1
}
}
}
fun filtered(filters: Filters): SessionList {
return SessionList(filter { filters.isPass(it) })
}
fun toPageToScrollPositionMap(): Map<SessionPage, Int> {
val map = mutableMapOf<SessionPage, Int>()
map += dayToSessionMap
.map { (day, sessions) ->
val index = sessions.currentSessionIndex
day to index
}
.filter { (_, value) -> value != -1 }
.toMap()
val favoriteCurrentSessionIndex = favorited.currentSessionIndex
if (favoriteCurrentSessionIndex != -1) {
map += SessionPage.Favorite to favoriteCurrentSessionIndex
}
return map
}
companion object {
val EMPTY = SessionList(listOf())
}
}
| 46 | Kotlin | 329 | 782 | 4c5533e4611d4bf6007284dd1f61db2fc92eb0ae | 1,859 | conference-app-2020 | Apache License 2.0 |
app/src/main/java/com/app/exchanger/domain/usecase/ExchangeUseCase.kt | Splinterggg | 735,589,378 | false | {"Kotlin": 45000} | package com.app.exchanger.domain.usecase
import com.app.exchanger.domain.model.Balance
import com.app.exchanger.domain.model.BalanceChange
import com.app.exchanger.domain.model.ExchangeRate
import com.app.exchanger.domain.model.ExchangeTransaction
import com.app.exchanger.domain.model.ExchangeTransactionResult
import com.app.exchanger.domain.provider.ExchangeRulesProvider
import java.math.BigDecimal
import java.math.MathContext
class ExchangeUseCase(
private val exchangeRulesProvider: ExchangeRulesProvider,
private val getExchangeRateUseCase: GetExchangeRateUseCase,
) {
operator fun invoke(
exchangeRates: List<ExchangeRate>,
balance: List<Balance>,
transaction: ExchangeTransaction,
): ExchangeTransactionResult {
val rate = getExchangeRateUseCase(
exchangeRates = exchangeRates,
sellCurrency = transaction.sellCurrency,
buyCurrency = transaction.buyCurrency,
)
val buyAmount = transaction.amount.multiply(rate, MathContext.DECIMAL64)
val transactionFee = getTransactionFee(transaction)
val sellCurrencyBalance = balance.first { it.currency == transaction.sellCurrency }
val sellBalanceChange = transaction.amount + transactionFee
if (sellBalanceChange > sellCurrencyBalance.amount) {
return ExchangeTransactionResult(
transaction = transaction,
transactionFee = transactionFee,
isProcessed = false,
change = BalanceChange(
sellCurrency = transaction.sellCurrency,
sellBalanceChange = BigDecimal.ZERO,
buyCurrency = transaction.buyCurrency,
buyBalanceChange = BigDecimal.ZERO,
),
)
}
return ExchangeTransactionResult(
transaction = transaction,
transactionFee = transactionFee,
isProcessed = true,
change = BalanceChange(
transaction.sellCurrency,
-sellBalanceChange,
transaction.buyCurrency,
buyAmount,
)
)
}
private fun getTransactionFee(transaction: ExchangeTransaction): BigDecimal {
for (rule in exchangeRulesProvider.rules) {
val result = rule.process(transaction)
if (result.fee != null) {
return result.fee
}
}
return BigDecimal.ZERO
}
} | 0 | Kotlin | 0 | 0 | 2b81abab0061f74aea9dc07cc45888dd94d06770 | 2,509 | CurrencyExchanger | MIT License |
app/src/main/java/com/dew/aihua/settings/preference_fragment/DownloadSettingsFragment.kt | ed828a | 172,828,123 | false | null | package com.dew.aihua.settings.preference_fragment
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.preference.Preference
import com.dew.aihua.R
import com.dew.aihua.util.FilePickerActivityHelper
import com.nononsenseapps.filepicker.Utils
/**
* Created by Edward on 3/2/2019.
*/
class DownloadSettingsFragment : BasePreferenceFragment() {
private lateinit var downloadPathPreference: String
private lateinit var downloadPathAudioPreference: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initKeys()
updatePreferencesSummary()
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.download_settings)
}
private fun initKeys() {
downloadPathPreference = getString(R.string.download_path_key)
downloadPathAudioPreference = getString(R.string.download_path_audio_key)
}
private fun updatePreferencesSummary() {
findPreference(downloadPathPreference).summary = defaultPreferences.getString(downloadPathPreference, getString(R.string.download_path_summary))
findPreference(downloadPathAudioPreference).summary = defaultPreferences.getString(downloadPathAudioPreference, getString(R.string.download_path_audio_summary))
}
override fun onPreferenceTreeClick(preference: Preference): Boolean {
Log.d(TAG, "onPreferenceTreeClick() called with: preference = [$preference]")
if (preference.key == downloadPathPreference || preference.key == downloadPathAudioPreference) {
val intent = Intent(activity, FilePickerActivityHelper::class.java)
.putExtra(com.nononsenseapps.filepicker.FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)
.putExtra(com.nononsenseapps.filepicker.FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, true)
.putExtra(com.nononsenseapps.filepicker.FilePickerActivity.EXTRA_MODE, com.nononsenseapps.filepicker.FilePickerActivity.MODE_DIR)
if (preference.key == downloadPathPreference) {
startActivityForResult(intent, REQUEST_DOWNLOAD_PATH)
} else if (preference.key == downloadPathAudioPreference) {
startActivityForResult(intent, REQUEST_DOWNLOAD_AUDIO_PATH)
}
}
return super.onPreferenceTreeClick(preference)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Log.d(TAG, "onActivityResult() called with: requestCode = [$requestCode], resultCode = [$resultCode], data = [$data]")
if ((requestCode == REQUEST_DOWNLOAD_PATH || requestCode == REQUEST_DOWNLOAD_AUDIO_PATH)
&& resultCode == Activity.RESULT_OK && data!!.data != null) {
val key = getString(if (requestCode == REQUEST_DOWNLOAD_PATH) R.string.download_path_key else R.string.download_path_audio_key)
val path = Utils.getFileForUri(data.data!!).absolutePath
defaultPreferences.edit().putString(key, path).apply()
updatePreferencesSummary()
}
}
companion object {
private val TAG = DownloadSettingsFragment::class.simpleName
private const val REQUEST_DOWNLOAD_PATH = 0x1235
private const val REQUEST_DOWNLOAD_AUDIO_PATH = 0x1236
}
}
| 0 | Kotlin | 0 | 1 | 1896f46888b5a954b367e83f40b845ce174a2328 | 3,484 | Aihua | Apache License 2.0 |
src/main/kotlin/dev/seeruk/mc/autoequip/event/BreakListener.kt | seeruk | 198,523,416 | false | null | package dev.seeruk.mc.autoequip.event
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerItemBreakEvent
import org.bukkit.inventory.ItemStack
/**
* BreakListener is a listener that listens for the PlayerItemBreakEvent. If an item breaks, and
* another of the same Material exists in the player's inventory, we'll replace the item in the same
* hand the broken item was in with that item in the inventory (i.e. move it to the hand).
*/
class BreakListener : Listener {
@EventHandler
fun onPlayerItemBreak(evt: PlayerItemBreakEvent) {
val brokenItem = evt.brokenItem
val player = evt.player
val brokeMainHand = player.inventory.itemInMainHand == brokenItem
if (this.hasItemInInventory(brokenItem, player)) {
// Find the first item that matches the broken item. It should definitely exist at this
// point, so it's safe to continue without checking.
val replacementItem = this.getFirstMatchingItem(brokenItem, player)
val replacementIndex = player.inventory.indexOf(replacementItem)
if (brokeMainHand) {
player.inventory.setItemInMainHand(replacementItem.clone())
} else {
player.inventory.setItemInOffHand(replacementItem.clone())
}
// Remove the original item, at the index it was found at.
player.inventory.setItem(replacementIndex, null)
}
player.updateInventory()
}
/**
* Find the first item in the contents of the given PlayerInventory that matches the given
* ItemStack.
*
* @param itemStack The item to try to find.
* @param player The player whose inventory we're looking in.
* @return The first matching item.
*/
private fun getFirstMatchingItem(itemStack: ItemStack, player: Player): ItemStack {
// Make sure we're not replacing the item with the broken item.
return player.inventory.contents.first { item ->
item != null && item != itemStack && item.type == itemStack.type
}
}
/**
* Check if the given ItemStack exists in the contents of the given PlayerInventory.
*
* @param itemStack The item to try to find.
* @param player The player whose inventory we're looking in.
* @return True if the PlayerInventory's contents contains the given ItemStack.
*/
private fun hasItemInInventory(itemStack: ItemStack, player: Player): Boolean {
return player.inventory.contents.any { item ->
item != null && item != itemStack && item.type == itemStack.type
}
}
}
| 2 | Kotlin | 0 | 0 | 64ac016420cf97e8905a0589bbb5157243619489 | 2,715 | mc-autoequip | MIT License |
lib/src/main/java/com/sd/lib/compose/swich/SwitchState.kt | zj565061763 | 554,967,041 | false | {"Kotlin": 22285} | package com.sd.lib.compose.swich
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.calculateTargetValue
import androidx.compose.animation.core.tween
import androidx.compose.animation.splineBasedDecay
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.unit.Density
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable
fun rememberFSwitchState(): FSwitchState {
val coroutineScope = rememberCoroutineScope()
return remember(coroutineScope) {
FSwitchState(coroutineScope)
}
}
class FSwitchState internal constructor(scope: CoroutineScope) {
private val _scope = scope
/** 是否可用 */
var enabled: Boolean by mutableStateOf(true)
internal set
/** 当前进度[0-1] */
var progress: Float by mutableFloatStateOf(0f)
private set
/** Thumb的偏移量 */
internal var thumbOffset: Int by mutableIntStateOf(0)
private set
internal var hasInitialized: Boolean by mutableStateOf(false)
private set
internal lateinit var onCheckedChange: (Boolean) -> Unit
internal lateinit var density: Density
private var _isChecked = false
private val _uncheckedOffset: Float by mutableFloatStateOf(0f)
private var _checkedOffset: Float by mutableFloatStateOf(0f)
private val _animOffset = Animatable(0f)
private var _animJob: Job? = null
private var _internalOffset: Float = 0f
set(value) {
val newValue = value.coerceIn(_uncheckedOffset, _checkedOffset)
if (field != newValue) {
field = newValue
thumbOffset = newValue.toInt()
progress = calculateProgress()
}
}
private fun calculateProgress(): Float {
val checkedOffset = _checkedOffset
val uncheckedOffset = _uncheckedOffset
if (checkedOffset <= uncheckedOffset) return 0f
val offset = thumbOffset
return when {
offset <= uncheckedOffset -> 0f
offset >= checkedOffset -> 1f
else -> {
val current = offset - uncheckedOffset
val total = checkedOffset - uncheckedOffset
(current / total).coerceIn(0f, 1f)
}
}
}
internal fun setSize(boxSize: Int, thumbSize: Int) {
val delta = boxSize - thumbSize
_checkedOffset = _uncheckedOffset + delta.coerceAtLeast(0)
}
@Composable
internal fun HandleComposable(checked: Boolean) {
_isChecked = checked
LaunchedEffect(checked, _uncheckedOffset, _checkedOffset) {
if (_uncheckedOffset == _checkedOffset) {
progress = 0f
return@LaunchedEffect
}
if (!hasInitialized) {
updateOffsetByStateStatic()
hasInitialized = true
} else {
val offset = boundsOffset(_isChecked)
animateToOffset(offset)
}
}
}
internal fun handleDrag(delta: Float): Boolean {
if (_animJob?.isActive == true) return false
if (_checkedOffset == _uncheckedOffset) return false
val oldOffset = _internalOffset
_internalOffset += delta
return _internalOffset != oldOffset
}
internal fun handleFling(velocity: Float) {
if (_animJob?.isActive == true) return
if (_checkedOffset == _uncheckedOffset) return
val decayTarget = splineBasedDecay<Float>(density).calculateTargetValue(
initialValue = _internalOffset,
initialVelocity = velocity,
)
val offset = boundsValue(decayTarget, _uncheckedOffset, _checkedOffset)
animateToOffset(
offset = offset,
initialVelocity = velocity,
) {
if (_checkedOffset != _uncheckedOffset) {
val checked = _internalOffset == _checkedOffset
if (checked != _isChecked) {
notifyCallback(checked)
delay(500)
}
}
}
}
internal fun handleDragCancel() {
_animJob?.cancel()
updateOffsetByStateStatic()
}
internal fun handleClick() {
if (_animJob?.isActive == true) return
notifyCallback(!_isChecked)
}
private fun animateToOffset(
offset: Float,
initialVelocity: Float? = null,
onFinish: (suspend () -> Unit)? = null,
) {
_animJob?.cancel()
_scope.launch {
_animOffset.snapTo(_internalOffset)
_animOffset.animateTo(
targetValue = offset,
animationSpec = tween(durationMillis = 150),
initialVelocity = initialVelocity ?: _animOffset.velocity,
) {
_internalOffset = value
}
onFinish?.invoke()
updateOffsetByStateStatic()
}.also {
_animJob = it
}
}
private fun updateOffsetByStateStatic() {
_internalOffset = boundsOffset(_isChecked)
}
private fun boundsOffset(isChecked: Boolean): Float {
return if (isChecked) _checkedOffset else _uncheckedOffset
}
private fun notifyCallback(isChecked: Boolean) {
onCheckedChange(isChecked)
}
}
private fun boundsValue(value: Float, min: Float, max: Float): Float {
if (value <= min) return min
if (value >= max) return max
val center = (min + max) / 2
return if (value > center) max else min
} | 0 | Kotlin | 0 | 1 | bd51d5034f303792d7b4c846fd19d07d3da6857d | 6,021 | compose-switch | MIT License |
ocpp-1-6-core/src/main/kotlin/com/izivia/ocpp/core16/model/setchargingprofile/SetChargingProfileResp.kt | IZIVIA | 501,708,979 | false | {"Kotlin": 1884583} | package com.izivia.ocpp.core16.model.setchargingprofile
import com.izivia.ocpp.core16.model.setchargingprofile.enumeration.ChargingProfileStatus
data class SetChargingProfileResp(
val status: ChargingProfileStatus
)
| 1 | Kotlin | 4 | 23 | e17a6c6072bf73b1d4a2ce5a62068a11ab913572 | 222 | ocpp-toolkit | MIT License |
app/src/main/java/io/horizontalsystems/bankwallet/ui/extensions/BottomSheetSelectorDialog.kt | Mike117687 | 473,915,173 | true | {"Kotlin": 3173344, "Shell": 2039, "Ruby": 1350} | package io.horizontalsystems.bankwallet.ui.extensions
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.Divider
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.fragment.app.FragmentManager
import io.horizontalsystems.bankwallet.R
import io.horizontalsystems.bankwallet.ui.compose.ComposeAppTheme
import io.horizontalsystems.bankwallet.ui.compose.components.ButtonPrimaryYellow
import io.horizontalsystems.bankwallet.ui.compose.components.CellMultilineLawrence
import io.horizontalsystems.bankwallet.ui.compose.components.TextImportantWarning
class BottomSheetSelectorDialog(
private val title: String,
private val subtitle: String,
@DrawableRes private val icon: Int,
private val items: List<BottomSheetSelectorViewItem>,
private val selectedIndex: Int,
private val onItemSelected: (Int) -> Unit,
private val onCancelled: (() -> Unit)?,
private val warning: String?,
private val notifyUnchanged: Boolean
) : BaseComposableBottomSheetFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
setViewCompositionStrategy(
ViewCompositionStrategy.DisposeOnLifecycleDestroyed(viewLifecycleOwner)
)
setContent {
ComposeAppTheme {
BottomSheetScreen()
}
}
}
}
@Composable
private fun BottomSheetScreen() {
var selected by remember { mutableStateOf(selectedIndex) }
BottomSheetHeader(
iconPainter = painterResource(icon),
title = title,
subtitle = subtitle,
onCloseClick = { close() }
) {
Divider(
modifier = Modifier.fillMaxWidth(),
thickness = 1.dp,
color = ComposeAppTheme.colors.steel10
)
warning?.let {
TextImportantWarning(
modifier = Modifier.padding(horizontal = 21.dp, vertical = 12.dp),
text = it
)
Divider(
modifier = Modifier.fillMaxWidth(),
thickness = 1.dp,
color = ComposeAppTheme.colors.steel10
)
}
items.forEachIndexed { index, item ->
CellMultilineLawrence(
borderBottom = true
) {
Row(
modifier = Modifier
.fillMaxSize()
.clickable {
selected = index
}
.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column {
Text(
text = item.title,
style = ComposeAppTheme.typography.body,
color = ComposeAppTheme.colors.leah
)
Text(
text = item.subtitle,
style = ComposeAppTheme.typography.subhead2,
color = ComposeAppTheme.colors.grey
)
}
Spacer(modifier = Modifier.weight(1f))
if (index == selected) {
Image(
modifier = Modifier.padding(start = 5.dp),
painter = painterResource(id = R.drawable.ic_checkmark_20),
colorFilter = ColorFilter.tint(ComposeAppTheme.colors.jacob),
contentDescription = ""
)
}
}
}
}
ButtonPrimaryYellow(
modifier = Modifier.fillMaxWidth().padding(16.dp),
title = getString(R.string.Button_Done),
onClick = {
if (notifyUnchanged || selectedIndex != selected) {
onItemSelected(selected)
}
dismiss()
}
)
}
}
override fun onCancel(dialog: DialogInterface) {
super.onCancel(dialog)
onCancelled?.invoke()
}
override fun close() {
super.close()
onCancelled?.invoke()
}
companion object {
fun show(
fragmentManager: FragmentManager,
title: String,
subtitle: String,
@DrawableRes icon: Int,
items: List<BottomSheetSelectorViewItem>,
selected: Int,
onItemSelected: (Int) -> Unit,
onCancelled: (() -> Unit)? = null,
warning: String? = null,
notifyUnchanged: Boolean = false
) {
BottomSheetSelectorDialog(
title,
subtitle,
icon,
items,
selected,
onItemSelected,
onCancelled,
warning,
notifyUnchanged
)
.show(fragmentManager, "selector_dialog")
}
}
}
data class BottomSheetSelectorViewItem(val title: String, val subtitle: String)
| 1 | null | 1 | 1 | 9941cc3b354e157d41295455a5200d77acf64202 | 6,394 | unstoppable-wallet-android | MIT License |
device-cleaner/src/test/kotlin/pl/droidsonroids/stf/devicecleaner/DeviceExtensionsTest.kt | mansya | 140,306,987 | true | {"Kotlin": 10439} | package pl.droidsonroids.stf.devicecleaner
import assertk.all
import assertk.assert
import assertk.assertions.*
import com.android.ddmlib.IDevice
import com.android.ddmlib.IShellOutputReceiver
import com.nhaarman.mockito_kotlin.*
import org.junit.Test
import java.io.IOException
class DeviceExtensionsTest {
@Test
fun `desired actions performed on clean run`() {
val device = mock<IDevice> {
on { executeShellCommand(eq("pm list packages -3"), any()) } doAnswer {
val receiver = it.arguments[1] as NonCancellableMultilineReceiver
receiver.processNewLines(arrayOf("package:foo.bar", "package:foo.baz", " "))
}
}
val commandCaptor = argumentCaptor<String>()
val packageCaptor = argumentCaptor<String>()
val receiverCaptor = argumentCaptor<IShellOutputReceiver>()
assert(device.clean(emptyArray())).isTrue()
verify(device, times(2)).uninstallPackage(packageCaptor.capture())
assert(packageCaptor.allValues).hasSize(2)
assert(packageCaptor.firstValue).isEqualTo("foo.bar")
assert(packageCaptor.secondValue).isEqualTo("foo.baz")
verify(device, times(3)).executeShellCommand(commandCaptor.capture(), receiverCaptor.capture())
assert(commandCaptor.allValues).all {
contains("rm -rf /data/local/tmp/*")
contains("rm -rf /sdcard/*")
}
}
@Test
fun `returns false on clean failure`() {
val device = mock<IDevice> {
on { reboot(anyOrNull()) } doThrow IOException::class
}
assert(device.clean(emptyArray())).isFalse()
}
@Test
fun `falls back to default serial number if property missing`() {
val device = mock<IDevice> {
on { getProperty("ro.serialno") } doReturn null as String?
}
assert(device.serialProperty).isNotNull()
}
} | 0 | Kotlin | 0 | 0 | 9ecf887baa73cb1ffd05eeb28a05ba46442e2f9a | 1,918 | android-device-cleaner | MIT License |
app/src/main/java/com/example/skindiseasedetectionapp/ui/custom/CustomEditTextPassword.kt | Capstone-2022-C22-PS080 | 500,401,347 | false | {"Kotlin": 126529} | package com.example.skindiseasedetectionapp.ui.custom
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.text.Editable
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.content.ContextCompat
import androidx.core.view.marginLeft
import com.example.skindiseasedetectionapp.R
class CustomEditTextPassword : AppCompatEditText , View.OnTouchListener {
private lateinit var image : Drawable
private lateinit var showPass : Drawable
private lateinit var hidePass: Drawable
private lateinit var lock: Drawable
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
}
private fun setButtonDrawable(
startOfTheText: Drawable? = null,
topOfTheText:Drawable? = null,
endOfTheText:Drawable? = null,
bottomOfTheText: Drawable? = null
){
setCompoundDrawablesWithIntrinsicBounds(
startOfTheText,
topOfTheText,
endOfTheText,
bottomOfTheText
)
}
private fun init(){
showPass = ContextCompat.getDrawable(context,R.drawable.ic_visibility) as Drawable
hidePass = ContextCompat.getDrawable(context,R.drawable.ic_visibility_off) as Drawable
lock = ContextCompat.getDrawable(context,R.drawable.ic_padlock) as Drawable
setButtonDrawable(endOfTheText = showPass)
setOnTouchListener(this)
}
override fun onTouch(p0: View?, event: MotionEvent?): Boolean {
if(compoundDrawables[2] != null ){
if(event?.action == MotionEvent.ACTION_UP){
if(event.rawX >= this.right - this.compoundDrawables[2].bounds.right){
val selection = this.selectionEnd
if(visiblePas == false){
setButtonDrawable(endOfTheText = showPass)
setCompoundDrawablesWithIntrinsicBounds(lock,null,hidePass,null)
this.transformationMethod = HideReturnsTransformationMethod.getInstance()
visiblePas = true
return true
}else{
setButtonDrawable(endOfTheText = hidePass)
setCompoundDrawablesWithIntrinsicBounds(lock,null,showPass,null)
visiblePas = false
this.transformationMethod = PasswordTransformationMethod.getInstance()
return true
}
}
}
}
return false
}
companion object{
private var visiblePas : Boolean = false
}
private fun logger(str: String){
Log.d("password",str)
}
} | 0 | Kotlin | 1 | 0 | 389db0480b81f4ef88c0394783718e18963694bc | 3,323 | sskin-mobile | MIT License |
app/src/main/java/gr/blackswamp/damagereports/data/repos/BaseRepository.kt | JMavrelos | 212,301,077 | false | null | package gr.blackswamp.damagereports.data.repos
interface BaseRepository | 0 | Kotlin | 0 | 0 | 125ceef68db9554d9c047500e41f0fa96085ae64 | 72 | DamageReportsKTX | Apache License 2.0 |
scanner/src/funTest/kotlin/scanners/BoyterLcScannerTest.kt | mercedes-benz | 246,283,016 | true | {"Kotlin": 1936701, "JavaScript": 310482, "HTML": 27680, "CSS": 25864, "Python": 21638, "Shell": 5460, "Dockerfile": 4679, "Ruby": 3545, "ANTLR": 1938, "Go": 328, "Rust": 280} | /*
* Copyright (C) 2017-2019 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package com.here.ort.scanner.scanners
import io.kotlintest.Tag
class BoyterLcScannerTest : AbstractScannerTest() {
override val scanner = BoyterLc("BoyterLc", config)
override val expectedFileLicenses = sortedSetOf("Apache-2.0", "ECL-2.0")
override val expectedDirectoryLicenses = sortedSetOf("Apache-2.0", "ECL-2.0")
override val testTags = emptySet<Tag>()
}
| 0 | null | 1 | 0 | 5babc890a34127d4ab20177d823eb31fd76f79a1 | 1,059 | oss-review-toolkit | Apache License 2.0 |
packages/cactus-plugin-ledger-connector-corda/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/NodeDiagnosticInfo.kt | charellesandig | 445,015,288 | true | {"TypeScript": 5698529, "Kotlin": 1780016, "Go": 1012797, "Rust": 536971, "JavaScript": 278685, "Shell": 246264, "Solidity": 91133, "Makefile": 57788, "Dockerfile": 56920, "Python": 41787, "Logos": 15724, "PLpgSQL": 14954, "Java": 11112, "Smarty": 2942, "Mustache": 2447, "CSS": 1644, "ANTLR": 1108, "TeX": 802, "Roff": 775, "EJS": 98} | /**
* Hyperledger Cactus Plugin - Connector Corda
*
* Can perform basic tasks on a Corda ledger
*
* The version of the OpenAPI document: 0.3.0
*
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package org.openapitools.client.models
import org.openapitools.client.models.CordappInfo
import com.squareup.moshi.Json
/**
* A NodeDiagnosticInfo holds information about the current node version.
*
* @param cordapps A list of CorDapps currently installed on this node
* @param platformVersion The platform version of this node. This number represents a released API version, and should be used to make functionality decisions (e.g. enabling an app feature only if an underlying platform feature exists)
* @param revision The git commit hash this node was built from
* @param vendor The vendor of this node
* @param version The current node version string, e.g. 4.3, 4.4-SNAPSHOT. Note that this string is effectively freeform, and so should only be used for providing diagnostic information. It should not be used to make functionality decisions (the platformVersion is a better fit for this).
*/
data class NodeDiagnosticInfo (
/* A list of CorDapps currently installed on this node */
@Json(name = "cordapps")
val cordapps: kotlin.collections.List<CordappInfo>,
/* The platform version of this node. This number represents a released API version, and should be used to make functionality decisions (e.g. enabling an app feature only if an underlying platform feature exists) */
@Json(name = "platformVersion")
val platformVersion: kotlin.Int,
/* The git commit hash this node was built from */
@Json(name = "revision")
val revision: kotlin.String,
/* The vendor of this node */
@Json(name = "vendor")
val vendor: kotlin.String,
/* The current node version string, e.g. 4.3, 4.4-SNAPSHOT. Note that this string is effectively freeform, and so should only be used for providing diagnostic information. It should not be used to make functionality decisions (the platformVersion is a better fit for this). */
@Json(name = "version")
val version: kotlin.String
)
| 0 | TypeScript | 0 | 0 | 6a4ecf10c7259714716d769a5689e45b1b2dc1dc | 2,357 | cactus | Apache License 2.0 |
project-euler/kotlin/build.gradle.kts | mddburgess | 469,258,868 | false | {"Kotlin": 47737} | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
group = "com.metricalsky"
version = "1.0-SNAPSHOT"
plugins {
kotlin("jvm") version "1.6.10"
}
repositories {
mavenCentral()
}
dependencies {
testImplementation(kotlin("test"))
testImplementation("org.assertj:assertj-core:3.22.0")
}
tasks.test {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "17"
}
| 0 | Kotlin | 0 | 0 | 9ad8f26583b204e875b07782c8d09d9d8b404b00 | 416 | code-kata | MIT License |
src/main/kotlin/info/benjaminhill/mediaworker/ImageAccumulator.kt | salamanders | 184,637,169 | false | null | package info.benjaminhill.mediaworker
import java.awt.image.BufferedImage
/** RGB totals */
@ExperimentalUnsignedTypes
class ImageAccumulator(
private val width: Int,
private val height: Int
) {
private val accumulatedChannels = UIntArray(width * height * 3)
private var frames: ULong = 0u
val size: Int
get() = frames.toInt()
fun add(bi: BufferedImage) {
require(width == bi.width && height == bi.height)
frames++
bi.toPixels().forEachIndexed { index, uByteColor ->
accumulatedChannels[index * 3 + 0] += uByteColor.red.toUInt()
accumulatedChannels[index * 3 + 1] += uByteColor.green.toUInt()
accumulatedChannels[index * 3 + 2] += uByteColor.blue.toUInt()
}
}
fun toRawImage(): RawImage {
val result = RawImage(width, height,
accumulatedChannels.chunked(3).map { (r, g, b) ->
UByteColor(
(r / frames).toUByte(),
(g / frames).toUByte(),
(b / frames).toUByte()
)
})
check(width == result.width && height == result.height)
frames = 0u
accumulatedChannels.fill(0u)
return result
}
} | 0 | Kotlin | 0 | 0 | a1482ccbbcd4bab99a5908574c9cc1c8111f69a2 | 1,251 | mediaworker | MIT License |
app/src/main/java/com/nicco/animationsandroid/animation_part10/ui/adapter/top/HeaderDiffUtil.kt | nicconicco | 247,769,117 | false | null | package com.nicco.animationsandroid.animation_part10.ui.adapter.top
import androidx.recyclerview.widget.DiffUtil
class HeaderDiffUtil : DiffUtil.ItemCallback<HeaderDescriptionUi>() {
override fun areItemsTheSame(
oldItem: HeaderDescriptionUi,
newItem: HeaderDescriptionUi
): Boolean =
oldItem.title == newItem.title
override fun areContentsTheSame(
oldItem: HeaderDescriptionUi,
newItem: HeaderDescriptionUi
): Boolean =
oldItem == newItem
} | 0 | Kotlin | 1 | 6 | 70c79721681021fe9915653d458c40bcbda00e8f | 508 | AnimationAndroid | Apache License 2.0 |
app/src/main/java/com/uos/smsmsm/activity/welcome/IntroFragment.kt | eeswq | 384,945,359 | true | {"Kotlin": 278817} | package com.uos.smsmsm.activity.welcome
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.uos.smsmsm.R
class AdultCheckFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_adult_check, container, false)
}
} | 1 | Kotlin | 1 | 0 | d488b05047d5856c9022e7dd6dbedab68f1f44cd | 537 | project_S | Apache License 2.0 |
src/main/kotlin/com/housing/movie/features/purchase/domain/usecase/current_enrolled_plan_status/GetCurrentEnrolledPlanStatusUseCase.kt | thinhlh | 431,658,207 | false | {"Kotlin": 187649, "Shell": 2612} | package com.housing.movie.features.purchase.domain.usecase.current_enrolled_plan_status
import com.housing.movie.base.BaseUseCase
import com.housing.movie.features.purchase.domain.service.PurchasedService
import org.springframework.stereotype.Component
@Component
class GetCurrentEnrolledPlanStatusUseCase(
private val purchasedService: PurchasedService
) : BaseUseCase {
override fun invoke(data: Any?): GetCurrentEnrolledPlanStatusResponse {
return purchasedService.getCurrentEnrolledPlanStatus()
}
} | 0 | Kotlin | 0 | 0 | f88c15909040f54baf9be3f2adf47429eeccfac5 | 524 | oo-movie-backend | MIT License |
common/src/test/kotlin/com/github/vatbub/matchmaking/common/data/UserTest.kt | vatbub | 162,929,659 | false | null | /*-
* #%L
* matchmaking.common
* %%
* Copyright (C) 2016 - 2019 <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.
* #L%
*/
package com.github.vatbub.matchmaking.common.data
import com.github.vatbub.matchmaking.common.defaultInet4Address
import com.github.vatbub.matchmaking.common.defaultInet6Address
import com.github.vatbub.matchmaking.testutils.KotlinTestSuperclass
import com.github.vatbub.matchmaking.testutils.TestUtils
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class UserTest : KotlinTestSuperclass<User>() {
override fun newObjectUnderTest() =
User(TestUtils.defaultConnectionId, "vatbub")
override fun getCloneOf(instance: User) =
User(instance.connectionId, instance.userName, instance.ipv4Address, instance.ipv6Address)
@Test
fun defaultParamTest() {
val userName = "vatbub"
val user = User(TestUtils.defaultConnectionId, userName)
Assertions.assertEquals(TestUtils.defaultConnectionId, user.connectionId)
Assertions.assertEquals(userName, user.userName)
Assertions.assertNull(user.ipv4Address)
Assertions.assertNull(user.ipv6Address)
}
@Test
fun ipv4GetTest() {
val user = User(TestUtils.defaultConnectionId, "vatbub", ipv4Address = defaultInet4Address)
Assertions.assertEquals(defaultInet4Address, user.ipv4Address)
}
@Test
fun ipv6GetTest() {
val user = User(TestUtils.defaultConnectionId, "vatbub", ipv6Address = defaultInet6Address)
Assertions.assertEquals(defaultInet6Address, user.ipv6Address)
}
@Test
override fun notEqualsTest() {
val user1 = newObjectUnderTest()
val user2 = User(user1.connectionId, TestUtils.getRandomHexString(user1.userName), user1.ipv4Address, user1.ipv6Address)
Assertions.assertNotEquals(user1, user2)
}
}
| 11 | Kotlin | 5 | 32 | 7ece6b79c6ea15dcf636851a61fde6dc6615188d | 2,409 | matchmaking | Apache License 2.0 |
app/src/main/java/com/dev/anzalone/luca/facelandmarks/utils/RectUtils.kt | Luca96 | 151,882,221 | false | null | package com.dev.anzalone.luca.facelandmarks.utils
import android.graphics.Rect
import com.dev.anzalone.luca.facelandmarks.camera.CameraPreview
/**
* a list of extension function for rect class
*/
/** force the rect to be in bound defined by [left], [top], [right] and [bottom] */
fun Rect.inBounds(left: Int = 0, top: Int = 0, right: Int, bottom: Int): Rect {
val w = this.width()
val h = this.height()
if (this.left < left)
this.left = left
if (this.right > right)
this.right = right
if (this.top < top)
this.top = top
if (this.bottom > bottom)
this.bottom = bottom
return this
}
/** return a representation of the rect */
fun Rect.repr() = "[Rect] (left: $left top: $top), (right: $right bottom: $bottom)"
/** scale the given rect according to [xScale] and [yScale] */
fun Rect.scale(xScale: Float = 1f, yScale: Float = 1f): Rect {
val dw = (((this.width() * xScale) - this.width()) * .5).toInt()
val dh = (((this.height() * yScale) - this.height()) * .5).toInt()
this.left = this.left - dw
this.right = this.right + dw
this.top = this.top - dh
this.bottom = this.bottom + dh
return this
}
/** map the rect to the specified coordinate space */
fun Rect.mapTo(width: Int, height: Int, rotation: Int): Rect {
val hw = this.width() / 2f
val hh = this.height() / 2f
val cx = this.left + hw
val cy = this.top + hh
val side = (hh + hw) / 2f
val left = cx - side
val right = cx + side
val top = cy - side
val bottom = cy + side
val l = (left + 1000) / 2000f
val r = (right + 1000) / 2000f
val t = (top + 1000) / 2000f
val b = (bottom + 1000) / 2000f
// handle different display modes
when (rotation) {
CameraPreview.portrait -> {
val w = if (width > height) height else width
val h = if (width > height) width else height
this.left = Math.round(w - (w * b))
this.right = Math.round(w - (w * t))
this.top = Math.round(h - (h * r))
this.bottom = Math.round(h - (h * l))
}
CameraPreview.landleft -> {
val w = if (width < height) height else width
val h = if (width < height) width else height
this.left = Math.round(w - (w * r))
this.right = Math.round(w - (w * l))
this.top = Math.round(h * t)
this.bottom = Math.round(h * b)
val wr = this.width() * .5f
val hr = this.height() * .5f
val x0 = this.centerX()
val y0 = this.centerY()
this.left = (x0 - hr).toInt()
this.right = (x0 + hr).toInt()
this.top = (y0 - wr).toInt()
this.bottom = (y0 + wr).toInt()
}
CameraPreview.landright -> {
val w = if (width < height) height else width
val h = if (width < height) width else height
this.left = Math.round(w * l)
this.right = Math.round(w * r)
this.top = Math.round(h - (h * b))
this.bottom = Math.round(h - (h * t))
val wr = this.width() * .5f
val hr = this.height() * .5f
val x0 = this.centerX()
val y0 = this.centerY()
this.left = (x0 - hr).toInt()
this.right = (x0 + hr).toInt()
this.top = (y0 - wr).toInt()
this.bottom = (y0 + wr).toInt()
}
}
return this
} | 4 | C++ | 28 | 67 | d978b1f668891b2a19c0e128edf90c7bff9b2066 | 3,549 | android-face-landmarks | MIT License |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/teleops/testing/ClawTest.kt | LincolnRoboticsFTC14298 | 540,653,062 | false | {"Kotlin": 210193, "Java": 150037, "HTML": 18885, "JavaScript": 6894, "CMake": 606, "C++": 599} | package org.firstinspires.ftc.teamcode.teleops.testing
import com.acmerobotics.dashboard.FtcDashboard
import com.acmerobotics.dashboard.telemetry.MultipleTelemetry
import com.acmerobotics.dashboard.telemetry.TelemetryPacket
import com.qualcomm.robotcore.eventloop.opmode.Disabled
import com.qualcomm.robotcore.eventloop.opmode.OpMode
import com.qualcomm.robotcore.eventloop.opmode.TeleOp
import org.firstinspires.ftc.teamcode.subsystems.Claw
class ClawTest() : OpMode() {
lateinit var claw: Claw
override fun init() {
claw = Claw(hardwareMap)
claw.open()
}
var lastRead = false
override fun loop() {
lastRead = if(!lastRead && claw.isConeInside()) {
claw.close()
true
} else claw.isConeInside()
if(gamepad1.a) {
claw.open()
}
claw.periodic()
val p = TelemetryPacket()
p.put("Is cone", claw.isConeInside())
p.put("Last read", lastRead)
claw.fetchTelemetry(p)
FtcDashboard.getInstance().sendTelemetryPacket(p)
}
} | 0 | Kotlin | 2 | 2 | 22f70612dd68abf083437f806be235af2db4b5fb | 1,077 | Robotics2022-23 | BSD 3-Clause Clear License |
app/src/main/java/pl/coopsoft/trackme/location/GeofenceHelper.kt | adybkows | 533,266,520 | false | {"Kotlin": 25167} | package pl.coopsoft.trackme.location
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofencingRequest
import com.google.android.gms.location.LocationServices
class GeofenceHelper(applicationContext: Context) {
private companion object {
private const val TAG = "GeofenceHelper"
private const val REQUEST_ID = "1"
private const val GEOFENCE_RADIUS_IN_METERS = 2.0f
}
private val geofencingClient = LocationServices.getGeofencingClient(applicationContext)
private val broadcastReceiverIntent = Intent(applicationContext, GeofenceBroadcastReceiver::class.java)
.apply { action = GeofenceBroadcastReceiver.ACTION_GEOFENCE_EVENT }
private val pendingIntent =
if (Build.VERSION.SDK_INT >= 31)
PendingIntent.getBroadcast(applicationContext, 0, broadcastReceiverIntent, PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
else
PendingIntent.getBroadcast(applicationContext, 0, broadcastReceiverIntent, PendingIntent.FLAG_UPDATE_CURRENT)
fun setup(lat: Double, lon: Double) {
if (lat == 0.0 && lon == 0.0) {
return
}
val geofence = Geofence.Builder()
.setRequestId(REQUEST_ID)
.setCircularRegion(lat, lon, GEOFENCE_RADIUS_IN_METERS)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
.build()
val request = GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_EXIT)
.addGeofence(geofence)
.build()
geofencingClient.removeGeofences(listOf(REQUEST_ID)).run {
addOnCompleteListener {
try {
geofencingClient.addGeofences(request, pendingIntent).run {
addOnSuccessListener {
}
addOnFailureListener {
Log.e(TAG, "Cannot add GPS geofence: $it")
}
}
} catch (e: SecurityException) {
Log.e(TAG, "Cannot add GPS geofence: $e")
}
}
}
}
fun shutdown() {
geofencingClient.removeGeofences(listOf(REQUEST_ID)).run {
addOnCompleteListener {
}
}
}
} | 0 | Kotlin | 0 | 0 | 78b1696300d79686e5b4e716c7c62bda05b3e8f5 | 2,603 | trackme | Apache License 2.0 |
oauth2-commons/src/main/kotlin/com/labijie/infra/oauth2/ITokenValueResolver.kt | hongque-pro | 308,310,231 | false | {"Kotlin": 217778} | package com.labijie.infra.oauth2
import org.springframework.core.Ordered
import org.springframework.security.core.Authentication
interface ITokenValueResolver : Ordered {
override fun getOrder(): Int = 0
fun support(authentication: Authentication): Boolean
fun resolveToken(authentication: Authentication): String
} | 0 | Kotlin | 0 | 4 | 4ae8212f8b96ef2983eead32dd0128b22f64e4fe | 329 | infra-oauth2 | Apache License 2.0 |
examples/imageviewer/common/src/desktopMain/kotlin/example/imageviewer/utils/Application.kt | PXNX | 333,455,392 | true | {"Kotlin": 108938, "Dockerfile": 3493, "Shell": 3103, "PowerShell": 1708} | package example.imageviewer.utils
import androidx.compose.desktop.AppManager
import androidx.compose.desktop.AppWindow
import androidx.compose.desktop.WindowEvents
import androidx.compose.runtime.Applier
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.ExperimentalComposeApi
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Recomposer
import androidx.compose.runtime.compositionFor
import androidx.compose.runtime.dispatch.MonotonicFrameClock
import androidx.compose.runtime.emptyContent
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.window.MenuBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import java.awt.image.BufferedImage
import javax.swing.SwingUtilities
import kotlin.system.exitProcess
fun Application(
content: @Composable ApplicationScope.() -> Unit
) = SwingUtilities.invokeLater {
AppManager.setEvents(onWindowsEmpty = null)
val scope = ApplicationScope(content)
scope.start()
}
@OptIn(ExperimentalComposeApi::class, ExperimentalCoroutinesApi::class)
class ApplicationScope(
private val content: @Composable ApplicationScope.() -> Unit
) {
private val frameClock = ImmediateFrameClock()
private val context = Dispatchers.Main + frameClock
private val scope = CoroutineScope(context)
private val recomposer = Recomposer(context)
private val composition = compositionFor(Unit, EmptyApplier(), recomposer)
private val windows = mutableSetOf<AppWindow>()
private var windowsVersion by mutableStateOf(Any())
fun start() {
scope.launch(start = CoroutineStart.UNDISPATCHED) {
recomposer.runRecomposeAndApplyChanges()
}
composition.setContent {
content()
WindowsMonitor()
}
}
@Composable
private fun WindowsMonitor() {
LaunchedEffect(windowsVersion) {
if (windows.isEmpty()) {
dispose()
exitProcess(0)
}
}
}
private fun dispose() {
composition.dispose()
scope.cancel()
}
// TODO make parameters observable (now if any parameter is changed we don't change the window)
@Composable
fun ComposableWindow(
title: String = "JetpackDesktopWindow",
size: IntSize = IntSize(800, 600),
location: IntOffset = IntOffset.Zero,
centered: Boolean = true,
icon: BufferedImage? = null,
menuBar: MenuBar? = null,
undecorated: Boolean = false,
resizable: Boolean = true,
events: WindowEvents = WindowEvents(),
onDismissRequest: (() -> Unit)? = null,
content: @Composable () -> Unit = emptyContent()
) {
var isOpened by remember { mutableStateOf(true) }
if (isOpened) {
DisposableEffect(Unit) {
lateinit var window: AppWindow
fun onClose() {
if (isOpened) {
windows.remove(window)
onDismissRequest?.invoke()
windowsVersion = Any()
isOpened = false
}
}
window = AppWindow(
title = title,
size = size,
location = location,
centered = centered,
icon = icon,
menuBar = menuBar,
undecorated = undecorated,
resizable = resizable,
events = events,
onDismissRequest = {
onClose()
}
)
windows.add(window)
window.show(recomposer, content)
onDispose {
if (!window.isClosed) {
window.close()
}
onClose()
}
}
}
}
}
private class ImmediateFrameClock : MonotonicFrameClock {
override suspend fun <R> withFrameNanos(
onFrame: (frameTimeNanos: Long) -> R
) = onFrame(System.nanoTime())
}
@OptIn(ExperimentalComposeApi::class)
private class EmptyApplier : Applier<Unit> {
override val current: Unit = Unit
override fun down(node: Unit) = Unit
override fun up() = Unit
override fun insertTopDown(index: Int, instance: Unit) = Unit
override fun insertBottomUp(index: Int, instance: Unit) = Unit
override fun remove(index: Int, count: Int) = Unit
override fun move(from: Int, to: Int, count: Int) = Unit
override fun clear() = Unit
}
| 0 | null | 0 | 1 | 728b4d5f762f5d901a869824c4b5a2da8b516b05 | 5,091 | compose-jb | Apache License 2.0 |
src/main/kotlin/ru/coding4fun/intellij/database/ui/form/state/StateChanger.kt | scrappyCoco | 201,919,288 | false | null | package ru.coding4fun.intellij.database.ui.form.state
import javax.swing.JComponent
object StateChanger {
@JvmStatic
fun enable(targetComponent: JComponent, state: Boolean): Unit? {
targetComponent.isEnabled = state
return null
}
@JvmStatic
fun disable(targetComponent: JComponent, state: Boolean): Unit? {
targetComponent.isEnabled = !state
return null
}
@JvmStatic
fun enableRecurse(targetComponent: JComponent, state: Boolean): Unit? {
traverse(targetComponent) {
it.isEnabled = state
}
return null
}
@JvmStatic
fun visibleRecurse(targetComponent: JComponent, state: Boolean): Unit? {
traverse(targetComponent) {
it.isVisible = state
}
return null
}
@JvmStatic
private fun traverse(targetComponent: JComponent, action: ((component: JComponent) -> Unit)): Unit? {
action(targetComponent)
for (child in targetComponent.components) {
val jChild = child as? JComponent ?: continue
traverse(jChild, action)
}
return null
}
} | 0 | Kotlin | 2 | 1 | 1408f2a9229dbdf9ad99966faa5e7a5b74786270 | 984 | SQL-Server-Administration-Tool | Apache License 2.0 |
compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/arguments/CommonCompilerArguments.kt | cpovirk | 113,101,073 | true | {"Java": 27299655, "Kotlin": 26644510, "JavaScript": 155518, "HTML": 57096, "Lex": 18174, "Groovy": 14207, "ANTLR": 9797, "IDL": 8587, "Shell": 5436, "CSS": 4679, "Batchfile": 4437} | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* 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.jetbrains.kotlin.cli.common.arguments
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.config.AnalysisFlag
import java.util.*
@SuppressWarnings("WeakerAccess")
abstract class CommonCompilerArguments : CommonToolArguments() {
companion object {
@JvmStatic private val serialVersionUID = 0L
const val PLUGIN_OPTION_FORMAT = "plugin:<pluginId>:<optionName>=<value>"
const val WARN = "warn"
const val ERROR = "error"
const val ENABLE = "enable"
}
@GradleOption(DefaultValues.LanguageVersions::class)
@Argument(
value = "-language-version",
valueDescription = "<version>",
description = "Provide source compatibility with specified language version"
)
var languageVersion: String? by FreezableVar(null)
@GradleOption(DefaultValues.LanguageVersions::class)
@Argument(
value = "-api-version",
valueDescription = "<version>",
description = "Allow to use declarations only from the specified version of bundled libraries"
)
var apiVersion: String? by FreezableVar(null)
@Argument(
value = "-kotlin-home",
valueDescription = "<path>",
description = "Path to Kotlin compiler home directory, used for runtime libraries discovery"
)
var kotlinHome: String? by FreezableVar(null)
@Argument(value = "-P", valueDescription = PLUGIN_OPTION_FORMAT, description = "Pass an option to a plugin")
var pluginOptions: Array<String>? by FreezableVar(null)
// Advanced options
@Argument(value = "-Xno-inline", description = "Disable method inlining")
var noInline: Boolean by FreezableVar(false)
// TODO Remove in 1.0
@Argument(
value = "-Xrepeat",
valueDescription = "<count>",
description = "Repeat compilation (for performance analysis)"
)
var repeat: String? by FreezableVar(null)
@Argument(
value = "-Xskip-metadata-version-check",
description = "Load classes with bad metadata version anyway (incl. pre-release classes)"
)
var skipMetadataVersionCheck: Boolean by FreezableVar(false)
@Argument(value = "-Xallow-kotlin-package", description = "Allow compiling code in package 'kotlin' and allow not requiring kotlin.stdlib in module-info")
var allowKotlinPackage: Boolean by FreezableVar(false)
@Argument(value = "-Xreport-output-files", description = "Report source to output files mapping")
var reportOutputFiles: Boolean by FreezableVar(false)
@Argument(value = "-Xplugin", valueDescription = "<path>", description = "Load plugins from the given classpath")
var pluginClasspaths: Array<String>? by FreezableVar(null)
@Argument(value = "-Xmulti-platform", description = "Enable experimental language support for multi-platform projects")
var multiPlatform: Boolean by FreezableVar(false)
@Argument(value = "-Xno-check-actual", description = "Do not check presence of 'actual' modifier in multi-platform projects")
var noCheckActual: Boolean by FreezableVar(false)
@Argument(
value = "-Xintellij-plugin-root",
valueDescription = "<path>",
description = "Path to the kotlin-compiler.jar or directory where IntelliJ configuration files can be found"
)
var intellijPluginRoot: String? by FreezableVar(null)
@Argument(
value = "-Xcoroutines",
valueDescription = "{enable|warn|error}",
description = "Enable coroutines or report warnings or errors on declarations and use sites of 'suspend' modifier"
)
var coroutinesState: String? by FreezableVar(WARN)
@Argument(
value = "-Xnew-inference",
description = "Enable new experimental generic type inference algorithm"
)
var newInference: Boolean by FreezableVar(false)
@Argument(
value = "-Xlegacy-smart-cast-after-try",
description = "Allow var smart casts despite assignment in try block"
)
var legacySmartCastAfterTry by FreezableVar(false)
@Argument(
value = "-Xeffect-system",
description = "Enable experimental language feature: effect system"
)
var effectSystem: Boolean by FreezableVar(false)
open fun configureAnalysisFlags(collector: MessageCollector): MutableMap<AnalysisFlag<*>, Any> {
return HashMap<AnalysisFlag<*>, Any>().apply {
put(AnalysisFlag.skipMetadataVersionCheck, skipMetadataVersionCheck)
put(AnalysisFlag.multiPlatformDoNotCheckActual, noCheckActual)
put(AnalysisFlag.allowKotlinPackage, allowKotlinPackage)
}
}
// Used only for serialize and deserialize settings. Don't use in other places!
class DummyImpl : CommonCompilerArguments()
}
| 2 | Java | 2 | 1 | b6ca9118ffe142e729dd17deeecfb35badba1537 | 5,488 | kotlin | Apache License 2.0 |
app/src/main/java/com/example/astrobin/ui/screens/ImageScreen.kt | lelandrichardson | 434,749,871 | false | {"Kotlin": 89608} | package com.example.astrobin.ui.screens
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.foundation.shape.RoundedCornerShape
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Fullscreen
import androidx.compose.material.icons.outlined.BookmarkBorder
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.PersonAdd
import androidx.compose.material.icons.outlined.ThumbUp
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import coil.compose.rememberImagePainter
import com.example.astrobin.api.*
import com.example.astrobin.exp.load
import com.example.astrobin.ui.components.*
import com.google.accompanist.flowlayout.FlowRow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import java.net.URLEncoder
import java.time.OffsetDateTime
data class ImageModel(
val image: AstroImageV2? = null,
val author: AstroUserProfile? = null,
val plateSolve: PlateSolve? = null,
val comments: List<AstroComment>? = null,
val commentAuthors: Map<Int, AstroUser> = emptyMap(),
) {
companion object {
val Empty = ImageModel()
}
}
@Composable
fun ImageScreen(
hash: String,
padding: PaddingValues,
nav: NavController
) {
val api = LocalAstrobinApi.current
val (model, loading) = load(ImageModel.Empty) {
val image = api.image(hash)
push { it.copy(image = image) }
launch {
val author = api.user(image.user)
val profileId = author.userprofile ?: return@launch
val authorProfile = api.userProfile(profileId)
push { it.copy(author = authorProfile) }
}
launch {
val plateSolve = api.plateSolve(19, image.pk)
push { it.copy(plateSolve = plateSolve) }
}
launch {
val comments = api.comments(19, image.pk)
push { it.copy(comments = comments) }
val commentAuthors = comments.map { it.author }.distinct().asFlow().map {
api.user(it)
}.toList().associateBy { it.id }
push { it.copy(commentAuthors = commentAuthors) }
}
}
ImageScreen(
loading,
model.image,
model.author,
model.plateSolve,
model.comments,
model.commentAuthors,
padding,
nav
)
}
@Composable fun ImageScreen(
loading: Boolean,
image: AstroImageV2?,
author: AstroUserProfile?,
plateSolve: PlateSolve?,
comments: List<AstroComment>?,
commentAuthors: Map<Int, AstroUser>,
padding: PaddingValues,
nav: NavController,
) {
var annotations by remember { mutableStateOf(false) }
LazyColumn(Modifier.fillMaxSize(), contentPadding = padding) {
if (image != null) {
item {
val regularPainter = rememberImagePainter(image.url_regular)
val annotatedPainter = rememberImagePainter(plateSolve?.image_file)
Box {
Image(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(image.aspectRatio),
painter = regularPainter,
contentDescription = "Full Image",
)
if (annotations) {
Image(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(image.aspectRatio),
painter = annotatedPainter,
contentDescription = "Full Image",
)
}
}
}
item {
Row(
Modifier
.background(Color.Black)
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
AstroButton(
icon = Icons.Filled.Fullscreen,
onClick = {
val hd = image.url_hd.urlEncode()
val solution = plateSolve?.image_file?.urlEncode() ?: ""
val w = image.w.toString()
val h = image.h.toString()
nav.navigate(
"fullscreen?hd=$hd&solution=$solution&w=$w&h=$h"
)
},
modifier = Modifier.padding(end = 8.dp),
)
AstroButton(
icon = Icons.Outlined.Layers,
selected = annotations,
onClick = { annotations = !annotations },
modifier = Modifier.padding(end = 8.dp),
)
Spacer(Modifier.weight(1f))
CountButton(
icon = Icons.Outlined.BookmarkBorder,
label = image.bookmarksCount.toString(),
selected = false,
onClick = {},
)
CountButton(
icon = Icons.Outlined.ThumbUp,
label = image.likesCount.toString(),
selected = false,
onClick = {},
)
}
}
item {
Column(Modifier.padding(horizontal = 10.dp)) {
Text(image.title ?: "", style = MaterialTheme.typography.h1)
if (author != null) {
Row(
Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
UserRow(author, nav)
AstroButton2(
icon = Icons.Outlined.PersonAdd,
label = "Follow",
selected = false,
onClick = {},
modifier = Modifier
)
}
} else {
CircularProgressIndicator(
Modifier
.align(Alignment.CenterHorizontally)
)
}
}
}
if (plateSolve != null) {
item {
Section("What is this") {
FlowRow(mainAxisSpacing = 10.dp, crossAxisSpacing = 4.dp) {
for (subject in plateSolve.objects_in_field.split(","))
Chip(subject.trim(), onClick = { nav.navigate("search?q=${subject.trim().urlEncode()}")})
}
}
}
if (image.description != null) {
item {
Section("Description") {
Text(image.description)
}
}
}
item {
Section("Technical Card") {
TechCardItem("Declination", plateSolve.dec)
TechCardItem("Right Ascension", plateSolve.ra)
TechCardItem("Data Source", image.dataSource)
TechCardItem("Resolution", "${image.w}px x ${image.h}px")
TechCardItem("Pixel Scale", "${plateSolve.pixscale} arc-sec/px")
TechCardItem("Imaging Camera(s)", image
.imagingCameras
.joinToString(", ") { "${it.make} ${it.name}" }
)
TechCardItem("Imaging Telescope(s)", image
.imagingTelescopes
.joinToString(", ") { "${it.make} ${it.name}" }
)
}
}
item {
Section("Sky Plot") {
Image(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f),
painter = rememberImagePainter(plateSolve.skyplot_zoom1),
contentScale = ContentScale.FillWidth,
contentDescription = "Sky Plot",
)
}
}
}
item {
Section("Histogram") {
Image(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(274f / 120f),
painter = rememberImagePainter(image.url_histogram),
contentScale = ContentScale.FillWidth,
contentDescription = "Histogram",
)
}
}
if (comments != null) {
item {
Section("Comments") {}
}
items(comments, key = {it.id }) {
CommentRow(it, commentAuthors[it.author])
}
}
}
}
if (loading) {
LoadingBar(modifier = Modifier.fillMaxWidth())
}
}
@Composable fun CommentRow(comment: AstroComment, author: AstroUser?) {
Row(Modifier.padding(start=50.dp * (comment.depth-1))) {
AstroAvatar(imageUrl = comment.author_avatar)
Column(Modifier.padding(start=8.dp)) {
Row {
Text(author?.username ?: "...", fontWeight = FontWeight.Bold)
Text(timeAgo(comment.created), color=Color.Gray, modifier = Modifier.padding(start = 8.dp))
}
Text(comment.text, modifier=Modifier.padding(vertical=4.dp))
}
}
}
fun timeAgo(isoDate: String): String {
return "5 days ago"
// return OffsetDateTime.parse(isoDate).
}
@Composable fun IconCount(
count: Int,
icon: ImageVector,
contentDescription: String? = null,
) {
Row(Modifier.padding(end=12.dp)) {
Icon(
icon,
contentDescription = contentDescription,
modifier = Modifier
.padding(top = 0.dp, end = 4.dp)
.size(14.dp)
)
Text("$count", style = MaterialTheme.typography.subtitle2)
}
}
@Composable fun Section(
title: String,
fullWidth: Boolean = false,
content: @Composable () -> Unit
) {
Column(
Modifier
.padding(horizontal = if (fullWidth) 0.dp else 16.dp)
.padding(bottom = 16.dp)
) {
Text(title, style = MaterialTheme.typography.h1, modifier = Modifier.padding(bottom = 8.dp))
content()
}
}
@Composable fun Chip(
value: String,
color: Color = Color.White,
onClick: () -> Unit,
) {
Text(
value,
modifier = Modifier
.clickable(onClick = onClick)
.border(1.dp, color, RoundedCornerShape(6.dp))
.padding(4.dp, 4.dp),
style = MaterialTheme.typography.caption,
fontWeight = FontWeight.Bold,
color = color,
)
}
@Composable fun TechCardItem(
key: String,
value: String?,
) {
if (value != null) {
Row {
Text(key, fontWeight = FontWeight.Bold)
Text(": ")
Text(value)
}
}
}
fun String.urlEncode(): String = URLEncoder.encode(this, "utf-8") | 1 | Kotlin | 3 | 20 | 54054d8f2e62e0a8ec1deb818e6471880a630f42 | 10,591 | astrobin-compose | MIT License |
producer/src/main/kotlin/com/glinboy/tapsell/producer/controller/GeneratorController.kt | GLinBoy | 398,836,478 | false | null | package com.glinboy.tapsell.producer.controller
import com.glinboy.tapsell.producer.service.GeneratorServiceApi
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/generators")
class GeneratorController(private val generatorServiceApi: GeneratorServiceApi) {
@PostMapping("start")
fun startGenerators(@RequestParam(name = "p", required = false, defaultValue = "75") probability: Int): ResponseEntity<Void> {
generatorServiceApi.startGenerateEvents(probability)
return ResponseEntity.ok().build()
}
@PostMapping("stop")
fun stopGenerators(): ResponseEntity<Void> {
generatorServiceApi.stopGenerateEvents()
return ResponseEntity.ok().build()
}
} | 0 | Kotlin | 0 | 0 | 44e7152ffdab01104439e7d0002b4d889777a3f0 | 975 | tapsell-assignment | MIT License |
app/src/main/java/com/yoyiyi/soleil/mvp/contract/region/AllRegionRankContract.kt | yoyiyi | 97,073,764 | false | null | package com.yoyiyi.soleil.mvp.contract.region
import com.yoyiyi.soleil.base.BaseContract
import com.yoyiyi.soleil.bean.region.AllRegionRank
/**
* @author zzq 作者 E-mail: <EMAIL>
* *
* @date 创建时间:2017/5/12 10:09
* * 描述:全区排行Contract
*/
interface AllRegionRankContract {
interface View : BaseContract.BaseView {
fun showAllRegionRank(regionRank: List<AllRegionRank.RankBean.ListBean>)
}
interface Presenter<in T> : BaseContract.BasePresenter<T> {
fun getAllRegionRankData(type: String)
}
}
| 2 | Kotlin | 27 | 137 | 044f76fd499bb49b0fe94d9c83c9bb1db283b8ea | 575 | bilisoleil-kotlin | Apache License 2.0 |
spring-boot-client/src/main/kotlin/com/allianz/t2i/client/rpc/server/model/Models.kt | joshtharakan | 202,050,957 | true | {"Kotlin": 212216, "HTML": 169, "JavaScript": 53} | package com.allianz.t2i.client.rpc.server.model
import com.allianz.t2i.common.contracts.states.BankAccountState
import com.allianz.t2i.common.contracts.types.AccountNumber
import com.allianz.t2i.common.contracts.types.BankAccount
import com.allianz.t2i.common.contracts.types.BankAccountType
import net.corda.core.node.NodeInfo
/**
* Represents basic response from the server
*/
abstract class BasicResponse() {
abstract val status: String
}
/**
* Represents RPCConnect model
*/
data class RPCConnect (override val status: String, val response: String): BasicResponse()
/**
* Represents response model for Node Info API fetch
*/
data class NodeInfoResponse(override val status: String, val nodeInfo: NodeInfo): BasicResponse()
/**
* Represents response model for Account Addition
*/
data class AccountAdditionResponse(override val status: String, val response: BankAccountState): BasicResponse()
/**
* Represents response model for Token Balance fetch
*/
data class TokenBalanceResponse(override val status: String, val tokenBalance: String): BasicResponse()
/**
* Represents response model for Token Transfer call
*/
data class TokenTransferResponse(override val status: String, val updatedTokenBalance: String): BasicResponse()
/**
* Represents response model for Token Redemption call
*/
data class TokenRedemptionResponse(override val status: String, val updatedTokenBalance: String): BasicResponse()
data class AddBankAccountRequest(val node: String, val bankAccountDetails: BankAccount) | 0 | Kotlin | 0 | 0 | 34b4b04274b4c85fd8e9e327297aaefe919a49d9 | 1,528 | cash-issuer | Apache License 2.0 |
app/src/main/java/com/example/monni/data/local/source/InitializerSavingTips.kt | TheKiesling | 521,474,974 | false | {"Kotlin": 99073} | package com.example.monni.data.local.source
import com.example.monni.data.local.entity.SavingTip
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
private lateinit var Database: CategoryDatabase
private val limitCardTip = SavingTip(
name = "Limit on your card",
description = "Set a limit to how much you can spend on your credit or debit cards. This stops you from overspending"
)
private val unusedItemsTip = SavingTip(
name = "Sell your unused items",
description = "Not only does this help declutter your home, but it can also mean earning quite a good amount of extra money"
)
private val savingAccountTip = SavingTip(
name = "Designated savings account",
description = "To save money fast, you need to separate the money you spend on your daily needs from the money you intend to save. This means setting up a designated savings account. "
)
private val RecordExpensesTip = SavingTip(
name = "Record your expenses",
description = "The first step to start saving money is figuring out how much you spend. Keep track of all your expenses "
)
object InitializerSavingTips {
fun createTip(name: String, description: String, database: CategoryDatabase) {
val savingTip = SavingTip(
name = name,
description = description
)
Database = database
CoroutineScope(Dispatchers.IO).launch {
Database.savingTipsDao().insert(savingTip)
}
}
fun createTipCall(database:CategoryDatabase) {
val listOfTips = listOf(
limitCardTip, unusedItemsTip, savingAccountTip,
RecordExpensesTip
)
for (tip in listOfTips) {
createTip(tip.name, tip.description, database)
}
}
}
| 1 | Kotlin | 0 | 3 | 11e6f32970b087c40e93bf7550916199a22bfbf5 | 1,813 | Monni | MIT License |
domain/src/main/java/com/semicolon/domain/usecase/user/FetchMypageUseCase.kt | Walkhub | 443,006,389 | false | {"Kotlin": 781114} | package com.semicolon.domain.usecase.user
import com.semicolon.domain.entity.users.UserMyPageEntity
import com.semicolon.domain.repository.UserRepository
import com.semicolon.domain.usecase.UseCase
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class FetchMypageUseCase @Inject constructor(
private val userRepository: UserRepository
) : UseCase<Unit, Flow<UserMyPageEntity>>() {
override suspend fun execute(data: Unit): Flow<UserMyPageEntity> =
userRepository.fetchMyPage()
} | 5 | Kotlin | 1 | 29 | 5070c2c33365f2db6f57975078e1ecd7594f66fa | 512 | walkhub_android | MIT License |
app/src/main/java/com/example/androiddevchallenge/presentation/components/autocomplete/AutoCompleteBox.kt | pauloaapereira | 350,889,182 | false | {"Kotlin": 32660} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.presentation.components.autocomplete
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
const val AutoCompleteBoxTag = "AutoCompleteBox"
@ExperimentalAnimationApi
@Composable
fun <T : AutoCompleteEntity> AutoCompleteBox(
items: List<T>,
itemContent: @Composable (T) -> Unit,
content: @Composable AutoCompleteScope<T>.() -> Unit
) {
val autoCompleteState = remember { AutoCompleteState(startItems = items) }
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
autoCompleteState.content()
AnimatedVisibility(visible = autoCompleteState.isSearching) {
LazyColumn(
modifier = Modifier.autoComplete(autoCompleteState),
horizontalAlignment = Alignment.CenterHorizontally
) {
items(autoCompleteState.filteredItems) { item ->
Box(modifier = Modifier.clickable { autoCompleteState.selectItem(item) }) {
itemContent(item)
}
}
}
}
}
}
private fun Modifier.autoComplete(
autoCompleteItemScope: AutoCompleteDesignScope
): Modifier = composed {
val baseModifier = if (autoCompleteItemScope.shouldWrapContentHeight)
wrapContentHeight()
else
heightIn(0.dp, autoCompleteItemScope.boxMaxHeight)
baseModifier
.testTag(AutoCompleteBoxTag)
.fillMaxWidth(autoCompleteItemScope.boxWidthPercentage)
.border(
border = autoCompleteItemScope.boxBorderStroke,
shape = autoCompleteItemScope.boxShape
)
}
| 1 | Kotlin | 2 | 31 | 407a6f269cbcf654bceb1b04363f0c7273baa06b | 3,124 | Medium_JetpackCompose_AutoCompleteSearchBar | Apache License 2.0 |
library/src/androidTest/java/com/nextcloud/android/lib/resources/profile/GetHoverCardRemoteOperationIT.kt | nextcloud | 60,562,363 | false | {"Java": 1010666, "Kotlin": 607184, "Shell": 13597, "Python": 3743, "Ruby": 1620} | /* Nextcloud Android Library is available under MIT license
*
* @author <NAME>
* Copyright (C) 2021 <NAME>
* Copyright (C) 2021 Nextcloud GmbH
*
* 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.nextcloud.android.lib.resources.profile
import com.owncloud.android.AbstractIT
import com.owncloud.android.lib.resources.status.NextcloudVersion
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class GetHoverCardRemoteOperationIT : AbstractIT() {
@Before
fun before() {
testOnlyOnServer(NextcloudVersion.nextcloud_23)
}
@Test
fun testHoverCard() {
val result =
GetHoverCardRemoteOperation(nextcloudClient.userId)
.execute(nextcloudClient)
assertTrue(result.logMessage, result.isSuccess)
val hoverCard = result.resultData
assertEquals(nextcloudClient.userId, hoverCard?.userId)
}
}
| 43 | Java | 84 | 87 | 146f04d1f1c1344e03be6af00488a48e86af65f9 | 2,045 | android-library | Apache License 2.0 |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/Indent.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: Indent
*
* Full name: System`Indent
*
* Usage: System`Indent
*
* Options: None
*
* Protected
* Attributes: ReadProtected
*
* local: <>None[Local]
* Documentation: web: <>None[Web]
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun indent(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("Indent", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 861 | mathemagika | Apache License 2.0 |
app/src/main/java/com/paging/android/task/app/UiHelper.kt | Vasanthnalla | 293,063,220 | false | null | package com.paging.android.task.app
import android.app.Application
import android.content.Context
import android.net.ConnectivityManager
import android.view.View
import com.google.android.material.snackbar.Snackbar
class UiHelper constructor(private val application: Application)
{
fun getConnectivityStatus() : Boolean
{
val connectivityManager = application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo = connectivityManager.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnected
}
fun showSnackBar(view: View, content: String) = Snackbar.make(view, content, Snackbar.LENGTH_LONG).show()
} | 0 | Kotlin | 0 | 0 | 24e9ca96428ac0cae5c119283f4edd9135e3ace0 | 711 | REcyclerview-using-Paging3-Darabinbinding-MVVM- | Apache License 2.0 |
app/src/main/java/com/creepersan/rectprogressbarsample/MainActivity.kt | CreeperSan | 199,470,545 | false | null | package com.creepersan.rectprogressbarsample
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.SeekBar
import com.creepersan.rectprogressbar.RectProgressBar
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val ids = arrayOf(
progressbar_01,
progressbar_02,
progressbar_03,
progressbar_04,
progressbar_05,
progressbar_06
)
seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{
override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
ids.forEach {
it.setProgress(p1)
}
}
override fun onStartTrackingTouch(p0: SeekBar?) {
}
override fun onStopTrackingTouch(p0: SeekBar?) {
}
})
progressbar_01.setTextDecorator(object : RectProgressBar.TextDecorator{
override fun onDrawText(progress: Int): String {
return ""
}
})
progressbar_03.setTextDecorator(object : RectProgressBar.TextDecorator{
override fun onDrawText(progress: Int): String {
return when{
progress >= 99 -> {
"Done"
}
progress > 66 -> {
"Almost get it"
}
progress > 33 -> {
"Working"
}
else -> {
"Preparing"
}
}
return "IncompressibleValue->$progress"
}
})
progressbar_04.setTextDecorator(object : RectProgressBar.TextDecorator{
override fun onDrawText(progress: Int): String {
return "IncompressibleValue->$progress"
}
})
progressbar_05.setTextDecorator(object : RectProgressBar.TextDecorator{
override fun onDrawText(progress: Int): String {
return "Value->$progress"
}
})
progressbar_06.setTextDecorator(object : RectProgressBar.TextDecorator{
override fun onDrawText(progress: Int): String {
return "CompressibleValue->$progress"
}
})
}
}
| 0 | Kotlin | 0 | 0 | 4df1f5790f0124ee1eab67bcfb34eb59a0287481 | 2,590 | RectProgressBar | MIT License |
src/main/kotlin/com/swisschain/matching/engine/services/validators/common/OrderValidationUtils.kt | swisschain | 255,464,363 | false | null | package com.swisschain.matching.engine.services.validators.common
import com.swisschain.matching.engine.daos.AssetPair
import com.swisschain.matching.engine.daos.LimitOrder
import com.swisschain.matching.engine.daos.Order
import com.swisschain.matching.engine.order.OrderStatus
import com.swisschain.matching.engine.services.validators.impl.OrderValidationException
import com.swisschain.utils.logging.MetricsLogger
import java.math.BigDecimal
import java.util.Date
class OrderValidationUtils {
companion object {
private val METRICS_LOGGER = MetricsLogger.getLogger()
fun checkMinVolume(order: Order, assetPair: AssetPair): Boolean {
return order.getAbsVolume() >= assetPair.minVolume
}
fun validateBalance(availableBalance: BigDecimal, limitVolume: BigDecimal) {
if (availableBalance < limitVolume) {
throw OrderValidationException(OrderStatus.NotEnoughFunds, "not enough funds to reserve")
}
}
fun validateExpiration(order: LimitOrder, orderProcessingTime: Date) {
if (order.isExpired(orderProcessingTime)) {
throw OrderValidationException(OrderStatus.Cancelled, "expired")
}
}
fun validateOrderBookTotalSize(currentOrderBookTotalSize: Int, orderBookMaxTotalSize: Int?) {
if (orderBookMaxTotalSize != null && currentOrderBookTotalSize >= orderBookMaxTotalSize) {
val errorMessage = "Order book max total size reached (current: $currentOrderBookTotalSize, max: $orderBookMaxTotalSize)"
METRICS_LOGGER.logWarning(errorMessage)
throw OrderValidationException(OrderStatus.OrderBookMaxSizeReached, errorMessage)
}
}
}
} | 0 | Kotlin | 0 | 0 | 5ef23544e9c5b21864ec1de7ad0f3e254044bbaa | 1,769 | Exchange.MatchingEngine | Apache License 2.0 |
app/src/main/java/dev/sertan/android/videogames/util/Converter.kt | scnplt | 419,744,023 | false | null | package dev.sertan.android.videogames.util
import androidx.core.text.HtmlCompat
internal object Converter {
@JvmStatic
fun htmlToString(html: String?): String =
html?.let { HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_COMPACT).toString() } ?: ""
}
| 0 | Kotlin | 0 | 0 | 7c83c7e941cc06d0c87c7e360a4dbcbc63cfd348 | 275 | video-games | MIT License |
settings.gradle.kts | ohdyno | 711,216,044 | false | {"Kotlin": 6253, "Gherkin": 722} | plugins { id("org.gradle.toolchains.foojay-resolver-convention") version "0.7.0" }
rootProject.name = "simple-event-store"
include("lib")
| 3 | Kotlin | 0 | 0 | 6521a16036c5d74acad762067546ba33cf8b8e74 | 140 | simple-event-store | MIT License |
src/main/kotlin/de/pixel/restriddle/ErrorController.kt | HacktoberfestMunich | 391,101,431 | false | null | package de.pixel.restriddle
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.web.error.ErrorAttributeOptions
import org.springframework.boot.web.servlet.error.ErrorAttributes
import org.springframework.boot.web.servlet.error.ErrorController
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.context.request.ServletWebRequest
import org.springframework.web.context.request.WebRequest
import javax.servlet.http.HttpServletRequest
@Controller
@RequestMapping("/error")
class ErrorViewController @Autowired constructor(private val errorAttributes: ErrorAttributes) : ErrorController {
companion object {
private const val EXCEPTION_KEY = "exception"
private val LOGGER = LoggerFactory.getLogger(ErrorViewController::class.java)
}
@ResponseBody
@RequestMapping(produces = [MediaType.TEXT_PLAIN_VALUE])
fun error(model: Model, request: HttpServletRequest): ResponseEntity<String> {
val errorMap: Map<String, Any?> = if (model.containsAttribute(EXCEPTION_KEY)) {
model.asMap()
} else {
getErrorAttributes(request)
}
val status = HttpStatus.valueOf(getError(errorMap, "status") as Int)
val path = getError(errorMap, "path") as String
if (status != HttpStatus.NOT_FOUND) {
LOGGER.warn("An error occurred: $status - $path")
}
return ResponseEntity("$status - $path", status)
}
private fun getErrorAttributes(request: HttpServletRequest): Map<String, Any?> {
val webrequest: WebRequest = ServletWebRequest(request)
return errorAttributes.getErrorAttributes(webrequest, ErrorAttributeOptions.defaults())
}
private fun getError(errorMap: Map<String, Any?>, k: String): Any? {
return errorMap.getOrDefault(k, "")
}
}
| 0 | Kotlin | 0 | 0 | 6d5332b53fa6f12e6d1cfb1cdbf7f267ecd5d09b | 2,190 | rest-riddle | MIT License |
android/src/main/java/com/reactnativemidiplayback/MidiPlaybackModule.kt | clef-musical-assistant | 331,123,433 | false | {"Java": 6306, "Objective-C": 3681, "Swift": 2500, "TypeScript": 2016, "Kotlin": 1724, "JavaScript": 1419, "Ruby": 1244, "C": 103} | package com.reactnativemidiplayback
import android.media.MediaPlayer
import android.net.Uri
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
class MidiPlaybackModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
private var mediaPlayer: MediaPlayer = MediaPlayer();
override fun getName(): String {
return "MidiPlayback"
}
@ReactMethod(isBlockingSynchronousMethod = true)
fun setPlaybackFile(url: String) {
val uri = Uri.parse(url);
val context = reactApplicationContext;
if (context != null) {
mediaPlayer = MediaPlayer.create(reactApplicationContext.currentActivity, uri);
mediaPlayer.setVolume(50F, 50F);
};
}
@ReactMethod(isBlockingSynchronousMethod = true)
fun play() {
mediaPlayer.start();
}
@ReactMethod
fun stop() {
mediaPlayer.stop();
}
@ReactMethod
fun pause() {
mediaPlayer.pause();
}
@ReactMethod(isBlockingSynchronousMethod = true)
fun isPlaying(): Boolean {
return mediaPlayer.isPlaying;
}
}
| 6 | Java | 0 | 5 | c7f6480ea4fd4b5730a98bfa53615cb18c0d8d29 | 1,154 | react-native-midi-playback | MIT License |
src/main/kotlin/Main.kt | rtmigo | 552,581,689 | false | {"Kotlin": 78659, "Python": 973, "Shell": 148} | /**
* SPDX-FileCopyrightText: (c) 2022 Ar<NAME> (rtmigo.github.io)
* SPDX-License-Identifier: ISC
**/
import com.github.ajalt.clikt.core.*
import com.github.ajalt.clikt.parameters.options.*
import kotlinx.coroutines.runBlocking
import maven.*
import stages.build.*
import stages.sign.*
import stages.upload.*
import tools.rethrowingState
import java.nio.file.*
import kotlin.io.path.absolute
import kotlin.system.exitProcess
class Cli : NoOpCliktCommand(
name = "mavence",
help = "Publishes Gradle projects to Maven Central\n\nSee: https://github.com/rtmigo/mavence#readme"
) {
private val trace by option("--trace", help = "Show full stack traces on errors").flag()
init {
versionOption(Build.version) {
"$commandName $it (${Build.date})\n" +
"ISC (c) Artsiom iG <<EMAIL>>\n" +
"http://github.com/rtmigo/mavence"
}
}
override fun run() {
currentContext.findOrSetObject { CliConfig(trace = this.trace) }
}
}
fun theArtifactDir() = ArtifactDir(Paths.get(".").absolute())
//private suspend fun gaa(): GroupArtifact {
// val ad = ArtifactDir(Paths.get(".").absolute())
// return GroupArtifact(ad.group(), ad.artifact())
//}
suspend fun ArtifactDir.toGroupArtifact() = GroupArtifact(this.group(), this.artifact())
data class CliConfig(val trace: Boolean)
open class CheckCentral : CliktCommand(
help = "Check that environment is set for publishing to Maven Central") {
override fun run() = catchingCommand(this) {
fun checkVar(k: String) = rethrowingState(
{ "Environment variable $k is not set." },
{ check(System.getenv(k).isNotBlank()) })
checkVar(EnvVarNames.MAVEN_GPG_KEY)
checkVar(EnvVarNames.MAVEN_GPG_PASSWORD)
checkVar(EnvVarNames.SONATYPE_USERNAME)
checkVar(EnvVarNames.SONATYPE_PASSWORD)
System.err.println("At first glance, everything is OK.")
}
}
open class Local(help: String = "Build, publish to $m2str") : CliktCommand(help = help) {
override fun run() = catchingCommand(this) {
cmdLocal(theArtifactDir(), isFinal = true)
Unit
}
}
object EnvVarNames {
const val MAVEN_GPG_KEY = "MAVEN_GPG_KEY"
const val MAVEN_GPG_PASSWORD = "<PASSWORD>"
const val SONATYPE_USERNAME = "SONATYPE_USERNAME"
const val SONATYPE_PASSWORD = "<PASSWORD>"
}
open class Stage(help: String = "Build, sign, publish to OSSRH Staging") :
Local(help = help) {
val gpgKey by option("--gpg-key", envvar = EnvVarNames.MAVEN_GPG_KEY).required()
val gpgPwd by option("--gpg-password", envvar = EnvVarNames.MAVEN_GPG_PASSWORD).required()
protected val sonatypeUser by option(
"--sonatype-username",
envvar = EnvVarNames.SONATYPE_USERNAME).required()
protected val sonatypePassword by option(
"--sonatype-password",
envvar = EnvVarNames.SONATYPE_PASSWORD).required()
override fun run() = catchingCommand(this) {
cmdSign(
cmdLocal(theArtifactDir()),
key = GpgPrivateKey(gpgKey),
pass = G<PASSWORD>(gpgPwd)
).use {
it.toStaging(
user = SonatypeUsername(sonatypeUser),
pass = <PASSWORD>(<PASSWORD>),
it.content.notation)
}
Unit
}
}
class Central : Stage(help = "Build, sign, publish to OSSRH Staging, release to Central") {
override fun run() = catchingCommand(this) {
cmdSign(
cmdLocal(theArtifactDir()),
key = GpgPrivateKey(gpgKey),
pass = <PASSWORD>(gpgPwd)
).use { signed ->
val user = SonatypeUsername(sonatypeUser)
val pass = <PASSWORD>(<PASSWORD>)
signed.toStaging(
user = user,
pass = <PASSWORD>,
signed.content.notation).toRelease(user = user, pass = pass)
}
}
}
fun catchingCommand(cmd: CliktCommand, block: suspend () -> Unit) {
try {
runBlocking {
block()
}
} catch (e: Exception) {
if (cmd.currentContext.findObject<CliConfig>()!!.trace)
e.printStackTrace()
else
System.err.println("ERROR: $e")
System.err.println("Run with --trace to see full stack trace.")
exitProcess(1)
}
}
fun main(args: Array<String>) {
Cli()
.subcommands(Local(), Stage(), Central(), CheckCentral())
.main(args)
} | 0 | Kotlin | 0 | 1 | b0a6fced70eb91300a39d451515160343c03f698 | 4,526 | mavence | ISC License |
codegen-cli/src/main/java/pro/bilous/codegen/process/FromModelProcessor.kt | v-bilous | 296,634,785 | false | null | package pro.bilous.codegen.process
import org.openapitools.codegen.CodeCodegen
import org.openapitools.codegen.CodegenModel
import org.slf4j.LoggerFactory
import pro.bilous.codegen.process.models.CommonModelsProcessor
import pro.bilous.codegen.process.models.IModelStrategyResolver
import pro.bilous.codegen.process.models.ModelStrategyResolver
class FromModelProcessor(val codegen: CodeCodegen) {
companion object {
private val LOGGER = LoggerFactory.getLogger(FromModelProcessor::class.java)
}
fun process(codegenModel: CodegenModel): CodegenModel {
removeIgnoredFields(codegenModel)
applyStrategyResolver(ModelStrategyResolver(codegenModel))
fixEnumName(codegenModel)
val properties = codegen.additionalProperties()
CommonModelsProcessor(properties).process(model = codegenModel)
fixRequiredFieldsDefaultValue(codegenModel)
return codegenModel
}
fun fixEnumName(model: CodegenModel) {
// do not add suffix to the Enum!
if (model.isEnum) {
LOGGER.debug("enum detected")
model.classname = model.name
//codegenModel.classFilename = codegenModel.name
}
}
fun removeIgnoredFields(model: CodegenModel) {
model.vars = model.vars.filter { !it.name.startsWith("_") && !it.name.startsWith("#")}
}
fun fixRequiredFieldsDefaultValue(model: CodegenModel) {
// should introduce processor for the default values
model.vars.forEach {
if (it.required && it.defaultValue == "null") {
it.defaultValue = null
}
}
}
fun applyStrategyResolver(resolver: IModelStrategyResolver) {
val args = resolver.buildArgs()
resolver.resolveParent(args)
resolver.cleanupImports()
resolver.addExtensions(args)
}
}
| 18 | Kotlin | 4 | 3 | 3a32f8ecd14f477e59b541a10c752b352dded29e | 1,662 | difhub-codegen | MIT License |
src/main/kotlin/core/lambdaAndCollection/collectionOfHigherOrderFunctionsAPI/MapDemo.kt | programing-language | 375,609,760 | false | null | package core.lambdaAndCollection.collectionOfHigherOrderFunctionsAPI
/**
* Created by ChenJinXin on 2021/7/1 下午2:29
*/
fun test() {
val list = listOf<Int>(1, 2, 3)
fun foo(bar: Int) = bar * 2
val newList = list.map { foo(it) }
println(newList)
}
fun main() {
test()
} | 0 | Kotlin | 0 | 0 | f614aef0f625b0ac403dd0f8acfe3be384ae25e5 | 295 | KotlinCoreProgramming | Apache License 2.0 |
settings.gradle.kts | spbu-math-cs | 698,589,492 | false | {"Kotlin": 145510} |
rootProject.name = "RollPlayer"
| 0 | Kotlin | 1 | 3 | 7e5561f612a147e1631eec4648095e42693e5427 | 33 | RollPlayer-backend | Apache License 2.0 |