path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
arrow-libs/core/arrow-core/src/commonTest/kotlin/arrow/core/raise/TraceSpec.kt
arrow-kt
86,057,409
false
{"Gradle Kotlin DSL": 21, "JSON": 1, "Java Properties": 20, "Markdown": 11, "Shell": 2, "Text": 1, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "TOML": 1, "INI": 13, "YAML": 5, "SVG": 2, "Kotlin": 620, "Java": 2, "Gradle": 3, "XML": 1}
package arrow.core.raise import arrow.core.right import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import io.kotest.property.Arb import io.kotest.property.arbitrary.int import io.kotest.property.arbitrary.string import io.kotest.property.checkAll import kotlin.test.Test import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.test.runTest @OptIn(ExperimentalTraceApi::class) class TraceSpec { @Test fun traceIsEmptyWhenNoErrors() = runTest { checkAll(Arb.int()) { i -> either<Nothing, Int> { traced({ i }) { _,_ -> unreachable() } } shouldBe i.right() } } @Test fun traceIsEmptyWithException() = runTest { checkAll(Arb.string()) { msg -> val error = RuntimeException(msg) shouldThrow<RuntimeException> { either<Nothing, Int> { traced({ throw error }) { _,_ -> unreachable() } } }.message shouldBe msg } } @Test fun nestedTracingIdentity() = runTest { val inner = CompletableDeferred<String>() ior(String::plus) { traced({ traced({ raise("") }) { traced, _ -> inner.complete(traced.stackTraceToString()) } }) { traced, _ -> inner.await() shouldBe traced.stackTraceToString() } } } @Test fun nestedTracingDifferentTypes() = runTest { either { traced<Any?, _>({ traced<String, _> ({ raise(Unit) }) { _, _ -> unreachable() } }) { _, unit -> unit shouldBe Unit } } } }
1
null
1
1
1911025b2f6e84b70074edc578becb69cda8fb24
1,528
arrow
Apache License 2.0
ANDROID APP/app/src/main/java/com/app/hbcu/activity/BaseAppCompatActivity.kt
CodeCraftsCanvas
426,396,978
false
{"C++": 4530070, "C": 930961, "Swift": 378772, "Kotlin": 308625, "Python": 247661, "M4": 171945, "Makefile": 95271, "Shell": 54819, "HTML": 50621, "CSS": 43194, "Roff": 35838, "QMake": 26144, "Assembly": 7639, "Objective-C++": 7326, "Java": 2100, "Ruby": 931}
package com.app.hbcu.activity import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo import android.os.Bundle import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.fragment.app.FragmentManager import com.app.hbcu.R import com.app.hbcu.util.Config import io.github.inflationx.viewpump.ViewPumpContextWrapper import io.socket.client.IO import io.socket.client.Socket open class BaseAppCompatActivity : AppCompatActivity() { // public ProgressDialog mProgressDialog; var mContext: Context? = null var onDialogClickListener: OnDialogClickListener? = null private val TAG = BaseAppCompatActivity::class.java.name //lateinit var mySocket: Socket override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mContext = this // mySocket = IO.socket(Config.SERVER_URL_SOCKET) // mySocket.connect() } override fun attachBaseContext(newBase: Context?) { super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase!!)) } fun setToolbar( toolbar: Toolbar, title: String?, isbackenable: Boolean ) { toolbar.title = title setSupportActionBar(toolbar) if (isbackenable) { toolbar.setNavigationIcon(R.drawable.ic_back) toolbar.setNavigationOnClickListener { finish() } } } /** * Popup message and after short time this popup will automatically destroy. * * @param message Message for display in popup. */ fun showToast(message: String?) { Toast.makeText(this, message, Toast.LENGTH_LONG).show() } /** * Hide keyboard */ protected fun hideKeyboard() { val viewGroup = findViewById<View>(R.id.content) as ViewGroup val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm?.hideSoftInputFromWindow(viewGroup.windowToken, 0) } /** * Open Keyboard. */ fun showKeyboard() { val viewGroup = findViewById<View>(R.id.content) as ViewGroup val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm?.toggleSoftInputFromWindow( viewGroup.applicationWindowToken, InputMethodManager.SHOW_FORCED, 0 ) } fun clearBackStack() { val manager = supportFragmentManager if (manager.backStackEntryCount > 0) { val first = manager.getBackStackEntryAt(0) manager.popBackStackImmediate( first.id, FragmentManager.POP_BACK_STACK_INCLUSIVE ) } } fun showOKAlert( messageString: String?, onDialogClickListener1: OnDialogClickListener? ) { onDialogClickListener = onDialogClickListener1 val builder = AlertDialog.Builder(this@BaseAppCompatActivity) builder.setMessage(messageString) builder.setPositiveButton("Ok") { dialog, which -> dialog.dismiss() onDialogClickListener!!.onPositive() } val alert = builder.create() alert.show() } fun showPositiveNegativeAlert( messageString: String?, yes: Int, no: Int, onDialogClickListener1: OnDialogClickListener? ) { onDialogClickListener = onDialogClickListener1 val builder = AlertDialog.Builder(this@BaseAppCompatActivity) builder.setMessage(messageString) builder.setPositiveButton(yes) { dialog, which -> dialog.dismiss() onDialogClickListener!!.onPositive() } builder.setNegativeButton(no) { dialog, which -> dialog.dismiss() onDialogClickListener!!.onNegative() } val alert = builder.create() alert.show() } val isConnectedToInternet: Boolean get() { val cm = this@BaseAppCompatActivity.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager var activeNetwork: NetworkInfo? = null if (cm != null) { activeNetwork = cm.activeNetworkInfo } if (activeNetwork != null) { if (activeNetwork.type == ConnectivityManager.TYPE_WIFI) { return true } else if (activeNetwork.type == ConnectivityManager.TYPE_MOBILE) { return true } } else { showToast(resources.getString(R.string.msg_no_internet)) return false } return false } interface OnDialogClickListener { fun onPositive() fun onNegative() } override fun onDestroy() { super.onDestroy() } }
1
C++
0
0
a1a999af442f81d760cef5b50e2976fc8b3cff79
5,132
hbcur
MIT License
vxutil-vertigram/src/main/kotlin/ski/gagar/vxutil/vertigram/methods/SendVideo.kt
gagarski
314,041,476
false
null
package ski.gagar.vxutil.vertigram.methods import ski.gagar.vertigram.annotations.TgMethod import ski.gagar.vxutil.vertigram.types.ChatId import ski.gagar.vxutil.vertigram.types.Message import ski.gagar.vxutil.vertigram.types.MessageEntity import ski.gagar.vxutil.vertigram.types.ParseMode import ski.gagar.vxutil.vertigram.types.ReplyMarkup import ski.gagar.vxutil.vertigram.types.attachments.Attachment import ski.gagar.vxutil.vertigram.util.multipart.TgMedia import java.time.Duration @TgMethod data class SendAnimation( val chatId: ChatId, @TgMedia val animation: Attachment, val duration: Duration? = null, val width: Int? = null, val height: Int? = null, @TgMedia val thumb: Attachment? = null, val caption: String? = null, val parseMode: ParseMode? = null, val captionEntities: List<MessageEntity>? = null, val disableNotification: Boolean = false, val protectContent: Boolean = false, val replyToMessageId: Long? = null, val allowSendingWithoutReply: Boolean = false, val replyMarkup: ReplyMarkup? = null ) : MultipartTgCallable<Message>()
0
Kotlin
0
0
20cd7a50d017f865814891fa15324c11434e679a
1,114
vertigram
Apache License 2.0
data/src/main/java/com/team_sunshijo/data/remote/response/auth/TokenResponse.kt
Team-Sunshijo
640,839,334
false
null
package com.team_sunshijo.data.remote.response.auth import com.google.gson.annotations.SerializedName import com.team_sunshijo.domain.entity.auth.TokenEntity import org.threeten.bp.LocalDateTime data class TokenResponse( @SerializedName("access_token") val access_token: String, @SerializedName("refresh_token") val refresh_token: String, @SerializedName("access_token_exp") val access_token_exp: String ) fun TokenResponse.toEntity() = TokenEntity( access_token = access_token, refresh_token = refresh_token, access_token_exp = LocalDateTime.parse(access_token_exp) )
0
Kotlin
0
1
bd983ab706f202c6560118426544501c5ae002f2
595
Sunshijo-Android
MIT License
src/main/kotlin/org/bilalkilic/kediatrhelper/utils/constants/TemplateFileConstants.kt
bilal-kilic
285,244,277
false
{"Kotlin": 23907}
package org.bilalkilic.kediatrhelper.utils.constants object TemplateFileConstants { const val CLASS = "CLASS" const val RETURN = "RETURN" const val MESSAGE = "MESSAGE" const val SUFFIX_HANDLER = "Handler" const val SUFFIX_HANDLER_ASYNC = "AsyncHandler" const val TEMPLATE_FILE_HANDLER_QUERY = "createNewQueryHandler" const val TEMPLATE_FILE_HANDLER_QUERY_ASYNC = "createNewQueryAsyncHandler" const val TEMPLATE_FILE_HANDLER_COMMAND = "createNewCommandHandler" const val TEMPLATE_FILE_HANDLER_COMMAND_ASYNC = "createNewCommandAsyncHandler" const val TEMPLATE_FILE_HANDLER_COMMAND_WITH_RESULT = "createNewCommandWithResultHandler" const val TEMPLATE_FILE_HANDLER_COMMAND_WITH_RESULT_ASYNC = "createNewCommandWithResultAsyncHandler" const val TEMPLATE_FILE_HANDLER_NOTIFICATION = "createNewNotificationHandler" const val TEMPLATE_FILE_HANDLER_NOTIFICATION_ASYNC = "createNewNotificationAsyncHandler" }
2
Kotlin
5
4
ac41fcb1346f1153991745a03a9dae33df6c212f
952
kediatr-helper
MIT License
src/main/kotlin/ltd/icecold/music/musicUrlBean/FreeTrialPrivilege.kt
GceCold
338,926,661
false
null
package ltd.icecold.music.musicUrlBean data class FreeTrialPrivilege( val resConsumable: Boolean, val userConsumable: Boolean )
0
Kotlin
0
3
bec035ccbfb4db33ea7388994e99a3ef852a13f4
136
MusicBot
MIT License
src/main/kotlin/ltd/icecold/music/musicUrlBean/FreeTrialPrivilege.kt
GceCold
338,926,661
false
null
package ltd.icecold.music.musicUrlBean data class FreeTrialPrivilege( val resConsumable: Boolean, val userConsumable: Boolean )
0
Kotlin
0
3
bec035ccbfb4db33ea7388994e99a3ef852a13f4
136
MusicBot
MIT License
server/src/test/kotlin/com/adobe/testing/s3mock/HttpRangeHeaderConverterTest.kt
adobe
97,753,277
false
{"Kotlin": 519898, "Java": 424551, "Shell": 3792, "Dockerfile": 3156}
/* * Copyright 2017-2024 Adobe. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.adobe.testing.s3mock import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class HttpRangeHeaderConverterTest { @Test fun testRangeHeader() { val iut = HttpRangeHeaderConverter() val rangeHeader = "bytes=1-2" val actual = iut.convert(rangeHeader) assertThat(actual).isNotNull() assertThat(actual!!.getRangeStart(Long.MAX_VALUE)).isEqualTo(1) assertThat(actual.getRangeEnd(Long.MAX_VALUE)).isEqualTo(2) } }
17
Kotlin
180
826
2a375f602dc130d5a789b2812e2b8760c6689e87
1,098
S3Mock
Apache License 2.0
Kotlin/sigaa/src/main/java/sigaa/acristoffers/me/sigaagrades/Utils.kt
acristoffers
141,364,244
false
{"Dart": 153946, "Kotlin": 92257, "C++": 21356, "CMake": 18200, "Ruby": 2684, "Swift": 1766, "C": 1425, "HTML": 184, "Objective-C": 38}
/* * Copyright (c) 2018 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package sigaa.acristoffers.me.sigaagrades fun <T> tryOrDefault(defaultValue: T, f: () -> T): T { return try { f() } catch (_: Throwable) { defaultValue } } fun <T, U> Collection<T>.zipBy(B: Collection<T>, filter: (E: T) -> U): Collection<Pair<T, T>> { return this.mapNotNull { a -> val second = B.firstOrNull { b -> filter(b) == filter(a) } if (second != null) { Pair(a, second) } else { null } } } fun <T, R> Collection<Pair<T, T>>.comparePairWith(comparator: (a: T, b: T) -> R): Collection<R> { return this.map { comparator(it.first, it.second) } }
1
Dart
1
5
bc8172dbffea97278370f5790210ae182a2d62e8
1,764
SIGAAGrades
MIT License
src/main/kotlin/io/sharptree/maximo/app/label/sse/okhttp/OkHttp.kt
sharptree
489,526,298
false
null
package io.sharptree.maximo.app.label.sse.okhttp import io.sharptree.maximo.app.label.sse.AwaitConnectivity import io.sharptree.maximo.app.label.sse.EventId import io.sharptree.maximo.app.label.sse.Logger import io.sharptree.maximo.app.label.sse.MaybeAwaitConnectivity import io.sharptree.maximo.app.label.sse.Milliseconds import io.sharptree.maximo.app.label.sse.connectToSse import kotlinx.coroutines.CoroutineScope import okhttp3.MediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okio.BufferedSource import java.io.IOException import kotlin.random.Random @PublishedApi internal val NoWait: AwaitConnectivity? = null /** @see [connectToSse] */ fun CoroutineScope.connectToSse( client: OkHttpClient, requestBuilder: Request.Builder, initialRetryTime: Milliseconds? = null, initialEventId: EventId? = null, maybeAwaitConnectivity: MaybeAwaitConnectivity = { NoWait }, logger: Logger? = null, random: Random = Random.Default ) = connectToSse<Response, IOException>( addHeaderToRequest = { name, value -> requestBuilder.header(name, value) }, performRequest = { client.enqueueSuspending(requestBuilder.build()) }, getResponseHttpCode = { code }, getResponseMediaType = { contentType?.type }, getResponseMediaSubType = { contentType?.subtype }, indexOfInBuffer = { source.buffer.indexOf(it) }, readAllInBuffer = { source.buffer.readUtf8() }, bufferSize = { source.buffer.size }, readInStream = { source.readUtf8(it) }, skipInStream = { source.skip(it) }, isStreamExhausted = { source.exhaustedSafe() }, disposeResponse = { body?.close() }, initialRetryTime = initialRetryTime, initialEventId = initialEventId, maybeAwaitConnectivity = maybeAwaitConnectivity, logger = logger, random = { random.nextLong(Long.MAX_VALUE) } ) inline val Response.contentType: MediaType? get() = body?.contentType() inline val Response.source: BufferedSource get() = body!!.source()
0
Kotlin
0
0
6f0179f8022a7881ae78ef207a33e43ded634ede
2,086
label-print-agent
MIT License
app/src/main/java/com/solarexsoft/constraintlayoutlearningdemo/motion/MotionBasic.kt
flyfire
287,486,056
false
null
package com.solarexsoft.constraintlayoutlearningdemo.motion import com.solarexsoft.constraintlayoutlearningdemo.BaseDemoActivity import com.solarexsoft.constraintlayoutlearningdemo.R /** * <pre> * Author: houruhou * CreatAt: 23:45/2020/8/24 * Desc: * </pre> */ class MotionBasic : BaseDemoActivity() { override fun layoutId(): Int = R.layout.motion_basic_0 }
0
Kotlin
0
0
41abe56914aa77813d6523a3acb3f72511c7ce6e
381
ConstraintLayoutLearningDemo
MIT License
core/src/commonMain/kotlin/work/socialhub/planetlink/model/paging/DatePaging.kt
uakihir0
733,128,300
false
{"Kotlin": 687284, "Shell": 1521, "Makefile": 363}
package work.socialhub.planetlink.model.paging import work.socialhub.planetlink.model.Identify import work.socialhub.planetlink.model.Paging /** * Paging with date range * 時間範囲指定 * (Slack) */ class DatePaging : Paging() { var latest: String? = null var oldest: String? = null var inclusive: Boolean? = null /** * {@inheritDoc} */ override fun <K : Identify> newPage(entities: List<K>): Paging { val newPage = DatePaging() newPage.count = count if (entities.isNotEmpty()) { val first = entities[0].id as String? newPage.inclusive = false newPage.oldest = first return newPage } else { // デフォルト動作 if (latest != null && inclusive != null) { newPage.inclusive = !inclusive!! newPage.oldest = latest return newPage } // 上記以外は再度リクエスト return this.copy() } } /** * {@inheritDoc} */ override fun <K : Identify> pastPage(entities: List<K>): Paging { val newPage = DatePaging() newPage.count = count if (entities.isNotEmpty()) { val index = (entities.size - 1) val last = entities[index].id as String? newPage.inclusive = false newPage.latest = last return newPage } else { // デフォルト動作 if (oldest != null && inclusive != null) { newPage.inclusive = !inclusive!! newPage.latest = oldest return newPage } // 上記以外は再度リクエスト return this.copy() } } /** * {@inheritDoc} */ override fun setMarkPagingEnd(entities: List<*>) { if (isHasPast && entities.isEmpty() && (oldest == null) && (count!! > 0) ) { isHasPast = false } } /** * オプジェクトコピー */ override fun copy(): DatePaging { return DatePaging().also { it.latest = latest it.oldest = oldest it.inclusive = inclusive copyTo(it) } } companion object { /** * From Paging instance */ fun fromPaging(paging: Paging?): DatePaging { if (paging is DatePaging) { return paging.copy() } // Count の取得 val pg = DatePaging() if ((paging != null) && (paging.count != null)) { pg.count = paging.count } return pg } } }
1
Kotlin
0
1
04213c5d21f0df4c0f2424b680efd4d159784572
2,663
planetlink
MIT License
src/test/java/com/bukowiecki/breakpoints/utils/BreakpointManagerUtilsTest.kt
marcin-bukowiecki
401,104,358
false
null
/* * Copyright 2021 <NAME>. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.bukowiecki.breakpoints.utils import com.bukowiecki.breakpoints.service.MyMockProject import com.bukowiecki.breakpoints.service.MyProjectWrapper import org.junit.Assert import org.junit.Test /** * @author <NAME> */ class BreakpointManagerUtilsTest { @Test fun testCreateAbsolutePath1() { val expected = "file:///C:/foo/src/Test.java" val given = BreakpointManagerUtils.createAbsolutePath(MyProjectWrapper(MyMockProject()), "src/Test.java") Assert.assertEquals(expected, given) } }
0
Kotlin
0
2
a6f5005b34894980bd49c04a61387cca79877307
670
breakpoint-manager-plugin
Apache License 2.0
api/src/main/kotlin/br/com/strn/erp/api/database/dao/seguranca/UsuarioLoginRepository.kt
IvoSestren
331,951,557
false
null
package br.com.strn.erp.api.database.dao.seguranca import br.com.strn.erp.api.database.dao.BaseRepository import br.com.strn.erp.api.database.entities.seguranca.UsuarioLogin import org.springframework.data.jpa.repository.Query interface UsuarioLoginRepository : BaseRepository<UsuarioLogin> { @Query("select b from UsuarioLogin b inner join Email c on c = b.email where c.email = ?1") fun findByEmail(email: String): UsuarioLogin? }
0
Kotlin
0
0
a955b4a4b8b4e4f2b746bbe5bc4fe3674ab9caf1
442
erp_001
The Unlicense
Core/src/commonMain/kotlin/io/nacular/doodle/deviceinput/KeyboardFocusManager.kt
Hazer
273,358,963
true
{"Kotlin": 1307880}
package io.nacular.doodle.deviceinput import io.nacular.doodle.core.View import io.nacular.doodle.event.KeyEvent import io.nacular.doodle.event.KeyState import io.nacular.doodle.focus.FocusManager import io.nacular.doodle.focus.FocusTraversalPolicy.TraversalType import io.nacular.doodle.focus.FocusTraversalPolicy.TraversalType.Backward import io.nacular.doodle.focus.FocusTraversalPolicy.TraversalType.Downward import io.nacular.doodle.focus.FocusTraversalPolicy.TraversalType.Forward import io.nacular.doodle.focus.FocusTraversalPolicy.TraversalType.Upward import io.nacular.doodle.system.KeyInputService import io.nacular.doodle.system.KeyInputService.Listener import io.nacular.doodle.utils.contains /** * Created by <NAME> on 3/10/18. */ interface Listener { operator fun invoke(keyEvent: KeyEvent) } interface Preprocessor { operator fun invoke(keyEvent: KeyEvent) } interface Postprocessor { operator fun invoke(keyEvent: KeyEvent) } interface KeyboardFocusManager { fun shutdown() } class KeyboardFocusManagerImpl( private val keyInputService : KeyInputService, private val focusManager : FocusManager, private val defaultTraversalKeys: Map<TraversalType, Set<KeyState>>): KeyboardFocusManager, Listener { private var preprocessors = mutableListOf<Preprocessor >() private var postprocessors = mutableListOf<Postprocessor>() init { keyInputService += this } override fun shutdown() { keyInputService -= this } override operator fun invoke(keyState: KeyState): Boolean { focusManager.focusOwner?.let { focusOwner -> val keyEvent = KeyEvent(focusOwner, keyState) preprocessKeyEvent(keyEvent) if (!keyEvent.consumed) { handleKeyEvent(focusOwner, keyEvent) } if (!keyEvent.consumed) { postprocessKeyEvent(keyEvent) } return !keyEvent.consumed } return false } operator fun plusAssign (preprocessor: Preprocessor) { preprocessors.add (preprocessor) } operator fun minusAssign(preprocessor: Preprocessor) { preprocessors.remove(preprocessor) } operator fun plusAssign (postprocessor: Postprocessor) { postprocessors.add (postprocessor) } operator fun minusAssign(postprocessor: Postprocessor) { postprocessors.remove(postprocessor) } private fun handleKeyEvent(view: View, keyEvent: KeyEvent) { val keyState = keyEvent.run { KeyState(code, key, modifiers, type) } val upwardKeyEvents = view[Upward ] ?: defaultTraversalKeys[Upward ] val forwardKeyEvents = view[Forward ] ?: defaultTraversalKeys[Forward ] val backwardKeyEvents = view[Backward] ?: defaultTraversalKeys[Backward] val downwardKeyEvents = if (view.isFocusCycleRoot_) view[Downward] else null when (keyState) { in forwardKeyEvents -> focusManager.moveFocusForward (view) in backwardKeyEvents -> focusManager.moveFocusBackward(view) in upwardKeyEvents -> focusManager.moveFocusUpward (view) in downwardKeyEvents -> focusManager.moveFocusDownward(view) else -> { // var g: View? = view // while (g != null) { // if (g.monitorsKeyboard) { view.handleKeyEvent_(keyEvent) // break // } else { // g = g.parent // } // } } } keyEvent.consume() } private fun preprocessKeyEvent(event: KeyEvent) { preprocessors.forEach { it(event) if (event.consumed) { return } } } private fun postprocessKeyEvent(event: KeyEvent) { postprocessors.forEach { it(event) if (event.consumed) { return } } } }
0
null
0
0
f878abf3163a49d515038f6699a4124f087e9885
3,986
doodle
MIT License
src/main/kotlin/xyz/xenondevs/nmsutils/advancement/trigger/LevitationTrigger.kt
xenondevs
510,266,783
false
null
package xyz.xenondevs.nmsutils.advancement.trigger import xyz.xenondevs.nmsutils.adapter.Adapter import xyz.xenondevs.nmsutils.adapter.impl.IntBoundsAdapter import xyz.xenondevs.nmsutils.advancement.predicate.DistancePredicate import xyz.xenondevs.nmsutils.advancement.predicate.EntityPredicate import net.minecraft.advancements.critereon.LevitationTrigger as MojangLevitationTrigger class LevitationTrigger( val player: EntityPredicate?, val distance: DistancePredicate?, val duration: IntRange? ) : Trigger { companion object : Adapter<LevitationTrigger, MojangLevitationTrigger.TriggerInstance> { override fun toNMS(value: LevitationTrigger): MojangLevitationTrigger.TriggerInstance { return MojangLevitationTrigger.TriggerInstance( EntityPredicate.EntityPredicateCompositeAdapter.toNMS(value.player), DistancePredicate.toNMS(value.distance), IntBoundsAdapter.toNMS(value.duration) ) } } class Builder : Trigger.Builder<LevitationTrigger>() { private var distance: DistancePredicate? = null private var duration: IntRange? = null fun distance(init: DistancePredicate.Builder.() -> Unit) { distance = DistancePredicate.Builder().apply(init).build() } fun duration(duration: IntRange) { this.duration = duration } override fun build(): LevitationTrigger { return LevitationTrigger(player, distance, duration) } } }
0
Kotlin
1
1
dd7bbb76240cf5c8316f67c9b076ce8ce7842d6f
1,611
NMS-Utilities
MIT License
app/src/main/java/com/example/pokedex/data/PokedexPagingSource.kt
RamziJabali
389,429,666
false
{"Kotlin": 35432}
package com.example.pokedex.data import android.annotation.SuppressLint import android.util.Log import androidx.paging.PagingSource import androidx.paging.PagingState import androidx.paging.rxjava2.RxPagingSource import com.example.pokedex.model.PokedexRepo import com.example.pokedex.model.UseCase import com.example.pokedex.network.Pokedex.Pokedex import com.example.pokedex.pokedex.view.GridProperties import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.addTo import io.reactivex.schedulers.Schedulers import retrofit2.HttpException import java.io.IOException private const val POKEMON_STARTING_POSITION = 0 class PokedexPagingSource(private val pokedexUseCase: UseCase) : RxPagingSource<Int, GridProperties>() { companion object { private const val LIMIT = 10 } val compositeDisposable = CompositeDisposable() override fun getRefreshKey(state: PagingState<Int, GridProperties>): Int? { return state.anchorPosition?.let { anchorPosition -> state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1) ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1) } } @SuppressLint("CheckResult") override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, GridProperties>> { val position = params.key ?: POKEMON_STARTING_POSITION return try { val pokedexList = mutableListOf<GridProperties>() pokedexUseCase.getPokedex(position, LIMIT) .subscribeOn(Schedulers.io()) .map { pokedex -> Log.i(PagingSource::class.toString(), "Got the pokedex") for (i in pokedex.pokemonId.indices) { val gridProperties = GridProperties( itemText = pokedex.pokemonName[i], itemOrderNumberString = pokedex.pokemonIdString[i], itemOrderNumber = pokedex.pokemonId[i] ) pokedexList.add(gridProperties) } LoadResult.Page( data = pokedexList, prevKey = if (position == POKEMON_STARTING_POSITION) null else position - 1, nextKey = position + LIMIT ) } } catch (exception: IOException) { Single.just(LoadResult.Error(exception)) } catch (exception: HttpException) { Single.just(LoadResult.Error(exception)) } } }
0
Kotlin
0
2
59e60563e32feabb07abb1cb22839f0c81a7c37a
2,674
pokedex-android
Apache License 2.0
src/main/kotlin/snc/openchargingnetwork/node/config/TaskConfig.kt
energywebfoundation
480,875,794
false
{"Kotlin": 612395, "Java": 136702, "Shell": 209, "Batchfile": 194, "Dockerfile": 150}
/* Copyright 2019-2020 eMobilify GmbH 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 snc.openchargingnetwork.node.config import org.springframework.context.annotation.Configuration import org.springframework.scheduling.annotation.SchedulingConfigurer import org.springframework.scheduling.config.IntervalTask import org.springframework.scheduling.config.ScheduledTaskRegistrar @Configuration class TaskConfig(private val scheduledTasks: List<IntervalTask>): SchedulingConfigurer { override fun configureTasks(taskRegistrar: ScheduledTaskRegistrar) { // override default thread pool task scheduler as follows: // note: not the same as the thread executor which runs async tasks (methods with with @Async annotations) // val threadPoolTaskScheduler = ThreadPoolTaskScheduler() // threadPoolTaskScheduler.poolSize = 10 // threadPoolTaskScheduler.setThreadNamePrefix("task-pool-") // threadPoolTaskScheduler.initialize() // taskRegistrar.setTaskScheduler(threadPoolTaskScheduler) for (task in scheduledTasks) { taskRegistrar.addFixedRateTask(task) } } }
16
Kotlin
4
5
396e4b54541981a5c9b8c0b5a56db2eff50a27ab
1,674
ocn-node
Apache License 2.0
src/main/kotlin/de/coaster/cringepvp/enums/Kits.kt
RasselbandeDE
524,159,699
false
{"Kotlin": 167161}
package de.coaster.cringepvp.enums import de.coaster.cringepvp.extensions.Currency import de.coaster.cringepvp.extensions.abbreviate import de.coaster.cringepvp.utils.toItemBuilder import org.bukkit.Material import org.bukkit.inventory.ItemStack import kotlin.time.Duration import kotlin.time.Duration.Companion.INFINITE import kotlin.time.Duration.Companion.minutes enum class Kits(val minRank: Ranks = Ranks.Spieler, val kaufPreis: Currency = Currency(0.0, 0), val currencyType: CurrencyType = CurrencyType.COINS, val duration: Duration = INFINITE, val cooldown: Duration, val icon: ItemStack, val items: Array<ItemStack> = arrayOf()) { Starter( cooldown = 5.minutes, icon = Material.LEATHER_CHESTPLATE.toItemBuilder { display("<#e67e22>Starter Kit") }.build(), items = arrayOf( Material.LEATHER_HELMET.toItemBuilder().build(), Material.LEATHER_CHESTPLATE.toItemBuilder().build(), Material.LEATHER_LEGGINGS.toItemBuilder().build(), Material.LEATHER_BOOTS.toItemBuilder().build(), Material.WOODEN_SWORD.toItemBuilder().build(), Material.BREAD.toItemBuilder().asQuantity(16).build(), ) ), Miner( kaufPreis = 10 abbreviate 0, currencyType = CurrencyType.CRYSTALS, cooldown = 15.minutes, icon = Material.DIAMOND_PICKAXE.toItemBuilder { display("<#e67e22>Miner Kit") }.build(), items = arrayOf( Material.STONE_PICKAXE.toItemBuilder { display("<#e67e22>Spitzhacke") }.build(), ) ), Archer( kaufPreis = 100 abbreviate 3, minRank = Ranks.Premium, cooldown = 10.minutes, icon = Material.BOW.toItemBuilder { display("<#e67e22>Archer Kit") }.build(), items = arrayOf( Material.ARROW.toItemBuilder { display("<#e67e22>Arrow") }.asQuantity(16).build(), Material.SPECTRAL_ARROW.toItemBuilder { display("<#e67e22>Sichtbarmach Pfeil") }.build(), Material.BOW.toItemBuilder { display("<#e67e22>Bow") }.build().asOne() ) ), Carl( kaufPreis = 500 abbreviate 10, currencyType = CurrencyType.GEMS, cooldown = 30.minutes, icon = Material.LLAMA_SPAWN_EGG.toItemBuilder { display("<#e67e22>Carl Kit") }.build(), items = arrayOf( Material.DIAMOND_SWORD.toItemBuilder { display("<#e67e22>Schwert") }.build(), Material.DIAMOND_AXE.toItemBuilder { display("<#e67e22>Axt") }.build(), Material.ARROW.toItemBuilder { display("<#e67e22>Arrow") }.asQuantity(16).build(), Material.SPECTRAL_ARROW.toItemBuilder { display("<#e67e22>Sichtbarmach Pfeil") }.build(), Material.BOW.toItemBuilder { display("<#e67e22>Bow") }.build(), Material.ENDER_PEARL.toItemBuilder { display("<#e67e22>Enderperle") }.asQuantity(16).build(), Material.GOLDEN_APPLE.toItemBuilder { display("<#e67e22>Goldener Apfel") }.asQuantity(5).build(), Material.COOKED_BEEF.toItemBuilder { display("<#e67e22>Steak") }.asQuantity(64).build(), ) ), }
1
Kotlin
0
0
d76595745f7ad74e8fb043f103ece1e590e33564
3,110
CringePvP
MIT License
src/main/kotlin/com/redlimerl/carnage/registry/CarnageEntities.kt
RedLime
336,246,065
false
null
package com.redlimerl.carnage.registry import com.redlimerl.carnage.CarnageMod.Companion.identifier import com.redlimerl.carnage.client.* import com.redlimerl.carnage.entity.* import net.fabricmc.fabric.api.`object`.builder.v1.entity.FabricDefaultAttributeRegistry import net.fabricmc.fabric.api.`object`.builder.v1.entity.FabricEntityTypeBuilder import net.fabricmc.fabric.api.client.rendereregistry.v1.EntityRendererRegistry import net.minecraft.client.render.entity.EntityRendererFactory import net.minecraft.entity.EntityDimensions import net.minecraft.entity.EntityType import net.minecraft.entity.SpawnGroup import net.minecraft.util.registry.Registry import net.minecraft.world.World object CarnageEntities { val CARCANO: EntityType<CarcanoEntity> = Registry.register(Registry.ENTITY_TYPE, identifier("carcano"), FabricEntityTypeBuilder.create(SpawnGroup.MONSTER, ::CarcanoEntity).dimensions(EntityDimensions.fixed(0.6f, 1.95f)).build()) val KILLBOT: EntityType<KillbotEntity> = Registry.register(Registry.ENTITY_TYPE, identifier("killbot"), FabricEntityTypeBuilder.create(SpawnGroup.MONSTER, ::KillbotEntity).dimensions(EntityDimensions.fixed(0.6f, 1.7f)).build()) val COGNITION: EntityType<CognitionEntity> = Registry.register(Registry.ENTITY_TYPE, identifier("cognition"), FabricEntityTypeBuilder.create(SpawnGroup.MONSTER, ::CognitionEntity).dimensions(EntityDimensions.fixed(0.6f, 1.99f)).build()) val ZIROKABI: EntityType<ZirokabiEntity> = Registry.register(Registry.ENTITY_TYPE, identifier("zirokabi"), FabricEntityTypeBuilder.create(SpawnGroup.MONSTER, ::ZirokabiEntity).dimensions(EntityDimensions.fixed(2.7f, 1.2f)).build()) val THE_RUPTURE: EntityType<TheRuptureEntity> = Registry.register(Registry.ENTITY_TYPE, identifier("the_rupture"), FabricEntityTypeBuilder.create(SpawnGroup.MONSTER, ::TheRuptureEntity).dimensions(EntityDimensions.fixed(1f, 2f)).build()) fun registry() { EntityRendererRegistry.INSTANCE.register(CARCANO, ::CarcanoRenderer) EntityRendererRegistry.INSTANCE.register(KILLBOT, ::KillbotRenderer) EntityRendererRegistry.INSTANCE.register(COGNITION, ::CognitionRenderer) EntityRendererRegistry.INSTANCE.register(ZIROKABI, ::ZirokabiRenderer) EntityRendererRegistry.INSTANCE.register(THE_RUPTURE, ::TheRuptureRenderer) } fun serverRegistry() { FabricDefaultAttributeRegistry.register(CARCANO, CarcanoEntity.createAttributes()) FabricDefaultAttributeRegistry.register(KILLBOT, KillbotEntity.createAttributes()) FabricDefaultAttributeRegistry.register(COGNITION, CognitionEntity.createAttributes()) FabricDefaultAttributeRegistry.register(ZIROKABI, ZirokabiEntity.createAttributes()) FabricDefaultAttributeRegistry.register(THE_RUPTURE, TheRuptureEntity.createAttributes()) } }
1
null
1
1
57051adce9e19aee7fbdcc5daa798f9d4e512af0
2,988
CarnageMod
Creative Commons Zero v1.0 Universal
ejemplo-validacion/src/main/kotlin/com/salesianostriana/dam/ejerciciojpakotlin/EjercicioJpaKotlinApplication.kt
lmlopezmagana
338,992,934
false
null
package com.salesianostriana.dam.ejerciciojpakotlin import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class EjercicioJpaKotlinApplication fun main(args: Array<String>) { runApplication<EjercicioJpaKotlinApplication>(*args) }
0
Kotlin
0
3
45c355d5f21d79e7172edcf24af6c17f8fe66291
317
ad-psp-springboot-kotlin-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/github/toncherami/mpd/web/adapter/properties/MpdProperties.kt
TonCherAmi
295,049,940
false
null
package com.github.toncherami.mpd.web.adapter.properties import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.context.properties.ConstructorBinding @ConstructorBinding @ConfigurationProperties(prefix = "mpd") data class MpdProperties( val host: String, val port: Int, val password: String? )
0
Kotlin
0
0
bf35157584e0856d11281572cd58d9ceccb57676
360
mpdweb.backend
MIT License
app/src/main/java/com/nisaefendioglu/errorhandler/ErrorActivity.kt
nisaefendioglu
780,402,400
false
{"Kotlin": 4504}
package com.nisaefendioglu.errorhandler import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.nisaefendioglu.errorhandler.databinding.ActivityErrorBinding import kotlin.system.exitProcess class ErrorActivity : AppCompatActivity() { private lateinit var binding: ActivityErrorBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityErrorBinding.inflate(layoutInflater) setContentView(binding.root) val errorText = intent.getStringExtra("error") binding.errorTextView.text = errorText binding.closeButton.setOnClickListener { exitProcess(0) } } }
0
Kotlin
0
1
14f08d6995903bdeb4c23c8123ab1d97d31e6204
718
ErrorHandler
MIT License
server/src/main/kotlin/com/thoughtworks/archguard/workbench/model/AsCodeResponse.kt
archguard
460,910,110
false
{"Kotlin": 1763628, "Java": 611399, "TypeScript": 11395, "C#": 5593, "Dockerfile": 2549, "C": 1223, "Shell": 926, "JavaScript": 400, "Go": 291, "Scala": 97, "Python": 42, "Rust": 32}
package com.thoughtworks.archguard.workbench.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable sealed class AsCodeContent @Serializable class RepoStatus(val success: List<String>, val existed: List<String>) : AsCodeContent() @Serializable class PlaceHolder() : AsCodeContent() @Serializable enum class ServerMessageType { @SerialName("normal") NORMAL, } @Serializable class AsCodeResponse( var msgType: ServerMessageType = ServerMessageType.NORMAL, var content: AsCodeContent, )
1
Kotlin
89
575
049f3cc8f2c0e2c34e65bb0049f645caa5be9bf8
553
archguard
MIT License
ui-library/src/main/java/app/surgo/ui/library/LibraryViewState.kt
tsukiymk
382,220,719
false
null
package app.surgo.ui.library import androidx.compose.runtime.Immutable import app.surgo.data.entities.PlaylistEntity @Immutable internal data class LibraryViewState( val playlists: List<PlaylistEntity> = emptyList() )
0
Kotlin
0
0
270baf768c5bfab528384693ed85289fecb0e365
224
surgo-android
Apache License 2.0
src/main/kotlin/com/google/androidstudiopoet/generators/project/ProjectBuildGradleGenerator.kt
ZacSweers
111,372,837
true
{"Kotlin": 60506}
package com.google.androidstudiopoet.generators.project import java.io.File import java.io.FileInputStream import java.nio.file.Files import java.nio.file.StandardCopyOption internal const val ASSETS_PATH = "src/main/assets" class ProjectBuildGradleGenerator { fun generate(root: String) { val buildGradle = "build.gradle" val gradleWFile = File(root, buildGradle).toPath() Files.copy(FileInputStream(File(ASSETS_PATH, buildGradle)), gradleWFile, StandardCopyOption.REPLACE_EXISTING) } }
0
Kotlin
0
1
ecae7eab1750910bf7357daed87efb1bd57e3250
526
android-studio-poet
Apache License 2.0
shared/src/commonMain/kotlin/dev/vladleesi/yac/ui/style/Colors.kt
vladleesi
655,099,053
false
null
package dev.vladleesi.yac.ui.style import androidx.compose.ui.graphics.Color val orange = Color(0xfff08e3a) val textColorBlack = Color(0xff707070) val textColorWhite = Color(0xfff7f7f7)
0
Kotlin
0
0
fbde78f124ab35fff9cc1e947b71f834712cc7a3
187
yet-another-calculator
Apache License 2.0
app/src/main/java/com/mohfahmi/mkaassesment/data/source/remote/response/SearchResponse.kt
MohFahmi27
447,899,964
false
null
package com.mohfahmi.mkaassesment.data.source.remote.response import com.google.gson.annotations.SerializedName data class SearchResponse( @field:SerializedName("items") val items: List<ItemsItem> ) data class ItemsItem( @field:SerializedName("login") val login: String )
0
Kotlin
0
1
9a53345d539d005c199a42123e4a0703f85974f6
279
MkaAssesment
MIT License
app/src/main/java/com/joseluisgs/mislugares/Utilidades/Fotos.kt
AlbertoMunozBautista
318,469,220
true
{"Kotlin": 85567}
package com.joseluisgs.mislugares.Utilidades import android.content.ContentUris import android.content.ContentValues import android.content.Context import android.graphics.Bitmap import android.net.Uri import android.os.Environment import android.provider.MediaStore import androidx.core.net.toFile import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream import java.util.* /** * Clase de Fotografías */ object Fotos { /** * Función para obtener el nombre del fichero en base a un prefijo y una extensión */ fun crearNombreFoto(prefijo: String, extension: String): String { // Si no sabemos el nombre return prefijo+"-" + UUID.randomUUID().toString() + extension } /** * Salva un fichero en un directorio */ fun salvarFoto(path: String, nombre: String, context: Context): File? { // Directorio publico // Almacenamos en nuestro directorio de almacenamiento externo asignado en Pictures val dirFotos = File((context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath) + path) // Solo si queremos crear un directorio y que todo sea público //val dirFotos = File(Environment.getExternalStorageDirectory().toString() + path) // Si no existe el directorio, lo creamos solo si es publico if (!dirFotos.exists()) { dirFotos.mkdirs() } try { val f = File(dirFotos, nombre) f.createNewFile() return f } catch (e1: Exception) { e1.printStackTrace() } return null } /** * Copia un bitmap en un path determinado */ fun copiarFoto(bitmap: Bitmap, nombre: String, path: String, compresion: Int, context: Context): File { val dirFotos = File((context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath) + path) // Solo si queremos crear un directorio y que todo sea público //val dirFotos = File(Environment.getExternalStorageDirectory().toString() + path) // Si no existe el directorio, lo creamos solo si es publico if (!dirFotos.exists()) { dirFotos.mkdirs() } val fichero = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath + path + File.separator + nombre val bytes = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, compresion, bytes) val fo = FileOutputStream(fichero) fo.write(bytes.toByteArray()) fo.close() return File(fichero) } /** * Comprime una imagen */ fun comprimirFoto(fichero: File, bitmap: Bitmap, compresion: Int) { // Recuperamos el Bitmap val bytes = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, compresion, bytes) val fo = FileOutputStream(fichero) fo.write(bytes.toByteArray()) fo.close() } /** * Elimina una imagen */ fun eliminarFoto(imagenUri: Uri) { if (imagenUri.toFile().exists()) imagenUri.toFile().delete() } /** * Añade una imagen a la galería */ fun añadirFotoGaleria(foto: Uri, nombre: String, context: Context): Uri? { val values = ContentValues() values.put(MediaStore.Images.Media.TITLE, "imagen") values.put(MediaStore.Images.Media.DISPLAY_NAME, nombre) values.put(MediaStore.Images.Media.DESCRIPTION, "") values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg") values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis()) values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()) values.put(MediaStore.Images.Media.DATA, foto.toFile().absolutePath) return context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) } /** * Elimina una imagen de la galería */ fun eliminarFotoGaleria(nombre: String, context: Context) { // Realizamos la consulta val projection = arrayOf( MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME, ) val selection = "${MediaStore.Images.Media.DISPLAY_NAME} == ?" val selectionArgs = arrayOf(nombre) val sortOrder = "${MediaStore.Images.Media.DISPLAY_NAME} ASC" context.contentResolver.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, sortOrder )?.use { cursor -> // Cache column indices. val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID) val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME) while (cursor.moveToNext()) { // Get values of columns for a given video. val id = cursor.getLong(idColumn) val name = cursor.getString(nameColumn) val contentUri: Uri = ContentUris.withAppendedId( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id ) // Borramos context.contentResolver.delete(contentUri, null, null); } } } fun salvarFotoTemp(context: Context): File? { // Almacenamos en nuestro directorio de almacenamiento externo asignado en Pictures try { val f = File.createTempFile("img_", ".jpg",context.cacheDir) f.createNewFile() return f } catch (e1: Exception) { e1.printStackTrace() } return null } fun deleteFotoDir(context: Context) { val dirFotos = File((context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath) + "MisLugares") dirFotos.deleteRecursively() } }
0
null
0
0
997247cb3302a93993212f886d22320a362e1a58
5,952
MisLugaresKotlin
MIT License
SharedCode/src/commonMain/kotlin/repository/RepositoryProvider.kt
billy-yoyo
294,122,084
true
{"Kotlin": 36988, "Swift": 28160}
package com.jetbrains.handson.mpp.mobile.repository import com.jetbrains.handson.mpp.mobile.repository.impl.FaresRepositoryImpl import com.jetbrains.handson.mpp.mobile.repository.impl.JourneyRepositoryImpl import com.jetbrains.handson.mpp.mobile.repository.impl.StationRepositoryImpl import kotlin.native.concurrent.ThreadLocal @ThreadLocal object RepositoryProvider { fun getStationsRepository(): StationRepository = StationRepositoryImpl() fun getJourneyRepository(): JourneyRepository = JourneyRepositoryImpl() fun getFaresRepository(): FaresRepository = FaresRepositoryImpl() }
0
Kotlin
0
0
0102fc7b8c04c493c16516e1434d7e93d7c86905
595
mpp-ios-android
Apache License 2.0
app/src/main/java/com/ersiver/gymific/ui/home/HomeViewModel.kt
ersiver
299,712,057
false
null
package com.ersiver.gymific.ui.home import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import com.ersiver.gymific.model.Workout import com.ersiver.gymific.model.WorkoutCategory import com.ersiver.gymific.repository.WorkoutRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import timber.log.Timber class HomeViewModel @ViewModelInject constructor( repository: WorkoutRepository ) : ViewModel() { init { Timber.i("HomeViewModel init") } private val recommendedUiFlow: Flow<RecommendedUiModel> = repository.getWorkouts().map { workouts -> val recommended = workouts.filter { it.isRecommended } RecommendedUiModel(recommended) } val recommendedUiModel: LiveData<RecommendedUiModel> = recommendedUiFlow.asLiveData() private val categoriesFlow: Flow<CategoryUiModel> = repository.getCategories().map { categories -> CategoryUiModel(categories) } val categoriesUiModel: LiveData<CategoryUiModel> = categoriesFlow.asLiveData() data class RecommendedUiModel( val workouts: List<Workout> ) data class CategoryUiModel( val categories: List<WorkoutCategory> ) }
1
Kotlin
11
40
8c581f69c022a3de1046cf0f8d24019c0f90796a
1,358
Gymific
Apache License 2.0
app/src/main/java/com/netchar/pixally/data/image/remote/ImageResponse.kt
netchar
540,591,203
false
null
package com.netchar.pixally.data.image.remote import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class ImageResponse( val total: Int, val totalHits: Int, val hits: List<Image> ) { @Serializable data class Image( val id: Int, val pageURL: String, val type: String, val tags: String, val previewURL: String, val previewWidth: Int, val previewHeight: Int, val webformatURL: String, val webformatWidth: Int, val webformatHeight: Int, val largeImageURL: String, val imageWidth: Int, val imageHeight: Int, val imageSize: Int, val views: Int, val downloads: Int, val likes: Int, val comments: Int, @SerialName("user_id") val user_id: Int, val user: String, val userImageURL: String ) }
0
Kotlin
0
0
0eeb2b83974dd784a6c938431b494cc6b237496f
935
Pixally
Apache License 2.0
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/SetShortcutHiddenActionType.kt
Waboodoo
34,525,124
false
null
package ch.rmy.android.http_shortcuts.scripting.actions.types import ch.rmy.android.framework.extensions.takeUnlessEmpty import ch.rmy.android.http_shortcuts.scripting.ActionAlias import ch.rmy.android.http_shortcuts.scripting.actions.ActionData import ch.rmy.android.http_shortcuts.scripting.actions.ActionRunnable import javax.inject.Inject class SetShortcutHiddenActionType @Inject constructor( private val setShortcutHiddenAction: SetShortcutHiddenAction, ) : ActionType { override val type = TYPE override fun getActionRunnable(actionDTO: ActionData) = ActionRunnable( action = setShortcutHiddenAction, params = SetShortcutHiddenAction.Params( shortcutNameOrId = actionDTO.getString(0)?.takeUnlessEmpty(), hidden = actionDTO.getBoolean(1) ?: true, ), ) override fun getAlias() = ActionAlias( functionName = FUNCTION_NAME, parameters = 2, ) companion object { private const val TYPE = "set_shortcut_hidden" private const val FUNCTION_NAME = "setShortcutHidden" } }
26
null
110
1,105
07faf75e2f1a53f8986d669946adf6de509176e1
1,118
HTTP-Shortcuts
MIT License
source-code/starter-project/app/src/main/java/com/droidcon/weatherglancewidget/ui/theme/Theme.kt
droidcon-academy
607,558,842
false
{"Kotlin": 48198}
package com.droidcon.weatherglancewidget.ui.theme import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext private val DarkColorScheme = darkColorScheme( primary = skyBlue300, surface = gray800, background = gray800, onSurface = Color.White, onBackground = Color.White ) private val LightColorScheme = lightColorScheme( primary = skyBlue500, onSurface = gray800, onBackground = gray800 ) @Composable fun WeatherGlanceWidgetTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colorScheme = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } else { if (darkTheme) DarkColorScheme else LightColorScheme } MaterialTheme( colorScheme = colorScheme, typography = Typography, shapes = Shapes, content = content ) }
0
Kotlin
0
0
1cf0e1aa90d41d58cdf5c9867f7b9869f396937f
1,441
android-jetpack-glance-study-materials
Apache License 2.0
app/src/main/java/com/override0330/teamim/viewmodel/TaskCompletedViewModel.kt
Override0330
202,737,292
false
null
package com.override0330.teamim.viewmodel import androidx.lifecycle.LiveData import com.override0330.teamim.Repository.TaskRepository import com.override0330.teamim.base.BaseViewModel import com.override0330.teamim.model.bean.Task /** * @data 2019-08-24 * @author Override0330 * @description */ class TaskCompletedViewModel :BaseViewModel(){ private val taskRepository = TaskRepository.getInstant() fun getCompletedTask():LiveData<List<Task>> = taskRepository.getCompletedTaskList() fun letTaskUnDone(task:Task):LiveData<TaskRepository.SendResult> = taskRepository.letTaskUnDone(task) }
1
Kotlin
0
2
cce6deecdbd07bf5acc95d5c7a7fa1f23c3ed42d
608
TeamIM
Apache License 2.0
android/src/main/kotlin/dev/juyoung/sign_in_with_kakao/extensions/Gender.kt
dev-juyoung
322,199,498
false
{"Dart": 34569, "Kotlin": 15018, "Swift": 13376, "Ruby": 2285, "Objective-C": 755}
package dev.juyoung.sign_in_with_kakao.extensions import com.kakao.sdk.user.model.Gender val Gender.rawValue: String? get() = when (this) { Gender.FEMALE -> "female" Gender.MALE -> "male" else -> null }
0
Dart
0
3
caec86de1adac3bd77add8a301375578f557d1da
237
sign_in_with_kakao
MIT License
components/faphub/installation/queue/api/src/main/java/com/flipperdevices/faphub/installation/queue/api/FapInstallationQueueApi.kt
flipperdevices
288,258,832
false
{"Kotlin": 4167715, "FreeMarker": 10352, "CMake": 1780, "C++": 1152, "Fluent": 21}
package com.flipperdevices.faphub.installation.queue.api import com.flipperdevices.faphub.installation.queue.api.model.FapActionRequest import com.flipperdevices.faphub.installation.queue.api.model.FapQueueState import kotlinx.collections.immutable.ImmutableList import kotlinx.coroutines.flow.Flow interface FapInstallationQueueApi { fun getFlowById(applicationUid: String): Flow<FapQueueState> fun getAllTasks(): Flow<ImmutableList<FapQueueState>> fun enqueue(actionRequest: FapActionRequest) suspend fun enqueueSync(actionRequest: FapActionRequest) }
21
Kotlin
174
1,528
8f293e596741a6c97409acbc8de10c7ae6e8d8b0
574
Flipper-Android-App
MIT License
core/src/main/java/com/whitecloud/socket/core/exceptions/UnConnectException.kt
femonres
228,414,465
false
null
package com.whitecloud.socket.core.exceptions class UnConnectException : RuntimeException { constructor() : super() constructor(message: String) : super(message) constructor(message: String, cause: Throwable) : super(message, cause) constructor(cause: Throwable) : super(cause) protected constructor( message: String, cause: Throwable, enableSuppression: Boolean, writableStackTrace: Boolean ) : super(message, cause, enableSuppression, writableStackTrace) }
0
Kotlin
0
0
419c84cdece8586a6dbcb6a587ea955b9ecda936
503
live-socket
MIT License
agp-7.1.0-alpha01/tools/base/lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/ProguardDetectorTest.kt
jomof
502,039,754
true
{"Markdown": 63, "Java Properties": 56, "Shell": 31, "Batchfile": 12, "Proguard": 30, "CMake": 10, "Kotlin": 3443, "C++": 594, "Java": 4446, "HTML": 34, "Makefile": 14, "RenderScript": 22, "C": 30, "JavaScript": 2, "CSS": 3, "INI": 11, "Filterscript": 11, "Prolog": 1, "GLSL": 1, "Gradle Kotlin DSL": 5, "Python": 12, "Dockerfile": 2}
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.lint.checks import com.android.tools.lint.detector.api.Detector class ProguardDetectorTest : AbstractCheckTest() { override fun getDetector(): Detector { return ProguardDetector() } fun testProguard() { lint().files(mProguard).run().expect( """ proguard.cfg:21: Error: Obsolete ProGuard file; use -keepclasseswithmembers instead of -keepclasseswithmembernames [Proguard] -keepclasseswithmembernames class * { ^ 1 errors, 0 warnings """ ) } fun testProguardNewPath() { lint().files(mProguard2).run().expect( """ proguard-project.txt:21: Error: Obsolete ProGuard file; use -keepclasseswithmembers instead of -keepclasseswithmembernames [Proguard] -keepclasseswithmembernames class * { ^ 1 errors, 0 warnings """ ) } fun testProguardRandomName() { lint().files( mProguard3, source( "project.properties", """ target=android-14 proguard.config=${"$"}{sdk.dir}/foo.cfg:${"$"}{user.home}/bar.pro;myfile.txt """ ) ).run().expect( """ myfile.txt:21: Error: Obsolete ProGuard file; use -keepclasseswithmembers instead of -keepclasseswithmembernames [Proguard] -keepclasseswithmembernames class * { ^ myfile.txt:8: Warning: Local ProGuard configuration contains general Android configuration: Inherit these settings instead? Modify project.properties to define proguard.config=${"$"}{sdk.dir}/tools/proguard/proguard-android.txt:myfile.txt and then keep only project-specific configuration here [ProguardSplit] -keep public class * extends android.app.Activity ^ 1 errors, 1 warnings """ ) } fun testSilent() { lint().files(mProguard4, projectProperties().compileSdk(3)).run().expectClean() } fun testSilent2() { lint().files(mProguard4, projectProperties().compileSdk(3)).run().expectClean() } fun testSplit() { lint().files( mProguard4, projectProperties() .compileSdk(3) .property("proguard.config", "proguard.cfg") ).run().expect( """ proguard.cfg:14: Warning: Local ProGuard configuration contains general Android configuration: Inherit these settings instead? Modify project.properties to define proguard.config=${"$"}{sdk.dir}/tools/proguard/proguard-android.txt:proguard.cfg and then keep only project-specific configuration here [ProguardSplit] -keep public class * extends android.app.Activity ^ 0 errors, 1 warnings """ ) } // Sample code private val mProguard = source( "proguard.cfg", """ -optimizationpasses 5 -dontusemixedcaseclassnames -dontskipnonpubliclibraryclasses -dontpreverify -verbose -optimizations !code/simplification/arithmetic,!field/*,!class/merging/* -keep public class * extends android.app.Activity -keep public class * extends android.app.Application -keep public class * extends android.app.Service -keep public class * extends android.content.BroadcastReceiver -keep public class * extends android.content.ContentProvider -keep public class * extends android.app.backup.BackupAgentHelper -keep public class * extends android.preference.Preference -keep public class com.android.vending.licensing.ILicensingService -keepclasseswithmembernames class * { native <methods>; } -keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet); } -keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet, int); } -keepclassmembers enum * { public static **[] values(); public static ** valueOf(java.lang.String); } -keep class * implements android.os.Parcelable { public static final android.os.Parcelable${"$"}Creator *; } """ ).indented() // Sample code private val mProguard2 = source( "proguard-project.txt", """ -optimizationpasses 5 -dontusemixedcaseclassnames -dontskipnonpubliclibraryclasses -dontpreverify -verbose -optimizations !code/simplification/arithmetic,!field/*,!class/merging/* -keep public class * extends android.app.Activity -keep public class * extends android.app.Application -keep public class * extends android.app.Service -keep public class * extends android.content.BroadcastReceiver -keep public class * extends android.content.ContentProvider -keep public class * extends android.app.backup.BackupAgentHelper -keep public class * extends android.preference.Preference -keep public class com.android.vending.licensing.ILicensingService -keepclasseswithmembernames class * { native <methods>; } -keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet); } -keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet, int); } -keepclassmembers enum * { public static **[] values(); public static ** valueOf(java.lang.String); } -keep class * implements android.os.Parcelable { public static final android.os.Parcelable${"$"}Creator *; } """ ).indented() // Sample code private val mProguard3 = source( "myfile.txt", """ -optimizationpasses 5 -dontusemixedcaseclassnames -dontskipnonpubliclibraryclasses -dontpreverify -verbose -optimizations !code/simplification/arithmetic,!field/*,!class/merging/* -keep public class * extends android.app.Activity -keep public class * extends android.app.Application -keep public class * extends android.app.Service -keep public class * extends android.content.BroadcastReceiver -keep public class * extends android.content.ContentProvider -keep public class * extends android.app.backup.BackupAgentHelper -keep public class * extends android.preference.Preference -keep public class com.android.vending.licensing.ILicensingService -keepclasseswithmembernames class * { native <methods>; } -keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet); } -keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet, int); } -keepclassmembers enum * { public static **[] values(); public static ** valueOf(java.lang.String); } -keep class * implements android.os.Parcelable { public static final android.os.Parcelable${"$"}Creator *; } """ ).indented() // Sample code private val mProguard4 = source( "proguard.cfg", """ -optimizationpasses 5 -dontusemixedcaseclassnames -dontskipnonpubliclibraryclasses -verbose -optimizations !code/simplification/arithmetic,!code/simplification/cast,!field/*,!class/merging/* -allowaccessmodification -keepattributes *Annotation* # dex does not like code run through proguard optimize and preverify steps. -dontoptimize -dontpreverify -keep public class * extends android.app.Activity -keep public class * extends android.app.Application -keep public class * extends android.app.Service -keep public class * extends android.content.BroadcastReceiver -keep public class * extends android.content.ContentProvider -keep public class * extends android.app.backup.BackupAgent -keep public class * extends android.preference.Preference -keep public class com.android.vending.licensing.ILicensingService # For native methods, see http://proguard.sourceforge.net/manual/examples.html#native -keepclasseswithmembernames class * { native <methods>; } -keep public class * extends android.view.View { public <init>(android.content.Context); public <init>(android.content.Context, android.util.AttributeSet); public <init>(android.content.Context, android.util.AttributeSet, int); public void set*(...); } -keepclasseswithmembers class * { public <init>(android.content.Context, android.util.AttributeSet); } -keepclasseswithmembers class * { public <init>(android.content.Context, android.util.AttributeSet, int); } -keepclassmembers class * extends android.app.Activity { public void *(android.view.View); } # For enumeration classes, see http://proguard.sourceforge.net/manual/examples.html#enumerations -keepclassmembers enum * { public static **[] values(); public static ** valueOf(java.lang.String); } -keep class * implements android.os.Parcelable { public static final android.os.Parcelable${"$"}Creator *; } -keepclassmembers class **.R$* { public static <fields>; } # The support library contains references to newer platform versions. # Don't warn about those in case this app is linking against an older # platform version. We know about them, and they are safe. -dontwarn android.support.** """ ).indented() }
1
null
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
10,850
CppBuildCacheWorkInProgress
Apache License 2.0
safeToRunInternal/src/main/kotlin/com/safetorun/models/builders/DeviceInformationBuilder.kt
Safetorun
274,838,056
false
null
package com.safetorun.models.builders import com.safetorun.models.core.BlacklistedApps import com.safetorun.models.core.DeviceInformation import com.safetorun.models.core.DeviceSignature import com.safetorun.models.core.InstallOrigin import com.safetorun.models.core.OsCheck internal class DeviceInformationBuilder( private val osInformation: IOsInformationDtoBuilder = OsInformationDtoBuilder() ) : IOsInformationDtoBuilder by osInformation, IDeviceInformationBuilder { private val _installedApplications: MutableList<String> = mutableListOf() private var _signature: String = "" private var _installOrigin: String = "" /** * Add installed application */ override fun installedApplication(packageName: String) { _installedApplications.add(packageName) } /** * Add install origin */ override fun installOrigin(installOrigin: String) { _installOrigin = installOrigin } /** * Add signature */ override fun signature(signature: String) { _signature = signature } /** * Build a full device information DTO. Will exception if * there are missing values not added * * @return a device information object * @throws IllegalArgumentException if any items are null */ internal fun build(): DeviceInformation { return buildForUnwrappedValues( osInformation.buildOsCheck(), _installOrigin, _signature ) } private fun buildForUnwrappedValues( osVersionCheck: OsCheck, installOrigin: String, signature: String ) = DeviceInformation( osCheck = osVersionCheck, installOrigin = InstallOrigin(installOrigin), blacklistedApp = BlacklistedApps( installedPackages = _installedApplications ), signatureVerification = DeviceSignature( signature = signature ) ) }
24
Kotlin
0
29
83176f07ab4351d2f84dc9718224dc03458e6658
2,002
safe_to_run
Apache License 2.0
kotter/src/main/kotlin/com/varabyte/kotter/runtime/internal/ansi/commands/AnsiCommand.kt
varabyte
397,769,020
false
null
package com.varabyte.kotter.runtime.internal.ansi.commands import com.varabyte.kotter.runtime.internal.TerminalCommand import com.varabyte.kotter.runtime.internal.ansi.Ansi.Csi internal open class AnsiCommand(ansiCode: String) : TerminalCommand(ansiCode) internal open class AnsiCsiCommand(csiCode: Csi.Code) : AnsiCommand(csiCode.toFullEscapeCode())
19
Kotlin
3
74
a077138a3b07f994cea0f28a3a41cab962f47402
352
kotter
Apache License 2.0
shared/src/commonMain/kotlin/config/Parameter.kt
west2-online
840,273,230
false
{"Kotlin": 742964, "Swift": 592, "Shell": 228}
package config import kotlinx.datetime.TimeZone /** 软件支持的时区,默认为东八区 */ val CurrentZone = TimeZone.of("UTC+8")
6
Kotlin
2
0
484b699b372e6ff5c43ae725372b28c6de4eaa73
111
fzuhelper-KMP
Apache License 2.0
src/day16/Code.kt
fcolasuonno
162,470,286
false
null
package day16 import java.io.File fun main(args: Array<String>) { val name = if (true) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } data class Sue(val name: String, val attribs: Map<String, Int>) private val lineStructure = """Sue (\d+): (\w+): (\d+), (\w+): (\d+), (\w+): (\d+)""".toRegex() val detect = mapOf( "children" to 3, "cats" to 7, "samoyeds" to 2, "pomeranians" to 3, "akitas" to 0, "vizslas" to 0, "goldfish" to 5, "trees" to 3, "cars" to 2, "perfumes" to 1 ) fun parse(input: List<String>) = input.map { lineStructure.matchEntire(it)?.destructured?.let { val sue = it.toList() Sue(sue.first(), sue.drop(1).chunked(2).map { (attr, number) -> attr to number.toInt() }.toMap()) } }.requireNoNulls() fun part1(input: List<Sue>): Any? = input.single { sue -> detect.filterKeys { it in sue.attribs.keys } == sue.attribs }.name fun part2(input: List<Sue>): Any? { val exclusions = listOf("cats", "trees", "pomeranians", "goldfish") val exact = detect - exclusions return input.single { sue -> exact.filterKeys { it in sue.attribs.keys } == sue.attribs - exclusions && (sue.attribs["cats"] ?: Int.MAX_VALUE) > detect.getValue("cats") && (sue.attribs["trees"] ?: Int.MAX_VALUE) > detect.getValue("trees") && (sue.attribs["pomeranians"] ?: 0) < detect.getValue("pomeranians") && (sue.attribs["goldfish"] ?: 0) < detect.getValue("goldfish") }.name }
0
Kotlin
0
0
24f54bf7be4b5d2a91a82a6998f633f353b2afb6
1,716
AOC2015
MIT License
core/src/main/kotlin/converters/Converters.kt
hexagonkt
56,139,239
false
null
package com.hexagonkt.core.converters import kotlin.reflect.KClass /** * Utility method to convert one type to another. * * @param target Target type for the source instance. * @receiver Value to convert to another type. * * @see ConvertersManager.convert */ fun <T : Any> Any.convert(target: KClass<T>): T = ConvertersManager.convert(this, target) /** * Utility method to convert one type to another. * * @param T Target type for the source instance. * @receiver Value to convert to another type. * * @see ConvertersManager.convert */ inline fun <reified T : Any> Any.convert(): T = convert(T::class) // TODO Add conversion utilities to transform collections (lists, sets or maps)
21
Kotlin
80
371
fdeda404a295a08335d6033a1d5c341d97873311
708
hexagon
MIT License
server/src/main/kotlin/de/sambalmueslie/openevent/server/announcement/api/AnnouncementAPI.kt
sambalmueslie
270,265,994
false
{"Kotlin": 265865, "Dockerfile": 434, "Batchfile": 61}
package de.sambalmueslie.openevent.server.announcement.api import de.sambalmueslie.openevent.server.common.CrudAPI import io.micronaut.data.model.Page import io.micronaut.data.model.Pageable import io.micronaut.security.authentication.Authentication interface AnnouncementAPI : CrudAPI<Announcement, AnnouncementChangeRequest> { fun getItemAnnouncements(authentication: Authentication, itemId: Long, pageable: Pageable): Page<Announcement> }
0
Kotlin
0
1
053fb05dbe4242941659518f93dcac4c34b29126
445
open-event
Apache License 2.0
cryptocurrencychallenge/src/test/java/com/yoti/android/cryptocurrencychallenge/domain/GetMarketDataTest.kt
photizzo
432,595,756
false
{"Kotlin": 38245}
package com.yoti.android.cryptocurrencychallenge.domain import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.yoti.android.cryptocurrencychallenge.domain.repository.CoinRepository import com.yoti.android.cryptocurrencychallenge.domain.usecase.GetMarketData import com.yoti.android.cryptocurrencychallenge.utils.generateAssetData import com.yoti.android.cryptocurrencychallenge.utils.generateMarketData import io.mockk.MockKAnnotations import io.mockk.coEvery import io.mockk.impl.annotations.MockK import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.setMain import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class GetMarketDataTest { @get:Rule var instantExecutorRule = InstantTaskExecutorRule() lateinit var getMarketData: GetMarketData val dispatcher = Dispatchers.Unconfined @MockK lateinit var coinRepository: CoinRepository @ExperimentalCoroutinesApi @Before fun setup() { MockKAnnotations.init(this) getMarketData = GetMarketData(coinRepository) Dispatchers.setMain(dispatcher) } @Test fun `get posts executes`() = runBlocking { coEvery { coinRepository.getMarkets() } returns flowOf(generateMarketData(10)) val result = getMarketData.execute().first() assert(result.first().baseId.toString().isNullOrEmpty().not()) assert(result.first().priceUsd.toString().isNullOrEmpty().not()) assert(result.first().volumeUsd24Hr.isNullOrEmpty().not()) assert(result.first().updated.toString().isNullOrEmpty().not()) } }
0
Kotlin
0
0
2351339f8397decbb91a1bfe5ad061b5f07b3578
1,854
yoti-android-challenge
MIT License
data/src/main/kotlin/com/github/hchery/kd/data/Transactional.kt
hchery
789,581,942
false
{"Kotlin": 20369, "Java": 10023, "Python": 5290}
package com.github.hchery.kd.data import com.github.hchery.kd.GetOrNull import com.github.hchery.kd.spring.bean import org.springframework.stereotype.Component import org.springframework.transaction.annotation.Transactional /** * DATE: 2024/4/24 * AUTHOR: hchery * URL: https://github.com/hchery * EMAIL: h.chery@qq.com */ interface Transaction { fun <T> default(getOrNull: GetOrNull<T>): T? } fun transaction(): Transaction = bean<Transaction>() @Component class SpringManagedTransaction : Transaction { @Transactional override fun <T> default(getOrNull: GetOrNull<T>): T? { return getOrNull() } }
0
Kotlin
0
0
0f608cf20c60a06042f0d9b8559319975bc20710
634
KitDiscovery
MIT License
src/main/kotlin/id/walt/services/key/import/JwkKeyImport.kt
walt-id
392,607,264
false
{"Kotlin": 1154151, "Java": 9175, "Open Policy Agent": 2974, "Shell": 2842, "Dockerfile": 1615, "JavaScript": 891, "Python": 351}
package id.walt.services.key.import import com.nimbusds.jose.jwk.Curve import com.nimbusds.jose.jwk.JWK import com.nimbusds.jose.jwk.KeyType import id.walt.crypto.* import id.walt.services.CryptoProvider import id.walt.services.keystore.KeyStoreService class JwkKeyImport(private val keyString: String) : KeyImportStrategy { override fun import(keyStore: KeyStoreService): KeyId { val key = parseJwkKey(keyString) keyStore.store(key) return key.keyId } private fun parseJwkKey(jwkKeyStr: String): Key { val jwk = JWK.parse(jwkKeyStr) val key = when (jwk.keyType) { KeyType.RSA -> Key( keyId = KeyId(jwk.keyID ?: newKeyId().id), algorithm = KeyAlgorithm.RSA, cryptoProvider = CryptoProvider.SUN, keyPair = jwk.toRSAKey().toKeyPair() ) KeyType.EC -> { val alg = when (jwk.toECKey().curve) { Curve.P_256 -> KeyAlgorithm.ECDSA_Secp256r1 Curve.SECP256K1 -> KeyAlgorithm.ECDSA_Secp256k1 else -> throw IllegalArgumentException("EC key with curve ${jwk.toECKey().curve} not suppoerted") } Key( keyId = KeyId(jwk.keyID ?: newKeyId().id), algorithm = alg, cryptoProvider = CryptoProvider.SUN, keyPair = jwk.toECKey().toKeyPair() ) } KeyType.OKP -> { val alg = when (jwk.toOctetKeyPair().curve) { Curve.Ed25519 -> KeyAlgorithm.EdDSA_Ed25519 else -> throw IllegalArgumentException("OKP key with curve ${jwk.toOctetKeyPair().curve} not supported") } buildKey( keyId = jwk.keyID ?: newKeyId().id, algorithm = alg.name, provider = CryptoProvider.SUN.name, publicPart = jwk.toOctetKeyPair().x.toString(), privatePart = jwk.toOctetKeyPair().d?.let { jwk.toOctetKeyPair().d.toString() }, format = KeyFormat.BASE64_RAW ) } else -> throw IllegalArgumentException("KeyType ${jwk.keyType} / Algorithm ${jwk.algorithm} not supported") } return key } }
2
Kotlin
34
97
1a8776a899ac97aa32f58d2f70aba23683d2c9b3
2,386
waltid-ssikit
Apache License 2.0
core/ui/src/main/kotlin/dev/yacsa/ui/composable/dialog/UpdateDialog.kt
andrew-malitchuk
589,720,124
false
null
package dev.yacsa.ui.composable.dialog import androidx.compose.material.AlertDialog import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import dev.yacsa.model.model.update.CheckUpdateUiModel import dev.yacsa.ui.theme.YacsaTheme @Composable fun UpdateDialog( modifier: Modifier, updateModel: CheckUpdateUiModel, // showDialog: MutableStateFlow<Boolean>, showDialog: (Boolean) -> Unit, confirmClick: () -> Unit, dismissClick: () -> Unit, ) { AlertDialog( onDismissRequest = { // showDialog.value = false showDialog(false) }, title = { Text( text = updateModel.title ?: "SWW", style = YacsaTheme.typography.caption, color = YacsaTheme.colors.primary, ) }, text = { Text( text = updateModel.content ?: "SWW", style = YacsaTheme.typography.title, color = YacsaTheme.colors.secondary, ) }, confirmButton = { TextButton(onClick = { confirmClick() }) { Text("ok") } }, dismissButton = { TextButton(onClick = { // showDialog.value = false showDialog(false) dismissClick() }) { Text("Cancel") } }, ) }
0
Kotlin
0
0
e35620cf1c66b4f76f0ed30d9c6d499acd134403
1,521
yet-another-compose-showcase-app
MIT License
base/src/main/kotlin/browser/tts/Import.kt
DATL4G
372,873,797
false
null
@file:JsModule("webextension-polyfill") @file:JsQualifier("tts") package browser.tts import browser.events.Event import kotlin.js.Promise /** * Speaks text using a text-to-speech engine. * * @param utterance The text to speak, either plain text or a complete, well-formed SSML document. * Speech engines that do not support SSML will strip away the tags and speak the text. The maximum * length of the text is 32,768 characters. * @param options The speech options. * @return Called right away, before speech finishes. Check $(ref:runtime.lastError) to make sure * there were no errors. Use options.onEvent to get more detailed feedback. */ public external fun speak(utterance: String, options: TtsOptions? = definedExternally): Promise<Nothing>? /** * Stops any current speech and flushes the queue of any pending utterances. In addition, if speech * was paused, it will now be un-paused for the next call to speak. */ public external fun stop(): Nothing /** * Pauses speech synthesis, potentially in the middle of an utterance. A call to resume or stop will * un-pause speech. */ public external fun pause(): Nothing /** * If speech was paused, resumes speaking where it left off. */ public external fun resume(): Nothing /** * Checks whether the engine is currently speaking. On Mac OS X, the result is true whenever the * system speech engine is speaking, even if the speech wasn't initiated by Chrome. */ public external fun isSpeaking(): Promise<Boolean>? /** * Gets an array of all available voices. */ public external fun getVoices(): Promise<Array<TtsVoice>>? /** * Used to pass events back to the function calling speak(). */ public external val onEvent: Event<OnEventListener, Unit> = definedExternally
0
Kotlin
1
37
ab2a825dd8dd8eb704278f52c603dbdd898d1875
1,751
Kromex
Apache License 2.0
feature/convertcurrency/src/main/java/com/nicoqueijo/android/convertcurrency/composables/util/NumPadKey.kt
nicoqueijo
794,591,762
false
{"Kotlin": 128109}
package com.nicoqueijo.android.convertcurrency.composables.util enum class NumPadKey(var value: Char) { ONE(value = '1'), TWO(value = '2'), THREE(value = '3'), FOUR(value = '4'), FIVE(value = '5'), SIX(value = '6'), SEVEN(value = '7'), EIGHT(value = '8'), NINE(value = '9'), DECIMAL_SEPARATOR(value = '.'), ZERO(value = '0'), BACKSPACE(value = '⌫') }
0
Kotlin
0
0
5fcb4e2e0892ec8d999d4d2aad8cb2f180ff2d11
400
Android-Currency-Converter-v2
Apache License 2.0
app/src/main/java/com/mudassir/moviesapp/util/BindingAdapter.kt
mookyjan
313,948,503
false
null
package com.mudassir.moviesapp.util import android.os.Build import android.text.Html import android.text.Spanned import android.view.View import android.widget.ImageView import android.widget.RatingBar import android.widget.TextView import androidx.core.content.ContextCompat import androidx.databinding.BindingAdapter import coil.api.load import com.bumptech.glide.Glide import com.github.florent37.glidepalette.BitmapPalette import com.github.florent37.glidepalette.GlidePalette import com.google.android.material.chip.Chip import com.google.android.material.chip.ChipGroup import com.mudassir.moviesapp.R import com.mudassir.moviesapp.ui.detail.GenreModel @BindingAdapter("android:src", "palette") fun bindingImage(imageView: ImageView, path: String?, palette: View?) { path?.let { Glide.with(imageView.context) .load(AppConstants.getPosterPath(it)) .error(ContextCompat.getDrawable(imageView.context, R.drawable.loading)) .listener( palette?.let { GlidePalette.with(AppConstants.getPosterPath(path)) .use(BitmapPalette.Profile.VIBRANT) .intoBackground(it) .crossfade(true) } ) .into(imageView) } } @BindingAdapter("loadImage") fun loadImage(imageView: ImageView, url: String?) { url?.let { imageView.load(AppConstants.getPosterPath(it)) { placeholder(R.drawable.loading) } } } /** * binding for the rating bar, and divide it by 2 t */ @BindingAdapter("android:rating") fun setRating(view: RatingBar?, rating: Double) { if (view != null) { val rate = rating.toFloat() view.rating = rate/2 } } @BindingAdapter("time") fun calculateTime(view:TextView,time: Int){ val hours = time/60 val min = time % 60 view.text = "$hours h: $min m" } @BindingAdapter("mapGenersList") fun bindMapKeywordList(chipGroup: ChipGroup, geners: List<GenreModel>?) { geners?.let { chipGroup.visible() for (keyword in it) { val chip = Chip(chipGroup.context) chip.text = keyword.name chip.isCheckable = false chip.setTextAppearanceResource(R.style.ChipTextStyle) chip.setChipBackgroundColorResource(R.color.colorPrimary) chipGroup.addView(chip) } } } /** makes visible a view. */ fun View.visible() { visibility = View.VISIBLE } /** makes gone a view. */ fun View.gone() { visibility = View.GONE }
0
Kotlin
0
4
ebdc9848305a3cb2272e2ac8c396e0db223172ae
2,571
MoviesApp
Apache License 2.0
PrimFastKotlin/KotlinAction/app/src/main/java/com/prim/gkapp/anno/POKO.kt
zyl4265097
194,000,972
true
{"Java": 261503, "Kotlin": 104047, "JavaScript": 6068, "Objective-C": 4141, "Python": 2070, "CMake": 1603, "Shell": 398}
package com.prim.gkapp.anno /** * @desc 给数据类添加 注解 * @author prim * @time 2019-05-28 - 18:26 * @version 1.0.0 */ @Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.CLASS) annotation class POKO
0
Java
0
0
dba30a1b3518da41cdc5c492f70b8d3ae4146ee4
210
PrimFastApp
Apache License 2.0
sdk-core/src/main/java/co/reachfive/identity/sdk/core/ProfileClient.kt
ReachFive
177,561,302
false
{"Kotlin": 151288}
package co.reachfive.identity.sdk.core import co.reachfive.identity.sdk.core.ProfileManagement.Companion.fields import co.reachfive.identity.sdk.core.api.ReachFiveApi import co.reachfive.identity.sdk.core.api.ReachFiveApiCallback import co.reachfive.identity.sdk.core.models.AuthToken import co.reachfive.identity.sdk.core.models.Profile import co.reachfive.identity.sdk.core.models.ReachFiveError import co.reachfive.identity.sdk.core.models.SdkInfos import co.reachfive.identity.sdk.core.models.requests.UpdateEmailRequest import co.reachfive.identity.sdk.core.models.requests.UpdatePhoneNumberRequest import co.reachfive.identity.sdk.core.models.requests.VerifyPhoneNumberRequest import co.reachfive.identity.sdk.core.utils.Failure import co.reachfive.identity.sdk.core.utils.Success internal class ProfileManagementClient( private val reachFiveApi: ReachFiveApi, ) : ProfileManagement { override fun getProfile( authToken: AuthToken, success: Success<Profile>, failure: Failure<ReachFiveError> ) { reachFiveApi .getProfile( authToken.authHeader, SdkInfos.getQueries().plus(Pair("fields", fields.joinToString(","))) ) .enqueue(ReachFiveApiCallback.withContent<Profile>(success, failure)) } override fun verifyPhoneNumber( authToken: AuthToken, phoneNumber: String, verificationCode: String, success: Success<Unit>, failure: Failure<ReachFiveError> ) { reachFiveApi .verifyPhoneNumber( authToken.authHeader, VerifyPhoneNumberRequest(phoneNumber, verificationCode), SdkInfos.getQueries() ) .enqueue(ReachFiveApiCallback.noContent(success, failure)) } override fun updateEmail( authToken: AuthToken, email: String, redirectUrl: String?, success: Success<Profile>, failure: Failure<ReachFiveError> ) { reachFiveApi .updateEmail( authToken.authHeader, UpdateEmailRequest(email, redirectUrl), SdkInfos.getQueries() ) .enqueue(ReachFiveApiCallback.withContent<Profile>(success, failure)) } override fun updatePhoneNumber( authToken: AuthToken, phoneNumber: String, success: Success<Profile>, failure: Failure<ReachFiveError> ) { reachFiveApi .updatePhoneNumber( authToken.authHeader, UpdatePhoneNumberRequest(phoneNumber), SdkInfos.getQueries() ) .enqueue(ReachFiveApiCallback.withContent<Profile>(success, failure)) } override fun updateProfile( authToken: AuthToken, profile: Profile, success: Success<Profile>, failure: Failure<ReachFiveError> ) { reachFiveApi .updateProfile(authToken.authHeader, profile, SdkInfos.getQueries()) .enqueue(ReachFiveApiCallback.withContent<Profile>(success, failure)) } } internal interface ProfileManagement { companion object { val fields = arrayOf( "addresses", "auth_types", "bio", "birthdate", "company", "consents", "created_at", "custom_fields", "devices", "email", "emails", "email_verified", "external_id", "family_name", "first_login", "first_name", "full_name", "gender", "given_name", "has_managed_profile", "has_password", "id", "identities", "last_login", "last_login_provider", "last_login_type", "last_name", "likes_friends_ratio", "lite_only", "locale", "local_friends_count", "login_summary", "logins_count", "middle_name", "name", "nickname", "origins", "phone_number", "phone_number_verified", "picture", "provider_details", "providers", "social_identities", "sub", "uid", "updated_at" ) } fun getProfile( authToken: AuthToken, success: Success<Profile>, failure: Failure<ReachFiveError> ) fun verifyPhoneNumber( authToken: AuthToken, phoneNumber: String, verificationCode: String, success: Success<Unit>, failure: Failure<ReachFiveError> ) fun updateEmail( authToken: AuthToken, email: String, redirectUrl: String? = null, success: Success<Profile>, failure: Failure<ReachFiveError> ) fun updatePhoneNumber( authToken: AuthToken, phoneNumber: String, success: Success<Profile>, failure: Failure<ReachFiveError> ) fun updateProfile( authToken: AuthToken, profile: Profile, success: Success<Profile>, failure: Failure<ReachFiveError> ) }
4
Kotlin
2
2
c88e8ab52d32a2069d31a9606e96c7868fdf3c99
5,285
identity-android-sdk
MIT License
app/src/main/java/com/yuhang/novel/pirate/repository/DataRepository.kt
yuhanghate
200,383,190
false
null
package com.yuhang.novel.pirate.repository import android.annotation.SuppressLint import android.content.Context import androidx.work.* import com.google.gson.Gson import com.orhanobut.logger.Logger import com.yuhang.novel.pirate.app.PirateApp import com.yuhang.novel.pirate.extension.niceBody import com.yuhang.novel.pirate.extension.niceDir import com.yuhang.novel.pirate.repository.api.KanShuNetApi import com.yuhang.novel.pirate.repository.api.KuaiDuNetApi import com.yuhang.novel.pirate.repository.api.NetApi import com.yuhang.novel.pirate.repository.database.AppDatabase import com.yuhang.novel.pirate.repository.database.entity.* import com.yuhang.novel.pirate.repository.network.Http import com.yuhang.novel.pirate.repository.network.NetManager import com.yuhang.novel.pirate.repository.network.NetURL import com.yuhang.novel.pirate.repository.network.data.kanshu.result.* import com.yuhang.novel.pirate.repository.network.data.kuaidu.result.BookCategoryDataResult import com.yuhang.novel.pirate.repository.network.data.kuaidu.result.CategoryDetailResult import com.yuhang.novel.pirate.repository.network.data.pirate.result.* import com.yuhang.novel.pirate.repository.preferences.PreferenceUtil import com.yuhang.novel.pirate.utils.application import com.yuhang.novel.pirate.workmanager.NovelDownloadWorker import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.util.* /** * 数据提供源 */ class DataRepository { /** * 网络 */ private val mNetManager by lazy(LazyThreadSafetyMode.SYNCHRONIZED, ::NetManager) /** * 提供网络操作 */ fun getNetApi() = Http.createRetrofit(NetURL.HOST).create(NetApi::class.java) /** * 看书神器 */ fun getKSNetApi() = Http.createRetrofit(NetURL.HOST_KUAIDU).create(KanShuNetApi::class.java) /** * 提供数据库操作 */ fun getDatabase() = AppDatabase.getInstance(application) /** * 快读 */ fun getKuaiDuApi() = Http.createRetrofit(NetURL.HOST_KUAIDU).create(KuaiDuNetApi::class.java) /** * 看书神器站内搜索 */ suspend fun searchBook(keyword: String) = withContext(Dispatchers.IO) { getKSNetApi().searchBook(keyword) } /** * 男生 -> 分类 */ suspend fun getBookCategory() = withContext(Dispatchers.IO) { getKSNetApi().getBookCategory() } /** * 书本详情 */ suspend fun getBookDetails(id: String) = withContext(Dispatchers.IO) { getKSNetApi().getBookDetails(dirId = niceDir(id.toLong()), bookId = id.toLong()) } /** * 书本章节目录 */ suspend fun getBookChapterList(bookid: String) = withContext(Dispatchers.IO) { //返回的格式第二条数据是空的,单独进行处理 val str = getKSNetApi().getBookChapterList( dirId = niceDir(bookid.toLong()), bookId = bookid.toLong() ).replace("},]}}", "}]}}") Gson().fromJson(str, ChapterListResult::class.java) } /** * 查询数据库书籍章节 */ suspend fun queryChapterObjList(bookid: String) = withContext(Dispatchers.IO) { getDatabase().bookChapterKSDao.queryObj(bookid) } /** * 插入数据库书籍章节 */ suspend fun insertChapterList(list: List<BookChapterKSEntity>) = withContext(Dispatchers.IO){ getDatabase().bookChapterKSDao.insert(list) } /** * 删除数据库书籍对应的章节列表 */ suspend fun deleteChapterList(bookid: String) = withContext(Dispatchers.IO) { getDatabase().bookChapterKSDao.query(bookid)?.let { getDatabase().bookChapterKSDao.delete(bookid) } } /** * 更新章节内容 */ suspend fun updateChapter(obj: BookChapterKSEntity) = withContext(Dispatchers.IO) { getDatabase().bookChapterKSDao.update(obj) } /** * 从数据库查询当前id对应的书籍信息 */ suspend fun queryBookInfo(bookid: String) = withContext(Dispatchers.IO) { getDatabase().bookInfoKSDao.query(bookid) } /** * 插入数据库书籍信息 */ suspend fun insertBookInfo(obj: BookInfoKSEntity) = withContext(Dispatchers.IO) { getDatabase().bookInfoKSDao.insert(obj) } /** * 更新数据库书籍信息 */ suspend fun updateBookInfo(obj: BookInfoKSEntity) = withContext(Dispatchers.IO){ //更新标签 updateLable(obj.bookid, obj.lastChapterName) getDatabase().bookInfoKSDao.update(obj) } /** * 数据库查询章节内容 */ suspend fun queryBookContent(bookid: String, chapterid: String) = withContext(Dispatchers.IO) { getDatabase().bookContentKSDao.query(bookid, chapterid) } /** * 插入数据库章节内容 */ @Synchronized suspend fun insertBookContent(obj: BookContentKSEntity) = withContext(Dispatchers.IO) { val contentObj = queryBookContentObj(obj.bookId, obj.chapterId) //防止重复插入 if (contentObj == null) { getDatabase().bookContentKSDao.insert(obj) } else { getDatabase().bookContentKSDao.delete(obj.bookId, obj.chapterId) //记录最后一次阅读角标 obj.lastContentPosition = contentObj.lastContentPosition getDatabase().bookContentKSDao.insert(obj) } return@withContext obj } /** * 数据库查询章节内容 */ suspend fun queryBookContentObj(bookid: String, chapterid: String) = withContext(Dispatchers.IO) { getDatabase().bookContentKSDao.queryObj(bookid, chapterid) } /** * 查询搜索记录记录 */ suspend fun querySearchHistoryList() = withContext(Dispatchers.IO) { getDatabase().searchHistoryKSDao.query() } /** * 插入历史记录 */ suspend fun insertSearchHistory(obj: SearchHistoryKSEntity) = withContext(Dispatchers.IO) { getDatabase().searchHistoryKSDao.insert(obj) } /** * 删除历史记录 */ suspend fun deleteSearchHistory(obj: SearchHistoryKSEntity) = withContext(Dispatchers.IO){ getDatabase().searchHistoryKSDao.delete(obj) } /** * 搜索历史记录 */ suspend fun querySearchHisotry(keyword: String) = withContext(Dispatchers.IO) { getDatabase().searchHistoryKSDao.query(keyword) } /** * 收藏书籍 */ suspend fun insertCollection(obj: BooksResult) = withContext(Dispatchers.IO){ val collectionKSEntity = getDatabase().bookCollectionKSDao.query(obj.getBookid()) if (collectionKSEntity == null) { getDatabase().bookCollectionKSDao.insert( BookCollectionKSEntity( bookid = obj.getBookid(), resouce = obj.getType(), time = System.currentTimeMillis() ) ) } } /** * 查询书箱 */ suspend fun queryCollection(bookid: String) = withContext(Dispatchers.IO) { getDatabase().bookCollectionKSDao.query(bookid) } /** * 查询所有收藏书籍 */ suspend fun queryCollectionAll() = withContext(Dispatchers.IO) { getDatabase().bookCollectionKSDao.queryAll() } /** * 删除收藏 */ suspend fun deleteCollection(bookid: String) = withContext(Dispatchers.IO) { getDatabase().bookCollectionKSDao.delete(bookid) } /** * 更新置顶时间戳 */ suspend fun updateBookInfoStickTime(bookid: String) = withContext(Dispatchers.IO) { getDatabase().bookInfoKSDao.update(System.currentTimeMillis(), bookid) getDatabase().bookInfoKSDao.query(bookid) } /** * 取消置顶 */ suspend fun updateBookInfoClearStickTime(bookid: String) = withContext(Dispatchers.IO) { getDatabase().bookInfoKSDao.update(0, bookid) getDatabase().bookInfoKSDao.query(bookid) } /** * 排行榜 */ suspend fun getRankingList( gender: String, type: String, date: String, pageNum: Int, ) = withContext(Dispatchers.IO) { getKSNetApi().getRankingList(gender, type, date, pageNum) } /** * 获取最近浏览的小说 */ suspend fun queryReadHistoryList(pageNum: Int) = withContext(Dispatchers.IO) { getDatabase().bookInfoKSDao.queryReadHistoryList(pageNum) } /** * 更新最后一次打开的时间和内容角标 */ suspend fun updateLastOpenContent(bookid: String, chapterid: String, lastContentPosition: Int) = withContext(Dispatchers.IO){ getDatabase().bookContentKSDao.updateLastOpenContent( bookid, chapterid, System.currentTimeMillis(), lastContentPosition ) } /** * 根据小说id查询最近阅读章节 */ suspend fun queryLastOpenChapter(bookid: String) = withContext(Dispatchers.IO) { getDatabase().bookContentKSDao.queryLastOpenChapter(bookid) } /** * 更新标签数据 */ suspend fun updateLable(bookid: String, chapterName: String) = withContext(Dispatchers.IO) { val infoKSEntity = getDatabase().bookInfoKSDao.query(bookid) ?: return@withContext if (chapterName != infoKSEntity.lastChapterName) { PreferenceUtil.commitBoolean(bookid, true) } } /** * 清理标签 */ fun clearLable(bookid: String) { PreferenceUtil.commitBoolean(bookid, false) } /** * 是否显示更新标签 */ @SuppressLint("SimpleDateFormat") fun isShowUpdateLable(bookid: String): Boolean { return PreferenceUtil.getBoolean(bookid, false) } /** * 登录 */ suspend fun login(username: String, password: String) = withContext(Dispatchers.IO) { val map = hashMapOf<String, String>("username" to username, "password" to password) getNetApi().login(niceBody(map)) } /** * 注册 */ suspend fun register(username: String, password: String, email: String) = withContext(Dispatchers.IO) { val map = hashMapOf<String, String>( "username" to username, "password" to password, "email" to email ) getNetApi().register(niceBody(map)) } /** * 添加收藏 */ suspend fun addCollection( bookName: String, bookid: String, author: String, cover: String, description: String, bookStatus: String, classifyName: String, resouceType: String, ) = withContext(Dispatchers.IO) { val kdEntity = getResouceTypeKd(bookid) val tocId = kdEntity?.tocId ?: "" val tocName = kdEntity?.tocId ?: "" val map = hashMapOf( "bookName" to bookName, "bookid" to bookid, "author" to author, "cover" to cover, "description" to description, "bookStatus" to bookStatus, "classifyName" to classifyName, "resouceType" to resouceType, "tocId" to tocId, "tocName" to tocName ) return@withContext getNetApi().addCollection(niceBody(map)) } /** * 获取收藏列表 */ suspend fun getCollectionList(pageNum: Int) = withContext(Dispatchers.IO) { getNetApi().getCollectionList(pageNum, pageSize = 30) } /** * 检测版本号 */ suspend fun checkVersion(versionName: String) = withContext(Dispatchers.IO) { getNetApi().checkVersion(versionName) } /** * 查找最后一次登录帐号 */ suspend fun getLastUser() = withContext(Dispatchers.IO) { getDatabase().userDao.queryUser() } /** * 插入一条帐号 */ suspend fun insert(userEntity: UserEntity) = withContext(Dispatchers.IO){ getDatabase().userDao.insert(userEntity) } /** * 修改最后登陆时间 */ suspend fun updateUserLastTime(uid: String) = withContext(Dispatchers.IO){ getDatabase().userDao.updateLastTime(uid, Date()) } /** * 删除用户 */ suspend fun deleteUser(userEntity: UserEntity) = withContext(Dispatchers.IO){ getDatabase().userDao.delete(userEntity) } /** * 根据uid查询 */ suspend fun queryUser(username: String) = withContext(Dispatchers.IO) { getDatabase().userDao.queryUser(username) } /** * 查询所有收藏书本信息 */ suspend fun queryBookInfoCollectionAll() = withContext(Dispatchers.IO) { getDatabase().bookInfoKSDao.queryCollectionAll() } /** * 查询排行榜数据 */ suspend fun queryRankingListAll() = withContext(Dispatchers.IO) { getDatabase().rankingListDao.queryAll() } /** * 删除排行榜所有数据 */ suspend fun deleteRankingListAll() = withContext(Dispatchers.IO){ getDatabase().rankingListDao.deleteAll() } /** * 批量插入排行榜数据 */ suspend fun insertRankingList(list: List<RankingListEntity>) = withContext(Dispatchers.IO) { val listAll = queryRankingListAll() if (listAll.isEmpty()) { getDatabase().rankingListDao.insert(list) } else { //本地有保存就删除, 只缓存一页数据 deleteRankingListAll() getDatabase().rankingListDao.insert(list) } } /** * 删除收藏 */ suspend fun deleteNetCollect(bookid: String, resouceType: String) = withContext(Dispatchers.IO) { getNetApi().deleteCollectList(bookid, resouceType) } /** * 清空帐号 */ suspend fun clearUsers() = withContext(Dispatchers.IO){ getDatabase().bookReadHistoryDao.clear() getDatabase().userDao.clear() getDatabase().bookCollectionKSDao.clear() getDatabase().bookInfoKSDao.clear() getDatabase().bookChapterKSDao.clear() getDatabase().bookContentKSDao.clear() getDatabase().searchHistoryKSDao.clear() getDatabase().bookResouceTypeKDDao.clear() getDatabase().bookDownloadDao.clear() } /** * 清除书箱所有数据 */ suspend fun clearBookInfo() = withContext(Dispatchers.IO){ getDatabase().bookCollectionKSDao.clear() getDatabase().bookInfoKSDao.clear() getDatabase().bookChapterKSDao.clear() getDatabase().bookContentKSDao.clear() getDatabase().bookResouceTypeKDDao.clear() getDatabase().bookReadHistoryDao.clear() getDatabase().bookDownloadDao.clear() } /** * 最近浏览 */ suspend fun getReadHistoryList(pageNum: Int) = withContext(Dispatchers.IO) { getNetApi().getReadHistoryList(pageNum = pageNum, pageSize = 100) } /** * 获取收藏列表的阅读记录 */ suspend fun getReadHistoryCollectionsList(pageNum: Int) = withContext(Dispatchers.IO) { getNetApi().getReadHistoryCollectionsList(pageNum = pageNum, pageSize = 100) } /** * 获取指定小说阅读记录 */ suspend fun getReadHistoryCollectionsList(bookid: String) = withContext(Dispatchers.IO) { getNetApi().getReadHistoryCollectionsList(bookid = bookid) } /** * 更新阅读记录 */ suspend fun updateReadHistory( bookName: String, bookid: String, chapterid: String, chapterName: String, author: String, cover: String, description: String, resouceType: String, content: String, ) = withContext(Dispatchers.IO) { val kdEntity = getResouceTypeKd(bookid) val tocId = kdEntity?.tocId ?: "" val tocName = kdEntity?.typeName ?: "" val map = hashMapOf<String, Any>( "bookName" to bookName, "bookid" to bookid, "chapterid" to chapterid, "chapterName" to chapterName, "author" to author, "cover" to cover, "description" to description, "resouceType" to resouceType, "content" to content, "tocId" to tocId, "tocName" to tocName ) //没登陆返回空 if (application.getToken().isEmpty()) { return@withContext StatusResult(-1, "未查询到阅读记录") } getNetApi().updateReadHistory(niceBody(map)) } /** * 查看章节对应记录 */ suspend fun queryBookReadHistoryEntity(bookid: String, chapterid: String) = withContext(Dispatchers.IO) { getDatabase().bookReadHistoryDao.queryBookReadHistoryEntity(bookid, chapterid) } /** * 更新最后一次阅读记录到本地 */ suspend fun updateLocalREadHistory( bookid: String, chapterid: String, lastReadTime: Long = System.currentTimeMillis(), ) = withContext(Dispatchers.IO){ val entity = getDatabase().bookReadHistoryDao.queryBookReadHistoryEntity(bookid, chapterid) if (entity == null) { getDatabase().bookReadHistoryDao.insert(BookReadHistoryEntity().apply { this.bookid = bookid this.chapterid = chapterid this.lastReadTime = lastReadTime }) } else { entity.lastReadTime = lastReadTime getDatabase().bookReadHistoryDao.update(entity) } } /** * 获取最近阅读记录 */ suspend fun queryBookReadHistoryEntity(bookid: String) = withContext(Dispatchers.IO) { getDatabase().bookReadHistoryDao.queryLastChanpterEntity(bookid) } /** * 开始下载任务 */ fun startWorker(obj: BooksResult): UUID { val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .setRequiresBatteryNotLow(true)//指定设备电池是否不应低于临界阈值 .build() val data = Data.Builder().putString(NovelDownloadWorker.BOOKS_RESULT, obj.toJson()) .build() val request = OneTimeWorkRequest.Builder(NovelDownloadWorker::class.java) .setConstraints(constraints) .setInputData(data) .build() WorkManager.getInstance().enqueue(request) return request.id } /** * 发送邮箱验证码 */ suspend fun getMailCode(mail: String) = withContext(Dispatchers.IO) { getNetApi().getMailCode(mail) } /** * 检测用户邮箱是否存在 */ suspend fun checkEmailEmpty(email: String) = withContext(Dispatchers.IO) { getNetApi().checkEmailEmpty(email) } /** * 检测邮箱验证码 */ suspend fun checkEmailCode(email: String, newCode: String, oldCode: String) = withContext(Dispatchers.IO) { val map = hashMapOf<String, String>( "email" to email, "newCode" to newCode, "oldCode" to oldCode ) getNetApi().checkEmailCode(niceBody(map)) } /** * 修改密码 */ suspend fun updatePassword( email: String, username: String, password: String, againPassword: String, ) = withContext(Dispatchers.IO) { val map = hashMapOf<String, String>( "email" to email, "username" to username, "password" to password, "againPassword" to againPassword ) getNetApi().updatePassword(niceBody(map)) } /** * 书源列表 */ suspend fun getResouceList(pageNum: Int) = withContext(Dispatchers.IO) { val map = hashMapOf<String, Int>("type" to 0, "pageNum" to pageNum, "pageSize" to 100) getNetApi().getResouceList(niceBody(map)) } /** * 书名/作者搜索 */ suspend fun getBookSearchList(keyword: String) = withContext(Dispatchers.IO) { val map = hashMapOf<String, String>("keyword" to keyword) getNetApi().getBookSearchList(niceBody(map)) } /** * 作者所有作品 */ suspend fun getAuthorBooksList(author: String) = withContext(Dispatchers.IO) { val map = hashMapOf<String, String>("author" to author) getNetApi().getAuthorBooksList(niceBody(map)) } /** * 保存公告信息 */ suspend fun insert(obj: PushMessageEntity) = withContext(Dispatchers.IO){ getDatabase().pushMessageDao.insert(obj) } /** * 查询最后一次公告信息 */ suspend fun queryNoteEntity() = withContext(Dispatchers.IO) { getDatabase().pushMessageDao.queryNote() } /** * 删除推送消息 */ suspend fun delete(obj: PushMessageEntity) = withContext(Dispatchers.IO){ getDatabase().pushMessageDao.delete(obj) } /** * 修改书籍详情修改时间 */ suspend fun updateBookInfoLastReadTime(bookid: String) = withContext(Dispatchers.IO){ getDatabase().bookInfoKSDao.updateLastReadTime(System.currentTimeMillis(), bookid) } /** * 快读源插入 */ suspend fun insertKuaiDuResouce(obj: BookResouceTypeKDEntity) = withContext(Dispatchers.IO) { val typeKDEntity = getDatabase().bookResouceTypeKDDao.query(obj.bookid) if (typeKDEntity == null) { getDatabase().bookResouceTypeKDDao.insert(obj) return@withContext } obj.id = typeKDEntity.id getDatabase().bookResouceTypeKDDao.update(obj) } /** * 删除指定小说记录 */ suspend fun deleteBookHistory(bookid: String) = withContext(Dispatchers.IO) { getDatabase().bookReadHistoryDao.clear(bookid) } /** * 删除小说内容 */ suspend fun deleteBookContent(bookid: String) = withContext(Dispatchers.IO) { getDatabase().bookContentKSDao.delete(bookid) } /** * 更改收藏 */ suspend fun updateCollection(obj: BookCollectionKSEntity) = withContext(Dispatchers.IO){ getDatabase().bookCollectionKSDao.update(obj) } /** * 获取快读渠道源 */ suspend fun getResouceTypeKd(bookid: String) = withContext(Dispatchers.IO) { getDatabase().bookResouceTypeKDDao.query(bookid) } /** * 快读精确求书 */ suspend fun getBookFeedback(bookName: String, author: String) = withContext(Dispatchers.IO){ val map = hashMapOf<String, String>( "book" to bookName, "author" to author, "system" to "Android", "package" to "kuaidu.xiaoshuo.yueduqi", "version" to "1100" ) getKuaiDuApi().getBookFeedback(niceBody(map)) } /** * 获取所有下载的书籍 */ suspend fun queryDownloadBooks() = withContext(Dispatchers.IO) { getDatabase().bookDownloadDao.queryAll() } /** * 更新下载记录 */ suspend fun updateDownloadBook( bookid: String, bookName: String, resouce: String, progress: Int, total: Int, cover: String, author: String, uuid: String, ) = withContext(Dispatchers.IO){ val entity = getDatabase().bookDownloadDao.query(bookid) if (entity == null) { getDatabase().bookDownloadDao.insert(BookDownloadEntity().apply { this.bookId = bookid this.bookName = bookName this.resouce = resouce this.progress = progress this.total = total this.cover = cover this.author = author this.uuid = uuid }) return@withContext } getDatabase().bookDownloadDao.update(entity.apply { this.progress = progress this.total = total }) } /** * 删除缓存记录 */ @Synchronized suspend fun deleteDownload(bookid: String) = withContext(Dispatchers.IO){ getDatabase().bookDownloadDao.deleteDownload(bookid) } /** * 书城 -> 男生 */ suspend fun getStoreMan() = withContext(Dispatchers.IO) { getKSNetApi().getStoreMan() } /** * 书城 -> 女生 */ suspend fun getStoreLady() = withContext(Dispatchers.IO) { getKSNetApi().getStoreLady() } /** * 书城 -> 榜单 -> 男生 */ suspend fun getStoreRankingMan() = withContext(Dispatchers.IO) { getKSNetApi().getStoreRankingMan() } /** * 书城 -> 榜单 -> 女生 */ suspend fun getStoreRankingLady() = withContext(Dispatchers.IO){ getKSNetApi().getStoreRankingLady() } /** * 获取书单 * * 最新发布/本周最热/最多收藏/小编推荐 */ suspend fun getBooksList(gender: String, type: String, pageNum: Int) = withContext(Dispatchers.IO) { getKSNetApi().getBooksList(gender, type, pageNum.toString()) } /** * 正版排行榜 * * 起点/纵横/去起/若初/红薯/潇湘/逐浪 */ suspend fun getMoreRankingList(gender: String, type: Int, pageNum: Int) = withContext(Dispatchers.IO) { getKSNetApi().getMoreRankingList(gender, type, pageNum.toString()) } /** * 看书神器 排行榜 */ suspend fun getKanShuRankingList( gender: String, type: String, date: String, pageNum: Int, ) = withContext(Dispatchers.IO) { getKSNetApi().getKanShuRankingList(gender, type, date, pageNum) } /** * 书单详情页 */ suspend fun getBookListDetail(id: String) = withContext(Dispatchers.IO) { getKSNetApi().getBookListDetail(id) } /** * 分类 */ suspend fun getCategoryList() = withContext(Dispatchers.IO){ getKuaiDuApi().getCategoryList() } /** * 快读 男生分类 */ suspend fun queryCategoryMan() = withContext(Dispatchers.IO) { getDatabase().categoryKDDao.queryMan() } /** * 快读 女生分类 */ suspend fun queryCategoryLady() = withContext(Dispatchers.IO) { getDatabase().categoryKDDao.queryLady() } /** * 快读 出版分类 */ suspend fun queryCategoryPress() = withContext(Dispatchers.IO) { getDatabase().categoryKDDao.queryPress() } /** * 快读 插入分类 */ suspend fun insertCategoryList(obj: List<CategoryKDEntity>) = withContext(Dispatchers.IO) { if (obj.isEmpty()) return@withContext getDatabase().categoryKDDao.clear() getDatabase().categoryKDDao.insert(obj = obj) } /** * 分类详情 */ suspend fun getCategoryDetailList( gender: String, type: Int, major: String, pageNum: Int, ) = withContext(Dispatchers.IO) { getKuaiDuApi().getCategoryDetailList(gender, type, major, pageNum, 50) } /** * 获取游戏推荐 */ suspend fun getGameRecommentList(pageNum: Int) = withContext(Dispatchers.IO) { getNetApi().getGameRecommentList(pageNum, 20) } /** * 获取配置文件 */ suspend fun getAppConfig() = withContext(Dispatchers.IO) { getNetApi().getAppConfig() } /** * 查询配置 */ suspend fun queryConfig() = withContext(Dispatchers.IO) { getDatabase().configDao.query() } /** * 保存配置文件 */ suspend fun insertConfig(obj: ConfigEntity) = withContext(Dispatchers.IO) { getDatabase().configDao.insert(obj) } /** * 保存看书神器 排行榜 */ suspend fun insertStoreRanking(obj: StoreRankingEntity) = withContext(Dispatchers.IO) { getDatabase().storeRankingDao.insert(obj) } /** * 清空书城记录 */ suspend fun cleanStoreRanking(genderType: String) = withContext(Dispatchers.IO) { getDatabase().storeRankingDao.clean(genderType) } /** * 查询看书神器 排行榜 */ suspend fun queryStoreRanking(genderType: String) = withContext(Dispatchers.IO) { getDatabase().storeRankingDao.query(genderType) } /** * 看书神器 保存书城列表 */ suspend fun insertStoreEntity(obj: List<StoreEntity>) = withContext(Dispatchers.IO) { getDatabase().storeDao.insert(obj) } /** * 看书神器 查看看书列表 */ suspend fun queryStoreEntity(genderType: String) = withContext(Dispatchers.IO) { getDatabase().storeDao.query(genderType) } /** * 看书神器 删除书城列表 */ suspend fun deleteStoreEntity(genderType: String) = withContext(Dispatchers.IO){ getDatabase().storeDao.delete(genderType) } /** * 查询 书城 -> 点击更多 */ suspend fun queryBooksKSEntity( name: String, gender: String, type: String, date: String = "", ) = withContext(Dispatchers.IO) { getDatabase().booksKSDao.query( gender = gender, toobarName = name, type = type, date = date ) } /** * 删除 书城 -> 点击更多 */ suspend fun deleteBooksKSEntity(name: String, gender: String, type: String, date: String = "") = withContext(Dispatchers.IO) { getDatabase().booksKSDao.delete( gender = gender, toobarName = name, type = type, date = date ) } /** * 保存 书城 -> 点击更多 * 保存 书城 -> 书单 */ suspend fun insertBooksKSEntity(obj: List<BooksKSEntity>) = withContext(Dispatchers.IO) { getDatabase().booksKSDao.insert(obj) } /** * 查询 书城 -> 书单 */ suspend fun queryShuDanEntity(name: String, gender: String, type: String) = withContext(Dispatchers.IO) { getDatabase().shuDanDao.query(gender = gender, name = name, type = type) } /** * 删除 书城 -> 书单 */ suspend fun deleteShuDanEntity(name: String, gender: String, type: String) = withContext(Dispatchers.IO) { getDatabase().shuDanDao.delete(gender = gender, name = name, type = type) } /** * 保存 书城 -> 书单 */ suspend fun insertShuDanEntity(list: List<ShuDanEntity>) = withContext(Dispatchers.IO) { getDatabase().shuDanDao.insert(list) } /** * 查询收藏列表 看书源 */ suspend fun queryCollectionKS() = withContext(Dispatchers.IO) { getDatabase().bookInfoKSDao.queryCollectionKS() } /** * 查询收藏列表 快读源 */ suspend fun queryCollectionKD() = withContext(Dispatchers.IO) { getDatabase().bookInfoKSDao.queryCollectionKD() } /** * 获取所有收藏的连载列表 */ suspend fun queryCollectionAllSerial() = withContext(Dispatchers.IO) { getDatabase().bookInfoKSDao.queryCollectionAllSerial() } /** * 随机获取小黄书列表 */ suspend fun getBookSexList(pageNum: Int) = withContext(Dispatchers.IO) { val map = hashMapOf<String, Int>("limit" to pageNum) getNetApi().getBookSexList(niceBody(map)) } /** * 插入小黄书 */ suspend fun insert(list: List<SexBooksEntity>) = withContext(Dispatchers.IO) { getDatabase().sexBooksDao.insert(list) } /** * 删除小黄书列表 */ suspend fun cleanSexBooksEntity() = withContext(Dispatchers.IO) { getDatabase().sexBooksDao.clean() } /** * 获取小黄书列表 */ suspend fun querySexBooksEntityAll() = withContext(Dispatchers.IO) { getDatabase().sexBooksDao.queryAll() } /** * 更新 最后更新时间 */ suspend fun updateLastTime(bookid: String, lastTime: Long) { getDatabase().bookInfoKSDao.updateLastTime(bookid, lastTime) } }
1
null
1
2
8c72fc787a2927efb10c8c03b714195c7b1a6c76
30,228
Pirate
Apache License 2.0
protocol/src/main/kotlin/org/openrs2/protocol/create/downstream/PasswordInvalidLengthCodec.kt
openrs2
315,027,372
false
null
package org.openrs2.protocol.create.downstream import org.openrs2.protocol.EmptyPacketCodec import javax.inject.Singleton @Singleton public class PasswordInvalidLengthCodec : EmptyPacketCodec<CreateResponse.PasswordInvalidLength>( packet = CreateResponse.PasswordInvalidLength, opcode = 30 )
0
Kotlin
2
8
12eba96055ba13e8a8e3ec0ad3be7d93b3dd5b1b
302
openrs2
ISC License
libnavigation-tripdata/src/main/java/com/mapbox/navigation/tripdata/shield/internal/api/MapboxRouteShieldApiEx.kt
mapbox
87,455,763
false
{"Kotlin": 8885438, "Makefile": 8762, "Python": 7925, "Java": 4624}
package com.mapbox.navigation.tripdata.shield.internal.api import com.mapbox.bindgen.Expected import com.mapbox.navigation.tripdata.shield.api.MapboxRouteShieldApi import com.mapbox.navigation.tripdata.shield.internal.model.RouteShieldToDownload import com.mapbox.navigation.tripdata.shield.model.RouteShieldError import com.mapbox.navigation.tripdata.shield.model.RouteShieldResult import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine suspend fun MapboxRouteShieldApi.getRouteShieldsFromModels( shieldsToDownload: List<RouteShieldToDownload>, ): List<Expected<RouteShieldError, RouteShieldResult>> { return suspendCoroutine { continuation -> getRouteShieldsInternal(shieldsToDownload) { continuation.resume(it) } } }
508
Kotlin
318
621
88163ae3d7e34948369d6945d5b78a72bdd68d7c
781
mapbox-navigation-android
Apache License 2.0
app/src/test/java/com/ankitgh/employeeportal/ui/LauncherViewModelTest.kt
AnkitGhate
267,842,910
false
null
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ankitgh.employeeportal.ui import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.ankitgh.employeeportal.data.MainRepository import com.ankitgh.employeeportal.util.MainCoroutineRule import com.ankitgh.employeeportal.util.observeForTesting import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.doReturn import org.mockito.junit.MockitoJUnitRunner @ExperimentalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class LauncherViewModelTest { @Rule @JvmField val instantExecutorRule = InstantTaskExecutorRule() // Sets the main coroutines dispatcher to a TestCoroutineScope for unit testing. @ExperimentalCoroutinesApi @get:Rule var mainCoroutineRule = MainCoroutineRule() private lateinit var SUT: LauncherViewModel @Mock private lateinit var mainRepository: MainRepository @Before fun setUp() { success(mainRepository) SUT = LauncherViewModel(mainRepository) } @ExperimentalCoroutinesApi @Test fun ifUserRegistered_returnsTrue() { SUT.launchDestination.observeForTesting { assertEquals(Destination.HOME, SUT.launchDestination.value) } } @ExperimentalCoroutinesApi @Test fun ifUserRegistered_returnsFalse() { failure(mainRepository) SUT.launchDestination.observeForTesting { assertEquals(Destination.ONBOARDING, SUT.launchDestination.value) } } private fun success(mainRepo: MainRepository) { doReturn(true).`when`(mainRepo).isUserAlreadyRegistered() } private fun failure(mainRepo: MainRepository) { doReturn(false).`when`(mainRepo).isUserAlreadyRegistered() } }
0
Kotlin
0
2
c92797926019fb62a30226f54fc8327c1517c9df
2,474
EmployeePortal
Apache License 2.0
app/src/main/java/org/phcbest/neteasymusic/ui/activity/PlayDetailActivity.kt
phcbest
471,621,513
false
null
package org.phcbest.neteasymusic.ui.activity import android.annotation.SuppressLint import android.content.ComponentName import android.content.Intent import android.content.ServiceConnection import android.graphics.Color import android.os.IBinder import android.text.Spannable import android.text.SpannableStringBuilder import android.text.style.AbsoluteSizeSpan import android.text.style.ForegroundColorSpan import android.util.Log import androidx.databinding.DataBindingUtil import androidx.lifecycle.MutableLiveData import androidx.viewbinding.ViewBinding import com.google.android.material.slider.Slider import org.phcbest.neteasymusic.R import org.phcbest.neteasymusic.base.BaseActivity import org.phcbest.neteasymusic.databinding.ActivityPlayDetailBinding import org.phcbest.neteasymusic.service.meida.MusicPlayerService import org.phcbest.neteasymusic.ui.widget.playDisc.PlayDiscHelper import org.phcbest.neteasymusic.utils.ui.StatusBarUtil import java.text.SimpleDateFormat import java.util.* class PlayDetailActivity : BaseActivity() { private var playDiscHelper: PlayDiscHelper? = null companion object { const val TAG = "PlayDetailActivity" } override fun initPresenter() { } override fun initView() { //设置透明状态栏 isSemiTransparentStatusBar = true //设置状态栏沉浸 binding?.llTop?.setPadding(0, StatusBarUtil.getStatusBarHeight(this), 0, 0) //初始化cd view帮助器 playDiscHelper = PlayDiscHelper().setView(binding?.clCd?.rootView!!) //设置Slider从*到* binding?.srSongProgress?.valueFrom = 0.0F binding?.srSongProgress?.valueTo = 300.0F } override fun initEvent() { super.initEvent() binding?.ivPlayBtn?.setOnClickListener { //设置不同状态下的ui表现 //设置不同状态下的暂停和播放事件 if (mMusicPlayerServiceLD.value?.isPlayerLD?.value!!) { binding?.ivPlayBtn?.setImageResource(R.drawable.ic_play_detail_play) mMusicPlayerServiceLD.value?.playControl(1) } else { binding?.ivPlayBtn?.setImageResource(R.drawable.ic_play_detail_pause) mMusicPlayerServiceLD.value?.playControl(2) } } //上一首和下一首的事件 ,执行完动画之后再执行切换 binding?.ivPlayPrevious?.setOnClickListener { mMusicPlayerServiceLD.value?.switchSongNOP(false) } binding?.ivPlayNext?.setOnClickListener { mMusicPlayerServiceLD.value?.switchSongNOP(true) } //设置进度条改变事件 binding?.srSongProgress?.addOnSliderTouchListener(object : Slider.OnSliderTouchListener { @SuppressLint("RestrictedApi") override fun onStartTrackingTouch(slider: Slider) { enableProgress = false Log.i(TAG, "onStartTrackingTouch: ") } @SuppressLint("RestrictedApi") override fun onStopTrackingTouch(slider: Slider) { // Log.i(TAG, "当前进度: ${slider.value} 全部进度: ${slider.valueFrom}") //切换歌曲进度 //计算歌曲进度 val progress = slider.value / 300F Log.i(TAG, "onStopTrackingTouch: $progress") mMusicPlayerServiceLD.value?.seekTo(progress) enableProgress = true } }) } private val sdf = SimpleDateFormat("mm:ss", Locale.CHINA) private var enableProgress = true override fun observeViewModel() { super.observeViewModel() //服务绑定的回调 mMusicPlayerServiceLD.observe(this) { //设置初始指针位置,初始播放按钮样式 if (it!!.isPlayerLD.value!!) { binding?.ivPlayBtn?.setImageResource(R.drawable.ic_play_detail_pause) playDiscHelper?.setInitNeedlePlace(PlayDiscHelper.NEEDLE_STATE.OVERLAY) } else { binding?.ivPlayBtn?.setImageResource(R.drawable.ic_play_detail_play) playDiscHelper?.setInitNeedlePlace(PlayDiscHelper.NEEDLE_STATE.LEAVE) } //设置歌曲变动的观察者回调 it.currentSongEntityLD.observe(this) { songEntity -> Log.i(TAG, "observeViewModel: $songEntity") //设置模糊背景 binding?.songEntity = songEntity //设置歌曲封面 playDiscHelper?.setDiscInfo(songEntity?.cover!!) //设置歌曲名字 //使用ssb设置不同的样式 val ssb = SpannableStringBuilder() ssb.append(songEntity.name) ssb.append("\n") val l1 = ssb.length ssb.append(songEntity.author) ssb.setSpan(ForegroundColorSpan(Color.parseColor("#8bffffff")), l1, ssb.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) ssb.setSpan(AbsoluteSizeSpan(10, true), l1, ssb.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) binding?.tvSongName?.text = ssb } //设置播放状态的观察者 it.isPlayerLD.observe(this) { isPlayer -> if (isPlayer!!) { playDiscHelper?.play() } else { playDiscHelper?.stop() } } //设置进度推出器的观察者 it.playProgressLD.observe(this) { progress -> if (progress == null || !enableProgress) return@observe val fullProgressText = sdf.format(progress.fullProgress) //设置全部进度 if (binding?.tvFullProgress?.text != fullProgressText) { binding?.tvFullProgress?.text = fullProgressText } //设置当前进度 binding?.tvCurrentProgress?.text = sdf.format(progress.currentProgress) //设置进度条 binding?.srSongProgress?.value = (300F * (progress.currentProgress.toFloat() / progress.fullProgress.toFloat())) } } } var binding: ActivityPlayDetailBinding? = null override fun getViewBinding(): ViewBinding { //绑定播放服务 doBindService() binding = DataBindingUtil.inflate(layoutInflater, R.layout.activity_play_detail, null, false) return binding!! } private fun doBindService() { bindService(Intent(this, MusicPlayerService::class.java), playServiceConnection(), BIND_AUTO_CREATE) } var mMusicPlayerServiceLD: MutableLiveData<MusicPlayerService?> = MutableLiveData() private fun playServiceConnection(): ServiceConnection { return object : ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { mMusicPlayerServiceLD.postValue((service as MusicPlayerService.MyBinder).getService()) Log.i(TAG, "onServiceConnected: 活动和服务连接完成") } //这个是由服务决定的 override fun onServiceDisconnected(name: ComponentName?) { mMusicPlayerServiceLD.postValue(null) Log.i(TAG, "onServiceDisconnected: 服务断开连接") } } } }
0
Kotlin
1
2
d94a834216d24f81ee5e2e35b0c54ef6da8b50af
7,173
KotlinNetEasyMusic
MIT License
idea/testData/copyPaste/plainTextLiteral/WithEntries.kt
JakeWharton
99,388,807
false
null
val a="<caret>"
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
15
kotlin
Apache License 2.0
idea/testData/copyPaste/plainTextLiteral/WithEntries.kt
JakeWharton
99,388,807
false
null
val a="<caret>"
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
15
kotlin
Apache License 2.0
app/src/main/java/com/qflow/main/domain/DataConstant.kt
DanielPinaM
303,209,249
true
{"Kotlin": 167916, "Java": 3748}
package com.qflow.main.domain const val COLLECTION_QUEUE = "queue" const val COLLECTION_QUEUE_USER = "queue_user" const val COLLECTION_USER = "user" //crear demas bbdd
0
null
0
0
7a5a91096dffc75fbc167d8d1483b7f1adcfbe0b
168
QueueApp
Apache License 2.0
mpp-library/feature/list/src/commonMain/kotlin/org/example/library/feature/list/di/ListFactory.kt
icerockdev
210,767,979
false
null
/* * Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package org.example.library.feature.list.di import org.example.library.feature.list.model.ListSource import org.example.library.feature.list.presentation.ListViewModel class ListFactory<T>( private val listSource: ListSource<T>, private val strings: ListViewModel.Strings, private val unitsFactory: ListViewModel.UnitsFactory<T> ) { fun createListViewModel(): ListViewModel<T> { return ListViewModel( listSource = listSource, strings = strings, unitsFactory = unitsFactory ) } }
8
Kotlin
43
413
1e202b699153a337944ca4b00353ecf3a685884d
659
moko-template
Apache License 2.0
discussions/discussions-common/src/commonMain/kotlin/DiscCorSettings.kt
Piligrim678
600,730,971
false
null
package ru.music.common import repo.IDiscussionRepository import ru.music.discussions.MpLoggerProvider data class DiscCorSettings( val loggerProvider: MpLoggerProvider = MpLoggerProvider(), val repoStub: IDiscussionRepository = IDiscussionRepository.NONE, val repoTest: IDiscussionRepository = IDiscussionRepository.NONE, val repoProd: IDiscussionRepository = IDiscussionRepository.NONE ) { companion object { val NONE = DiscCorSettings() } }
1
Kotlin
0
0
2a10c588334d27a8864ff893c8a4871b8cbecac4
477
music
Apache License 2.0
src/test/kotlin/world/cepi/kstom/item/ItemTests.kt
Project-Cepi
320,725,364
false
null
package world.cepi.kstom.item import io.kotest.core.plan.Descriptor.EngineDescriptor.displayName import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.shouldBe import net.kyori.adventure.text.Component import world.cepi.kstom.nbt.classes.CollectionClass import world.cepi.kstom.nbt.classes.ComplexClass import world.cepi.kstom.nbt.classes.InterestingClass class ItemTests : StringSpec({ val item = item(amount = 5) { lore = listOf(Component.text("Hello!")) displayName = Component.text("Hey!") damage = 5 unbreakable = true this["complexData"] = ComplexClass(5, 4, 2, true, InterestingClass("hey", 'h')) this["complexListData"] = CollectionClass(5, 9, 3, listOf(4, 3)) }.withAmount(7).and { displayName(Component.text("Hay!")) } "item should be mutated" { item.amount shouldBe 7 item.displayName shouldBe Component.text("Hay!") } "complex data should be stored" { val data = ComplexClass(5, 4, 2, true, InterestingClass("hey", 'h')) val otherData = CollectionClass(5, 9, 3, listOf(4, 3)) item.meta.get<ComplexClass>("complexData") shouldBe data item.meta.get<CollectionClass>("complexListData") shouldBe otherData } "data should return null if not found" { item.meta.get<ComplexClass>("weirdData").shouldBeNull() } })
3
Kotlin
3
7
9ae0eb4872458661315ecadc4d570617039e10ca
1,433
KStom
MIT License
Data/azure.android.data/src/main/java/com/microsoft/azureandroid/data/services/ResourceResponse.kt
NateRickard
108,568,001
false
null
package com.microsoft.azureandroid.data.services import com.microsoft.azureandroid.data.model.DataError import com.microsoft.azureandroid.data.model.ResourceBase import com.microsoft.azureandroid.data.model.Result import okhttp3.Request /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ open class ResourceResponse<T : ResourceBase>( // The URL request sent to the server. request: Request? = null, // The server's response to the URL request. response: okhttp3.Response? = null, // The data returned by the server. jsonData: String? = null, // The result of response deserialization. override val result: Result<T>) : Response(request, response, jsonData, result) { constructor( // the error error: DataError, // The URL request sent to the server. request: Request? = null, // The server's response to the URL request. response: okhttp3.Response? = null, // The json data returned by the server. jsonData: String? = null) : this(request, response, jsonData, Result(error)) /** * Returns the associated value of the result if it is a success, null otherwise. */ val resource: T? get() = result.resource }
1
Kotlin
1
1
4eab6b9b30698081e7f7092e3b5d7e5645fd33f9
1,346
Azure.Android
MIT License
compose-ide-plugin/src/com/android/tools/compose/debug/ComposableSingletonsUtil.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.android.tools.compose.debug import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils import org.jetbrains.kotlin.psi.KtFile /** * Compute the name of the ComposableSingletons class for the given file. * * The Compose compiler plugin creates per-file ComposableSingletons classes to cache composable * lambdas without captured variables. We need to locate these classes in order to search them for * breakpoint locations. * * NOTE: The pattern for ComposableSingletons classes needs to be kept in sync with the code in * `ComposerLambdaMemoization.getOrCreateComposableSingletonsClass`. The optimization was * introduced in I8c967b14c5d9bf67e5646e60f630f2e29e006366 */ internal fun computeComposableSingletonsClassName(file: KtFile): String { // The code in `ComposerLambdaMemoization` always uses the file short name and // ignores `JvmName` annotations, but (implicitly) respects `JvmPackageName` // annotations. val filePath = file.virtualFile?.path ?: file.name val fileName = filePath.split('/').last() val shortName = PackagePartClassUtils.getFilePartShortName(fileName) val fileClassFqName = runReadAction { JvmFileClassUtil.getFileClassInfoNoResolve(file) }.facadeClassFqName return buildString { val pgk = fileClassFqName.parent() if (!pgk.isRoot) { append(pgk.asString()) append(".") } append("ComposableSingletons") append("\$") append(shortName) } } /** * Compute the class name for a given lambda * @param composeSingletonsClassName: The 'ComposableSingletons' class: See [computeComposableSingletonsClassName] * @param lambdaIndex The index of the current lambda (first lambda has index 0) */ internal fun computeComposableSingletonsLambdaClassName( composeSingletonsClassName: String, lambdaIndex: Int, ): String { return "$composeSingletonsClassName\$lambda-${lambdaIndex + 1}\$1" }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
2,127
android
Apache License 2.0
app/src/main/java/com/example/inventory/data/Item.kt
emmanuelwithme
502,542,936
false
{"Kotlin": 49308}
package com.example.inventory.data import android.content.ContentValues import android.net.Uri import androidx.core.net.toUri import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.example.inventory.MainActivity.Companion.ITEM_TABLE_COLNAME_BIRTHDAY import com.example.inventory.MainActivity.Companion.ITEM_TABLE_COLNAME_CHINESE import com.example.inventory.MainActivity.Companion.ITEM_TABLE_COLNAME_EMAIL import com.example.inventory.MainActivity.Companion.ITEM_TABLE_COLNAME_ENGLISH import com.example.inventory.MainActivity.Companion.ITEM_TABLE_COLNAME_FAVORITE import com.example.inventory.MainActivity.Companion.ITEM_TABLE_COLNAME_ID import com.example.inventory.MainActivity.Companion.ITEM_TABLE_COLNAME_PHONE import com.example.inventory.MainActivity.Companion.ITEM_TABLE_COLNAME_PHOTO import java.text.SimpleDateFormat import java.util.* // In here, create a table Entity and name it "item" @Entity(tableName = "item") data class Item( @PrimaryKey(autoGenerate = true) var id: Int = 0, @ColumnInfo(name = "vocEnglish") var vocEnglish: String, @ColumnInfo(name = "vocChinese") var vocChinese: String, @ColumnInfo(name = "vocFavorite") var vocFavorite: Boolean, @ColumnInfo(name = "birthday") var birthday: Date, @ColumnInfo(name = "phone") var phone: String, @ColumnInfo(name = "email") var email: String, @ColumnInfo(name = "photo") var photo: Uri ) { /* * Outside apps do not know the exact structure of your Item class, * so they send your ContentProvider a general object of the type ContentValues, * leaving it up to you to turn it into the desired object (in our case, an Item) * */ companion object { fun fromContentValues(contentValues: ContentValues): Item { val dateString = "2000.02.02" val formatter = SimpleDateFormat("yyyy.MM.dd", Locale.TAIWAN) val date = formatter.parse(dateString) val emptyUri = Uri.EMPTY val item = Item( 0, "item1-eng", "item1-cn", false, date!!, "0988222222", "<EMAIL>", emptyUri ) if (contentValues.containsKey(ITEM_TABLE_COLNAME_ID)) { item.id = contentValues.getAsInteger(ITEM_TABLE_COLNAME_ID) } if (contentValues.containsKey(ITEM_TABLE_COLNAME_ENGLISH)) { item.vocEnglish = contentValues.getAsString(ITEM_TABLE_COLNAME_ENGLISH) } if (contentValues.containsKey(ITEM_TABLE_COLNAME_CHINESE)) { item.vocChinese = contentValues.getAsString(ITEM_TABLE_COLNAME_CHINESE) } if (contentValues.containsKey(ITEM_TABLE_COLNAME_FAVORITE)) { item.vocFavorite = contentValues.getAsBoolean(ITEM_TABLE_COLNAME_FAVORITE) } if (contentValues.containsKey(ITEM_TABLE_COLNAME_BIRTHDAY)) { val birthdayString = contentValues.getAsString(ITEM_TABLE_COLNAME_BIRTHDAY) val formatter = SimpleDateFormat("yyyy.MM.dd", Locale.TAIWAN) item.birthday = formatter.parse(birthdayString)!! } if (contentValues.containsKey(ITEM_TABLE_COLNAME_PHONE)) { item.phone = contentValues.getAsString(ITEM_TABLE_COLNAME_PHONE) } if (contentValues.containsKey(ITEM_TABLE_COLNAME_EMAIL)) { item.email = contentValues.getAsString(ITEM_TABLE_COLNAME_EMAIL) } if (contentValues.containsKey(ITEM_TABLE_COLNAME_PHOTO)) { val stringPhoto = contentValues.getAsString(ITEM_TABLE_COLNAME_PHOTO) item.photo = stringPhoto.toUri() } return item } } /* The class ContentValues is actually a fairly basic dictionary * that allows us to retrieve a value from a key */ }
0
Kotlin
0
0
b9c226a98c058c5798c745f26983aa3d499b21d1
3,917
android_final_project
Apache License 2.0
sample/src/main/java/com/kiven/sample/network/socket/AHSocketTest.kt
WangKiven
64,111,499
false
null
package com.kiven.sample.network.socket import android.net.Uri import android.os.Bundle import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.Button import android.widget.TextView import androidx.core.widget.NestedScrollView import com.google.android.flexbox.AlignContent import com.google.android.flexbox.FlexWrap import com.google.android.flexbox.FlexboxLayout import com.kiven.kutils.activityHelper.KActivityHelper import com.kiven.kutils.activityHelper.KHelperActivity import com.kiven.kutils.tools.KNetwork import com.kiven.kutils.tools.KUtil import com.kiven.sample.util.* import com.sxb.kutils_ktx.util.RxBus import kotlinx.coroutines.* import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.Main import java.io.File import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetAddress import java.net.MulticastSocket import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine /** * https://www.cnblogs.com/xujian2014/p/5072215.html */ class AHSocketTest : KActivityHelper() { override fun onCreate(activity: KHelperActivity, savedInstanceState: Bundle?) { super.onCreate(activity, savedInstanceState) val flexboxLayout = FlexboxLayout(activity) flexboxLayout.flexWrap = FlexWrap.WRAP flexboxLayout.alignContent = AlignContent.FLEX_START setContentView(NestedScrollView(activity).apply { addView(flexboxLayout) }) val addTitle = fun(text: String) { val tv = TextView(activity) tv.text = text tv.layoutParams = ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT) flexboxLayout.addView(tv) } val addView = fun(text: String, click: View.OnClickListener) { val btn = Button(activity) btn.text = text btn.setOnClickListener(click) flexboxLayout.addView(btn) } addTitle("- 广播分为:定向广播,本地广播" + "\n- 定向广播:将数据报包发送到本网络之外的特定网络的所有主机,然而,由于互联网上的大部分路由器都不转发定向广播消息,所以这里不深入介绍了" + "\n- 本地广播:将数据报包发送到本地网络的所有主机,IPv4的本地广播地址为“255.255.255.255”,路由器不会转发此广播" + "\n- 多播(组播): 一台主机向指定的一组主机发送数据报包. IP网络的组播一般通过组播IP地址来实现。组播IP地址就是D类IP地址,即224.0.0.0至239.255.255.255之间的IP地址" + "\n- https://www.cnblogs.com/xujian2014/p/5072215.html" + "\n- 本机ip:${KNetwork.getIPAddress()}") addView("发送广播获取服务器IP", View.OnClickListener { GlobalScope.launch(IO) { val host = "255.255.255.255" //广播地址 val port = 9999 //广播的目的端口 // port 是监听接口,接收数据时用到,发送数据时可以不放接口,如:val ds = DatagramSocket() val ds = DatagramSocket(port) try { // 发送部分 val adds: InetAddress = InetAddress.getByName(host) val message = Datagram(0, "KUtils请求服务").toByteArray() //用于发送的字符串 val dp = DatagramPacket(message, message.size, adds, port) ds.send(dp) // 接收部分 val receiveBytes = ByteArray(512) val receivePacket = DatagramPacket(receiveBytes, receiveBytes.size) ds.soTimeout = 3000 // 3秒超时 // 需要排除接收到自己发送的数据 var data: Datagram? val curTime = System.currentTimeMillis() do { ds.receive(receivePacket) data = Datagram.parse(receivePacket) } while (data?.type != 1 && System.currentTimeMillis() - 3000 < curTime) withContext(Main) { mActivity.showSnack(data.toString()) } } catch (e: Exception) { e.printStackTrace() } finally { ds.close() } } }) addView("组播得IP", View.OnClickListener { GlobalScope.launch(IO) { val maxLength = 1024 val port = 8888 try { val ms = MulticastSocket(port) ms.loopbackMode = false // 设置本MulticastSocket发送的数据报会被回送到自身 val address = InetAddress.getByName("239.0.0.255") val message = Datagram(0, "KUtils请求服务").toByteArray() ms.send(DatagramPacket(message, message.size, address, port)) val dp = DatagramPacket(ByteArray(maxLength), maxLength) ms.timeToLive = 32 // ms.soTimeout = 3000 //等待时间 ms.joinGroup(address)// Mac上不行,似乎是ipv4、ipv6的问题, 需要用下面那个方法,不过在安卓上目前可用该方法 // ms.joinGroup(InetSocketAddress(address, port), // NetworkInterface.getByInetAddress(address)) // ms.receive(dp) // 需要排除接收到自己发送的数据 var data: Datagram? val curTime = System.currentTimeMillis() do { ms.receive(dp) data = Datagram.parse(dp) } while (data?.type != 1 && System.currentTimeMillis() - 3000 < curTime) withContext(Main) { mActivity.showSnack("收到数据包(${dp.address?.hostAddress}:${dp.port}):$data") } ms.close() } catch (e: Exception) { e.printStackTrace() } } }) val serverSocketPortKey = "AHSocketTest_serverSocketPortKey" var serverSocketPort = KUtil.getSharedPreferencesIntValue(serverSocketPortKey, 9999) addView("ServerSocket", View.OnClickListener { activity.getInput("设置监听端口", serverSocketPort.toString(), EditorInfo.TYPE_CLASS_NUMBER) { if (it.isBlank()) return@getInput activity.showSnack("不能为空") serverSocketPort = it.toString().toInt() KUtil.putSharedPreferencesIntValue(serverSocketPortKey, serverSocketPort) SocketFactory.createServiceSocket(serverSocketPort) } }) val socket2IpKey = "AHSocketTest_socket2IpKey" val socket2PortKey = "AHSocketTest_socket2PortKey" var socket2Ip = KUtil.getSharedPreferencesStringValue(socket2IpKey, "192.168.0.145") var socket2Port = KUtil.getSharedPreferencesIntValue(socket2PortKey, 9999) addView("Socket", View.OnClickListener { GlobalScope.launch(Dispatchers.Main){ var ip = "" suspendCoroutine<Boolean> { continuation -> activity.getInput("输入服务器IP", socket2Ip, onCancel = { continuation.resume(false) }) { if (it.isBlank()) { activity.showSnack("不能为空") } else { ip = it.toString() } continuation.resume(false) } } if (ip.isBlank()) return@launch socket2Ip = ip KUtil.putSharedPreferencesStringValue(socket2IpKey, socket2Ip) var port = 0 suspendCoroutine<Unit> {continuation -> activity.getInput("输入服务器端口", socket2Port.toString(), EditorInfo.TYPE_CLASS_NUMBER, { continuation.resume(Unit) }) { if (it.isBlank()) { activity.showSnack("不能为空") } else { port = it.toString().toInt() } continuation.resume(Unit) } } if (port == 0) return@launch socket2Port = port KUtil.putSharedPreferencesIntValue(socket2PortKey, socket2Port) var messageType = 0 suspendCoroutine<Unit> {continuation -> activity.showBottomSheetDialog(arrayOf("text", "image"), {continuation.resume(Unit)}) { index, _ -> messageType = index + 1 continuation.resume(Unit) } } when(messageType) { 1 -> { var text = "" suspendCoroutine<Unit> { continuation -> activity.getInput("发送内容", "你若安好,便是晴天。", onCancel = {continuation.resume(Unit)}) { if (it.isBlank()) activity.showSnack("不能为空") text = it.toString() continuation.resume(Unit) } } if (text.isBlank()) return@launch withContext(Dispatchers.IO) { SocketFactory.sendSocketMessage(socket2Ip, socket2Port, SocketFactory.DataType.String, text) } } 2 -> { var uri: Uri? = null suspendCoroutine<Unit> { continuation -> activity.randomPhoneImage({ activity.showSnack(it) continuation.resume(Unit) }) { uri = it continuation.resume(Unit) } } withContext(Dispatchers.IO) { uri?.apply { SocketFactory.sendSocketMessage(socket2Ip, socket2Port, SocketFactory.DataType.Image, this) } } } } } }) RxBus.register<Message>(activity, SocketFactory.newAccept) { GlobalScope.launch(Dispatchers.Main) { when(it.dataType) { SocketFactory.DataType.String -> activity.showDialog("收到来自${it.fromIp}的消息:${it.data}") SocketFactory.DataType.Image -> activity.showImageDialog((it.data as File).absolutePath) SocketFactory.DataType.File -> activity.showDialog("收到来自${it.fromIp}的文件消息,文件路径${it.data}") } } } } class Datagram( val type: Int = 0,// 0:发送的请求,1:返回的结果, -1:不明 val text: String = ""// 请求内容 ) { companion object { fun parse(dp: DatagramPacket): Datagram { return parse(dp.data, dp.length) } fun parse(data: ByteArray, length: Int): Datagram { val content = String(data, 0, length) var type: Int = -1 var text: String = "" if (content.isNotEmpty()) { type = content.substring(0, 1).toIntOrNull() ?: -1 if (type == -1) { text = content } else { if (content.length > 1) { text = content.substring(1) } } } text.toByteArray() return Datagram(type, text) } } override fun toString(): String { return "${type}${text}" } fun toByteArray(): ByteArray { return toString().toByteArray() } } }
0
null
5
5
fc73477823f89e741588862e243a46e45279fdf3
11,814
KUtils
Apache License 2.0
tempest2-testing/src/main/kotlin/app/cash/tempest2/testing/TestTable.kt
cashapp
270,829,467
false
{"Kotlin": 487620, "Shell": 2116, "Java": 2108}
/* * Copyright 2021 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.tempest2.testing import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest import kotlin.reflect.KClass /** * Use this with [TestDynamoDbClient] to configure your DynamoDB * tables for each test execution. * * Use [configureTable] to customize the table creation request for testing, such as to configure * the secondary indexes required by `ProjectionType.ALL`. */ data class TestTable internal constructor( val tableName: String, val tableClass: KClass<*>, val configureTable: (CreateTableEnhancedRequest) -> CreateTableEnhancedRequest = { it } ) { companion object { inline fun <reified T> create( tableName: String, noinline configureTable: (CreateTableEnhancedRequest) -> CreateTableEnhancedRequest = { it } ) = create(tableName, T::class, configureTable) fun create( tableName: String, tableClass: KClass<*>, configureTable: (CreateTableEnhancedRequest) -> CreateTableEnhancedRequest = { it } ) = TestTable(tableName, tableClass, configureTable) @JvmStatic @JvmOverloads fun create( tableName: String, tableClass: Class<*>, configureTable: (CreateTableEnhancedRequest) -> CreateTableEnhancedRequest = { it } ) = create(tableName, tableClass.kotlin, configureTable) } }
17
Kotlin
33
83
8430cf3ad4be5f1e6786dd927bcc494fe0ea7baf
1,907
tempest
Apache License 2.0
agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/test/java/com/android/build/gradle/internal/tasks/GenerateLibraryProguardRulesTaskTest.kt
jomof
502,039,754
false
{"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277}
package com.android.build.gradle.internal.tasks import com.android.build.gradle.internal.fixtures.FakeGradleProperty import com.android.build.gradle.internal.fixtures.FakeNoOpAnalyticsService import com.android.build.gradle.internal.fixtures.FakeObjectFactory import com.android.build.gradle.internal.profile.AnalyticsService import com.android.builder.files.SerializableChange import com.android.ide.common.resources.FileStatus import com.android.utils.FileUtils import com.google.common.truth.Truth.assertThat import org.gradle.api.provider.Property import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.File class GenerateLibraryProguardRulesTaskTest { @get:Rule val temporaryFolder = TemporaryFolder() /** * Test to verify only added layout resources (no changed or removed) can trigger incremental * task run. */ @Test fun testCanBeProcessedIncrementally_layoutFiles() { val layoutsFolder = temporaryFolder.newFolder("layout") val layoutFile = File(layoutsFolder, "test_activity.xml") val newLayoutFile = SerializableChange( layoutFile, FileStatus.NEW, layoutFile.absolutePath) val changedLayoutFile = SerializableChange( layoutFile, FileStatus.CHANGED, layoutFile.absolutePath) val removedLayoutFile = SerializableChange( layoutFile, FileStatus.REMOVED, layoutFile.absolutePath) assertThat(canResourcesBeProcessedIncrementally(newLayoutFile)).isTrue() assertThat(canResourcesBeProcessedIncrementally(changedLayoutFile)).isFalse() assertThat(canResourcesBeProcessedIncrementally(removedLayoutFile)).isFalse() } /** * Test to verify that adding, changing or removing non-layout resources allows for incremental * task run. */ @Test fun testCanBeProcessedIncrementally_nonLayoutFiles() { val valuesFolder = temporaryFolder.newFolder("values") val stringsFile = File(valuesFolder, "strings.xml") val newStringsFile = SerializableChange( stringsFile, FileStatus.NEW, stringsFile.absolutePath) val changedStringsFile = SerializableChange( stringsFile, FileStatus.CHANGED, stringsFile.absolutePath) val removedStringsFile = SerializableChange( stringsFile, FileStatus.REMOVED, stringsFile.absolutePath) assertThat(canResourcesBeProcessedIncrementally(newStringsFile)).isTrue() assertThat(canResourcesBeProcessedIncrementally(changedStringsFile)).isTrue() assertThat(canResourcesBeProcessedIncrementally(removedStringsFile)).isTrue() } /** * Test to verify that adding a new layout file will only add the new unique keep classes to * the Proguard keep classes file ("aapt_rules.txt"). This * assumes that the other conditions are set for an incremental run. */ @Test fun testRunIncrementalTask_appendsNewLayoutClasspaths() { val parentFolder = temporaryFolder.newFolder("parent") val resourcesFolder = File(parentFolder, "res") val layoutFolder = File(resourcesFolder, "layout") val previousProguardOutput = File(parentFolder, "aapt_rules.txt") val addedLayout = File(layoutFolder, "main_activity.xml") val changedResources = listOf( SerializableChange(addedLayout, FileStatus.NEW, addedLayout.absolutePath) ) FileUtils.createFile(previousProguardOutput, """# Generated by the gradle plugin |-keep class android.support.v7.widget.Toolbar { <init>(...); } |-keep class com.google.android.material.chip.Chip { <init>(...); }""".trimMargin() ) FileUtils.createFile(addedLayout, """<root> <org.sampleapp.android.Instrument>txt</org.sampleapp.android.Instrument> <com.google.android.material.chip.Chip>txt</com.google.android.material.chip.Chip> </root>""" ) val params = object : GenerateLibraryProguardRulesTask.GenerateProguardRulesWorkAction.Params() { override val manifestFile = FakeObjectFactory.factory.fileProperty().fileValue( File(parentFolder, "AndroidManifiest.xml")) override val proguardOutputFile = FakeObjectFactory.factory.fileProperty().fileValue(previousProguardOutput) override val inputResourcesDir = FakeObjectFactory.factory.directoryProperty().fileValue(resourcesFolder) override val changedResources = FakeObjectFactory.factory.listProperty( SerializableChange::class.java).value(changedResources) override val incremental = FakeGradleProperty(true) override val projectName = FakeGradleProperty("project") override val taskOwner = FakeGradleProperty("taskOwner") override val workerKey = FakeGradleProperty("workerKey") override val analyticsService: Property<AnalyticsService> = FakeGradleProperty( FakeNoOpAnalyticsService() ) } runIncrementalTask(params) assertThat(params.proguardOutputFile.get().asFile.readLines()).containsNoDuplicates() assertThat(params.proguardOutputFile.get().asFile.readLines()).containsExactly( "# Generated by the gradle plugin", "-keep class org.sampleapp.android.Instrument { <init>(...); }", "-keep class com.google.android.material.chip.Chip { <init>(...); }", "-keep class android.support.v7.widget.Toolbar { <init>(...); }" ) } /** * Test to verify that adding a new layout file will only add the new unique keep classes to * the Proguard keep classes file ("aapt_rules.txt"). This assumes that the other conditions * are set for an incremental run. */ @Test fun testRunFullTask_createsExpectedKeepRules() { val parentFolder = temporaryFolder.newFolder("parent") val resourcesFolder = File(parentFolder, "res") val layoutFolder = File(resourcesFolder, "layout") val previousProguardOutput = File(parentFolder, "aapt_rules.txt") val manifestFile = File(parentFolder, "AndroidManifiest.xml") val layoutFile = File(layoutFolder, "main_activity.xml") FileUtils.createFile(manifestFile, """<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.google.android.apps.santatracker" xmlns:tools="http://schemas.android.com/tools"> <uses-feature android:name="android.hardware.screen.landscape" android:required="false"/> <application android:allowBackup="false" android:icon="@mipmap/ic_launcher_santa" android:label="@string/app_name_santa" android:name=".SantaApplication" tools:replace="android:allowBackup, icon, label" android:banner="@drawable/santatracker_logo_banner" android:usesCleartextTraffic="false" android:largeHeap="true" android:theme="@style/SantaTheme"> </application> </manifest>""") FileUtils.createFile(layoutFile, """<root> <org.sampleapp.android.Instrument>txt</org.sampleapp.android.Instrument> <com.google.android.material.chip.Chip>txt</com.google.android.material.chip.Chip> </root>""" ) val params = object : GenerateLibraryProguardRulesTask.GenerateProguardRulesWorkAction.Params() { override val manifestFile = FakeObjectFactory.factory.fileProperty().fileValue(manifestFile) override val proguardOutputFile = FakeObjectFactory.factory.fileProperty().fileValue(previousProguardOutput) override val inputResourcesDir = FakeObjectFactory.factory.directoryProperty().fileValue(resourcesFolder) override val changedResources = FakeObjectFactory.factory.listProperty(SerializableChange::class.java) override val incremental = FakeGradleProperty(false) override val projectName = FakeGradleProperty("project") override val taskOwner = FakeGradleProperty("taskOwner") override val workerKey = FakeGradleProperty("workerKey") override val analyticsService: Property<AnalyticsService> = FakeGradleProperty(FakeNoOpAnalyticsService()) } runFullTask(params) assertThat(params.proguardOutputFile.get().asFile.readLines()).containsNoDuplicates() assertThat(params.proguardOutputFile.get().asFile.readLines()).containsExactly( "# Generated by the gradle plugin", "-keep class com.google.android.apps.santatracker.SantaApplication { <init>(...); }", "-keep class org.sampleapp.android.Instrument { <init>(...); }", "-keep class com.google.android.material.chip.Chip { <init>(...); }" ) } }
1
Java
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
9,341
CppBuildCacheWorkInProgress
Apache License 2.0
app/src/test/java/com/movietrivia/filmfacts/model/SessionDataSourceTest.kt
jlynchsd
631,418,923
false
{"Kotlin": 524037}
package com.movietrivia.filmfacts.model import android.content.SharedPreferences import io.mockk.clearAllMocks import io.mockk.every import io.mockk.mockk import io.mockk.mockkObject import io.mockk.verify import org.junit.After import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class SessionDataSourceTest { private lateinit var sharedPreferences: SharedPreferences private lateinit var datsSource: SessionDataSource @Before fun setup() { mockkObject(EncryptedSharedPreferencesFactory) sharedPreferences = mockk(relaxed = true) every { EncryptedSharedPreferencesFactory.createSharedPrefs(any(), any()) } returns sharedPreferences datsSource = SessionDataSource(mockk()) } @After fun teardown() { clearAllMocks() } @Test fun `When initially created has no session`() { every { sharedPreferences.getString(any(), any()) } returns null Assert.assertNull(SessionDataSource(mockk()).sessionId.value) } @Test fun `When created with existing session loads session`() { val session = "foo" every { sharedPreferences.getString(any(), any()) } returns session val newDataSource = SessionDataSource(mockk()) Assert.assertEquals(session, newDataSource.sessionId.value) } @Test fun `When setting a session updates flow and shared preferences`() { val session = "foo" datsSource.setSessionId(session) Assert.assertEquals(session, datsSource.sessionId.value) verify(exactly = 1) { sharedPreferences.edit() } } @Test fun `When clearing a session updates flow and shared preferences`() { val session = "foo" datsSource.setSessionId(session) Assert.assertEquals(session, datsSource.sessionId.value) datsSource.clearSessionId() Assert.assertNull(datsSource.sessionId.value) verify(exactly = 2) { sharedPreferences.edit() } } }
0
Kotlin
0
0
9a6c9ae5bc2f7a743c9399a64d0c9edf5c7e0d84
2,171
FilmFacts
Apache License 2.0
app/src/main/java/com/safeboda/ui/scroller/PaginatedScrollListener.kt
jumaallan
313,547,738
false
null
/* * Copyright 2020 Safeboda * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.safeboda.ui.scroller import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.OnScrollListener import com.safeboda.core.network.ApiRequestStatus.* import timber.log.Timber class PaginatedScrollListener(private val viewModel: com.safeboda.ui.interfaces.PaginatedViewModel) : OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val layoutManager = recyclerView.layoutManager if (layoutManager is LinearLayoutManager) { val visibleItemCount = layoutManager.childCount val totalItemCount = layoutManager.itemCount val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition() when { firstVisibleItemPosition >= 0 && viewModel.requestStatus == SUCCESS && viewModel.currentPage.hasNextPage && visibleItemCount * 2 + firstVisibleItemPosition >= totalItemCount // we are within one screen-size of the end of the list -> { Timber.d("Triggering page ${viewModel.currentPage.endCursor}") viewModel.loadNextPage() } } } } }
2
Kotlin
14
21
ec11c0ce526d2a790cb3b6fdd90f4ed56e9bfff8
1,903
safeboda
The Unlicense
argus-apm-gradle/src/main/kotlin/com/argusapm/gradle/internal/PluginConfig.kt
Qihoo360
159,286,067
false
null
package com.argusapm.gradle.internal import com.android.build.gradle.* import com.argusapm.gradle.ArgusApmConfig import com.argusapm.gradle.internal.utils.getVariants import org.gradle.api.GradleException import org.gradle.api.Project import org.gradle.api.tasks.compile.JavaCompile import java.io.File class PluginConfig { companion object { lateinit var project: Project lateinit var encoding: String lateinit var bootClassPath: String lateinit var sourceCompatibility: String lateinit var targetCompatibility: String fun init(project: Project) { val hasAppPlugin = project.plugins.hasPlugin(AppPlugin::class.java) val hasLibPlugin = project.plugins.hasPlugin(LibraryPlugin::class.java) if (!hasAppPlugin && !hasLibPlugin) { throw GradleException("argusapm: The 'com.android.application' or 'com.android.library' plugin is required.") } Companion.project = project getVariants(project).all { variant -> val javaCompile = variant.javaCompile as JavaCompile encoding = javaCompile.options.encoding bootClassPath = getBootClasspath().joinToString(File.pathSeparator) sourceCompatibility = javaCompile.sourceCompatibility targetCompatibility = javaCompile.targetCompatibility } } private fun getBootClasspath(): List<File> { val hasAppPlugin = project.plugins.hasPlugin(AppPlugin::class.java) val plugin = project.plugins.getPlugin(if (hasAppPlugin) { AppPlugin::class.java } else { LibraryPlugin::class.java }) val extAndroid = if (hasAppPlugin) { project.extensions.getByType(AppExtension::class.java) } else { project.extensions.getByType(LibraryExtension::class.java) } return extAndroid.bootClasspath ?: plugin::class.java.getMethod("getRuntimeJarList").invoke(plugin) as List<File> } fun argusApmConfig(): ArgusApmConfig { return project.extensions.getByType(ArgusApmConfig::class.java) } } }
31
Java
412
2,603
75ead19ca98a8a1f776688e9df5b572f20c80b12
2,273
ArgusAPM
Apache License 2.0
hubdle-gradle-plugin/main/kotlin/com/javiersc/hubdle/project/extensions/config/project/HubdleProjectExtension.kt
JavierSegoviaCordoba
348,863,451
false
{"Kotlin": 501858, "Shell": 21101, "Perl": 4726, "CSS": 195}
package com.javiersc.hubdle.project.extensions.config.project import com.javiersc.hubdle.project.extensions.HubdleDslMarker import com.javiersc.hubdle.project.extensions._internal.getHubdleExtension import com.javiersc.hubdle.project.extensions.apis.HubdleConfigurableExtension import com.javiersc.hubdle.project.extensions.apis.HubdleEnableableExtension import com.javiersc.hubdle.project.extensions.config.hubdleConfig import com.javiersc.hubdle.project.extensions.kotlin.hubdleKotlinAny import com.javiersc.hubdle.project.extensions.shared.features.tasks.GenerateAdditionalDataTask import com.javiersc.hubdle.project.extensions.shared.features.tasks.GenerateProjectDataTask import com.javiersc.kotlin.stdlib.isNotNullNorBlank import javax.inject.Inject import org.gradle.api.Project import org.gradle.api.provider.Property @HubdleDslMarker public open class HubdleProjectExtension @Inject constructor(project: Project) : HubdleConfigurableExtension(project) { override val isEnabled: Property<Boolean> = property { false } override val oneOfExtensions: Set<HubdleEnableableExtension> get() = hubdleKotlinAny override val requiredExtensions: Set<HubdleEnableableExtension> get() = setOf(hubdleConfig) public val projectData: Property<Boolean> = property { true } @HubdleDslMarker public fun generateProjectData(value: Boolean) { projectData.set(value) } public val additionalData: Property<String?> = property { null } @HubdleDslMarker public fun generateAdditionalData(data: AdditionalDataBuilder.() -> Unit) { additionalData.set( provider { val additionalData = AdditionalDataBuilder() additionalData.data() additionalData.text } ) } override fun Project.defaultConfiguration() { lazyConfigurable { GenerateProjectDataTask.register(project).configure { task -> task.enabled = isFullEnabled.get() && projectData.get() } GenerateAdditionalDataTask.register(project, additionalData).configure { task -> task.enabled = isFullEnabled.get() && additionalData.orNull.isNotNullNorBlank() } } } public class AdditionalDataBuilder { private var _text: MutableList<String> = mutableListOf() internal val text: String get() = _text.joinToString("\n") public fun text(text: String) { this._text.addAll(text.split("\n")) } public fun const(name: String, type: String, value: String) { _text.add("public const val $name: $type = \"$value\"") } } } internal val HubdleEnableableExtension.hubdleProjectConfig: HubdleProjectExtension get() = getHubdleExtension()
12
Kotlin
10
26
0f7c0b7fb2d1fd15a2cdaeee2ec1cacea522cca2
2,825
hubdle
Apache License 2.0
app/src/main/java/dev/seabat/android/hellobottomnavi/di/DataSourceModuleProvider.kt
seabat
614,867,401
false
{"Kotlin": 67436}
package dev.seabat.android.hellobottomnavi.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import dev.seabat.android.hellobottomnavi.data.datasource.github.GithubApi import dev.seabat.android.hellobottomnavi.data.datasource.github.GithubApiService import dev.seabat.android.hellobottomnavi.data.datasource.qiita.QiitaApi import dev.seabat.android.hellobottomnavi.data.datasource.qiita.QiitaApiService @Module @InstallIn(SingletonComponent::class) object DataSourceModuleProvider { @Provides fun provideGithubApiEndpoint(): GithubApiService = GithubApi.githubApiService @Provides fun provideQiitaApiEndpoint(): QiitaApiService = QiitaApi.qiitaApiService }
0
Kotlin
0
0
b4c5afa9609ef0e07e36593b8545d9ab093c33ea
751
hello-bottom-navigation
Apache License 2.0
sdk/src/main/kotlin/io/rover/sdk/ui/blocks/poll/text/ViewTextPoll.kt
RoverPlatform
55,724,334
false
null
package io.rover.sdk.ui.blocks.poll.text import android.graphics.Typeface import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import io.rover.sdk.data.domain.TextPoll import io.rover.sdk.data.mapToFont import io.rover.sdk.logging.log import io.rover.sdk.platform.addView import io.rover.sdk.platform.optionView import io.rover.sdk.platform.setupLayoutParams import io.rover.sdk.platform.textView import io.rover.sdk.streams.androidLifecycleDispose import io.rover.sdk.streams.subscribe import io.rover.sdk.ui.asAndroidColor import io.rover.sdk.ui.blocks.concerns.background.BackgroundViewModelInterface import io.rover.sdk.ui.blocks.concerns.background.createBackgroundDrawable import io.rover.sdk.ui.blocks.poll.VotingState import io.rover.sdk.ui.concerns.MeasuredBindableView import io.rover.sdk.ui.concerns.MeasuredSize import io.rover.sdk.ui.concerns.ViewModelBinding internal class ViewTextPoll(override val view: LinearLayout) : ViewTextPollInterface { private val questionView = view.textView { setupLayoutParams( width = ViewGroup.LayoutParams.MATCH_PARENT, height = ViewGroup.LayoutParams.WRAP_CONTENT ) } private var optionViews = mapOf<String, TextOptionView>() init { view.addView { questionView } view.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO } override var viewModelBinding: MeasuredBindableView.Binding<TextPollViewModelInterface>? by ViewModelBinding(view, cancellationBlock = { viewModelBinding?.viewModel?.cancel() }) { binding, subscriptionCallback -> binding?.viewModel?.let { viewModel -> bindQuestion(viewModel.textPoll, viewModel.textPoll.options.size) if (optionViews.isNotEmpty()) { optionViews.forEach { view.removeView(it.value) } } setupOptionViews(viewModel) log.d("poll view bound") viewModel.votingState.subscribe({ votingState : VotingState -> when (votingState) { is VotingState.InitialState -> { setPollNotWaiting() } is VotingState.ResultsSeeded -> { setPollNotWaiting() } is VotingState.SubmittingAnswer -> { setVoteResultsReceived(votingState) setPollNotWaiting() } is VotingState.RefreshingResults -> { if (votingState.shouldTransition) setVoteResultUpdate(votingState) setPollNotWaiting() } is VotingState.PollAnswered -> setPollAnsweredWaiting() } }, { e -> log.e("${e.message}") }, { subscriptionCallback(it) }) viewModel.bindInteractor(viewModel.id, optionViews.keys.toList()) } } private fun setPollAnsweredWaiting() { view.alpha = 0.5f optionViews.forEach { it.value.setOnClickListener(null) } } private fun setPollNotWaiting() { view.alpha = 1f } private fun setupOptionViews(viewModel: TextPollViewModelInterface) { var indexForAccessibility = 1 optionViews = createOptionViews(viewModel.textPoll) startListeningForOptionImageUpdates(viewModel.optionBackgroundViewModel, optionViews) optionViews.forEach { (optionId, optionView) -> view.addView(optionView) optionView.setContentDescription(indexForAccessibility) optionView.setOnClickListener { viewModelBinding?.viewModel?.castVote(optionId, viewModel.textPoll.options.map { it.id }) } indexForAccessibility++ } informOptionBackgroundAboutSize(viewModel) } private fun bindQuestion(textPoll: TextPoll, numberOfOptions: Int) { questionView.run { text = textPoll.question.rawValue contentDescription = "Poll with $numberOfOptions options: ${textPoll.question.rawValue}" gravity = textPoll.question.alignment.convertToGravity() textSize = textPoll.question.font.size.toFloat() setTextColor(textPoll.question.color.asAndroidColor()) val font = textPoll.question.font.weight.mapToFont() typeface = Typeface.create(font.fontFamily, font.fontStyle) } } private fun createOptionViews(textPoll: TextPoll): Map<String, TextOptionView> { return textPoll.options.associate { option -> option.id to view.optionView { initializeOptionViewLayout(option) bindOptionView(option) } } } private fun informOptionBackgroundAboutSize(viewModel: TextPollViewModelInterface) { viewModelBinding?.measuredSize?.width?.let { measuredWidth -> val optionStyleHeight = viewModel.textPoll.options.first().height.toFloat() val measuredSize = MeasuredSize( measuredWidth, optionStyleHeight, view.resources.displayMetrics.density ) viewModel.optionBackgroundViewModel.informDimensions(measuredSize) } } private fun setVoteResultUpdate(votingUpdate: VotingState.RefreshingResults) { val maxVotingValue = votingUpdate.optionResults.results.map { it.value }.max() ?: 0 votingUpdate.optionResults.results.forEach { (id, votingShare) -> val option = optionViews[id] option?.setOnClickListener(null) val isSelectedOption = id == votingUpdate.selectedOption viewModelBinding?.viewModel?.let { if (votingUpdate.shouldTransition) { if (votingUpdate.shouldAnimate) { option?.updateResults(votingShare) } else { option?.goToResultsState(votingShare, isSelectedOption, it.textPoll.options.find { it.id == id }!!, false, viewModelBinding?.measuredSize?.width, maxVotingValue) } } } } } private fun setVoteResultsReceived(votingResults: VotingState.SubmittingAnswer) { val maxVotingValue = votingResults.optionResults.results.map { it.value }.max() ?: 0 votingResults.optionResults.results.forEach { (id, votingShare) -> val option = optionViews[id] option?.setOnClickListener(null) val isSelectedOption = id == votingResults.selectedOption viewModelBinding?.viewModel?.let { option?.goToResultsState(votingShare, isSelectedOption, it.textPoll.options.find { it.id == id }!!, votingResults.shouldAnimate, viewModelBinding?.measuredSize?.width, maxVotingValue) } } } private fun startListeningForOptionImageUpdates( viewModel: BackgroundViewModelInterface, textOptionViews: Map<String, TextOptionView> ) { viewModel.backgroundUpdates.androidLifecycleDispose(view) .subscribe { (bitmap, fadeIn, backgroundImageConfiguration) -> textOptionViews.forEach { val backgroundDrawable = bitmap.createBackgroundDrawable( view, viewModel.backgroundColor, fadeIn, backgroundImageConfiguration ) it.value.backgroundImage = backgroundDrawable } } } } internal interface ViewTextPollInterface : MeasuredBindableView<TextPollViewModelInterface>
16
Java
13
6
1b6e627a1e4b3651d0cc9f6e78f995ed9e4a821a
7,767
rover-android
Apache License 2.0
OnlinePK-Android/lib-live-room-service/src/main/java/com/netease/yunxin/lib_live_room_service/delegate/LiveRoomDelegate.kt
netease-george
377,830,443
true
{"Objective-C": 1325069, "Kotlin": 611041, "Java": 270376, "Swift": 124836, "C": 6974, "Python": 2874, "Ruby": 797}
/* * Copyright (c) 2021 NetEase, Inc. All rights reserved. * Use of this source code is governed by a MIT license that can be found in the LICENSE file */ package com.netease.yunxin.lib_live_room_service.delegate import com.netease.yunxin.lib_live_room_service.bean.LiveUser import com.netease.yunxin.lib_live_room_service.chatroom.RewardMsg import com.netease.yunxin.lib_live_room_service.chatroom.TextWithRoleAttachment import com.netease.yunxin.lib_live_room_service.param.ErrorInfo interface LiveRoomDelegate { /** * error occur when live,if serious stop live and exit */ fun onError(errorInfo: ErrorInfo) /** * room destroy,audience exit room */ fun onRoomDestroy() /** * user count in room changed */ fun onUserCountChange(userCount: Int) /** * receive text message */ fun onRecvRoomTextMsg(nickname: String, attachment: TextWithRoleAttachment) /** * user enter live room */ fun onUserEntered(nickname: String) /** * user left live room */ fun onUserLeft(nickname: String) /** * kicked out by login in other set */ fun onKickedOut() /** * anchor leave chatRoom */ fun onAnchorLeave() /** * audience reward a gift */ fun onUserReward(rewardInfo: RewardMsg) /** * audio effect callback */ fun onAudioEffectFinished(effectId: Int) /** * audio mixing callback */ fun onAudioMixingFinished() /** * audience change * ten audience will return in live room */ fun onAudienceChange(infoList: MutableList<LiveUser>) }
0
Objective-C
0
0
9ba2e45734d24bcc287a08288e25b6d27856744d
1,654
OnlinePK
MIT License
PRACTICE_JETPACK/app/src/main/java/nlab/practice/jetpack/ui/home/HomeViewModel.kt
skaengus2012
153,380,376
false
null
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nlab.practice.jetpack.ui.home import androidx.databinding.ObservableArrayList import nlab.practice.jetpack.repository.TestMenuRepository import nlab.practice.jetpack.repository.model.TestMenu import nlab.practice.jetpack.ui.main.ContainerFragmentCallback import nlab.practice.jetpack.util.nav.* import nlab.practice.jetpack.util.recyclerview.RecyclerViewConfig import nlab.practice.jetpack.util.recyclerview.RecyclerViewUsecase import javax.inject.Inject /** * HomeFragment 에 대한 ViewModel * * @author Doohyun */ class HomeViewModel @Inject constructor( containerFragmentCallback: ContainerFragmentCallback, homeItemDecoration: HomeItemDecoration, private val homeHeaderViewModel: HomeHeaderViewModel, private val activityNavUsecase: ActivityNavUsecase, private val fragmentNavUsecase: FragmentNavUsecase, private val testMenuRepository: TestMenuRepository, private val recyclerViewUsecase: RecyclerViewUsecase ) { val headers = ObservableArrayList<HomeHeaderViewModel>() val items = ObservableArrayList<HomeItemViewModel>() val recyclerViewConfig = RecyclerViewConfig().apply { itemDecorations += homeItemDecoration } init { containerFragmentCallback.onBottomNavReselected { scrollToZeroIfEmptyChild() } initializeItems() } private fun scrollToZeroIfEmptyChild(): Boolean { val isNeedScrollToZero = !fragmentNavUsecase.hasChild() if (isNeedScrollToZero) { recyclerViewUsecase.smoothScrollToPosition(0) } return isNeedScrollToZero } private fun initializeItems() { headers.add(homeHeaderViewModel) items.addAll(createItems()) } private fun createItems(): List<HomeItemViewModel> = listOf( createAnkoFirstViewMenu(), createPagingTestMenu(), createListAdapterMenu(), createDragDropMenu(), createCollapsingToolbarExMenu(), createSlideUpPanelExMenu(), createCenterScrollExMenu() ) private fun createViewModel(testMenu: TestMenu, onClickAction: () -> Unit): HomeItemViewModel { return HomeItemViewModel(testMenu, onClickAction) } private fun createAnkoFirstViewMenu() = createViewModel(testMenuRepository.getAnkoFirstViewMenu()) { activityNavUsecase.navAnko() } private fun createPagingTestMenu() = createViewModel(testMenuRepository.getPagingTestMenu()) { fragmentNavUsecase.navCountablePaging() } private fun createListAdapterMenu() = createViewModel(testMenuRepository.getListAdapterMenu()) { fragmentNavUsecase.navListAdapterExample() } private fun createDragDropMenu() = createViewModel(testMenuRepository.getDragDropMenu()) { fragmentNavUsecase.navDragDrop() } private fun createCollapsingToolbarExMenu() = createViewModel(testMenuRepository.getCollapsingToolbarExMenu()) { activityNavUsecase.navCollapsingToolbar() } private fun createSlideUpPanelExMenu() = createViewModel(testMenuRepository.getSlideUpPanelExMenus()) { activityNavUsecase.navSlide() } private fun createCenterScrollExMenu() = createViewModel(testMenuRepository.getCenterScrollRecyclerView()) { fragmentNavUsecase.navCenterScrolling() } }
2
Kotlin
0
0
6c742e0888f5e01e0d7f0f1dd3d57707c62716b0
3,904
Practice-Jetpack
Apache License 2.0
NavigationComponentExample/app/src/main/java/com/example/navigationcomponentexample/FragmentTwo.kt
velmurugan-murugesan
159,637,287
false
null
package com.example.navigationcomponentexample import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.findNavController import androidx.navigation.fragment.navArgs import kotlinx.android.synthetic.main.fragment_2.* class FragmentTwo : Fragment() { val args : FragmentTwoArgs by navArgs() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_2, container, false) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) Log.d("TAG", "onViewCreated:${args.username}") buttonFragment2.setOnClickListener { it.findNavController().navigate(R.id.action_fragmentTwo_to_fragmentThree) } } }
1
Java
1
6
8c2e8b2a0e8f33b5e8c0ea66890756e02577fa54
1,029
AndriodSamples
Apache License 2.0
8vim/src/test/kotlin/inc/flide/vim8/utils/GeometricUtilitiesSpec.kt
8VIM
72,917,629
false
{"Kotlin": 269386, "Java": 59286, "Ruby": 4678, "Shell": 55}
package inc.flide.vim8.utils import android.graphics.PointF import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe import io.mockk.mockk class GeometricUtilitiesSpec : FunSpec({ fun mockPointF(x: Float, y: Float): PointF { val point = mockk<PointF>() point.x = x point.y = y return point } test("square distance between two points") { val a = mockPointF(2f, 2f) val b = mockPointF(0f, 0f) val distance = GeometricUtilities.getSquaredDistanceBetweenPoints(a, b) distance shouldBe 8 } })
63
Kotlin
58
389
d13c901396710c38bb4d5f5dbe6856664ae1e76b
590
8VIM
Apache License 2.0
im-organization/organization-domain/src/commonMain/kotlin/city.smartb.im.organization.domain/OrganizationQueryFeatures.kt
smartbcity
651,445,390
false
null
package city.smartb.im.organization.domain import city.smartb.im.organization.domain.features.query.OrganizationGetFromInseeFunction import city.smartb.im.organization.domain.features.query.OrganizationGetFunction import city.smartb.im.organization.domain.features.query.OrganizationPageFunction import city.smartb.im.organization.domain.features.query.OrganizationRefListFunction import city.smartb.im.organization.domain.model.OrganizationDTO interface OrganizationQueryFeatures<MODEL: OrganizationDTO> { /** * Fetch an Organization by its ID. */ fun organizationGet(): OrganizationGetFunction<MODEL> /** * Fetch an Organization by its siret number from the Insee Sirene API. */ fun organizationGetFromInsee(): OrganizationGetFromInseeFunction /** * Fetch a page of organizations. */ fun organizationPage(): OrganizationPageFunction<MODEL> /** * Fetch all OrganizationRef. */ fun organizationRefList(): OrganizationRefListFunction }
0
Kotlin
0
0
6a727ac998241724d073ac66247496355316f934
1,014
connect-im
Apache License 2.0
app/src/main/java/com/arcadone/cheers/ui/mainFragment/BeerViewModelFactory.kt
ArcaDone
367,069,951
false
{"Kotlin": 46937}
package com.arcadone.cheers.ui.mainFragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.arcadone.cheers.repository.BeerRepository import kotlinx.coroutines.InternalCoroutinesApi // By using viewModels and ViewModelProvider.Factory, // the framework will take care of the lifecycle of the ViewModel. // It will survive configuration changes and even if the Activity is recreated, // you'll always get the right instance of the WordViewModel class. class BeerViewModelFactory(private val repository: BeerRepository) : ViewModelProvider.Factory { @InternalCoroutinesApi override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(MainViewModel::class.java)) { @Suppress("UNCHECKED_CAST") return MainViewModel(repository) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
0
Kotlin
0
2
72081135059cc5e4ea52194f147048c3e5d53fe8
931
PunkAPI
MIT License
app/src/main/java/com/example/frasesmotivadoras/model/JSONRepository.kt
FelipeSPB
272,586,238
false
null
package com.example.frasesmotivadoras.model import android.content.Context import com.google.gson.Gson import com.google.gson.reflect.TypeToken import java.io.IOException import java.io.InputStream class JSONRepository(context: Context) { fun getJSONFile(context: Context, fileName: String): String?{ val json: String try{ json = context.assets.open(fileName).bufferedReader().use{ it.readText()} } catch (ioException: IOException){ ioException.printStackTrace() return null } return json } val jsonFile = getJSONFile(context,"phrase.json") val gson = Gson() var listPhrases = object: TypeToken<ArrayList<Phrase>>() {}.type var phrases : ArrayList<Phrase> = gson.fromJson(jsonFile,listPhrases) }
0
Kotlin
0
0
3dcfe20b4b39c9dd0c6d3c8e1fe15f9c62fb3d90
790
FrasesMotivacionais
Apache License 2.0
core/util/src/main/kotlin/com/flixclusive/core/util/common/dispatcher/di/DispatchersModule.kt
rhenwinch
659,237,375
false
{"Kotlin": 1893733, "Java": 18011}
package com.flixclusive.core.util.common.dispatcher.di import com.flixclusive.core.util.common.dispatcher.AppDispatchers import com.flixclusive.core.util.common.dispatcher.Dispatcher import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers @Module @InstallIn(SingletonComponent::class) object DispatchersModule { @Provides @Dispatcher(AppDispatchers.IO) fun providesIODispatcher(): CoroutineDispatcher = Dispatchers.IO @Provides @Dispatcher(AppDispatchers.Default) fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default }
26
Kotlin
24
319
44517ccc0d77b78cf686f6f6d4464298a05c72fe
717
Flixclusive
MIT License
starbound-text/src/main/kotlin/com/windea/plugin/idea/sbtext/SbTextLanguage.kt
DragonKnightOfBreeze
271,196,420
false
null
package com.windea.plugin.idea.sbtext import com.intellij.lang.* object SbTextLanguage: Language(sbTextName)
1
Kotlin
2
4
abadd50d6fba765e64995f27d525270d4907efed
112
Idea-Plugins
MIT License
composeApp/src/commonMain/kotlin/presentation/screens/profile/ProfileScreen.kt
vrcm-team
746,586,818
false
{"Kotlin": 155380, "Swift": 4222}
package io.github.vrcmteam.vrcm.presentation.screens.profile import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.ArrowBackIosNew import androidx.compose.material.icons.rounded.Menu import androidx.compose.material.icons.rounded.Shield import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.blur import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import cafe.adriel.voyager.core.lifecycle.LifecycleEffect import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.koin.getScreenModel import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import coil3.PlatformContext import coil3.request.ImageRequest import coil3.request.crossfade import io.github.vrcmteam.vrcm.core.extensions.capitalizeFirst import io.github.vrcmteam.vrcm.network.api.attributes.IUser import io.github.vrcmteam.vrcm.presentation.compoments.AImage import io.github.vrcmteam.vrcm.presentation.extensions.drawSate import io.github.vrcmteam.vrcm.presentation.screens.auth.AuthAnimeScreen import io.github.vrcmteam.vrcm.presentation.theme.GameColor import io.github.vrcmteam.vrcm.presentation.theme.MediumRoundedShape import io.github.vrcmteam.vrcm.presentation.theme.SmallRoundedShape import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import org.koin.compose.koinInject data class ProfileScreen( private val user:IUser ) : Screen { @Composable override fun Content() { val profileScreenModel: ProfileScreenModel = getScreenModel() val currentNavigator = LocalNavigator.currentOrThrow LifecycleEffect( onStarted = { profileScreenModel.initUserState(user) } ) LaunchedEffect(Unit) { profileScreenModel.refreshUser(user.id){ // Token失效时返回重新登陆 currentNavigator.replace(AuthAnimeScreen(false)) } } val user = profileScreenModel.userState FriedScreen(user){ currentNavigator.pop() } } } @Composable fun FriedScreen( user: IUser?, popBackStack: () -> Unit, ) { BoxWithConstraints { val scrollState = rememberScrollState() val imageHeight = (maxHeight.value / 3) val offsetDp = with(LocalDensity.current) { scrollState.value.toDp() } val ratio = (((imageHeight - offsetDp.value) / imageHeight).let { if (it >= 0) it else 0f }).let { FastOutSlowInEasing.transform(it) } val fl = scrollState.value / imageHeight val blurDp = with(LocalDensity.current) { (fl * 20).toDp() } val inverseRatio = 1 - ratio val topBarHeight = 70 val lastIconPadding = imageHeight - (topBarHeight * ratio) val isHidden = imageHeight == lastIconPadding Surface( Modifier .systemBarsPadding() .verticalScroll(scrollState) .height(2000.dp) .fillMaxWidth() ) { ProfileUserImage( imageHeight, offsetDp, ratio, blurDp, user?.profileImageUrl ) BottomCard( imageHeight, ratio, topBarHeight, inverseRatio, user ) TopMenuBar( topBarHeight, offsetDp, ratio, inverseRatio, onReturn = popBackStack, onMenu = { /*TODO*/ } ) ProfileUserIcon( isHidden, lastIconPadding, offsetDp, imageHeight, inverseRatio, user?.iconUrl, ) { scrollState.animateScrollTo(0, tween(600)) } } } } @Composable private fun ProfileUserImage( imageHeight: Float, offsetDp: Dp, ratio: Float, blurDp: Dp, imageUrl: String? ) { Box( modifier = Modifier .fillMaxWidth() ) { AImage( modifier = Modifier .height(imageHeight.dp) .fillMaxWidth() .padding(top = offsetDp) .clip( RoundedCornerShape( bottomStart = (30 * ratio).dp, bottomEnd = (30 * ratio).dp ) ) .blur(blurDp), imageData = imageUrl, ) } } @Composable private fun BottomCard( initUserIconPadding: Float, ratio: Float, topBarHeight: Int, inverseRatio: Float, user: IUser? ) { Card( modifier = Modifier .fillMaxSize() .padding(top = initUserIconPadding.dp), shape = RoundedCornerShape( topStart = (30 * ratio).dp, topEnd = (30 * ratio).dp ) ) { if (user == null) return@Card val statusColor = GameColor.Status.fromValue(user.status) val trustRank = remember(user) { user.trustRank } val rankColor: Color = GameColor.Rank.fromValue(trustRank) val speakLanguages = remember(user) { user.speakLanguages } val statusDescription = when (user.statusDescription.isBlank()) { true -> user.status.value else -> user.statusDescription } Spacer(modifier = Modifier.height((topBarHeight * inverseRatio).dp)) // TrustRank + UserName + VRC+ UserInfoRow(user.displayName, user.isSupporter, rankColor) // status StatusRow(statusColor, statusDescription) // speakLanguages LanguagesRow(speakLanguages) HorizontalDivider( modifier = Modifier .fillMaxWidth() .padding(top = 10.dp, start = 50.dp, end = 50.dp) .align(Alignment.CenterHorizontally), color = Color.LightGray, thickness = 1.dp, ) Box( modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp, vertical = 10.dp) .background(CardDefaults.cardColors().containerColor) .align(Alignment.CenterHorizontally) ) { Text( modifier = Modifier.padding(10.dp), text = user.bio ) } } } @Composable private fun ColumnScope.UserInfoRow( userName: String, isSupporter: Boolean, rankColor: Color ) { Row( modifier = Modifier.Companion .align(Alignment.CenterHorizontally) .padding(horizontal = 10.dp, vertical = 10.dp), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( modifier = Modifier .size(26.dp) .align(Alignment.CenterVertically), imageVector = Icons.Rounded.Shield, contentDescription = "TrustRankIcon", tint = rankColor ) Text( modifier = Modifier.drawSate(0.25f, false, Alignment.TopEnd,isSupporter) { fl, offset -> // 画一个+号 val width = 4F this.drawContent() drawRoundRect( color = GameColor.Supporter, topLeft = offset + Offset((fl + width) / 2, 0f), size = Size(width, fl * 2), cornerRadius = CornerRadius(1F,1F) ) drawRoundRect( color = GameColor.Supporter, topLeft = offset + Offset(0F, (fl + width) / 2), size = Size(fl * 2, width), cornerRadius = CornerRadius(1F,1F) ) }, text = userName, fontWeight = FontWeight.Bold, fontSize = 24.sp, ) // 让名字居中 Box(modifier = Modifier.size(26.dp).align(Alignment.Top)) } } @Composable private fun ColumnScope.StatusRow( statusColor: Color, statusDescription: String ) { Row( modifier = Modifier.align(Alignment.CenterHorizontally), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp) ) { Canvas( modifier = Modifier .size(12.dp) ) { drawCircle(statusColor) } Text(text = statusDescription) } } @Composable private fun ColumnScope.LanguagesRow(speakLanguages: List<String>) { Row( modifier = Modifier .padding(top = 10.dp) .align(Alignment.CenterHorizontally), ) { speakLanguages.forEach { language -> Text( modifier = Modifier .align(Alignment.CenterVertically) .padding(horizontal = 6.dp) .background(MaterialTheme.colorScheme.primary, SmallRoundedShape) .padding(horizontal = 6.dp) .clip(MediumRoundedShape), text = remember(language) { language.capitalizeFirst() }, color = MaterialTheme.colorScheme.onPrimary ) } } } @Composable private fun ProfileUserIcon( isHidden: Boolean, lastIconPadding: Float, offsetDp: Dp, imageHeight: Float, inverseRatio: Float, avatarThumbnailImageUrl: String?, coroutineScope: CoroutineScope = rememberCoroutineScope(), onClickIcon: suspend () -> Unit = {} ) { val iconSize = (60 * inverseRatio).dp Box { Row( modifier = Modifier .run { if (isHidden) offset(y = (offsetDp - imageHeight.dp)) else this } .padding(top = (lastIconPadding + 5).dp) .alpha(inverseRatio), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, ) { Spacer(modifier = Modifier.weight(1f)) AImage( modifier = Modifier .align(Alignment.CenterVertically) .clip(CircleShape) .size(iconSize) .clickable { coroutineScope.launch { onClickIcon() } }, imageData = ImageRequest.Builder(koinInject<PlatformContext>()) .data(avatarThumbnailImageUrl) .crossfade(600) .size(70, 70).build(), contentDescription = "UserIcon", ) Spacer(modifier = Modifier.weight(1f)) } } } @Composable private fun TopMenuBar( topBarHeight: Int, offsetDp: Dp, ratio: Float, inverseRatio: Float, color: Color = Color.White, onReturn: () -> Unit, onMenu: () -> Unit ) { Box { Row( modifier = Modifier .fillMaxWidth() .align(Alignment.TopCenter) .height(topBarHeight.dp) .offset(y = offsetDp) .alpha(ratio), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Icon( modifier = Modifier .padding(horizontal = 10.dp) .clip(CircleShape) .clickable(onClick = onReturn), imageVector = Icons.Rounded.ArrowBackIosNew, tint = Color.White, contentDescription = "WhiteReturnIcon" ) Spacer(modifier = Modifier.weight(1f)) Icon( modifier = Modifier .padding(horizontal = 10.dp), imageVector = Icons.Rounded.Menu, tint = Color.White, contentDescription = "WhiteMenuIcon" ) } Row( modifier = Modifier .fillMaxWidth() .align(Alignment.TopCenter) .height(topBarHeight.dp) .offset(y = offsetDp) .alpha(inverseRatio) .background( color, RoundedCornerShape( bottomStart = 12.dp, bottomEnd = 12.dp ) ), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Icon( modifier = Modifier .padding(horizontal = 10.dp), imageVector = Icons.Rounded.ArrowBackIosNew, contentDescription = "BlackReturnIcon" ) Spacer(modifier = Modifier.weight(1f)) Icon( modifier = Modifier .padding(horizontal = 10.dp), imageVector = Icons.Rounded.Menu, contentDescription = "BlackMenuIcon" ) } } }
0
Kotlin
0
4
28582f66a8fe196e82c0d662c2791c5f507a8f59
13,955
VRCM
MIT License
composeApp/src/commonMain/kotlin/presentation/screens/profile/ProfileScreen.kt
vrcm-team
746,586,818
false
{"Kotlin": 155380, "Swift": 4222}
package io.github.vrcmteam.vrcm.presentation.screens.profile import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.ArrowBackIosNew import androidx.compose.material.icons.rounded.Menu import androidx.compose.material.icons.rounded.Shield import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.blur import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import cafe.adriel.voyager.core.lifecycle.LifecycleEffect import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.koin.getScreenModel import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import coil3.PlatformContext import coil3.request.ImageRequest import coil3.request.crossfade import io.github.vrcmteam.vrcm.core.extensions.capitalizeFirst import io.github.vrcmteam.vrcm.network.api.attributes.IUser import io.github.vrcmteam.vrcm.presentation.compoments.AImage import io.github.vrcmteam.vrcm.presentation.extensions.drawSate import io.github.vrcmteam.vrcm.presentation.screens.auth.AuthAnimeScreen import io.github.vrcmteam.vrcm.presentation.theme.GameColor import io.github.vrcmteam.vrcm.presentation.theme.MediumRoundedShape import io.github.vrcmteam.vrcm.presentation.theme.SmallRoundedShape import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import org.koin.compose.koinInject data class ProfileScreen( private val user:IUser ) : Screen { @Composable override fun Content() { val profileScreenModel: ProfileScreenModel = getScreenModel() val currentNavigator = LocalNavigator.currentOrThrow LifecycleEffect( onStarted = { profileScreenModel.initUserState(user) } ) LaunchedEffect(Unit) { profileScreenModel.refreshUser(user.id){ // Token失效时返回重新登陆 currentNavigator.replace(AuthAnimeScreen(false)) } } val user = profileScreenModel.userState FriedScreen(user){ currentNavigator.pop() } } } @Composable fun FriedScreen( user: IUser?, popBackStack: () -> Unit, ) { BoxWithConstraints { val scrollState = rememberScrollState() val imageHeight = (maxHeight.value / 3) val offsetDp = with(LocalDensity.current) { scrollState.value.toDp() } val ratio = (((imageHeight - offsetDp.value) / imageHeight).let { if (it >= 0) it else 0f }).let { FastOutSlowInEasing.transform(it) } val fl = scrollState.value / imageHeight val blurDp = with(LocalDensity.current) { (fl * 20).toDp() } val inverseRatio = 1 - ratio val topBarHeight = 70 val lastIconPadding = imageHeight - (topBarHeight * ratio) val isHidden = imageHeight == lastIconPadding Surface( Modifier .systemBarsPadding() .verticalScroll(scrollState) .height(2000.dp) .fillMaxWidth() ) { ProfileUserImage( imageHeight, offsetDp, ratio, blurDp, user?.profileImageUrl ) BottomCard( imageHeight, ratio, topBarHeight, inverseRatio, user ) TopMenuBar( topBarHeight, offsetDp, ratio, inverseRatio, onReturn = popBackStack, onMenu = { /*TODO*/ } ) ProfileUserIcon( isHidden, lastIconPadding, offsetDp, imageHeight, inverseRatio, user?.iconUrl, ) { scrollState.animateScrollTo(0, tween(600)) } } } } @Composable private fun ProfileUserImage( imageHeight: Float, offsetDp: Dp, ratio: Float, blurDp: Dp, imageUrl: String? ) { Box( modifier = Modifier .fillMaxWidth() ) { AImage( modifier = Modifier .height(imageHeight.dp) .fillMaxWidth() .padding(top = offsetDp) .clip( RoundedCornerShape( bottomStart = (30 * ratio).dp, bottomEnd = (30 * ratio).dp ) ) .blur(blurDp), imageData = imageUrl, ) } } @Composable private fun BottomCard( initUserIconPadding: Float, ratio: Float, topBarHeight: Int, inverseRatio: Float, user: IUser? ) { Card( modifier = Modifier .fillMaxSize() .padding(top = initUserIconPadding.dp), shape = RoundedCornerShape( topStart = (30 * ratio).dp, topEnd = (30 * ratio).dp ) ) { if (user == null) return@Card val statusColor = GameColor.Status.fromValue(user.status) val trustRank = remember(user) { user.trustRank } val rankColor: Color = GameColor.Rank.fromValue(trustRank) val speakLanguages = remember(user) { user.speakLanguages } val statusDescription = when (user.statusDescription.isBlank()) { true -> user.status.value else -> user.statusDescription } Spacer(modifier = Modifier.height((topBarHeight * inverseRatio).dp)) // TrustRank + UserName + VRC+ UserInfoRow(user.displayName, user.isSupporter, rankColor) // status StatusRow(statusColor, statusDescription) // speakLanguages LanguagesRow(speakLanguages) HorizontalDivider( modifier = Modifier .fillMaxWidth() .padding(top = 10.dp, start = 50.dp, end = 50.dp) .align(Alignment.CenterHorizontally), color = Color.LightGray, thickness = 1.dp, ) Box( modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp, vertical = 10.dp) .background(CardDefaults.cardColors().containerColor) .align(Alignment.CenterHorizontally) ) { Text( modifier = Modifier.padding(10.dp), text = user.bio ) } } } @Composable private fun ColumnScope.UserInfoRow( userName: String, isSupporter: Boolean, rankColor: Color ) { Row( modifier = Modifier.Companion .align(Alignment.CenterHorizontally) .padding(horizontal = 10.dp, vertical = 10.dp), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( modifier = Modifier .size(26.dp) .align(Alignment.CenterVertically), imageVector = Icons.Rounded.Shield, contentDescription = "TrustRankIcon", tint = rankColor ) Text( modifier = Modifier.drawSate(0.25f, false, Alignment.TopEnd,isSupporter) { fl, offset -> // 画一个+号 val width = 4F this.drawContent() drawRoundRect( color = GameColor.Supporter, topLeft = offset + Offset((fl + width) / 2, 0f), size = Size(width, fl * 2), cornerRadius = CornerRadius(1F,1F) ) drawRoundRect( color = GameColor.Supporter, topLeft = offset + Offset(0F, (fl + width) / 2), size = Size(fl * 2, width), cornerRadius = CornerRadius(1F,1F) ) }, text = userName, fontWeight = FontWeight.Bold, fontSize = 24.sp, ) // 让名字居中 Box(modifier = Modifier.size(26.dp).align(Alignment.Top)) } } @Composable private fun ColumnScope.StatusRow( statusColor: Color, statusDescription: String ) { Row( modifier = Modifier.align(Alignment.CenterHorizontally), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp) ) { Canvas( modifier = Modifier .size(12.dp) ) { drawCircle(statusColor) } Text(text = statusDescription) } } @Composable private fun ColumnScope.LanguagesRow(speakLanguages: List<String>) { Row( modifier = Modifier .padding(top = 10.dp) .align(Alignment.CenterHorizontally), ) { speakLanguages.forEach { language -> Text( modifier = Modifier .align(Alignment.CenterVertically) .padding(horizontal = 6.dp) .background(MaterialTheme.colorScheme.primary, SmallRoundedShape) .padding(horizontal = 6.dp) .clip(MediumRoundedShape), text = remember(language) { language.capitalizeFirst() }, color = MaterialTheme.colorScheme.onPrimary ) } } } @Composable private fun ProfileUserIcon( isHidden: Boolean, lastIconPadding: Float, offsetDp: Dp, imageHeight: Float, inverseRatio: Float, avatarThumbnailImageUrl: String?, coroutineScope: CoroutineScope = rememberCoroutineScope(), onClickIcon: suspend () -> Unit = {} ) { val iconSize = (60 * inverseRatio).dp Box { Row( modifier = Modifier .run { if (isHidden) offset(y = (offsetDp - imageHeight.dp)) else this } .padding(top = (lastIconPadding + 5).dp) .alpha(inverseRatio), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, ) { Spacer(modifier = Modifier.weight(1f)) AImage( modifier = Modifier .align(Alignment.CenterVertically) .clip(CircleShape) .size(iconSize) .clickable { coroutineScope.launch { onClickIcon() } }, imageData = ImageRequest.Builder(koinInject<PlatformContext>()) .data(avatarThumbnailImageUrl) .crossfade(600) .size(70, 70).build(), contentDescription = "UserIcon", ) Spacer(modifier = Modifier.weight(1f)) } } } @Composable private fun TopMenuBar( topBarHeight: Int, offsetDp: Dp, ratio: Float, inverseRatio: Float, color: Color = Color.White, onReturn: () -> Unit, onMenu: () -> Unit ) { Box { Row( modifier = Modifier .fillMaxWidth() .align(Alignment.TopCenter) .height(topBarHeight.dp) .offset(y = offsetDp) .alpha(ratio), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Icon( modifier = Modifier .padding(horizontal = 10.dp) .clip(CircleShape) .clickable(onClick = onReturn), imageVector = Icons.Rounded.ArrowBackIosNew, tint = Color.White, contentDescription = "WhiteReturnIcon" ) Spacer(modifier = Modifier.weight(1f)) Icon( modifier = Modifier .padding(horizontal = 10.dp), imageVector = Icons.Rounded.Menu, tint = Color.White, contentDescription = "WhiteMenuIcon" ) } Row( modifier = Modifier .fillMaxWidth() .align(Alignment.TopCenter) .height(topBarHeight.dp) .offset(y = offsetDp) .alpha(inverseRatio) .background( color, RoundedCornerShape( bottomStart = 12.dp, bottomEnd = 12.dp ) ), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Icon( modifier = Modifier .padding(horizontal = 10.dp), imageVector = Icons.Rounded.ArrowBackIosNew, contentDescription = "BlackReturnIcon" ) Spacer(modifier = Modifier.weight(1f)) Icon( modifier = Modifier .padding(horizontal = 10.dp), imageVector = Icons.Rounded.Menu, contentDescription = "BlackMenuIcon" ) } } }
0
Kotlin
0
4
28582f66a8fe196e82c0d662c2791c5f507a8f59
13,955
VRCM
MIT License
kotlin/lightning_talk/src/main/kotlin/me/bendoan/helloKotlin/user.kt
BenDoan
29,168,104
false
null
package me.bendoan.helloKotlin data class User(var name: String, var age: Int) fun main(args: Array<String>) { val ben = User("<NAME>", 22) val ben2 = User("<NAME>", 22) val nick = User("<NAME>", 21) println("Does $ben equal $nick? ${ben == nick}") println("Does $ben equal $ben2? ${ben == ben2}") }
56
Jupyter Notebook
1
1
80c74ac2edc8707b96a386099ce7dad5837f279f
324
playground
MIT License
src/test/java/de/platon42/intellij/plugins/cajon/inspections/AssertThatSizeInspectionTest.kt
myplacedk
463,208,541
true
{"Kotlin": 263139, "Java": 206801, "HTML": 8728}
package de.platon42.intellij.plugins.cajon.inspections import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture import de.platon42.intellij.jupiter.MyFixture import de.platon42.intellij.jupiter.TestDataSubPath import de.platon42.intellij.plugins.cajon.AbstractCajonTest import org.junit.jupiter.api.Test internal class AssertThatSizeInspectionTest : AbstractCajonTest() { @Test @TestDataSubPath("inspections/Size") internal fun assertThat_size_of_array_collection_or_map_can_be_simplified(@MyFixture myFixture: JavaCodeInsightTestFixture) { myFixture.enableInspections(AssertThatSizeInspection::class.java) myFixture.configureByFile("SizeBefore.java") assertHighlightings(myFixture, 1, "Try to operate on the iterable itself rather than its size") executeQuickFixes(myFixture, Regex.fromLiteral("Replace isEqualTo() with isEmpty()"), 5) executeQuickFixes(myFixture, Regex.fromLiteral("Replace isZero() with isEmpty()"), 5) executeQuickFixes(myFixture, Regex.fromLiteral("Replace isNotZero() with isNotEmpty()"), 5) executeQuickFixes(myFixture, Regex.fromLiteral("Replace isGreaterThan() with isNotEmpty()"), 5) executeQuickFixes(myFixture, Regex.fromLiteral("Replace isGreaterThanOrEqualTo() with isNotEmpty()"), 5) executeQuickFixes(myFixture, Regex.fromLiteral("Replace isLessThan() with isEmpty()"), 5) executeQuickFixes(myFixture, Regex.fromLiteral("Replace isLessThanOrEqualTo() with isEmpty()"), 5) executeQuickFixes(myFixture, Regex.fromLiteral("Replace isEqualTo() with hasSameSizeAs()"), 15) executeQuickFixes(myFixture, Regex.fromLiteral("Replace isEqualTo() with hasSize()"), 15) executeQuickFixes(myFixture, Regex.fromLiteral("Replace isGreaterThan() with hasSizeGreaterThan()"), 5) executeQuickFixes(myFixture, Regex.fromLiteral("Replace isGreaterThanOrEqualTo() with hasSizeGreaterThanOrEqualTo()"), 5) executeQuickFixes(myFixture, Regex.fromLiteral("Replace isLessThan() with hasSizeLessThan()"), 5) executeQuickFixes(myFixture, Regex.fromLiteral("Replace isLessThanOrEqualTo() with hasSizeLessThanOrEqualTo()"), 5) executeQuickFixes(myFixture, Regex.fromLiteral("Remove size determination of expected expression and replace hasSize() with hasSameSizeAs()"), 17) myFixture.checkResultByFile("SizeAfter.java") } }
0
null
0
0
2d92d71af0bbf7991c4709c3b36548c1be474b46
2,404
cajon-plugin
Apache License 2.0
app/src/main/java/dev/igorxp5/applada/data/repositories/SubscriptionRepository.kt
Igorxp5
743,171,374
false
{"Kotlin": 58397}
package dev.igorxp5.applada.data.repositories import dev.igorxp5.applada.data.Subscription import dev.igorxp5.applada.data.source.Result import dev.igorxp5.applada.data.source.SubscriptionDataSource import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers class SubscriptionRepository( private val remoteSource: SubscriptionDataSource, private val localSource: SubscriptionDataSource, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO ) { suspend fun getSubscriptions() : Result<List<Subscription>> { var result : Result<List<Subscription>> = remoteSource.getSubscriptions() if (result is Result.Error<*>) { result = Result.Error(result.exception, localSource.getSubscriptions()) } else if (result is Result.Success) { result.data.forEach { localSource.createSubscription(it) } } return result } suspend fun getMatchSubscription(matchId: String) : Result<Subscription?> { var result : Result<Subscription?> = remoteSource.getSubscriptionByMatchId(matchId) if (result is Result.Success && result.data != null) { localSource.createSubscription(result.data!!) } return result } suspend fun createMatchSubscription(matchId: String) : Result<Boolean> { val subscription = Subscription("", matchId) var result : Result<Subscription> = remoteSource.createSubscription(subscription) if (result is Result.Success) { val createdSubscription = result.data localSource.createSubscription(createdSubscription) return Result.Success(true) } return Result.Error((result as Result.Error).exception) } suspend fun cancelMatchSubscription(matchId: String) : Result<Boolean> { var result = remoteSource.deleteSubscriptionByMatchId(matchId) if (result is Result.Success) { result = localSource.deleteSubscriptionByMatchId(matchId) } return result } }
0
Kotlin
0
0
64f696fd87f7e76b1aaf385f34bcdd34f51cd9bd
2,075
applada-android
MIT License
app/src/main/java/oliveiradev/br/livromaterialdesign/ui/adapters/HeroesAdapter.kt
oliveiradev27
135,095,467
false
{"Kotlin": 10036}
package oliveiradev.br.livromaterialdesign.ui.adapters import android.support.v7.widget.CardView import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import oliveiradev.br.livromaterialdesign.R import oliveiradev.br.livromaterialdesign.data.models.Hero import oliveiradev.br.livromaterialdesign.ui.listeners.OnIteractionItemListener class HeroesAdapter(private var heroes: List<Hero>, private var listener: OnIteractionItemListener<Hero>) : RecyclerView.Adapter<HeroesAdapter.HeroViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HeroViewHolder { val context = parent.context val inflate = LayoutInflater.from(context) val view = inflate.inflate(R.layout.item_card_hero, parent, false) return HeroViewHolder(view) } override fun getItemCount(): Int { return heroes.size } override fun onBindViewHolder(holder: HeroViewHolder, position: Int) { holder.bindData(heroes[position], listener) } class HeroViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val imageProfile: ImageView = itemView.findViewById(R.id.imageProfile) val cardHeroInfo: CardView = itemView.findViewById(R.id.cardHeroInfo) val linearContentHeroCard: LinearLayout = itemView.findViewById(R.id.linearContentHeroCard) val textName : TextView = itemView.findViewById(R.id.textName) fun bindData(hero: Hero, listener: OnIteractionItemListener<Hero>) { imageProfile.setImageResource(hero.imgProfile) textName.text = hero.name imageProfile.setOnClickListener { listener.onClickItem(itemView, hero) } } } }
0
Kotlin
0
0
cb7bfac6f5d4358dc432d2e217886cfd9cf0161b
1,898
Painel-de-Herois
MIT License
seskar/seskar-compiler-plugin/src/main/kotlin/seskar/compiler/union/extensions/UnionTransformExtension.kt
turansky
279,976,108
false
{"Kotlin": 64960, "Shell": 286}
package seskar.compiler.union.extensions import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.ir.declarations.IrModuleFragment import seskar.compiler.union.backend.UnionTransformer internal class UnionTransformExtension : IrGenerationExtension { override fun generate( moduleFragment: IrModuleFragment, pluginContext: IrPluginContext, ) { moduleFragment.transformChildren(UnionTransformer(pluginContext), null) } }
0
Kotlin
4
30
50d17ed657653b7660ead90fb3201772e893c9ed
574
seskar
Apache License 2.0
android/benchmark/src/main/java/io/github/reactivecircus/benchmark/baselineprofile/BaselineProfileGenerator.kt
ReactiveCircus
513,535,591
false
{"Kotlin": 479642}
package io.github.reactivecircus.benchmark.baselineprofile import androidx.benchmark.macro.junit4.BaselineProfileRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import io.github.reactivecircus.benchmark.PackageName import io.github.reactivecircus.benchmark.home.homeFeedListScrollDown import io.github.reactivecircus.benchmark.home.waitForHomeFeedContent import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) class BaselineProfileGenerator { @get:Rule val rule = BaselineProfileRule() @Test fun generate() = rule.collect( packageName = PackageName, // TODO enable once https://issuetracker.google.com/issues/332982932 is fixed includeInStartupProfile = false, strictStability = true, ) { pressHome() startActivityAndWait() waitForHomeFeedContent() homeFeedListScrollDown() } }
1
Kotlin
0
0
57c1b136c769f0c444fcdc7028534b4ca278954a
982
kstreamlined-mobile
Apache License 2.0
android/app/src/main/kotlin/com/example/material_design/MainActivity.kt
flutter-codelabs
437,217,914
false
{"Dart": 26704, "C++": 16826, "CMake": 7955, "C": 734, "Swift": 404, "Kotlin": 132, "Objective-C": 38}
package com.example.material_design import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
248dab8c4c57eec768fa161e4967146095223d89
132
material_design
MIT License
urbanairship-core/src/test/java/com/urbanairship/permission/PermissionsManagerTest.kt
urbanairship
58,972,818
false
{"Kotlin": 3266979, "Java": 2582150, "Python": 10137, "Shell": 589}
/* Copyright Airship and Contributors */ package com.urbanairship.permission import android.app.Activity import android.content.Context import androidx.core.util.Consumer import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.urbanairship.TestActivityMonitor import app.cash.turbine.test import io.mockk.every import io.mockk.mockk import io.mockk.verify import io.mockk.verifyOrder import junit.framework.TestCase.assertEquals import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestResult import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @OptIn(ExperimentalCoroutinesApi::class) @RunWith(AndroidJUnit4::class) public class PermissionsManagerTest { private val testDispatcher = StandardTestDispatcher() private val systemSettingsLauncher: SystemSettingsLauncher = mockk() private val activityMonitor = TestActivityMonitor() private val context: Context = ApplicationProvider.getApplicationContext() private val permissionsManager = PermissionsManager(context, activityMonitor, systemSettingsLauncher, testDispatcher) private var mockDelegateStatus = PermissionRequestResult.notDetermined() private val mockDelegate: PermissionDelegate = mockk { every { checkPermissionStatus(any(), any()) } answers { secondArg<Consumer<PermissionStatus>>().accept(mockDelegateStatus.permissionStatus) } every { requestPermission(any(), any()) } answers { secondArg<Consumer<PermissionRequestResult>>().accept(mockDelegateStatus) } } private val mockStatusListener: OnPermissionStatusChangedListener = mockk(relaxed = true) @Before public fun setUp() { Dispatchers.setMain(testDispatcher) } @After public fun tearDown() { Dispatchers.resetMain() } @Test public fun testCheckPermissionNoDelegate(): TestResult = runTest { assertEquals( PermissionStatus.NOT_DETERMINED, permissionsManager.suspendingCheckPermissionStatus(Permission.LOCATION) ) } @Test public fun testRequestPermissionNoDelegate(): TestResult = runTest { assertEquals( PermissionRequestResult.notDetermined(), permissionsManager.suspendingRequestPermission(Permission.LOCATION) ) } @Test public fun testConfiguredPermissions(): TestResult = runTest { val expected: MutableSet<Permission> = HashSet() assertEquals(expected, permissionsManager.configuredPermissions) expected.add(Permission.LOCATION) permissionsManager.setPermissionDelegate(Permission.LOCATION, mockDelegate) assertEquals(expected, permissionsManager.configuredPermissions) expected.add(Permission.DISPLAY_NOTIFICATIONS) permissionsManager.setPermissionDelegate(Permission.DISPLAY_NOTIFICATIONS, mockDelegate) assertEquals(expected, permissionsManager.configuredPermissions) } @Test public fun testRequestPermission(): TestResult = runTest { permissionsManager.setPermissionDelegate(Permission.LOCATION, mockDelegate) mockDelegateStatus = PermissionRequestResult.granted() assertEquals( mockDelegateStatus, permissionsManager.suspendingRequestPermission(Permission.LOCATION) ) } @Test public fun testOnEnableAirship(): TestResult = runTest { val enabler = mockk<Consumer<Permission>>(relaxed = true) permissionsManager.setPermissionDelegate(Permission.DISPLAY_NOTIFICATIONS, mockDelegate) mockDelegateStatus = PermissionRequestResult.granted() permissionsManager.addAirshipEnabler(enabler) permissionsManager.suspendingRequestPermission(Permission.DISPLAY_NOTIFICATIONS, true) verify { enabler.accept(Permission.DISPLAY_NOTIFICATIONS) } } @Test public fun testOnEnableAirshipDenied(): TestResult = runTest { val enabler = mockk<Consumer<Permission>>(relaxed = true) permissionsManager.setPermissionDelegate(Permission.DISPLAY_NOTIFICATIONS, mockDelegate) mockDelegateStatus = PermissionRequestResult.denied(true) permissionsManager.addAirshipEnabler(enabler) permissionsManager.suspendingRequestPermission(Permission.DISPLAY_NOTIFICATIONS, true) verify(exactly = 0) { enabler.accept(Permission.DISPLAY_NOTIFICATIONS) } } @Test public fun testOnEnableAirshipNotDetermined(): TestResult = runTest { val enabler = mockk<Consumer<Permission>>(relaxed = true) permissionsManager.setPermissionDelegate(Permission.LOCATION, mockDelegate) mockDelegateStatus = PermissionRequestResult.notDetermined() permissionsManager.addAirshipEnabler(enabler) permissionsManager.suspendingRequestPermission(Permission.LOCATION, true) verify(exactly = 0) { enabler.accept(Permission.DISPLAY_NOTIFICATIONS) } } @Test public fun testStatusChangeCheckOnRequest(): TestResult = runTest { permissionsManager.setPermissionDelegate(Permission.LOCATION, mockDelegate) permissionsManager.suspendingRequestPermission(Permission.LOCATION) permissionsManager.addOnPermissionStatusChangedListener(mockStatusListener) mockDelegateStatus = PermissionRequestResult.granted() permissionsManager.suspendingRequestPermission(Permission.LOCATION) verify { mockStatusListener.onPermissionStatusChanged(Permission.LOCATION, PermissionStatus.GRANTED) } mockDelegateStatus = PermissionRequestResult.denied(true) permissionsManager.suspendingCheckPermissionStatus(Permission.LOCATION) verify { mockStatusListener.onPermissionStatusChanged(Permission.LOCATION, PermissionStatus.DENIED) } } @Test public fun testStatusChangeCheckOnCheck(): TestResult = runTest { permissionsManager.setPermissionDelegate(Permission.LOCATION, mockDelegate) permissionsManager.suspendingRequestPermission(Permission.LOCATION) permissionsManager.addOnPermissionStatusChangedListener(mockStatusListener) mockDelegateStatus = PermissionRequestResult.denied(true) permissionsManager.suspendingRequestPermission(Permission.LOCATION) verify { mockStatusListener.onPermissionStatusChanged(Permission.LOCATION, PermissionStatus.DENIED) } mockDelegateStatus = PermissionRequestResult.granted() permissionsManager.suspendingCheckPermissionStatus(Permission.LOCATION) verify { mockStatusListener.onPermissionStatusChanged(Permission.LOCATION, PermissionStatus.GRANTED) } } @Test public fun testStatusChangeCheckOnActivityResume(): TestResult = runTest { mockDelegateStatus = PermissionRequestResult.denied(true) permissionsManager.setPermissionDelegate(Permission.LOCATION, mockDelegate) permissionsManager.suspendingCheckPermissionStatus(Permission.LOCATION) permissionsManager.addOnPermissionStatusChangedListener(mockStatusListener) mockDelegateStatus = PermissionRequestResult.notDetermined() activityMonitor.resumeActivity(Activity()) advanceUntilIdle() verify { mockStatusListener.onPermissionStatusChanged(Permission.LOCATION, PermissionStatus.NOT_DETERMINED) } } @Test public fun testDedupeRequests(): TestResult = runTest { val resultFlow = MutableStateFlow<PermissionRequestResult?>(null) val delegate: PermissionDelegate = mockk { every { requestPermission(any(), any()) } answers { launch { secondArg<Consumer<PermissionRequestResult>>().accept(resultFlow.first { it != null }) } } every { checkPermissionStatus(any(), any()) } answers { launch { secondArg<Consumer<PermissionStatus>>().accept( resultFlow.first { it != null }?.permissionStatus ?: PermissionStatus.NOT_DETERMINED ) } } } permissionsManager.setPermissionDelegate(Permission.LOCATION, delegate) val requestJobs = (0..6).map { async { return@async permissionsManager.suspendingRequestPermission(Permission.LOCATION) } } val checkStatusJobs = (0..10).map { async { return@async permissionsManager.suspendingCheckPermissionStatus(Permission.LOCATION) } } resultFlow.value = PermissionRequestResult.granted() assertEquals((0..6).map { PermissionRequestResult.granted() }, requestJobs.map { it.await() }) assertEquals((0..10).map { PermissionStatus.GRANTED }, checkStatusJobs.map { it.await() }) verify(exactly = 1) { delegate.requestPermission(any(), any()) delegate.checkPermissionStatus(any(), any()) } } @Test public fun testFallbackSystemSettings(): TestResult = runTest { val settingsLaunched = MutableStateFlow(false) every { systemSettingsLauncher.openAppSettings(any()) } answers { settingsLaunched.value = true true } mockDelegateStatus = PermissionRequestResult.denied(true) permissionsManager.setPermissionDelegate(Permission.LOCATION, mockDelegate) val job = async(Dispatchers.Default) { permissionsManager.suspendingRequestPermission(Permission.LOCATION, fallback = PermissionPromptFallback.SystemSettings) } settingsLaunched.first { it } mockDelegateStatus = PermissionRequestResult.granted() activityMonitor.resumeActivity(Activity()) advanceUntilIdle() assertEquals( PermissionRequestResult.granted(), job.await() ) verifyOrder { mockDelegate.requestPermission(any(), any()) systemSettingsLauncher.openAppSettings(context) mockDelegate.checkPermissionStatus(context, any()) } } @Test public fun testFallbackSystemSettingsFails(): TestResult = runTest { val settingsLaunched = MutableStateFlow(false) every { systemSettingsLauncher.openAppSettings(any()) } answers { settingsLaunched.value = true false } mockDelegateStatus = PermissionRequestResult.denied(true) permissionsManager.setPermissionDelegate(Permission.LOCATION, mockDelegate) val job = async(Dispatchers.Default) { permissionsManager.suspendingRequestPermission(Permission.LOCATION, fallback = PermissionPromptFallback.SystemSettings) } settingsLaunched.first { it } mockDelegateStatus = PermissionRequestResult.granted() activityMonitor.resumeActivity(Activity()) advanceUntilIdle() assertEquals( PermissionRequestResult.denied(true), job.await() ) verifyOrder { mockDelegate.requestPermission(any(), any()) systemSettingsLauncher.openAppSettings(context) } } @Test public fun testFallbackSystemSettingsNotifications(): TestResult = runTest { val settingsLaunched = MutableStateFlow(false) every { systemSettingsLauncher.openAppNotificationSettings(any()) } answers { settingsLaunched.value = true true } mockDelegateStatus = PermissionRequestResult.denied(true) permissionsManager.setPermissionDelegate(Permission.DISPLAY_NOTIFICATIONS, mockDelegate) val job = async(Dispatchers.Default) { permissionsManager.suspendingRequestPermission(Permission.DISPLAY_NOTIFICATIONS, fallback = PermissionPromptFallback.SystemSettings) } settingsLaunched.first { it } mockDelegateStatus = PermissionRequestResult.granted() activityMonitor.resumeActivity(Activity()) advanceUntilIdle() assertEquals( PermissionRequestResult.granted(), job.await() ) verifyOrder { mockDelegate.requestPermission(any(), any()) systemSettingsLauncher.openAppNotificationSettings(context) mockDelegate.checkPermissionStatus(context, any()) } } @Test public fun testFallbackNone(): TestResult = runTest { mockDelegateStatus = PermissionRequestResult.denied(true) permissionsManager.setPermissionDelegate(Permission.DISPLAY_NOTIFICATIONS, mockDelegate) val result = permissionsManager.suspendingRequestPermission(Permission.DISPLAY_NOTIFICATIONS, fallback = PermissionPromptFallback.None) assertEquals( PermissionRequestResult.denied(true), result ) verifyOrder { mockDelegate.requestPermission(any(), any()) } } @Test public fun testFallbackCallback(): TestResult = runTest { val callbackCalled = MutableStateFlow(false) mockDelegateStatus = PermissionRequestResult.denied(true) permissionsManager.setPermissionDelegate(Permission.DISPLAY_NOTIFICATIONS, mockDelegate) val job = async(Dispatchers.Default) { permissionsManager.suspendingRequestPermission( Permission.DISPLAY_NOTIFICATIONS, fallback = PermissionPromptFallback.Callback { mockDelegateStatus = PermissionRequestResult.granted() callbackCalled.value = true } ) } callbackCalled.first { it } assertEquals( PermissionRequestResult.granted(), job.await() ) verifyOrder { mockDelegate.requestPermission(any(), any()) mockDelegate.checkPermissionStatus(context, any()) } } @Test public fun testFallbackIgnoredNotDetermined(): TestResult = runTest { mockDelegateStatus = PermissionRequestResult.notDetermined() permissionsManager.setPermissionDelegate(Permission.DISPLAY_NOTIFICATIONS, mockDelegate) val result = permissionsManager.suspendingRequestPermission(Permission.DISPLAY_NOTIFICATIONS, fallback = PermissionPromptFallback.SystemSettings) assertEquals( PermissionRequestResult.notDetermined(), result ) verifyOrder { mockDelegate.requestPermission(any(), any()) } } @Test public fun testFallbackIgnoredGranted(): TestResult = runTest { mockDelegateStatus = PermissionRequestResult.granted() permissionsManager.setPermissionDelegate(Permission.DISPLAY_NOTIFICATIONS, mockDelegate) val result = permissionsManager.suspendingRequestPermission(Permission.DISPLAY_NOTIFICATIONS, fallback = PermissionPromptFallback.SystemSettings) assertEquals( PermissionRequestResult.granted(), result ) verifyOrder { mockDelegate.requestPermission(any(), any()) } } @Test public fun testFallbackIgnoredDeniedFromPrompt(): TestResult = runTest { mockDelegateStatus = PermissionRequestResult.denied(false) permissionsManager.setPermissionDelegate(Permission.DISPLAY_NOTIFICATIONS, mockDelegate) val result = permissionsManager.suspendingRequestPermission(Permission.DISPLAY_NOTIFICATIONS, fallback = PermissionPromptFallback.SystemSettings) assertEquals( PermissionRequestResult.denied(false), result ) verifyOrder { mockDelegate.requestPermission(any(), any()) } } @Test public fun testPermissionUpdates(): TestResult = runTest { mockDelegateStatus = PermissionRequestResult.denied(false) permissionsManager.setPermissionDelegate(Permission.DISPLAY_NOTIFICATIONS, mockDelegate) permissionsManager.suspendingCheckPermissionStatus(Permission.DISPLAY_NOTIFICATIONS) permissionsManager.permissionsUpdate(Permission.DISPLAY_NOTIFICATIONS).test { assertEquals(PermissionStatus.DENIED, awaitItem()) mockDelegateStatus = PermissionRequestResult.granted() permissionsManager.suspendingCheckPermissionStatus(Permission.DISPLAY_NOTIFICATIONS) assertEquals(PermissionStatus.GRANTED, awaitItem()) mockDelegateStatus = PermissionRequestResult.notDetermined() permissionsManager.suspendingCheckPermissionStatus(Permission.DISPLAY_NOTIFICATIONS) assertEquals(PermissionStatus.NOT_DETERMINED, awaitItem()) } } }
2
Kotlin
122
111
21d49c3ffd373e3ba6b51a706a4839ab3713db11
17,353
android-library
Apache License 2.0
components/psi/imagevector/src/main/kotlin/io/github/composegears/valkyrie/psi/extension/PsiElement.kt
ComposeGears
778,162,113
false
{"Kotlin": 777429}
package io.github.composegears.valkyrie.psi.extension import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil inline fun <reified T : PsiElement> PsiElement.childrenOfType(): Collection<T> { return PsiTreeUtil.findChildrenOfType(this, T::class.java) } inline fun <reified T : PsiElement> PsiElement.childOfType(): T? { return PsiTreeUtil.findChildOfType(this, T::class.java) }
27
Kotlin
6
321
f0647081b15b907ad92b38c33eb62179ffd0f969
408
Valkyrie
Apache License 2.0
TeamCode/src/main/kotlin/org/firstinspires/ftc/teamcode/opModes/teleOp/OutreachTeleOp.kt
ftc13100
536,340,996
false
{"Java": 206334, "Kotlin": 72073}
package org.firstinspires.ftc.teamcode.opModes.teleOp import com.acmerobotics.dashboard.FtcDashboard import com.acmerobotics.dashboard.telemetry.MultipleTelemetry import com.arcrobotics.ftclib.command.CommandOpMode import com.arcrobotics.ftclib.command.ConditionalCommand import com.arcrobotics.ftclib.command.InstantCommand import com.arcrobotics.ftclib.gamepad.GamepadEx import com.arcrobotics.ftclib.gamepad.GamepadKeys import com.arcrobotics.ftclib.hardware.motors.Motor import com.qualcomm.hardware.rev.RevColorSensorV3 import com.qualcomm.robotcore.eventloop.opmode.TeleOp import com.qualcomm.robotcore.hardware.Servo import com.qualcomm.robotcore.hardware.TouchSensor import org.firstinspires.ftc.teamcode.commands.drive.DriveCommand import org.firstinspires.ftc.teamcode.commands.slides.SpinCommand import org.firstinspires.ftc.teamcode.constants.DeviceConfig import org.firstinspires.ftc.teamcode.constants.PoseStorage import org.firstinspires.ftc.teamcode.constants.SlidesConst import org.firstinspires.ftc.teamcode.roadrunner.drive.SampleMecanumDrive import org.firstinspires.ftc.teamcode.subsystems.DriveSubsystem import org.firstinspires.ftc.teamcode.subsystems.SlidesClawSubsystem @TeleOp(name = "Main (Outreach & One Controller)") class OutreachTeleOp: CommandOpMode() { // Hardware private lateinit var slidesLeft: Motor private lateinit var slidesRight: Motor private lateinit var limit: TouchSensor private lateinit var clawServo: Servo private lateinit var rotationServo: Servo // Subsystems private lateinit var driveSubsystem: DriveSubsystem private lateinit var slidesClawSubsystem: SlidesClawSubsystem // Gamepads private lateinit var driver: GamepadEx // Commands private lateinit var driveCommand: DriveCommand private lateinit var spinUpCommand: SpinCommand private lateinit var spinDownCommand: SpinCommand private lateinit var openClawCommand: InstantCommand private lateinit var closeClawCommand: InstantCommand override fun initialize() { // Debug telemetry = MultipleTelemetry(FtcDashboard.getInstance().telemetry, telemetry) // Hardware slidesLeft = Motor(hardwareMap, DeviceConfig.SLIDES_LEFT.deviceName) slidesRight = Motor(hardwareMap, DeviceConfig.SLIDES_RIGHT.deviceName) clawServo = hardwareMap.get(Servo::class.java, DeviceConfig.CLAW_SERVO.deviceName) rotationServo = hardwareMap.get(Servo::class.java, DeviceConfig.ROTATION_SERVO.deviceName) limit = hardwareMap.get(TouchSensor::class.java, DeviceConfig.SLIDES_LIMIT.deviceName) // Subsystems driveSubsystem = DriveSubsystem(SampleMecanumDrive(hardwareMap), false) slidesClawSubsystem = SlidesClawSubsystem(slidesLeft, slidesRight, clawServo, rotationServo, limit, telemetry) // Gamepads driver = GamepadEx(gamepad1) // Commands driveCommand = DriveCommand(driveSubsystem, leftX = driver::getLeftX, leftY = driver::getLeftY, rightX = driver::getRightX, zoneVal = 0.15 ) spinUpCommand = SpinCommand(slidesClawSubsystem, true) spinDownCommand = SpinCommand(slidesClawSubsystem, false) openClawCommand = InstantCommand({ slidesClawSubsystem.openClaw() slidesClawSubsystem.clawState = SlidesConst.ClawState.OPEN }, slidesClawSubsystem) closeClawCommand = InstantCommand({ slidesClawSubsystem.closeClaw() slidesClawSubsystem.clawState = SlidesConst.ClawState.CLOSE }, slidesClawSubsystem) driveSubsystem.poseEstimate = PoseStorage.poseEstimate // Assign commands to gamepads driver.getGamepadButton(GamepadKeys.Button.DPAD_DOWN).whileHeld(spinDownCommand) driver.getGamepadButton(GamepadKeys.Button.DPAD_UP).whileHeld(spinUpCommand) driver.getGamepadButton(GamepadKeys.Button.RIGHT_BUMPER).whenPressed( ConditionalCommand( openClawCommand, closeClawCommand, slidesClawSubsystem::isClosed ) ) // Register Subsystems register(driveSubsystem, slidesClawSubsystem) // Assign Default Commands driveSubsystem.defaultCommand = driveCommand } }
1
null
1
1
fac135fb57c4c84938c3d11a6b43fbe09b6c70cf
4,343
PowerPlay-2023
BSD 3-Clause Clear License
Android/app/src/main/java/io/agora/app/karaoke/kit/KaraokeUiKit.kt
apex-wang
659,114,842
true
{"Markdown": 19, "Text": 3, "Ignore List": 5, "Git Config": 1, "Ruby": 3, "Swift": 23, "OpenStep Property List": 1, "XML": 45, "JSON": 9, "Java Properties": 2, "Gradle": 4, "Shell": 2, "Batchfile": 2, "INI": 2, "Proguard": 2, "Kotlin": 7, "Java": 107, "JavaScript": 1, "Maven POM": 1, "Dockerfile": 1, "YAML": 2, "JSON with Comments": 1}
package io.agora.app.karaoke.kit import io.agora.app.karaoke.BuildConfig import io.agora.asceneskit.karaoke.AUIKaraokeRoomService import io.agora.asceneskit.karaoke.KaraokeRoomView import io.agora.auikit.model.AUICommonConfig import io.agora.auikit.model.AUICreateRoomInfo import io.agora.auikit.model.AUIRoomConfig import io.agora.auikit.model.AUIRoomContext import io.agora.auikit.model.AUIRoomInfo import io.agora.auikit.service.IAUIRoomManager.AUIRoomManagerRespDelegate import io.agora.auikit.service.callback.AUIException import io.agora.auikit.service.http.HttpManager import io.agora.auikit.service.imp.AUIRoomManagerImpl import io.agora.auikit.service.ktv.KTVApi import io.agora.auikit.service.rtm.AUIRtmErrorProxyDelegate import io.agora.auikit.utils.AUILogger import io.agora.rtc2.RtcEngine import io.agora.rtc2.RtcEngineEx import io.agora.rtm.RtmClient object KaraokeUiKit { private val notInitException = RuntimeException("The KaraokeServiceManager has not been initialized!") private val initedException = RuntimeException("The KaraokeServiceManager has been initialized!") private var mRoomManager: AUIRoomManagerImpl? = null private var shouldReleaseRtc = true private var mRtcEngineEx: RtcEngineEx? = null private var mKTVApi: KTVApi? = null private var mService: AUIKaraokeRoomService? = null /** * 初始化。 * 对于rtmClient、rtcEngineEx、ktvApi: * 当外部没传时内部会自行创建,并在release方法调用时销毁; * 当外部传入时在release时不会销毁 */ fun setup( config: AUICommonConfig, ktvApi: KTVApi? = null, rtcEngineEx: RtcEngineEx? = null, rtmClient: RtmClient? = null ) { if (mRoomManager != null) { throw initedException } HttpManager.setBaseURL(BuildConfig.SERVER_HOST) AUIRoomContext.shared().commonConfig = config mKTVApi = ktvApi if (rtcEngineEx != null) { // 用户塞进来的engine由用户自己管理生命周期 mRtcEngineEx = rtcEngineEx shouldReleaseRtc = false } mRoomManager = AUIRoomManagerImpl(config, rtmClient) AUILogger.initLogger(AUILogger.Config(AUIRoomContext.shared().commonConfig.context, "Karaoke")) } /** * 释放资源 */ fun release() { if (shouldReleaseRtc) { RtcEngine.destroy() } mRtcEngineEx = null mRoomManager = null mKTVApi = null } /** * 获取房间列表 */ fun getRoomList( startTime: Long?, pageSize: Int, success: (List<AUIRoomInfo>) -> Unit, failure: (AUIException) -> Unit ) { val roomManager = mRoomManager ?: throw notInitException roomManager.getRoomInfoList( startTime, pageSize ) { error, roomList -> if (error == null) { success.invoke(roomList ?: emptyList()) } else { failure.invoke(error) } } } /** * 创建房间 */ fun createRoom( createRoomInfo: AUICreateRoomInfo, success: (AUIRoomInfo) -> Unit, failure: (AUIException) -> Unit ) { val roomManager = mRoomManager ?: throw notInitException roomManager.createRoom( createRoomInfo ) { error, roomInfo -> if (error == null && roomInfo != null) { success.invoke(roomInfo) } else { failure.invoke(error ?: AUIException(-999, "RoomInfo return null")) } } } fun launchRoom( roomInfo: AUIRoomInfo, config: AUIRoomConfig, karaokeView: KaraokeRoomView, eventHandler: RoomEventHandler? = null, ) { AUIRoomContext.shared().roomConfig = config val roomManager = mRoomManager ?: throw notInitException val roomService = AUIKaraokeRoomService( mRtcEngineEx, mKTVApi, roomManager, config, roomInfo ) karaokeView.bindService(roomService) mService = roomService eventHandler?.onRoomLaunchSuccess } fun destroyRoom(roomId: String?) { mService?.destroyRoom() mService = null } fun subscribeError(roomId: String, delegate: AUIRtmErrorProxyDelegate) { mRoomManager?.rtmManager?.proxy?.subscribeError(roomId, delegate) } fun unsubscribeError(roomId: String, delegate: AUIRtmErrorProxyDelegate) { mRoomManager?.rtmManager?.proxy?.unsubscribeError(roomId, delegate) } fun bindRespDelegate(delegate: AUIRoomManagerRespDelegate) { mRoomManager?.bindRespDelegate(delegate) } fun unbindRespDelegate(delegate: AUIRoomManagerRespDelegate) { mRoomManager?.unbindRespDelegate(delegate) } enum class ErrorCode(val value: Int, val message: String) { RTM_LOGIN_FAILURE(100, "Rtm login failed!"), ROOM_PERMISSIONS_LEAK(101, "The room leak required permissions!"), ROOM_DESTROYED(102, "The room has been destroyed!"), } data class RoomEventHandler( val onRoomLaunchSuccess: (() -> Unit)? = null, val onRoomLaunchFailure: ((ErrorCode) -> Unit)? = null, ) }
0
null
0
0
acc5f2823364b3645ad21d5d7c29fb2c653e144a
5,193
AUIKitKaraoke
MIT License
app/src/main/java/com/stanica/speedoxtream/ui/settings/userinfo/UserInfoGuidedFragment.kt
Danini2308
587,394,185
false
{"Java Properties": 13, "Gradle": 50, "Shell": 9, "Markdown": 7, "Batchfile": 8, "Text": 5, "Ignore List": 5, "JSON": 77, "Python": 1, "Proguard": 26, "XML": 397, "Java": 441, "Kotlin": 59, "SVG": 1, "HTML": 1}
package com.stanica.speedoxtream.ui.settings.userinfo import android.content.Context import android.os.Bundle import androidx.leanback.app.ErrorSupportFragment import androidx.leanback.app.GuidedStepSupportFragment import androidx.leanback.app.ProgressBarManager import androidx.leanback.widget.GuidanceStylist import androidx.leanback.widget.GuidedAction import android.view.View import android.view.ViewGroup import com.stanica.speedoxtream.R import com.stanica.speedoxtream.util.Constants import java.util.* /** * Fragment used to show the current user's account status. * * @author stanica * @date 11/04/2021 */ class UserInfoGuidedFragment : GuidedStepSupportFragment(), UserInfoView { private lateinit var userProgressBarManager: ProgressBarManager override fun onStart() { super.onStart() guidanceStylist.apply { // Don't show the guidance stuff for the moment and show the progress bar titleView.visibility = View.INVISIBLE descriptionView.visibility = View.INVISIBLE breadcrumbView.visibility = View.INVISIBLE } userProgressBarManager = ProgressBarManager().apply { setRootView(activity?.findViewById(android.R.id.content) as ViewGroup) initialDelay = 250 show() } val sharedPreferences = activity?.getSharedPreferences(Constants.SPEEDOXTREAM_PREFERENCES, Context.MODE_PRIVATE) val url = sharedPreferences?.getString(Constants.PROVIDER_URL_PREFERENCE, "") val username = sharedPreferences?.getString(Constants.USERNAME_PREFERENCE, "") val password = sharedPreferences?.getString(Constants.PASSWORD_PREFERENCE, "") val endpoint = getString(R.string.provider_user_info_url, url, username, password) val userInfoPresenter = UserInfoPresenterImpl(endpoint, this) userInfoPresenter.retrieveUserInfo() } override fun onCreateGuidance(savedInstanceState: Bundle?): GuidanceStylist.Guidance { val sharedPreferences = activity?.getSharedPreferences(Constants.SPEEDOXTREAM_PREFERENCES, Context.MODE_PRIVATE) val title = getString(R.string.user_info_text) val breadcrumb = sharedPreferences?.getString(Constants.USERNAME_PREFERENCE, "") return GuidanceStylist.Guidance(title, null, breadcrumb, null) } override fun onCreateActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) { val builder = GuidedAction.Builder(context).apply { clickAction(GuidedAction.ACTION_ID_OK) }.build() actions.add(builder) } override fun onGuidedActionClicked(action: GuidedAction?) { /* There seems to have an issue with popBackStackToGuidedStepFragment(), let's just use the classical popBackStack(). */ fragmentManager?.popBackStack() } override fun onConnectionFailed() { guidanceStylist?.apply { titleView.visibility = View.VISIBLE descriptionView.visibility = View.VISIBLE breadcrumbView.visibility = View.VISIBLE iconView.visibility = View.VISIBLE titleView.text = getString(R.string.error_text) descriptionView.text = getString(R.string.user_info_not_accessible) iconView.setImageDrawable(context?.getDrawable(R.drawable.lb_ic_sad_cloud)) } userProgressBarManager.hide() } override fun onConnectionSuccess(status: String, expirationDate: Date, isTrial: Boolean, maxConnections: Int) { guidanceStylist?.apply { val trial = if (isTrial) getString(R.string.yes_text) else getString(R.string.no_text) descriptionView.text = getString(R.string.user_info_description, status, expirationDate, trial, maxConnections.toString()) titleView.visibility = View.VISIBLE descriptionView.visibility = View.VISIBLE breadcrumbView.visibility = View.VISIBLE } userProgressBarManager.hide() } override fun getUserInfoApiEndpoint(): String { val sharedPreferences = activity?.getSharedPreferences(Constants.SPEEDOXTREAM_PREFERENCES, Context.MODE_PRIVATE) val url = sharedPreferences?.getString(Constants.PROVIDER_URL_PREFERENCE, "") val username = sharedPreferences?.getString(Constants.USERNAME_PREFERENCE, "") val password = sharedPreferences?.getString(Constants.PASSWORD_PREFERENCE, "") return getString(R.string.provider_user_info_url, url, username, password) } }
1
null
1
1
fc502b55a4cc434e9c04e2ce7e12f966ced4e07c
4,557
SpeedoXtream
Apache License 2.0